はじめに
Rails 6 に追加されそうな新機能を試す第4段。 Date#before? Date#after? 編です。
記載時点では、Rails は 6.0.0.beta3 です。 gem install rails --prerelease でインストールできます。
試してみる
今回は、rails の projectを作らなくても試せるので、直接、ruby (irb) から試してみましょう。
$ irb -ractive_support/core_ext
# 今日は昨日より後?
irb(main):001:0> Date.today.after?(Date.today.yesterday)
=> true
# 今日は明日より後?
irb(main):002:0> Date.today.after?(Date.today.tomorrow)
=> false
# 今日は昨日より前?
irb(main):003:0> Date.today.before?(Date.today.yesterday)
=> false
# 今日は明日より前?
irb(main):004:0> Date.today.before?(Date.today.tomorrow)
=> true
# 今日は今日より後?
irb(main):005:0> Date.today.after?(Date.today)
=> false
# 今日は今日より前?
irb(main):006:0> Date.today.before?(Date.today)
=> false
DateTime, Time, TimeWithZone にも同様に before? と after? が追加されています。
これ、わかりやすいんですかね。英語ペラペラの人にとっては自然なのかもですが、そうでない人には、ちょっと微妙かもと思ったり思わなかったり。以下みたいな読み違いをしそうな気がしないでもない...
# 今日の後は昨日? => この解釈が間違い。
irb(main):001:0> Date.today.after?(Date.today.yesterday)
=> true
このメソッドは、 :> が after? の <: が before? の aliasとして定義されています。と書こうとしたのですが、どうやらそうではなかったようです。
irb(main):015:0> Date.today.method(:before?).original_name
=> :before?
irb(main):016:0> Date.today.method(:after?).original_name
=> :after?
アレッと思ってソースを調べてみました。
irb(main):018:0> Date.today.method(:before?).source_location
=> ["/usr/local/bundle/gems/activesupport-6.0.0.beta3/lib/active_support/core_ext/date_and_time/calculations.rb", 64]
irb(main):019:0> Date.today.method(:after?).source_location
=> ["/usr/local/bundle/gems/activesupport-6.0.0.beta3/lib/active_support/core_ext/date_and_time/calculations.rb", 69]
実際のコードはこんな感じです。
# Returns true if the date/time falls before <tt>date_or_time</tt>.
def before?(date_or_time)
self < date_or_time
end
# Returns true if the date/time falls after <tt>date_or_time</tt>.
def after?(date_or_time)
self > date_or_time
end
調べてみたら、alias で定義していたものを refactoring してました。
元のPRが Add before? and after? methods to date and time classes で、
refactoring の PR が Move implementation of before? and after? to DateAndTime::Calculations です。