Time#- coerces TimeWithZone argument to a Time instance so that difference in seconds can be calculated. Closes #10914 [Geoff Buesing, yyyc514]

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@8730 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
This commit is contained in:
Geoff Buesing 2008-01-25 23:55:07 +00:00
parent 4b2ac708b7
commit dad3e835f7
4 changed files with 27 additions and 0 deletions

@ -1,5 +1,7 @@
*SVN*
* Time#- coerces TimeWithZone argument to a Time instance so that difference in seconds can be calculated. Closes #10914 [Geoff Buesing, yyyc514]
* Adding UTC zone to TimeZone; TimeWithZone no longer has to fake UTC zone with nil [Geoff Buesing]
* Time.get_zone refactored to private method, given that the encapsulated logic is only useful internally [Geoff Buesing]

@ -13,6 +13,9 @@ def self.included(base) #:nodoc:
alias_method :minus_without_duration, :-
alias_method :-, :minus_with_duration
alias_method :minus_without_coercion, :-
alias_method :-, :minus_with_coercion
alias_method :compare_without_coercion, :<=>
alias_method :<=>, :compare_with_coercion
end
@ -218,6 +221,14 @@ def minus_with_duration(other) #:nodoc:
end
end
# Time#- can also be used to determine the number of seconds between two Time instances.
# We're layering on additional behavior so that ActiveSupport::TimeWithZone instances
# are coerced into values that Time#- will recognize
def minus_with_coercion(other)
other = other.comparable_time if other.respond_to?(:comparable_time)
minus_without_coercion(other)
end
# Layers additional behavior on Time#<=> so that DateTime and ActiveSupport::TimeWithZone instances
# can be chronologically compared with a Time
def compare_with_coercion(other)

@ -454,6 +454,10 @@ def test_compare_with_time_with_zone
assert_equal 0, Time.utc(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 0), TimeZone['UTC'] )
assert_equal(-1, Time.utc(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 1), TimeZone['UTC'] ))
end
def test_minus_with_time_with_zone
assert_equal 86_400.0, Time.utc(2000, 1, 2) - ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1), TimeZone['UTC'] )
end
protected
def with_timezone(new_tz = 'US/Eastern')

@ -121,6 +121,16 @@ def test_minus
def test_minus_with_duration
assert_equal Time.utc(1999, 12, 26, 19, 0 ,0), (@twz - 5.days).time
end
def test_minus_with_time
assert_equal 86_400.0, ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2), TimeZone['UTC'] ) - Time.utc(2000, 1, 1)
end
def test_minus_with_time_with_zone
twz1 = ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1), TimeZone['UTC'] )
twz2 = ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2), TimeZone['UTC'] )
assert_equal 86_400.0, twz2 - twz1
end
def test_to_time
assert_equal @twz, @twz.to_time