Ruby元编程:method_missing与define_method的正确使用指南
近期有若干文章推崇在 Ruby 中使用 method_missing 机制。
尽管许多开发者对其青睐有加,却往往忽视了潜在的风险与规范。因此,有必要深入探讨这一话题。
** 如何正确使用 method_missing **
何时应克制对 method_missing 的使用冲动
首要原则是,在未充分评估其必要性之前,切勿轻易采用 method_missing。实际上,日常开发中极少存在非用此法不可的情况:
常见场景:方法代理
具体案例:使一个类能够调用另一个类的方法
这是 method_missing 最常见的用途,尤其在 Gems 和 Rails 插件中广泛存在。其基本模型如下: 复制代码 代码如下: class A def hi puts "Hi from #{self.class}" end end
class B def initialize @b = A.new end
def method_missing(method_name, *args, &block) @b.send(method_name, *args, &block) end end
A.new.hi #=> Hi from A B.new.hi #=> Hi from A 通过这种方式,B 获得了 A 的所有实例方法。然而,需思考调用 @b.hi 时的内部机制。Ruby 环境会沿继承链查找 hi 方法,直到触发 NoMethodError 前才会调用 method_missing。
在上述简单示例中问题不大,仅涉及两个类。但在 Rails 等框架中,模型通常继承自 ActiveRecord,后者又集成自众多基类。这意味着每次调用 @b.hi 时,都需要遍历漫长的继承链,造成不必要的开销。
更优选择:define_method
顾名思义,它允许动态定义方法。其优势在于,一旦执行(通常在类加载后),这些方法便直接存在于类中,无需后续遍历继承链。
define_method 稳定且可靠,足以应对大多数日常需求。例如: 复制代码 代码如下: class B define_method(:hi) do @b.hi end end “但我需要定义大量方法!”你或许会抱怨。
“没问题!”我轻松回应。 复制代码 代码如下: class B [:hi, :bye, :achoo, :gesundheit].each do |name| define_method(name) do @b.send(name) end end end “可我不想逐个列出方法名!”
“看来你比较挑剔。” 复制代码 代码如下: class A # ... lots of methods in here end class B A.instance_methods.each do |name| define_method(name) do @b.send(name) end end end “那如果定义的方法与原方法略有不同呢?”
“这也很简单。” 复制代码 代码如下: class A def hi puts "Hi." end end
class B A.instance_methods.each do |name| define_method("what_is_#{name}") do if @b.respond_to?(name) @b.send(name) else false end end end end
B.new.what_is_hi #=> "Hi." B.new.what_is_wtf #=> false 虽然代码略显冗长,但逻辑清晰。
若追求代码简洁,可参考 ruby delegation library 或 Rails ActiveRecord 的委托实现。
接下来,我们总结 define_method 的强大之处。
改编自 ruby-doc.org 示例 复制代码 代码如下: class A def fred puts "In Fred" end def create_method(name, &block) self.class.send(:define_method, name, &block) end define_method(:wilma) { puts "Charge it!" } end class B < A define_method(:barney, instance_method(:fred)) end
a = B.new a.barney #=> In Fred a.wilma #=> Charge it! a.create_method(:betty) { p self.to_s } a.betty #=> B 何时才该使用 method_missing?
你可能会问,既然 define_method 这么好,method_missing 还有何用?答案是有特定场景。
动态命名方法(即元方法)
案例:需要根据某种模式提供一组方法,这些方法功能明确。即使从未调用过,当需要时它们必须可用。
这才是 method_missing 的用武之地。ActiveRecord 正是利用它来生成基于属性的动态查找方法,如 find_by_login_and_email(user_login, user_email)。
复制代码 代码如下: def method_missing(method_id, *arguments, &block) if match = DynamicFinderMatch.match(method_id) attribute_names = match.attribute_names super unless all_attributes_exists?(attribute_names) if match.finder? # ...you get the point end # my OCD makes me unable to omit this # ... else super # this is important, I'll tell you why in a second end end
利弊权衡
当需要定义大量可能不使用的元方法时,method_missing 是理想的折衷方案。
以 ActiveRecord 的基于属性查找为例。若使用 define_method,需检查表中所有字段并为每种组合定义方法。 复制代码 代码如下: find_by_email find_by_login find_by_name find_by_id find_by_email_and_login find_by_email_and_login_and_name find_by_email_and_name # ...
假如你的模型有 10 个字段,那就是 10! (362880)个查找方法需要定义。想象一下,在你的 Rails 项目跑起来的时候,有这么多个方法需要一次定义掉,而 ruby 环境还得把它们都放在内存里头。
即便是老虎·伍兹也做不到如此高效。
** method_missing 的正确姿势 **
(以下内容为简要摘译)
1、先进行模式检查
并非所有未定义方法都需处理,应先判断是否符合预期模式: 复制代码 代码如下: def method_missing(method_id, *arguments, &block) if method_id.to_s =~ /^what_is_[\w]+/ # do your thing end end 2、将其包裹起来
确认需处理后,利用 define_method 动态定义该方法,以便下次直接调用,避免再次触发 method_missing: 复制代码 代码如下: def method_missing(method_id, *arguments, &block) if method_id.to_s =~ /^what_is_[\w]+/ self.class.send :define_method, method_id do # do your thing end self.send(method_id) end end 3、妥善处理异常
对于无法处理的方法,应调用 super 交由父类处理: 复制代码 代码如下: def method_missing(method_id, *arguments, &block) if method_id.to_s =~ /^what_is_[\w]+/ self.class.send :define_method, method_id do # do your thing end self.send(method_id) else super end end
4、声明响应能力 复制代码 代码如下: def respond_to?(method_id, include_private = false) if method_id.to_s =~ /^what_is_[\w]+/ true else super end end 需告知外界,虽然方法尚未定义,但类能响应此类调用。
** 总结 **
在 Ruby 程序员的生命周期中,这三个方法至关重要:define_method 是可靠的朋友,method_missing 是需要谨慎对待的情人,而 respond_to? 则是确保无虞的爱子。