Skip to content

Commit

Permalink
Fix support for ActiveRecord 5.2
Browse files Browse the repository at this point in the history
  • Loading branch information
Josh Branham committed Oct 12, 2022
1 parent 87a8856 commit 4183e62
Showing 1 changed file with 16 additions and 9 deletions.
25 changes: 16 additions & 9 deletions lib/attr_encrypted/adapters/active_record.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,28 +53,35 @@ def attr_encrypted(*attrs)
super
options = attrs.extract_options!
attr = attrs.pop
attribute attr if ::ActiveRecord::VERSION::STRING >= "5.1.0"
attribute attr
options.merge! encrypted_attributes[attr]

define_method("#{attr}_was") do
attribute_was(attr)
end

if ::ActiveRecord::VERSION::STRING >= "4.1"
define_method("#{attr}_changed?") do |options = {}|
attribute_changed?(attr, options)
end
else
define_method("#{attr}_changed?") do
attribute_changed?(attr)
end
define_method("#{attr}_changed?") do |options = {}|
attribute_changed?(attr, options)
end

define_method("#{attr}_change") do
attribute_change(attr)
end

define_method("#{attr}_with_dirtiness=") do |value|
##
# In ActiveRecord 5.2+, due to changes to the way virtual
# attributes are handled, @attributes[attr].value is nil which
# breaks attribute_was. Setting it here returns us to the expected
# behavior.
if ::ActiveRecord::VERSION::STRING >= "5.2"
# This is needed support attribute_was before a record has
# been saved
set_attribute_was(attr, __send__(attr)) if value != __send__(attr)
# This is needed to support attribute_was after a record has
# been saved
@attributes.write_from_user(attr.to_s, value) if value != __send__(attr)
end
attribute_will_change!(attr) if value != __send__(attr)
__send__("#{attr}_without_dirtiness=", value)
end
Expand Down

0 comments on commit 4183e62

Please sign in to comment.