问题描述
我刚刚阅读了关于 Rails 3 的 Gems/插件开发并遇到了这篇文章 表示不再使用 alias_method_chain .我可以看到该方法仍然存在于 activesupport-3.0.0/lib/active_support/core_ext/module/aliasing.rb 中.
I was just reading about Gems/Plugin development for Rails 3 and ran across this post that says that alias_method_chain is no longer used. I can see the method is still there in activesupport-3.0.0/lib/active_support/core_ext/module/aliasing.rb.
我还应该在 Rails 3 中使用 alias_method_chain 吗?
Should I still be using alias_method_chain in Rails 3?
这是否仍然反映了 gems 的最佳实践Rails 3 中的/plugins 想要修改 ActiveRecord?
Is this still reflective of the best practices for gems/plugins in Rails 3 that want to modify ActiveRecord?
推荐答案
不,它已被巧妙地使用模块中的方法覆盖和 super
关键字所取代.
No, it has been replaced by a clever use of method overriding in modules and the super
keyword.
基本上,您在包含的模块中定义原始函数,并在另一个包含的模块中覆盖它.当您在覆盖函数中调用 super
时,它会调用原始函数.但有一个问题.您必须在包含基本模块之后包含扩展模块,并按照您希望链接发生的顺序.
Basically, you define the original function in an included module, and override it in another included module. When you call super
in the overriding function, it calls the original function. But there is one catch. You have to include the extending modules after including the base module, and in the order you want the chaining to occur.
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
来自 Railscasts 的 Ryan Bates 谈到了 如何在 Rails 路由代码中使用.我建议观看它,以及他的其他截屏视频.他们有能力将编织祖母变成 Rails 大师.
Ryan Bates of Railscasts talks about how this is used in the Rails Routing code. I'd recommend watching it, and his other screencasts. They have the power to transform a knitting grandmother into a Rails guru.
PS:感谢 Peeja 纠正了我原始答案中的一个基本错误.谢谢.
PS: Credit goes to Peeja for correcting a fundamental error in my original answer. Thanks.
这篇关于Rails 3:alias_method_chain 还在使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!