Instead of overriding to_s
in my model I'd like to alias it to an existing method called full_name
.
Both alias
and alias_method
don't seem to work as expected.
alias
class Person < ActiveRecord::Base
# ... other model code.
alias to_s full_name
def full_name
"#{first_name} #{last_name}"
end
end
# In Terminal
> Person.last.to_s #=> "#<Person:0x007fa5f8a81b50>"
alias_method
class Person < ActiveRecord::Base
# ... other model code.
alias_method :to_s, :full_name
def full_name
"#{first_name} #{last_name}"
end
end
# In Terminal
> Person.last.to_s #=> "#<Person:0x007fa5f8a81b50>"
Figured it out...
alias
and alias_method
need to come after the method you are aliasing to.
So both of the following work fine:
alias
class Person
def full_name
"#{first_name} #{last_name}"
end
alias to_s full_name
end
# In Terminal
> Person.last.to_s #=> "Don Draper"
alias_method
class Person
def full_name
"#{first_name} #{last_name}"
end
alias_method :to_s, :full_name
end
# In Terminal
> Person.last.to_s #=> "Don Draper"
Hopefully that helps somebody else.