Skip to content

Commit

Permalink
DirtyModel uses a hash to keep track of any changes made to attributes
Browse files Browse the repository at this point in the history
of an instance. When using the attribute_will_change! method, you must
supply a string and not a symbol or the *_changed? method will break
(because it is looking for the attribute name as a string in the keys
of the underlying hash). To remedy this, I simply made the underlying
hash a HashWithIndifferentAccess so it won't matter if you supply
the attribute name as a symbol or string to attribute_will_change!.
  • Loading branch information
griffinmyers committed May 28, 2013
1 parent 19b52d3 commit 0e65587
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
5 changes: 5 additions & 0 deletions activemodel/CHANGELOG.md
@@ -1,5 +1,10 @@
## Rails 4.0.0 (unreleased) ##

* Updated the DirtyModel *_changed? method to be indifferent between using
symbols and strings as keys.

*William Myers*

* Add `ActiveModel::Validations::AbsenceValidator`, a validator to check the
absence of attributes.

Expand Down
2 changes: 1 addition & 1 deletion activemodel/lib/active_model/dirty.rb
Expand Up @@ -139,7 +139,7 @@ def previous_changes
# person.name = 'robert'
# person.changed_attributes # => {"name" => "bob"}
def changed_attributes
@changed_attributes ||= {}
@changed_attributes ||= ActiveSupport::HashWithIndifferentAccess.new
end

private
Expand Down
17 changes: 16 additions & 1 deletion activemodel/test/cases/dirty_test.rb
Expand Up @@ -3,11 +3,12 @@
class DirtyTest < ActiveModel::TestCase
class DirtyModel
include ActiveModel::Dirty
define_attribute_methods :name, :color
define_attribute_methods :name, :color, :size

def initialize
@name = nil
@color = nil
@size = nil
end

def name
Expand All @@ -28,6 +29,15 @@ def color=(val)
@color = val
end

def size
@size
end

def size=(val)
attribute_will_change!(:size) unless val == @size
@size = val
end

def save
@previously_changed = changes
@changed_attributes.clear
Expand Down Expand Up @@ -114,4 +124,9 @@ def save
assert_equal ["Otto", "Mr. Manfredgensonton"], @model.name_change
assert_equal @model.name_was, "Otto"
end

test "using attribute_will_change! with a symbol" do
@model.size = 1
assert @model.size_changed?
end
end

0 comments on commit 0e65587

Please sign in to comment.