Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Time#advance recognizes fractional days and weeks [#970 state:resolved]

  • Loading branch information...
commit 27c70ff386e76ed0af41b53f2ba8cdb09bc94ace 1 parent 1abdc87
@cwninja cwninja authored gbuesing committed
View
10 activesupport/lib/active_support/core_ext/time/calculations.rb
@@ -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
View
34 activesupport/test/core_ext/duration_test.rb
@@ -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
Please sign in to comment.
Something went wrong with that request. Please try again.