Support for virtual attributes and redefined method accessors

This commit is contained in:
Ben Atkins 2015-04-27 15:35:48 -04:00
parent 8f0b5eb1c8
commit f5f310bfdc
3 changed files with 33 additions and 0 deletions

View File

@ -186,6 +186,8 @@ module PaperTrail
attrs.each do |k, v|
if model.has_attribute?(k)
model[k.to_sym] = v
elsif model.respond_to?("#{k}=")
model.send("#{k}=", v)
else
logger.warn "Attribute #{k} does not exist on #{item_type} (Version id: #{id})."
end

View File

@ -1,6 +1,7 @@
# Example from 'Overwriting default accessors' in ActiveRecord::Base.
class Song < ActiveRecord::Base
has_paper_trail
attr_accessor :name
# Uses an integer of seconds to hold the length of the song
def length=(minutes)
@ -9,4 +10,19 @@ class Song < ActiveRecord::Base
def length
read_attribute(:length) / 60
end
# override attributes hashes like some libraries do
def attributes_with_name
attributes_without_name.tap do |_hash|
_hash.merge!(:name => name) if name
end
end
alias_method_chain :attributes, :name
def changed_attributes_with_name
changed_attributes_without_name.tap do |_hash|
_hash.merge!(:name => name) if name
end
end
alias_method_chain :changed_attributes, :name
end

View File

@ -1126,6 +1126,21 @@ class HasPaperTrailModelTest < ActiveSupport::TestCase
should 'return "overwritten" value on reified instance' do
assert_equal 4, @song.versions.last.reify.length
end
context 'Has a virtual attribute injected into the ActiveModel::Dirty changes' do
setup do
@song.name = 'Good Vibrations'
@song.save
@song.name = nil
end
should 'return persist the changes on the live instance properly' do
assert_equal nil, @song.name
end
should 'return "overwritten" virtual attribute on the reified instance' do
assert_equal 'Good Vibrations', @song.versions.last.reify.name
end
end
end