Ruby method_missing类和模块中的用法

时间:2016-11-15 08:05:43

标签: ruby metaprogramming

如何在课堂和混合模块中使用method_missing

module Bar
  def method_missing(name, *args)
    p 'Bar' if name =~ /bar/
  end
end

class Foo
  include Bar

  def method_missing(name, *args)
    p 'Foo' if name =~ /foo/
  end
end

a = Foo.new
a.foofoo => "Foo"
a.barbar => nil

1 个答案:

答案 0 :(得分:5)

使用super

module Bar
  def method_missing(name, *args)
    p 'Bar' if name =~ /bar/
  end
end

class Foo
  include Bar

  def method_missing(name, *args)
    p 'Foo' if name =~ /foo/
    super # ⇐ HERE
  end
end

a = Foo.new
a.foofoo => "Foo"
a.barbar => "Bar"

正如@ndn在评论中指出的那样,人们可能会仔细处理不同的结果。当且仅当super实施未成功时,Foo#method_missing可能会被调整使用:

  def method_missing(name, *args)
    case name
    when /foo/ then p 'Foo'
    # .....
    else super # ⇐ HERE
    end
  end