问题描述
如果这两个方法只是同义词,为什么人们会麻烦写其他字符 _chain
?
If these two methods are simply synonyms, why do people go to the trouble of writing the additional characters "_chain
"?
推荐答案
否。 alias_method
是Ruby的标准方法。 alias_method_chain
是一个Rails附加组件,旨在简化以下常用操作:将旧方法别名为新名称,然后将新方法别名为原始名称。因此,例如,如果您要使用新功能 new_feature
创建新版本的方法
方法,则以下两个代码示例是等效的:
No. alias_method
is a standard method from Ruby. alias_method_chain
is a Rails add-on designed to simplify the common action of aliasing the old method to a new name and then aliasing a new method to the original name. So, if for example you are creating a new version of the method
method with the new feature new_feature
, the following two code examples are equivalent:
alias_method :method_without_new_feature, :method
alias_method :method, :method_with_new_feature
和
alias_method_chain :method, :new_feature
编辑
这是一个假设的示例:假设我们有一个Person类,其方法为 rename
。它所做的只是取一个像 John Doe的字符串,在空格上分割,然后将部分分配给first_name和last_name。例如:
EDIT
Here is a hypothetical example: suppose we had a Person class with a method rename
. All it does is take a string like "John Doe", split on the space, and assign parts to first_name and last_name. For example:
person.rename("Steve Jones")
person.first_name #=> Steve
person.last_name #=> Jones
现在我们遇到了问题。我们一直在获取不正确大写的新名称。因此,我们可以编写一个新方法 rename_with_capitalization
并使用 alias_method_chain
来解决此问题:
Now we're having a problem. We keep getting new names that aren't capitalized properly. So we can write a new method rename_with_capitalization
and use alias_method_chain
to resolve this:
class Person
def rename_with_capitalization(name)
rename_without_capitalization(name)
self.first_name[0,1] = self.first_name[0,1].upcase
self.last_name[0,1] = self.last_name[0,1].upcase
end
alias_method_chain :rename, :capitalization
end
现在,旧的重命名
称为不带大写字母的重命名
,而重命名和大写字母
的名称为重命名
。例如:
Now, the old rename
is called rename_without_capitalization
, and rename_with_capitalization
is rename
. For example:
person.rename("bob smith")
person.first_name #=> Bob
person.last_name #=> Smith
person.rename_without_capitalization("tom johnson")
person.first_name #=> tom
person.last_name #=> johnson
这篇关于alias_method_chain是否与alias_method同义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!