Use Module#prepend instead of alias chaining
Now that we no longer support ruby 1.9.3, the loveliness of Module#prepend is at our disposal!
This commit is contained in:
parent
6c7cdca245
commit
edecc8dd24
|
@ -1,4 +1,21 @@
|
||||||
# Example from 'Overwriting default accessors' in ActiveRecord::Base.
|
module OverrideSongAttributesTheRails4Way
|
||||||
|
def attributes
|
||||||
|
if name
|
||||||
|
super.merge(name: name)
|
||||||
|
else
|
||||||
|
super
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def changed_attributes
|
||||||
|
if name
|
||||||
|
super.merge(name: name)
|
||||||
|
else
|
||||||
|
super
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
class Song < ActiveRecord::Base
|
class Song < ActiveRecord::Base
|
||||||
has_paper_trail
|
has_paper_trail
|
||||||
|
|
||||||
|
@ -15,32 +32,6 @@ class Song < ActiveRecord::Base
|
||||||
attribute :name, :string
|
attribute :name, :string
|
||||||
else
|
else
|
||||||
attr_accessor :name
|
attr_accessor :name
|
||||||
|
prepend OverrideSongAttributesTheRails4Way
|
||||||
# override attributes hashes like some libraries do
|
|
||||||
def attributes_with_name
|
|
||||||
if name
|
|
||||||
attributes_without_name.merge(name: name)
|
|
||||||
else
|
|
||||||
attributes_without_name
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# `alias_method_chain` is deprecated in rails 5, but we cannot use the
|
|
||||||
# suggested replacement, `Module#prepend`, because we still support ruby 1.9.
|
|
||||||
alias attributes_without_name attributes
|
|
||||||
alias attributes attributes_with_name
|
|
||||||
|
|
||||||
def changed_attributes_with_name
|
|
||||||
if name
|
|
||||||
changed_attributes_without_name.merge(name: name)
|
|
||||||
else
|
|
||||||
changed_attributes_without_name
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# `alias_method_chain` is deprecated in rails 5, but we cannot use the
|
|
||||||
# suggested replacement, `Module#prepend`, because we still support ruby 1.9.
|
|
||||||
alias changed_attributes_without_name changed_attributes
|
|
||||||
alias changed_attributes changed_attributes_with_name
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
Loading…
Reference in New Issue