我在Rails初始化程序中有以下代码:
module Mongoid::ActiveRecordBridge
extend ActiveSupport::Concern
included do
def self.belongs_to_record(association_name, options={})
association_class = (options[:class_name] || association_name.to_s.singularize.classify).constantize
# index(#{ association_name }_id: 1)
class_eval <<-EOS
field :#{ association_name }_id, type: Integer
def #{ association_name }
@#{ association_name } ||= #{ association_class }.where(id: #{ association_name }_id).first
end
def #{ association_name }=(object)
@#{ association_name } = object
self.#{ association_name }_id = object.try :id
end
EOS
end
end
end
MyCode.all.map do |class_code|
dynamic_class = "#{class_code.code}_field".classify
Object.const_set dynamic_class, Class.new do
include Mongoid::Document
include Mongoid::ActiveRecordBridge
belongs_to_record :classification_code
end
end
它成功创建了类对象,因此如果class_code是SomeField,那么SomeField将被初始化。但是,当我运行以下命令时,它返回false:
SomeField.respond_to? :belongs_to_record => false
然而,如果我在Rails控制台中构建另一个对象,它可以正常工作:
2.1.2 :003 > SomeRandomField = Class.new do
2.1.2 :004 > include Mongoid::Document
2.1.2 :005?> include Mongoid::ActiveRecordBridge
2.1.2 :006?> belongs_to_record :classification_code
2.1.2 :007?> end
=> SomeRandomField
2.1.2 :008 > SomeRandomField.respond_to? :belongs_to_record
=> true
为什么当我在初始化程序中执行它时,它不起作用,但在Rails控制台中它可以工作?
答案 0 :(得分:1)
这是因为该块已附加到Object.const_set
,而不是Class.new
使用类似的东西:
klass = Class.new do
include Mongoid::Document
include Mongoid::ActiveRecordBridge
belongs_to_record :classification_code
end
Object.const_set dynamic_class, klass
或使用括号来强制执行正确的分组。