使用 MongoMapper 进行 Ruby 元编程

标签 ruby metaprogramming mongomapper

我正在尝试动态添加键到 MongoMapper 文档。

def build(attrs={})
  doc = self.new
  apply_scope(doc)
  doc.set_up_keys!
  doc.attributes = attrs
  doc
end

def set_up_keys!
  return unless form

  form.fields.each do |f|
    next if self.keys.include?(f.underscored_name)

    self.class.send(:key, f.underscored_name, f.keys['default'].type, :required => f.required, :default => f.default)
  end
end

相关代码可用 herehere .

form 是一个相关模型。我想根据 form#fields 所具有的内容在当前模型(自身)上创建键。

问题是,如果我创建两个模型,它们都具有来自两个模型的相同 key 。

self.class.send(:key...) 将键添加到模型中。

为什么将它们添加到两个模型中?

是因为该方法是在类上下文中调用的吗?

如何才能只影响单个实例?

最佳答案

Mongomapper 通过其类定义模型。此类的所有实例共享模型的键。如果您想即时创建模型,您可能需要dynamically create a class ,并向其中添加键:

def build(attrs={})
  c = Class.new(self.class)
  doc = c.new
  apply_scope(doc)
  doc.set_up_keys!
  doc.attributes = attrs
  doc
end

关于使用 MongoMapper 进行 Ruby 元编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21853671/

相关文章:

ruby - 如何使用 Ruby 将 Haryana 转换为 Haryana

ruby - 使用 Mechanize 进行身份验证的解析页面

ruby - 使用 Ruby 的 TracePoint 获取方法参数

ruby - 调用 instance_eval(&lambda) 传递当前上下文时出现错误 'wrong number of arguments'

ios - Paypal Ruby SDK 未获取刷新 token

ruby-on-rails - Rails 3 按字母顺序列出 ActiveRecord 对象

ruby - `eval` 和 `Kernel.const_get` 是否有任何替代方案?

ruby - 如何使用 MongoMapper 以随机顺序获取文档?

ruby-on-rails-3 - 在 mongo id 上查询 Generation_time

ruby-on-rails - 使用 MongoMapper 继承 : searching the parent class