[英]Override method_missing for class and instance methods?
我正在嘗試編寫一個通用模塊,將dynamic_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上....
你想要達到的目標非常簡單,同時又不同尋常。 ActiveSupport::Concern
讓您可以定義嵌套的ClassMethods
模塊,該模塊在included
模塊掛鈎上擴展基類。 通常這很方便,因為您不希望使用相同的方法擴充類及其實例。
您需要做的是停止使用ActiveSupport::Concern
並編寫included
鈎子以滿足您的特定需求:
module AsyncModule
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
private
def self.included(base)
base.extend self
end
end
你試過以下嗎?
module ClassAndInstanceVersion
extend ActiveSupport::Concern
def method_missing(meth, *args, &block)
self.class.method_missing(meth, *args, &block)
end
def respond_to_missing?(method_name, include_private = false)
self.class.respond_to_missing?(method_name, include_private)
end
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.