Skip to content

Commit

Permalink
Merge pull request rails#13131 from gja/changed-accepts-values
Browse files Browse the repository at this point in the history
Allows you to check if a field has changed to a particular value
  • Loading branch information
chancancode committed Dec 31, 2013
2 parents 969a077 + da2b05b commit f3a8be3
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
6 changes: 6 additions & 0 deletions activemodel/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
* `attribute_changed?` now accepts parameters which check the old and new value of the attribute

`model.name_changed?(from: "Pete", to: "Ringo")`

*Tejas Dinkar*

* Fix `has_secure_password` to honor bcrypt-ruby's cost attribute.

*T.J. Schuck*
Expand Down
8 changes: 6 additions & 2 deletions activemodel/lib/active_model/dirty.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ module ActiveModel
# person.name = 'Bob'
# person.changed? # => true
# person.name_changed? # => true
# person.name_changed?(from: "Uncle Bob", to: "Bob") # => true
# person.name_was # => "Uncle Bob"
# person.name_change # => ["Uncle Bob", "Bob"]
# person.name = 'Bill'
Expand Down Expand Up @@ -149,8 +150,11 @@ def changed_attributes
end

# Handle <tt>*_changed?</tt> for +method_missing+.
def attribute_changed?(attr) # :nodoc:
changed_attributes.include?(attr)
def attribute_changed?(attr, options = {}) #:nodoc:
result = changed_attributes.include?(attr)
result &&= options[:to] == __send__(attr) if options.key?(:to)
result &&= options[:from] == changed_attributes[attr] if options.key?(:from)
result
end

# Handle <tt>*_was</tt> for +method_missing+.
Expand Down
10 changes: 10 additions & 0 deletions activemodel/test/cases/dirty_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,16 @@ def save
assert_equal [nil, "John"], @model.changes['name']
end

test "checking if an attribute has changed to a particular value" do
@model.name = "Ringo"
assert @model.name_changed?(from: nil, to: "Ringo")
assert_not @model.name_changed?(from: "Pete", to: "Ringo")
assert @model.name_changed?(to: "Ringo")
assert_not @model.name_changed?(to: "Pete")
assert @model.name_changed?(from: nil)
assert_not @model.name_changed?(from: "Pete")
end

test "changes accessible through both strings and symbols" do
@model.name = "David"
assert_not_nil @model.changes[:name]
Expand Down

0 comments on commit f3a8be3

Please sign in to comment.