![](/img/trans.png)
[英]alias_method, alias_method_chain, and self.included
[英]what is the difference between alias_method and alias_method_chain?
我正在處理我的Web應用程序,我想覆蓋一個方法,例如,如果原始類是
class A
def foo
'original'
end
end
我想覆蓋foo方法,它可以這樣做
class A
alias_method :old_foo, :foo
def foo
old_foo + ' and another foo'
end
end
我可以像這樣調用新舊方法
obj = A.new
obj.foo #=> 'original and another foo'
obj.old_foo #=> 'original'
那么如果我能像我一樣訪問並保留兩種方法,那么alias_method_chain的用途是什么?
alias_method_chain
行為與alias_method
不同
如果你有方法do_something
並且想要覆蓋它,保留舊方法,你可以這樣做:
alias_method_chain :do_something, :something_else
這相當於:
alias_method :do_something_without_something_else, :do_something
alias_method :do_something, :do_something_with_something_else
這允許我們輕松覆蓋方法,添加例如自定義日志記錄。 想象一下帶有do_something
方法的Foo
類,我們想要覆蓋它。 我們可以做的:
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
為了完成你的工作,你可以做到:
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"
由於它不是很復雜,你也可以用普通的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"
有關更多信息,請參閱文檔 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.