From c121e5b9cc82ed47f0bde503b5e01dc8681d9562 Mon Sep 17 00:00:00 2001 From: Ari Epstein Date: Wed, 10 Nov 2010 15:08:22 -0500 Subject: [PATCH] Add accessors for _previously_changed?, previously_was, previous_change and a test to verify. --- activemodel/lib/active_model/dirty.rb | 21 +++++++++++++++++++-- activemodel/test/cases/dirty_test.rb | 15 +++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/activemodel/lib/active_model/dirty.rb b/activemodel/lib/active_model/dirty.rb index 1dfd0b6..0a17062 100644 --- a/activemodel/lib/active_model/dirty.rb +++ b/activemodel/lib/active_model/dirty.rb @@ -90,7 +90,8 @@ module ActiveModel include ActiveModel::AttributeMethods included do - attribute_method_suffix '_changed?', '_change', '_will_change!', '_was' + attribute_method_suffix '_changed?', '_change', '_will_change!', '_was', + '_previously_changed?', '_previous_change', '_previously_was' attribute_method_affix :prefix => 'reset_', :suffix => '!' end @@ -124,7 +125,7 @@ module ActiveModel # person.save # person.previous_changes # => {'name' => ['bob, 'robert']} def previous_changes - @previously_changed + @previously_changed ||= {} end # Map of change attr => original value. @@ -149,6 +150,21 @@ module ActiveModel attribute_changed?(attr) ? changed_attributes[attr] : __send__(attr) end + # Handle *_previously_changed? for +method_missing+. + def attribute_previously_changed?(attr) + previous_changes.keys.include?(attr) + end + + # Handle *_previous_change for +method_missing+. + def attribute_previous_change(attr) + previous_changes[attr] if attribute_previously_changed?(attr) + end + + # Handle *_previously_was for +method_missing+. + def attribute_previously_was(attr) + attribute_previously_changed?(attr) ? attribute_previous_change(attr).first : attribute_was(attr) + end + # Handle *_will_change! for +method_missing+. def attribute_will_change!(attr) begin @@ -166,3 +182,4 @@ module ActiveModel end end end + diff --git a/activemodel/test/cases/dirty_test.rb b/activemodel/test/cases/dirty_test.rb index 858ae9c..851f9c1 100644 --- a/activemodel/test/cases/dirty_test.rb +++ b/activemodel/test/cases/dirty_test.rb @@ -106,4 +106,19 @@ class DirtyTest < ActiveModel::TestCase assert_equal [nil, "Jericho Cane"], @model.previous_changes['name'] end + test "previous attribute accessors" do + @model.instance_variable_set("@name", "Yam") + assert !@model.name_changed? + assert !@model.name_previously_changed? + assert @model.name_previous_change.nil? + assert_equal "Yam", @model.name_previously_was + @model.name = "Bob" + @model.save + assert !@model.name_changed? + assert @model.name_previously_changed? + assert_equal ["Yam", "Bob"], @model.name_previous_change + assert_equal "Yam", @model.name_previously_was + end + end + -- 1.7.2.3