Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 类_eval中的未初始化常量_Ruby - Fatal编程技术网

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 # ...