我刚刚读到有关 Rails 3 的 Gems/Plugin 开发的内容,然后遇到了这个帖子这表示不再使用 alias_method_chain 。我可以看到该方法仍然存在于 activesupport-3.0.0/lib/active_support/core_ext/module/aliasing.rb 中。
我还应该在 Rails 3 中使用 alias_method_chain 吗?
Is this仍然反映了 Rails 3 中想要修改 ActiveRecord 的 gem/插件的最佳实践吗?
不,它已被模块中方法重写的巧妙使用所取代,并且super
关键词。
基本上,您在包含的模块中定义原始函数,并在另一个包含的模块中覆盖它。你打电话时super
在重写函数中,它调用原始函数。但有一个问题。您必须包含扩展模块after包括基本模块,并按照您希望链接发生的顺序。
class Something
module Base
def my_method
# (A) original functionality
end
end
module PreExtension
def my_method
# (B) before the original
super # calls whatever was my_method before this definition was made
end
end
module PostExtension
def my_method
super # calls whatever was my_method before this definition was made
# (C) after the original
end
end
include Base # this is needed to place the base methods in the inheritance stack
include PreExtension # this will override the original my_method
include PostExtension # this will override my_method defined in PreExtension
end
s = Something.new
s.my_method
#=> this is a twice extended method call that will execute code in this order:
#=> (B) before the original
#=> (A) the original
#=> (C) after the original
瑞安·贝茨铁路广播谈论如何在 Rails 路由代码中使用它。我建议观看它以及他的其他截屏视频。他们有能力将一位针织祖母转变为 Rails 大师。
PS:信用归于Peeja纠正我原来答案中的一个根本错误。谢谢。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)