我通过描述here和here的显着模式扩展了我的ActiveRecord类。
我找不到安全地让我的新包含类方法(extend_with_mod_a
和extend_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
之类的内容
答案 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