Ruby元编程之梦中情人method_missing方法详解

2019-09-25 09:42:07于丽

你有点难搞哦

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 delegation。

好,我们总结一下,看看 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?

现在你估计在想,总有该用它的时候吧,不然还要它干嘛?没错。

动态命名的方法(又名,元方法)

案例:我要依据某种模式提供一组方法。这些方法做的事情顾名思义。我可能从来没有调用过这些可能的方法,但是等我要用的时候,它们必须可用。

现在才是人话!这其实正是 ActiveRecord 所采用的方式,为你提供那些基于属性的动态构建的查找方法,比如 find_by_login_and_email(user_login, user_email)。