alias_method_chain是alias_method的同义词吗?
如果这两种方法只是同义词,为什么人们会去编写附加字符“ _chain
”呢?
编号alias_method
是Ruby的标准方法。 alias_method_chain
是一个Rails附加组件,旨在简化将旧方法别名化为新名称的常见操作,然后将新方法别名化为原始名称。 因此,如果您正在使用新functionnew_feature
创建method
方法的新版本,则以下两个代码示例是等效的:
alias_method :method_without_new_feature, :method alias_method :method, :method_with_new_feature
和
alias_method_chain :method, :new_feature
编辑
这是一个假设的例子:假设我们有一个带有方法rename
的Person类。 它所做的只是采用像“John Doe”这样的字符串,在空格上拆分,并将部分分配给first_name和last_name。 例如:
person.rename("Steve Jones") person.first_name #=> Steve person.last_name #=> Jones
现在我们遇到了问题。 我们不断获取未正确大写的新名称。 所以我们可以编写一个新方法rename_with_capitalization
并使用alias_method_chain
来解决这个问题:
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
现在,旧的rename
称为rename_without_capitalization
, rename_with_capitalization
是rename
。 例如:
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
是进行方法调用拦截的最糟糕方式。 如果您正在寻找类似的技术,请不要在轨道外使用它。