我将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,包括调用顺序。我想在extend_with_mod_a方法定义中使用类似于extend_with_mod_a的东西
发布于 2017-03-27 19:10:56
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发布于 2015-03-16 13:54:07
尝试:prepend您的模块。
ActiveRecord::Base.send :prepend, ExtModulehttps://stackoverflow.com/questions/29076435
复制相似问题