1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Allow checking whether an attribute previously changed from/to a particular value

This commit is contained in:
George Claghorn 2020-01-27 16:01:22 -05:00 committed by George Claghorn
parent 95bd55eca3
commit a6841c720a
3 changed files with 22 additions and 2 deletions

View file

@ -1,3 +1,11 @@
* `*_previously_changed?` accepts `:from` and `:to` keyword arguments like `*_changed?`.
topic.update!(status: :archived)
topic.status_previously_changed?(from: "active", to: "archived")
# => true
*George Claghorn*
* Raise FrozenError when trying to write attributes that aren't backed by the database on an object that is frozen: * Raise FrozenError when trying to write attributes that aren't backed by the database on an object that is frozen:
class Animal class Animal

View file

@ -83,6 +83,7 @@ module ActiveModel
# #
# person.previous_changes # => {"name" => [nil, "Bill"]} # person.previous_changes # => {"name" => [nil, "Bill"]}
# person.name_previously_changed? # => true # person.name_previously_changed? # => true
# person.name_previously_changed?(from: nil, to: "Bill") # => true
# person.name_previous_change # => [nil, "Bill"] # person.name_previous_change # => [nil, "Bill"]
# person.name_previously_was # => nil # person.name_previously_was # => nil
# person.reload! # person.reload!
@ -177,8 +178,8 @@ module ActiveModel
end end
# Dispatch target for <tt>*_previously_changed?</tt> attribute methods. # Dispatch target for <tt>*_previously_changed?</tt> attribute methods.
def attribute_previously_changed?(attr_name) # :nodoc: def attribute_previously_changed?(attr_name, **options) # :nodoc:
mutations_before_last_save.changed?(attr_name.to_s) mutations_before_last_save.changed?(attr_name.to_s, **options)
end end
# Dispatch target for <tt>*_previously_was</tt> attribute methods. # Dispatch target for <tt>*_previously_was</tt> attribute methods.

View file

@ -149,6 +149,17 @@ class DirtyTest < ActiveModel::TestCase
assert_predicate @model, :name_previously_changed? assert_predicate @model, :name_previously_changed?
end end
test "checking if an attribute was previously changed to a particular value" do
@model.name = "Ringo"
@model.save
assert @model.name_previously_changed?(from: nil, to: "Ringo")
assert_not @model.name_previously_changed?(from: "Pete", to: "Ringo")
assert @model.name_previously_changed?(to: "Ringo")
assert_not @model.name_previously_changed?(to: "Pete")
assert @model.name_previously_changed?(from: nil)
assert_not @model.name_previously_changed?(from: "Pete")
end
test "previous value is preserved when changed after save" do test "previous value is preserved when changed after save" do
assert_equal({}, @model.changed_attributes) assert_equal({}, @model.changed_attributes)
@model.name = "Paul" @model.name = "Paul"