diff options
author | Rafael França <rafaelmfranca@gmail.com> | 2017-11-28 23:06:52 -0500 |
---|---|---|
committer | GitHub <noreply@github.com> | 2017-11-28 23:06:52 -0500 |
commit | 02b5b1a609a582efafa0d619116109ca4a4e8abd (patch) | |
tree | dd853b50a5664ff708e7e37c7df885fab6b4366f /activesupport/lib/active_support/core_ext | |
parent | 055493ce056a663a7b61ae4f88f657d1a355995d (diff) | |
parent | 333ff24b8524094d55badb6c7f42f4b53832c0b6 (diff) | |
download | rails-02b5b1a609a582efafa0d619116109ca4a4e8abd.tar.gz rails-02b5b1a609a582efafa0d619116109ca4a4e8abd.tar.bz2 rails-02b5b1a609a582efafa0d619116109ca4a4e8abd.zip |
Merge pull request #31268 from tjschuck/refactor_prev_next_occurring
Refactor Date/Time next_occurring and prev_occurring
Diffstat (limited to 'activesupport/lib/active_support/core_ext')
-rw-r--r-- | activesupport/lib/active_support/core_ext/date_and_time/calculations.rb | 16 |
1 files changed, 12 insertions, 4 deletions
diff --git a/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb b/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb index 061b79e098..f6cb1a384c 100644 --- a/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb +++ b/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb @@ -330,20 +330,28 @@ module DateAndTime beginning_of_year..end_of_year end - # Returns specific next occurring day of week + # Returns a new date/time representing the next occurrence of the specified day of week. + # + # today = Date.today # => Thu, 14 Dec 2017 + # today.next_occurring(:monday) # => Mon, 18 Dec 2017 + # today.next_occurring(:thursday) # => Thu, 21 Dec 2017 def next_occurring(day_of_week) current_day_number = wday != 0 ? wday - 1 : 6 from_now = DAYS_INTO_WEEK.fetch(day_of_week) - current_day_number from_now += 7 unless from_now > 0 - since(from_now.days) + advance(days: from_now) end - # Returns specific previous occurring day of week + # Returns a new date/time representing the previous occurrence of the specified day of week. + # + # today = Date.today # => Thu, 14 Dec 2017 + # today.prev_occurring(:monday) # => Mon, 11 Dec 2017 + # today.prev_occurring(:thursday) # => Thu, 07 Dec 2017 def prev_occurring(day_of_week) current_day_number = wday != 0 ? wday - 1 : 6 ago = current_day_number - DAYS_INTO_WEEK.fetch(day_of_week) ago += 7 unless ago > 0 - ago(ago.days) + advance(days: -ago) end private |