【发布时间】:2015-03-16 12:08:25
【问题描述】:
我通过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 包含调用顺序。我想在extend_with_mod_a 方法定义中使用类似ModA::ClassMethods.bar 的东西
【问题讨论】:
标签: ruby-on-rails ruby metaprogramming mixins