0
0

More than 3 years have passed since last update.

all_month が気になって ActiveSupport DateAndTime::Calculations を読んでみた

Posted at

これ何

先輩にレビュー中に、 all_month 使った方がいいんじゃない?と言われたので、気になって調べてみた。
ActiveSupport の DateAndTime::Calculations に定義されていたので、周りのmethodも読んでみる

範囲指定のmethod

all_monthの内部実装を眺めてみた。rails/railsの内部実装だが、読めるコードでわかる。

def all_month
  beginning_of_month..end_of_month
end

ref: activesupport/lib/active_support/core_ext/date_and_time/calculations.rb

同じファイルの中を見てみるとall_month 以外にも all_xxx methodが存在した。対象範囲が変わるだけで、使えそうなmethodが多い。

  • all_day
  • all_month
  • all_quarter:3ヶ月ごとの日時情報が取れる
  • all_week:週の開始日を決めることができる
  • all_year

気づき 1. future?, past?

未来・過去かを判定するmethodが存在する!再定義しなくても、rails/railsであるものを使える!!気づき。

Date.yesterday.past?
=> true
Date.yesterday.future?
=> false
Date.tomorrow.future?
=> true
Date.tomorrow.past?
=> false

気づき 2. all_xxxと同様にnext_xxx, prev_xxxも存在する

next_xxx, prev_xxx が定義されている。 prev_xxx は last_xxx にaliasされている。

Date.current
=> Sun, 11 Jul 2020
Date.current.next_week
=> Mon, 13 Jul 2020
Date.current.prev_week
=> Mon, 29 Jun 2020
Date.current.last_week
=> Mon, 29 Jun 2020

参考文献

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0