Ruby 类_eval中的未初始化常量
我有一个进行类评估的方法调用:Ruby 类_eval中的未初始化常量,ruby,Ruby,我有一个进行类评估的方法调用: class BatchRecord < ActiveRecord::Base has_one_document :contact end class BatchRecord
class BatchRecord < ActiveRecord::Base
has_one_document :contact
end
class BatchRecord
这很好:
def has_one_document(association_name, options={})
class_eval <<-EOS
def #{ association_name }
MongoidContainer::Contact.where(#{ name.underscore }_id: id).first
end
EOS
end
def有一个文档(关联名称,选项={})
等级评估固定代码:
def has_one_document(association_name, options={})
class_eval <<-EOS
def #{ association_name }
MongoidContainer.const_get(#{association_name.to_s.classify.inspect})
.where(#{ name.underscore }_id: id).first
end
EOS
end
这将尝试在当前范围(您的BatchRecord
类)中搜索名为Contact
的常量,但失败const\u get
获取字符串,因此在将字符串放入eval
(或class\u eval
)之前,您必须检查字符串。回答得好。一个小点:可以接受符号或字符串(无论如何在v2.1中)。“你擅离职守了!”卡利斯沃夫兰,谢谢,我不知道。Ruby没有方法where
。您至少还需要一个标记。
def has_one_document(association_name, options={})
class_eval <<-EOS
def #{ association_name }
MongoidContainer.const_get(#{association_name.to_s.classify.inspect})
.where(#{ name.underscore }_id: id).first
end
EOS
end
MongoidContainer.const_get(Contact).where # ...