虽然不是一项面向外侧的功能,变更集 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.