Skip to content

Commit 0599bfa

Browse files
committed
DateTime#<=> return nil when compare to the invalid String as Time.
before: p Time.now == 'a' # => false p Time.now <=> 'a' # => nil require 'active_support' require 'active_support/core_ext' p Time.now == 'a' # => false p Time.now <=> 'a' # => invalid date (ArgumentError) and on ruby 2.2, Time.now == 'a' warning. warning: Comparable#== will no more rescue exceptions of #<=> in the next release. warning: Return nil in #<=> if the comparison is inappropriate or avoid such comparison. after: - Error handling. - Quiet warnings.
1 parent de4f408 commit 0599bfa

File tree

3 files changed

+15
-1
lines changed

3 files changed

+15
-1
lines changed

activesupport/lib/active_support/core_ext/date_time/calculations.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ def <=>(other)
168168
if other.kind_of?(Infinity)
169169
super
170170
elsif other.respond_to? :to_datetime
171-
super other.to_datetime
171+
super other.to_datetime rescue nil
172172
else
173173
nil
174174
end

activesupport/test/core_ext/date_time_ext_test.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -335,6 +335,13 @@ def test_compare_with_time_with_zone
335335
assert_equal(-1, DateTime.civil(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 1), ActiveSupport::TimeZone['UTC'] ))
336336
end
337337

338+
def test_compare_with_string
339+
assert_equal 1, DateTime.civil(2000) <=> Time.utc(1999, 12, 31, 23, 59, 59).to_s
340+
assert_equal 0, DateTime.civil(2000) <=> Time.utc(2000, 1, 1, 0, 0, 0).to_s
341+
assert_equal( -1, DateTime.civil(2000) <=> Time.utc(2000, 1, 1, 0, 0, 1).to_s)
342+
assert_equal nil, DateTime.civil(2000) <=> "Invalid as Time"
343+
end
344+
338345
def test_to_f
339346
assert_equal 946684800.0, DateTime.civil(2000).to_f
340347
assert_equal 946684800.0, DateTime.civil(1999,12,31,19,0,0,Rational(-5,24)).to_f

activesupport/test/core_ext/time_ext_test.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -721,6 +721,13 @@ def test_compare_with_time_with_zone
721721
assert_equal(-1, Time.utc(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 1), ActiveSupport::TimeZone['UTC'] ))
722722
end
723723

724+
def test_compare_with_string
725+
assert_equal 1, Time.utc(2000) <=> Time.utc(1999, 12, 31, 23, 59, 59, 999).to_s
726+
assert_equal 0, Time.utc(2000) <=> Time.utc(2000, 1, 1, 0, 0, 0).to_s
727+
assert_equal( -1, Time.utc(2000) <=> Time.utc(2000, 1, 1, 0, 0, 1, 0).to_s)
728+
assert_equal nil, Time.utc(2000) <=> 'Invalid as Time'
729+
end
730+
724731
def test_at_with_datetime
725732
assert_equal Time.utc(2000, 1, 1, 0, 0, 0), Time.at(DateTime.civil(2000, 1, 1, 0, 0, 0))
726733

0 commit comments

Comments
 (0)