Add saved changes helpers for store accessors

This commit is contained in:
Vladimir Dementyev 2019-03-25 18:50:27 -04:00
parent 61a39ffcc6
commit b574d283e5
No known key found for this signature in database
GPG Key ID: 8E0A19D3D1EDF5EB
2 changed files with 32 additions and 1 deletions

@ -11,7 +11,9 @@ module ActiveRecord
# of the model. This is very helpful for easily exposing store keys to a form or elsewhere that's
# already built around just accessing attributes on the model.
#
# Every accessor comes with dirty tracking methods (+key_changed?+, +key_was+ and +key_change+).
# Every accessor comes with dirty tracking methods (+key_changed?+, +key_was+ and +key_change+) and
# methods to access the changes made during the last save (+saved_change_to_key?+, +saved_change_to_key+ and
# +key_before_last_save+).
#
# NOTE: There is no +key_will_change!+ method for accessors, use +store_will_change!+ instead.
#
@ -155,6 +157,24 @@ def store_accessor(store_attribute, *keys, prefix: nil, suffix: nil)
prev_store, _new_store = changes[store_attribute]
prev_store&.dig(key)
end
define_method("saved_change_to_#{accessor_key}?") do
return false unless saved_change_to_attribute?(store_attribute)
prev_store, new_store = saved_change_to_attribute(store_attribute)
prev_store&.dig(key) != new_store&.dig(key)
end
define_method("saved_change_to_#{accessor_key}") do
return unless saved_change_to_attribute?(store_attribute)
prev_store, new_store = saved_change_to_attribute(store_attribute)
[prev_store&.dig(key), new_store&.dig(key)]
end
define_method("#{accessor_key}_before_last_save") do
return unless saved_change_to_attribute?(store_attribute)
prev_store, _new_store = saved_change_to_attribute(store_attribute)
prev_store&.dig(key)
end
end
end

@ -136,6 +136,17 @@ class StoreTest < ActiveRecord::TestCase
assert_equal ["Dallas", "Lena"], @john.partner_name_change
end
test "saved changes tracking for accessors" do
@john.spouse[:name] = "Lena"
assert @john.partner_name_changed?
@john.save!
assert_not @john.partner_name_change
assert @john.saved_change_to_partner_name?
assert_equal ["Dallas", "Lena"], @john.saved_change_to_partner_name
assert_equal "Dallas", @john.partner_name_before_last_save
end
test "object initialization with not nullable column" do
assert_equal true, @john.remember_login
end