Skip to content

Commit

Permalink
Time#advance recognizes fractional days and weeks [#970 state:resolved]
Browse files Browse the repository at this point in the history
  • Loading branch information
tomlea authored and gbuesing committed Oct 14, 2008
1 parent 1abdc87 commit 27c70ff
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
10 changes: 10 additions & 0 deletions activesupport/lib/active_support/core_ext/time/calculations.rb
Expand Up @@ -98,6 +98,16 @@ def change(options)
# <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>, <tt>:hours</tt>,
# <tt>:minutes</tt>, <tt>:seconds</tt>.
def advance(options)
unless options[:weeks].nil?
options[:weeks], partial_weeks = options[:weeks].divmod(1)
options[:days] = (options[:days] || 0) + 7 * partial_weeks
end

unless options[:days].nil?
options[:days], partial_days = options[:days].divmod(1)
options[:hours] = (options[:hours] || 0) + 24 * partial_days
end

d = to_date.advance(options)
time_advanced_by_date = change(:year => d.year, :month => d.month, :day => d.day)
seconds_to_advance = (options[:seconds] || 0) + (options[:minutes] || 0) * 60 + (options[:hours] || 0) * 3600
Expand Down
34 changes: 34 additions & 0 deletions activesupport/test/core_ext/duration_test.rb
Expand Up @@ -31,6 +31,40 @@ def test_argument_error
end

uses_mocha 'TestDurationSinceAndAgoWithCurrentTime' do
def test_fractional_weeks
Time.stubs(:now).returns Time.local(2000)

assert_in_delta((24 * 7 * 1.5).hours, 1.5.weeks, 2 ** -20)
assert_in_delta((24 * 7 * 1.7).hours, 1.7.weeks, 2 ** -20)
end

def test_fractional_days
Time.stubs(:now).returns Time.local(2000)

assert_in_delta((24 * 1.5).hours, 1.5.days, 2 ** -20)
assert_in_delta((24 * 1.7).hours, 1.7.days, 2 ** -20)
end

def test_since_and_ago_with_fractional_days
Time.stubs(:now).returns Time.local(2000)
# since
assert_equal 36.hours.since, 1.5.days.since
assert_equal((24 * 1.7).hours.since, 1.7.days.since)
# ago
assert_equal 36.hours.ago, 1.5.days.ago
assert_equal((24 * 1.7).hours.ago, 1.7.days.ago)
end

def test_since_and_ago_with_fractional_weeks
Time.stubs(:now).returns Time.local(2000)
# since
assert_equal((7 * 36).hours.since, 1.5.weeks.since)
assert_equal((7 * 24 * 1.7).hours.since, 1.7.weeks.since)
# ago
assert_equal((7 * 36).hours.ago, 1.5.weeks.ago)
assert_equal((7 * 24 * 1.7).hours.ago, 1.7.weeks.ago)
end

def test_since_and_ago_anchored_to_time_now_when_time_zone_default_not_set
Time.zone_default = nil
with_env_tz 'US/Eastern' do
Expand Down

0 comments on commit 27c70ff

Please sign in to comment.