1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Call super instead of returning nil for DateTime#<=>

The native DateTime#<=> implementation can be used to compare instances
with numeric values being considered as astronomical julian day numbers
so we should call that instead of returning nil.

Fixes #24228.
This commit is contained in:
Andrew White 2016-04-03 23:43:53 +01:00
parent ae2f193c03
commit 08073125a5
3 changed files with 29 additions and 5 deletions

View file

@ -1,3 +1,12 @@
* Rely on the native DateTime#<=> implementation to handle non-datetime like
objects instead of returning `nil` ourselves. This restores the ability
of `DateTime` instances to be compared with a `Numeric` that represents an
astronomical julian day number.
Fixes #24228.
*Andrew White*
* Add `String#upcase_first` method.
*Glauco Custódio*, *bogdanvlviv*

View file

@ -165,13 +165,10 @@ class DateTime
# Layers additional behavior on DateTime#<=> so that Time and
# ActiveSupport::TimeWithZone instances can be compared with a DateTime.
def <=>(other)
if other.kind_of?(Infinity)
super
elsif other.respond_to? :to_datetime
if other.respond_to? :to_datetime
super other.to_datetime rescue nil
else
nil
super
end
end
end

View file

@ -354,6 +354,24 @@ class DateTimeExtCalculationsTest < ActiveSupport::TestCase
assert_equal nil, DateTime.civil(2000) <=> "Invalid as Time"
end
def test_compare_with_integer
assert_equal 1, DateTime.civil(1970, 1, 1, 12, 0, 0) <=> 2440587
assert_equal 0, DateTime.civil(1970, 1, 1, 12, 0, 0) <=> 2440588
assert_equal(-1, DateTime.civil(1970, 1, 1, 12, 0, 0) <=> 2440589)
end
def test_compare_with_float
assert_equal 1, DateTime.civil(1970) <=> 2440586.5
assert_equal 0, DateTime.civil(1970) <=> 2440587.5
assert_equal(-1, DateTime.civil(1970) <=> 2440588.5)
end
def test_compare_with_rational
assert_equal 1, DateTime.civil(1970) <=> Rational(4881173, 2)
assert_equal 0, DateTime.civil(1970) <=> Rational(4881175, 2)
assert_equal(-1, DateTime.civil(1970) <=> Rational(4881177, 2))
end
def test_to_f
assert_equal 946684800.0, DateTime.civil(2000).to_f
assert_equal 946684800.0, DateTime.civil(1999,12,31,19,0,0,Rational(-5,24)).to_f