【发布时间】:2015-03-02 19:43:22
【问题描述】:
我正在尝试元编程一种基于谓词方法定义爆炸方法的方法。现在我有我想要使用method_missing的行为:
class PredicateBang
def true?
true
end
def false?
false
end
def method_missing(method, *args, &block)
if bang_match = /\A([^?]+)!\z/.match(method.to_s)
predicate_method = :"#{bang_match[1]}?"
if respond_to?(predicate_method)
unless send(predicate_method, *args, &block)
raise "#{predicate_method} is false"
end
return
end
end
super.method_missing(method, *args, &block)
end
end
PredicateBang.new.true!
PredicateBang.new.false! # false? is false (RuntimeError)
但是,我不想覆盖method_missing,而是想通过迭代instance_methods(false) 并使用define_method 为任何以问号结尾并带有匹配参数的方法创建一个bang 方法来动态定义这些方法,但我不确定如何反思这些方法的所有细节。
Method#parameters 似乎是一个不错的第一步,但我不确定如何将其转换为阻止参数或处理默认值。
【问题讨论】:
标签: ruby metaprogramming