[英]Is it possible to alias to_s?
Instead of overriding to_s
in my model I'd like to alias it to an existing method called full_name
.我不想在我的模型中覆盖
to_s
,而是想将其别名为一个名为full_name
的现有方法。
Both alias
and alias_method
don't seem to work as expected. alias
和alias_method
似乎都没有按预期工作。
alias
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
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. alias
和alias_method
需要跟在你别名的方法之后。
So both of the following work fine:所以以下两个都可以正常工作:
alias
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
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.希望这对其他人有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.