Ruby   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了ruby-on-rails – 覆盖类和实例方法的method_missing?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试编写一个通用模块,将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,&block
        else
          super meth,&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,&block)
      if meth.to_s =~ /^(.+)_async$/
        Async::handle_async self,&block
      else
        super meth,&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模块,该模块在包含的模块挂钩上扩展基类.通常这很方便,因为您不希望使用相同的方法扩充类及其实例.

您需要做的是停止使用ActiveSupport :: Concern并编写包含的钩子以满足您的特定需求:

module AsyncModule
  def method_missing(meth,&block)
    if meth.to_s =~ /^(.+)_async$/
      Async::handle_async self,&block
    else
      super meth,&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?全部内容,希望文章能够帮你解决ruby-on-rails – 覆盖类和实例方法的method_missing?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: