diff options
author | Sean Griffin <sean@thoughtbot.com> | 2014-07-12 18:30:49 -0600 |
---|---|---|
committer | Godfrey Chan <godfreykfc@gmail.com> | 2014-08-16 23:08:41 -0700 |
commit | 877ea784e4cd0d539bdfbd15839ae3d28169b156 (patch) | |
tree | fe249c2d53d6cd7062b131b6157b3d00bbb7a683 /activemodel | |
parent | 88d27ae9181151f448f39298adce9d1b7401a376 (diff) | |
download | rails-877ea784e4cd0d539bdfbd15839ae3d28169b156.tar.gz rails-877ea784e4cd0d539bdfbd15839ae3d28169b156.tar.bz2 rails-877ea784e4cd0d539bdfbd15839ae3d28169b156.zip |
Implement `_was` and `changes` for in-place mutations of AR attributes
Diffstat (limited to 'activemodel')
-rw-r--r-- | activemodel/lib/active_model/dirty.rb | 19 |
1 files changed, 16 insertions, 3 deletions
diff --git a/activemodel/lib/active_model/dirty.rb b/activemodel/lib/active_model/dirty.rb index d11243c4c0..ed00d8cf12 100644 --- a/activemodel/lib/active_model/dirty.rb +++ b/activemodel/lib/active_model/dirty.rb @@ -114,7 +114,7 @@ module ActiveModel include ActiveModel::AttributeMethods included do - attribute_method_suffix '_changed?', '_change', '_will_change!', '_was' + attribute_method_suffix '_changed?', '_change', '_will_change!', '_was', '_was=' attribute_method_affix prefix: 'reset_', suffix: '!' attribute_method_affix prefix: 'restore_', suffix: '!' end @@ -180,13 +180,26 @@ module ActiveModel attribute_changed?(attr) ? changed_attributes[attr] : __send__(attr) end + # Handle <tt>*_was=</tt> for +method_missing+ + def attribute_was=(attr, old_value) + attributes_changed_by_setter[attr] = old_value + end + alias_method :set_attribute_was, :attribute_was= + # Restore all previous data of the provided attributes. def restore_attributes(attributes = changed) attributes.each { |attr| restore_attribute! attr } end + # Remove changes information for the provided attributes. + def clear_attribute_changes(attributes) + attributes_changed_by_setter.except!(*attributes) + end + private + alias_method :attributes_changed_by_setter, :changed_attributes # :nodoc: + # Removes current changes and makes them accessible through +previous_changes+. def changes_applied # :doc: @previously_changed = changes @@ -219,7 +232,7 @@ module ActiveModel rescue TypeError, NoMethodError end - changed_attributes[attr] = value + set_attribute_was(attr, value) end # Handle <tt>reset_*!</tt> for +method_missing+. @@ -233,7 +246,7 @@ module ActiveModel def restore_attribute!(attr) if attribute_changed?(attr) __send__("#{attr}=", changed_attributes[attr]) - changed_attributes.delete(attr) + clear_attribute_changes([attr]) end end end |