【问题标题】:extending class with modules containing class methods of the same name使用包含同名类方法的模块扩展类
【发布时间】:2015-03-16 12:08:25
【问题描述】:

我通过herehere 描述的显着模式扩展了我的ActiveRecord 类。 我找不到安全的方法让我的新包含的类方法(extend_with_mod_aextend_with_mod_b)调用它们自己的类方法(bar

require 'active_record'

module ModA
  extend ActiveSupport::Concern

  module ClassMethods

    def extend_with_mod_a
      puts "extending #{self} with ModA"
      bar
    end

    def bar
      puts "this is method bar of ModA"
    end

  end

end


module ModB
  extend ActiveSupport::Concern

  module ClassMethods

    def extend_with_mod_b
      puts "extending #{self} with ModB"
      bar
    end

    def bar
      puts "this is method bar of ModB"
    end

  end

end

ActiveRecord::Base.send :include, ModA
ActiveRecord::Base.send :include, ModB

class TestModel < ActiveRecord::Base

  extend_with_mod_a
  extend_with_mod_b

end

输出是

extending with ModA
this is method bar of ModB
extending with ModB
this is method bar of ModB

当然,调用哪个 bar 方法取决于 ActiveRecord 包含调用顺序。我想在extend_with_mod_a 方法定义中使用类似ModA::ClassMethods.bar 的东西

【问题讨论】:

    标签: ruby-on-rails ruby metaprogramming mixins


    【解决方案1】:
    module ModA
      extend ActiveSupport::Concern
    
      module ClassMethods
        def bar
          puts "this is method bar of ModA"
        end
    
        # grab UnboundMethod of ModA::ClassMethods::bar
        a_bar = instance_method(:bar)
    
        # using define_method to capture a_bar
        define_method :extend_with_mod_a do
          puts "extending #{self} with ModA"
          # invoke ModA::ClassMethods::bar properly bound to the class being extended/included with ModA
          a_bar.bind(self).call
        end
      end
    end
    

    【讨论】:

      【解决方案2】:

      尝试:prepend你的模块。

      ActiveRecord::Base.send :prepend, ExtModule
      

      【讨论】:

      • 问题已更新且 :prepend 已尝试.. 无效。还是谢谢
      猜你喜欢
      • 2013-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-24
      • 2018-12-21
      • 1970-01-01
      • 2011-10-25
      相关资源
      最近更新 更多