Use :write_attribute everywhere. Add tests.

This commit is contained in:
Andy Stewart 2010-10-28 10:15:15 +01:00
parent a219759dfe
commit fce1c908ef
4 changed files with 35 additions and 2 deletions

View File

@ -126,7 +126,7 @@ module PaperTrail
previous = self.clone
previous.id = id
changes.each do |attr, ary|
previous.send "#{attr}=", ary.first
previous.send :write_attribute, attr.to_sym, ary.first
end
previous
end

View File

@ -102,7 +102,7 @@ class Version < ActiveRecord::Base
# and therefore impossible to know when "just before" was.
if (child_as_it_was = child.version_at(created_at - lookback.seconds))
child_as_it_was.attributes.each do |k,v|
model.send(assoc.name).send "#{k}=", v rescue nil
model.send(assoc.name).send :write_attribute, k.to_sym, v rescue nil
end
else
model.send "#{assoc.name}=", nil

View File

@ -43,6 +43,19 @@ class Person < ActiveRecord::Base
has_paper_trail
end
# Example from 'Overwriting default accessors' in ActiveRecord::Base.
class Song < ActiveRecord::Base
has_paper_trail
# Uses an integer of seconds to hold the length of the song
def length=(minutes)
write_attribute(:length, minutes.to_i * 60)
end
def length
read_attribute(:length) / 60
end
end
class HasPaperTrailModelTest < Test::Unit::TestCase
load_schema
@ -740,6 +753,22 @@ class HasPaperTrailModelTest < Test::Unit::TestCase
end
end
context 'An overwritten default accessor' do
setup do
@song = Song.create :length => 4
@song.update_attributes :length => 5
end
should 'return "overwritten" value on live instance' do
assert_equal 5, @song.length
end
should 'return "overwritten" value on reified instance' do
assert_equal 4, @song.versions.last.reify.length
end
end
private
# Updates `model`'s last version so it looks like the version was

View File

@ -63,4 +63,8 @@ ActiveRecord::Schema.define(:version => 0) do
t.string :name
end
create_table :songs, :force => true do |t|
t.integer :length
end
end