虽然不是一个面向用户的特性,但变更集 4276 引入了一个很好的方法,用于DRY(避免重复)和封装常见的别名方法模式,以便您在此基础上构建行为。
在 Rails 的内部,您会在模块中找到类似这样的代码
module Layout #:nodoc:
def self.included(base)
base.extend(ClassMethods)
base.class_eval do
alias_method :render_with_no_layout, :render
alias_method :render, :render_with_a_layout</p>
- … etc
</code></pre>
This makes it so that when the module is included into the base class, it adds behavior onto some method in that class without the method having to be aware of the fact that it’s being enhanced. In this case, the render method of ActionController::Base is enhanced to wrap its output in a layout.
The new Module#alias_method_chain wraps up this pattern into a single method call. The above example, once refactored to use Module#alias_method_chain, would simply be:
alias_method_chain :render, :layout
This will be used to refactor quite a bit of Rails internals which may not be of immediate relevance to what you do, but it serves as a nice example of the mechanisms Ruby provides for software organization. Small victories.