Michael Michael - 17 days ago 6
Ruby Question

Ruby method_missing usage in class and module

How

method_missing
can be used both in class and mixed module?

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

Answer

Use 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"

As pointed out by @ndn in comments, one might carefully handle different outcomes. super might be tuned to be used if and only if the Foo#method_missing implementation did not succeed:

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