Skip to content

Commit

Permalink
Use :write_attribute everywhere. Add tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
airblade committed Oct 28, 2010
1 parent a219759 commit fce1c90
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 2 deletions.
2 changes: 1 addition & 1 deletion lib/paper_trail/has_paper_trail.rb
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ def item_before_change
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
Expand Down
2 changes: 1 addition & 1 deletion lib/paper_trail/version.rb
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ def reify_has_ones(model, lookback)
# 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
Expand Down
29 changes: 29 additions & 0 deletions test/paper_trail_model_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions test/schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -63,4 +63,8 @@
t.string :name
end

create_table :songs, :force => true do |t|
t.integer :length
end

end

0 comments on commit fce1c90

Please sign in to comment.