Overriding attributes in ActiveRecord
I love that
method_missing if the method is not defined on the superclass.
Consider this case. You have some ActiveRecord named
Account, which has an associated
email_address. However, an account owner may optionally give a special “notification” email address, which will be used for things like newsletter emails and security issues and such. If no notification address has been explicitly given, it should fall back to the account’s primary email address. It’s as simple as this:
1 2 3 4 5
class Account < ActiveRecord::Base def notification_address super || email_address end end
super forces the superclass, ActiveRecord::Base, to be sent the
notification_address message, which it won’t understand. This causes
method_missing to be called on AR::Base, which looks for the
notification_address attribute in the record’s attribute set. If that has not been set, it will be nil, in which case we then default to the email_address value.
Just as you’d expect.