[英]what is the difference between alias_method and alias_method_chain?
I was working on my web-application and I wanted to override a method for example if the original class is 我正在处理我的Web应用程序,我想覆盖一个方法,例如,如果原始类是
class A
def foo
'original'
end
end
I want to override foo method it can be done like this 我想覆盖foo方法,它可以这样做
class A
alias_method :old_foo, :foo
def foo
old_foo + ' and another foo'
end
end
and I can call both old and new methods like this 我可以像这样调用新旧方法
obj = A.new
obj.foo #=> 'original and another foo'
obj.old_foo #=> 'original'
so what is the use of alias_method_chain if I can access and keep both methods like the way I did ? 那么如果我能像我一样访问并保留两种方法,那么alias_method_chain的用途是什么?
alias_method_chain
behaves different than alias_method
alias_method_chain
行为与alias_method
不同
If you have method do_something
and you want to override it, keeping the old method, you can do: 如果你有方法do_something
并且想要覆盖它,保留旧方法,你可以这样做:
alias_method_chain :do_something, :something_else
which is equivalent to: 这相当于:
alias_method :do_something_without_something_else, :do_something
alias_method :do_something, :do_something_with_something_else
this allows us to easily override method, adding for example custom logging. 这允许我们轻松覆盖方法,添加例如自定义日志记录。 Imagine a Foo
class with do_something
method, which we want to override. 想象一下带有do_something
方法的Foo
类,我们想要覆盖它。 We can do: 我们可以做的:
class Foo
def do_something_with_logging(*args, &block)
result = do_something_without_logging(*args, &block)
custom_log(result)
result
end
alias_method_chain :do_something, :logging
end
So to have your job done, you can do: 为了完成你的工作,你可以做到:
class A
def foo_with_another
'another foo'
end
alias_method_chain :foo, :another
end
a = A.new
a.foo # => "another foo"
a.foo_without_another # => "original"
Since it isn't very complicated, you can also do it with plain alias_method
: 由于它不是很复杂,你也可以用普通的alias_method
来做:
class A
def new_foo
'another foo'
end
alias_method :old_foo, :foo
alias_method :foo, :new_foo
end
a = A.new
a.foo # => "another foo"
a.old_foo # => "original"
For more information, you can refer documentation . 有关更多信息,请参阅文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.