【问题标题】:Ruby metaprogramming with MongoMapper使用 MongoMapper 进行 Ruby 元编程
【发布时间】:2014-02-18 12:21:43
【问题描述】:

我正在尝试向 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 的内容在当前模型(self)上创建密钥。

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

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

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

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

我怎样才能只影响单个实例?

【问题讨论】:

  • 不要发给班级。
  • 但是#key 不是类方法吗?不确定我是否关注:(

标签: ruby metaprogramming mongomapper


【解决方案1】:

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

【讨论】:

  • 谢谢!我不得不将它稍微更改为c = Class.new(klass.new.class),但除此之外它效果很好。由于不同的问题,我将原始代码更改为在 self.class 上使用 #send 而不是 class_eval。这时候就出现了这个新问题。 class_eval是否只影响实例的类(单例类/特征类),而不影响所有类的类?
  • AFAIK class_eval 是一个类方法,而不是一个实例方法,所以这个问题似乎没有实际意义——它会影响调用它的类。
猜你喜欢
  • 1970-01-01
  • 2014-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-01
  • 1970-01-01
  • 2011-06-28
相关资源
最近更新 更多