Date/Timeにこの週・月・年を判定するメソッドを追加
DateやTimeオブジェクトが現在の週・月・年に属するかを判定するthis_week?、this_month?、this_year?メソッドが追加されました。既存のtoday?、tomorrow?、yesterday?と同様のインターフェースで、時間範囲の判定をシンプルに記述できるようになります。
背景
ActiveSupportにはtoday?、tomorrow?、yesterday?という日単位の時間判定メソッドが存在していましたが、週・月・年単位の判定メソッドは提供されていませんでした。#55770は、この週・月・年単位の判定を既存の日単位メソッドと同じインターフェースで提供することで、コードの可読性を向上させています。
PRの説明によれば、これらのメソッドは時間インスタンスを現在の期間に対してクエリするのに有用です。
技術的な変更
activesupport/lib/active_support/core_ext/date_and_time/calculations.rbのDateAndTime::Calculationsモジュールに3つの判定メソッドが追加されました。
追加されたメソッド:
# Returns true if the date/time falls within the current week.
def this_week?
::Date.current.all_week.include?(to_date)
end
# Returns true if the date/time falls within the current month.
def this_month?
::Date.current.all_month.include?(to_date)
end
# Returns true if the date/time falls within the current year.
def this_year?
::Date.current.all_year.include?(to_date)
end
各メソッドはDate.currentを基準に、対象の日付が該当する範囲に含まれるかを判定します。to_dateにより、TimeオブジェクトもDateに変換して判定できる設計です。
使用例:
unless post.created_at.this_week?
link_to "See week recap", week_recap_path(date)
end
if invoice.due_at.this_month?
# 今月中の支払期限
end
reports.select { |r| r.created_at.this_year? }
実装は既存のall_week、all_month、all_yearメソッドを呼び出す形で行われており、これらのメソッドが返す範囲オブジェクトのinclude?メソッドを使用して判定しています。
テストケース
activesupport/test/core_ext/date_time_ext_test.rbに境界値テストが追加されました。
this_week?のテスト:
def test_this_week
Date.stub(:current, Date.new(2000, 1, 5)) do # Wed, 2000-01-05
assert_equal false, Time.utc(2000, 1, 2, 23, 59, 59).this_week?
assert_equal true, Time.utc(2000, 1, 3, 0, 0, 0).this_week?
assert_equal true, Time.utc(2000, 1, 9, 23, 59, 59).this_week?
assert_equal false, Time.utc(2000, 1, 10, 0, 0, 0).this_week?
end
end
2000年1月5日(水曜日)を現在日として、週の始まり(月曜日の1月3日 0:00:00)と終わり(日曜日の1月9日 23:59:59)の境界で正しく判定されることを検証しています。同様にthis_month?とthis_year?のテストも月・年の境界で判定が正確であることを確認しています。
本PRは、Railsの時間判定APIに週・月・年単位の判定メソッドを追加した変更です。既存のtoday?などの日単位メソッドと同じインターフェースを提供することで、日常的なコーディングでよく使われる時間範囲判定をより直感的に記述できるようになりました。