2009-08-28 44 views

回答

3

alias_method调用对重新实现某些内容,但保留原始版本也很有用。还有Rails的alias_method_chain,它使这种事情变得更加简单。

当你有一些行为最初是相同的,但在未来可能会发生分歧的时候,alias_method也会派上用场,至少你可以在这些行为中粗暴地开始。

def handle_default_situation 
    nil 
end 

%w[ poll push foo ].each do |type| 
    alias_method :"handle_#{type}_situation", :handle_default_situation 
end 
3

是的。

它通常用于在覆盖它们之前保留现有方法的句柄。 (人为的例子)

鉴于一类是这样的:

class Foo 
    def do_something 
    puts "something" 
    end 
end 

你可以看到代码,增加了新的行为,像这样:

class Foo 
    def do_something_with_logging 
    puts "started doing something" 
    do_something_without_logging # call original implementation 
    puts "stopped doing something" 
    end 

    alias_method :do_something_without_logging, :do_something 
    alias_method :do_something, :do_something_with_logging 
end 

(这正是如何alias_method_chain作品)

但是,对于这种用例,通常更适合于use inheritance and modules to your advantage

不过,alias_method是有一个有用的工具,如果你确实需要重新定义现有类的行为(或者,如果你想实现像alias_method_chain)