Skip to content

Commit

Permalink
Time.zone.parse: return nil for strings with no date information
Browse files Browse the repository at this point in the history
  • Loading branch information
gbuesing committed May 9, 2008
1 parent fb9bf16 commit 06a7c29
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 2 deletions.
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/attribute_methods.rb
Expand Up @@ -179,7 +179,7 @@ def define_write_method(attr_name)
def define_write_method_for_time_zone_conversion(attr_name) def define_write_method_for_time_zone_conversion(attr_name)
method_body = <<-EOV method_body = <<-EOV
def #{attr_name}=(time) def #{attr_name}=(time)
unless time.blank? || time.acts_like?(:time) unless time.acts_like?(:time)
time = time.is_a?(String) ? Time.zone.parse(time) : time.to_time rescue time time = time.is_a?(String) ? Time.zone.parse(time) : time.to_time rescue time
end end
time = time.in_time_zone rescue nil if time time = time.in_time_zone rescue nil if time
Expand Down
4 changes: 3 additions & 1 deletion activesupport/lib/active_support/values/time_zone.rb
Expand Up @@ -213,8 +213,10 @@ def at(secs)
# Time.zone.now # => Fri, 31 Dec 1999 14:00:00 HST -10:00 # Time.zone.now # => Fri, 31 Dec 1999 14:00:00 HST -10:00
# Time.zone.parse('22:30:00') # => Fri, 31 Dec 1999 22:30:00 HST -10:00 # Time.zone.parse('22:30:00') # => Fri, 31 Dec 1999 22:30:00 HST -10:00
def parse(str, now=now) def parse(str, now=now)
date_parts = Date._parse(str)
return if date_parts.blank?
time = Time.parse(str, now) rescue DateTime.parse(str) time = Time.parse(str, now) rescue DateTime.parse(str)
if Date._parse(str)[:offset].nil? if date_parts[:offset].nil?
ActiveSupport::TimeWithZone.new(nil, self, time) ActiveSupport::TimeWithZone.new(nil, self, time)
else else
time.in_time_zone(self) time.in_time_zone(self)
Expand Down
8 changes: 8 additions & 0 deletions activesupport/test/time_zone_test.rb
Expand Up @@ -198,6 +198,14 @@ def test_parse_far_future_date_with_time_zone_offset_in_string
assert_equal zone, twz.time_zone assert_equal zone, twz.time_zone
end end
end end

def test_parse_returns_nil_when_string_without_date_information_is_passed_in
silence_warnings do # silence warnings raised by tzinfo gem
zone = TimeZone['Eastern Time (US & Canada)']
assert_nil zone.parse('foobar')
assert_nil zone.parse(' ')
end
end


uses_mocha 'TestParseWithIncompleteDate' do uses_mocha 'TestParseWithIncompleteDate' do
def test_parse_with_incomplete_date def test_parse_with_incomplete_date
Expand Down

0 comments on commit 06a7c29

Please sign in to comment.