Skip to content

Commit

Permalink
Merge pull request #6054 from flexoid/column-fix
Browse files Browse the repository at this point in the history
Prevent creating valid time-like objects from blank string from db
  • Loading branch information
jonleighton committed May 5, 2012
2 parents 06c787d + 7f160b0 commit 3af9e72
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
6 changes: 3 additions & 3 deletions activerecord/lib/active_record/connection_adapters/column.rb
Expand Up @@ -158,7 +158,7 @@ def binary_to_string(value)

def value_to_date(value)
if value.is_a?(String)
return nil if value.empty?
return nil if value.blank?
fast_string_to_date(value) || fallback_string_to_date(value)
elsif value.respond_to?(:to_date)
value.to_date
Expand All @@ -169,14 +169,14 @@ def value_to_date(value)

def string_to_time(string)
return string unless string.is_a?(String)
return nil if string.empty?
return nil if string.blank?

fast_string_to_time(string) || fallback_string_to_time(string)
end

def string_to_dummy_time(string)
return string unless string.is_a?(String)
return nil if string.empty?
return nil if string.blank?

string_to_time "2000-01-01 #{string}"
end
Expand Down
28 changes: 28 additions & 0 deletions activerecord/test/cases/column_test.rb
Expand Up @@ -48,6 +48,34 @@ def test_type_cast_non_integer_to_integer
column.type_cast(false)
end
end

def test_type_cast_time
column = Column.new("field", nil, "time")
assert_equal nil, column.type_cast('')
assert_equal nil, column.type_cast(' ')

time_string = Time.now.utc.strftime("%T")
assert_equal time_string, column.type_cast(time_string).strftime("%T")
end

def test_type_cast_datetime_and_timestamp
[Column.new("field", nil, "datetime"), Column.new("field", nil, "timestamp")].each do |column|
assert_equal nil, column.type_cast('')
assert_equal nil, column.type_cast(' ')

datetime_string = Time.now.utc.strftime("%FT%T")
assert_equal datetime_string, column.type_cast(datetime_string).strftime("%FT%T")
end
end

def test_type_cast_date
column = Column.new("field", nil, "date")
assert_equal nil, column.type_cast('')
assert_equal nil, column.type_cast(' ')

date_string = Time.now.utc.strftime("%F")
assert_equal date_string, column.type_cast(date_string).strftime("%F")
end
end
end
end

0 comments on commit 3af9e72

Please sign in to comment.