我正在尝试编写一个通用模块,将method_missing模式应用于一些Rails模型的动态方法创建。这些模型既有类方法也有实例方法。虽然我可以相当简单地为类情况编写一个模块:
module ClassVersion
extend ActiveSupport::Concern
module ClassMethods
def method_missing(meth, *args, &block)
if meth.to_s =~ /^(.+)_async$/
Async::handle_async self, $1, *args, &block
else
super meth, *args, &block
end
end
# Logic for this method MUST match that of the detection in method_missing
def respond_to_missing?(method_name, include_private = false)
Async::async?(method_name) || super
end
end
end
例如这个案例:
module InstanceVersion
extend ActiveSupport::Concern
def method_missing(meth, *args, &block)
if meth.to_s =~ /^(.+)_async$/
Async::handle_async self, $1, *args, &block
else
super meth, *args, &block
end
end
# Logic for this method MUST match that of the detection in method_missing
def respond_to_missing?(method_name, include_private = false)
Async::async?(method_name) || super
end
end
我似乎无法在同一个类中同时支持这两种情况。有没有更好的方法来重写method_missing以支持这两种情况?我使用的是Rails 3.2。
method_missing
,则还必须提供模块的respond_to_missing?
,否则method_missing
就不会生效。 - Jeff Gran