Skip to content

Commit

Permalink
Rescue from invalid dates at write_attribute to preserve ActiveRecord…
Browse files Browse the repository at this point in the history
… original behavior.

Closes clemens#6.
  • Loading branch information
fmluizao committed Jun 16, 2010
1 parent 6d2b9a1 commit 5c4e028
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
9 changes: 5 additions & 4 deletions lib/delocalize/rails_ext/active_record.rb
Expand Up @@ -12,15 +12,16 @@ def time?
end

ActiveRecord::Base.class_eval do
def write_attribute_with_localization(attr_name, value)
def write_attribute_with_localization(attr_name, original_value)
new_value = original_value
if column = column_for_attribute(attr_name.to_s)
if column.date?
value = Date.parse_localized(value)
new_value = Date.parse_localized(original_value) rescue original_value
elsif column.time?
value = Time.parse_localized(value)
new_value = Time.parse_localized(original_value) rescue original_value
end
end
write_attribute_without_localization(attr_name, value)
write_attribute_without_localization(attr_name, new_value)
end
alias_method_chain :write_attribute, :localization

Expand Down
7 changes: 7 additions & 0 deletions test/delocalize_test.rb
Expand Up @@ -57,6 +57,13 @@ def setup
assert_equal time, @product.cant_think_of_a_sensible_time_field
end

test "invalid dates should be delocalized to nil" do
date = '32. Oktober 2009'
@product.released_on = date
assert_equal nil, @product.released_on
assert_equal date, @product.released_on_before_type_cast
end

test "uses default parse if format isn't found" do
date = Date.civil(2009, 10, 19)

Expand Down

0 comments on commit 5c4e028

Please sign in to comment.