使用包含同名类方法的模块扩展类

时间:2015-03-16 12:08:25

标签: ruby-on-rails ruby metaprogramming mixins

我通过描述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包括调用顺序。我想在ModA::ClassMethods.bar方法定义

中使用extend_with_mod_a之类的内容

2 个答案:

答案 0 :(得分:0)

尝试:prepend您的模块。

ActiveRecord::Base.send :prepend, ExtModule

答案 1 :(得分:0)

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
相关问题