简体   繁体   English

是否可以为 to_s 取别名?

[英]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. aliasalias_method似乎都没有按预期工作。

Using 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>"

Using 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. aliasalias_method需要跟你别名的方法之后

So both of the following work fine:所以以下两个都可以正常工作:

Using 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"

Using 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM