Permalink
Browse files

updates String#to_(date|date_time|time) to return nil for blank strings

  • Loading branch information...
1 parent b73177a commit 726b5d79845c0ef50db64e2991bfec4e108faf4d @hassox hassox committed with wycats Apr 21, 2010
@@ -30,16 +30,19 @@ def ord
# Form can be either :utc (default) or :local.
def to_time(form = :utc)
+ return nil if self.blank?
d = ::Date._parse(self, false).values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction).map { |arg| arg || 0 }
d[6] *= 1000000
::Time.send("#{form}_time", *d)
end
def to_date
+ return nil if self.blank?
::Date.new(*::Date._parse(self, false).values_at(:year, :mon, :mday))
end
def to_datetime
+ return nil if self.blank?
d = ::Date._parse(self, false).values_at(:year, :mon, :mday, :hour, :min, :sec, :zone, :sec_fraction).map { |arg| arg || 0 }
d[5] += d.pop
::DateTime.civil(*d)
@@ -117,17 +117,20 @@ def test_string_to_time
assert_equal Time.local(2005, 2, 27, 23, 50, 19, 275038), "2005-02-27T23:50:19.275038".to_time(:local)
assert_equal DateTime.civil(2039, 2, 27, 23, 50), "2039-02-27 23:50".to_time
assert_equal Time.local_time(2039, 2, 27, 23, 50), "2039-02-27 23:50".to_time(:local)
+ assert_equal nil, "".to_time
end
-
+
def test_string_to_datetime
assert_equal DateTime.civil(2039, 2, 27, 23, 50), "2039-02-27 23:50".to_datetime
assert_equal 0, "2039-02-27 23:50".to_datetime.offset # use UTC offset
assert_equal ::Date::ITALY, "2039-02-27 23:50".to_datetime.start # use Ruby's default start value
assert_equal DateTime.civil(2039, 2, 27, 23, 50, 19 + Rational(275038, 1000000), "-04:00"), "2039-02-27T23:50:19.275038-04:00".to_datetime
+ assert_equal nil, "".to_datetime
end
-
+
def test_string_to_date
assert_equal Date.new(2005, 2, 27), "2005-02-27".to_date
+ assert_equal nil, "".to_date
end
def test_access
@@ -255,7 +258,7 @@ def test_mb_chars_returns_string
string.rb - Interpolation for String.
Copyright (C) 2005-2009 Masao Mutoh
-
+
You may redistribute it and/or modify it under the same
license terms as Ruby.
=end

0 comments on commit 726b5d7

Please sign in to comment.