Mic*_*ael -1 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
Run Code Online (Sandbox Code Playgroud)
用途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"
Run Code Online (Sandbox Code Playgroud)
正如@ndn在评论中指出的那样,人们可能会仔细处理不同的结果.super可能会被调整为当且仅当Foo#method_missing实现没有成功时才使用:
def method_missing(name, *args)
case name
when /foo/ then p 'Foo'
# .....
else super # ? HERE
end
end
Run Code Online (Sandbox Code Playgroud)