gpt4 book ai didi

ruby-on-rails - 覆盖类和实例方法的 method_missing?

转载 作者:数据小太阳 更新时间:2023-10-29 07:05:08 24 4
gpt4 key购买 nike

我正在尝试编写一个通用模块,以将用于动态方法创建的 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 上....

最佳答案

您要实现的目标非常简单,同时又不寻常。 ActiveSupport::Concern 使您可以定义嵌套的 ClassMethods 模块,该模块在 included 模块 Hook 上扩展基类。通常这很方便,因为您不想使用相同的方法扩充类及其实例。

您需要做的是停止使用 ActiveSupport::Concern 并编写 included 钩子(Hook)来满足您的特定需求:

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

关于ruby-on-rails - 覆盖类和实例方法的 method_missing?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22846777/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com