Skip to content

Commit

Permalink
Override accessors for #attributes and #changed_attributes in a non-d…
Browse files Browse the repository at this point in the history
…estructive manner
  • Loading branch information
batter committed Apr 29, 2015
1 parent f5f310b commit 19d43ff
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
12 changes: 8 additions & 4 deletions test/dummy/app/models/song.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,19 @@ def length

# override attributes hashes like some libraries do
def attributes_with_name
attributes_without_name.tap do |_hash|
_hash.merge!(:name => name) if name
if name
attributes_without_name.merge(:name => name)
else
attributes_without_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
if name
changed_attributes_without_name.merge(:name => name)
else
changed_attributes_without_name
end
end
alias_method_chain :changed_attributes, :name
Expand Down
4 changes: 2 additions & 2 deletions test/unit/model_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1131,11 +1131,11 @@ def without(&block)
setup do
@song.name = 'Good Vibrations'
@song.save
@song.name = nil
@song.name = 'Yellow Submarine'
end

should 'return persist the changes on the live instance properly' do
assert_equal nil, @song.name
assert_equal 'Yellow Submarine', @song.name
end
should 'return "overwritten" virtual attribute on the reified instance' do
assert_equal 'Good Vibrations', @song.versions.last.reify.name
Expand Down

0 comments on commit 19d43ff

Please sign in to comment.