H.E*_*yed 7 ruby ruby-on-rails alias-method-chain alias-method ruby-on-rails-3
我正在处理我的Web应用程序,我想覆盖一个方法,例如,如果原始类是
class A
def foo
'original'
end
end
Run Code Online (Sandbox Code Playgroud)
我想覆盖foo方法,它可以这样做
class A
alias_method :old_foo, :foo
def foo
old_foo + ' and another foo'
end
end
Run Code Online (Sandbox Code Playgroud)
我可以像这样调用新旧方法
obj = A.new
obj.foo #=> 'original and another foo'
obj.old_foo #=> 'original'
Run Code Online (Sandbox Code Playgroud)
那么如果我可以像我一样访问并保留两种方法,那么alias_method_chain的用途是什么?
alias_method_chain 表现不同于 alias_method
如果你有方法do_something而你想覆盖它,保留旧方法,你可以这样做:
alias_method_chain :do_something, :something_else
Run Code Online (Sandbox Code Playgroud)
这相当于:
alias_method :do_something_without_something_else, :do_something
alias_method :do_something, :do_something_with_something_else
Run Code Online (Sandbox Code Playgroud)
这允许我们轻松覆盖方法,添加例如自定义日志记录.想象一个Foo带有do_something方法的类,我们想要覆盖它.我们可以做的:
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
Run Code Online (Sandbox Code Playgroud)
为了完成你的工作,你可以做到:
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"
Run Code Online (Sandbox Code Playgroud)
由于它不是很复杂,你也可以用plain来做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"
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅文档.