diff options
Diffstat (limited to 'activesupport/lib')
3 files changed, 29 insertions, 1 deletions
diff --git a/activesupport/lib/active_support/core_ext/date_time/calculations.rb b/activesupport/lib/active_support/core_ext/date_time/calculations.rb index d93c1148c4..5c351c21c6 100644 --- a/activesupport/lib/active_support/core_ext/date_time/calculations.rb +++ b/activesupport/lib/active_support/core_ext/date_time/calculations.rb @@ -7,6 +7,11 @@ module ActiveSupport #:nodoc: module Calculations def self.included(base) #:nodoc: base.extend ClassMethods + + base.class_eval do + alias_method :compare_without_coercion, :<=> + alias_method :<=>, :compare_with_coercion + end end module ClassMethods @@ -91,6 +96,13 @@ module ActiveSupport #:nodoc: def utc_offset (offset * 86400).to_i end + + # Layers additional behavior on DateTime#<=> so that Time and ActiveSupport::TimeWithZone instances can be compared with a DateTime + def compare_with_coercion(other) + other = other.comparable_time if other.respond_to?(:comparable_time) + other = other.to_datetime unless other.acts_like?(:date) + compare_without_coercion(other) + end end end end diff --git a/activesupport/lib/active_support/core_ext/time/calculations.rb b/activesupport/lib/active_support/core_ext/time/calculations.rb index 7181bac3fd..534571fe61 100644 --- a/activesupport/lib/active_support/core_ext/time/calculations.rb +++ b/activesupport/lib/active_support/core_ext/time/calculations.rb @@ -9,8 +9,12 @@ module ActiveSupport #:nodoc: base.class_eval do alias_method :plus_without_duration, :+ alias_method :+, :plus_with_duration + alias_method :minus_without_duration, :- alias_method :-, :minus_with_duration + + alias_method :compare_without_coercion, :<=> + alias_method :<=>, :compare_with_coercion end end @@ -218,6 +222,19 @@ module ActiveSupport #:nodoc: minus_without_duration(other) end 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) + # if other is an ActiveSupport::TimeWithZone, coerce a Time instance from it so we can do <=> comparision + other = other.comparable_time if other.respond_to?(:comparable_time) + if other.acts_like?(:date) + # other is a Date/DateTime, so coerce self #to_datetime and hand off to DateTime#<=> + to_datetime.compare_without_coercion(other) + else + compare_without_coercion(other) + end + end end end end diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb index dcd55ae93d..648fa16f4e 100644 --- a/activesupport/lib/active_support/time_with_zone.rb +++ b/activesupport/lib/active_support/time_with_zone.rb @@ -105,7 +105,6 @@ module ActiveSupport # Use the time in UTC for comparisons def <=>(other) - other = other.comparable_time if other.respond_to?(:comparable_time) # to coerce time from TimeWithZone utc <=> other end |