Ruby / Mongoid用新属性装饰记录

时间:2013-03-28 22:30:33

标签: ruby-on-rails ruby mongoid

我正在试图弄清楚如何使用属性修饰特定的Mongoid记录,以便to_json返回包含该属性(请不要告诉我将特定参数传递给to_json - 这是双重嵌套,在这里不起作用)。有没有办法做到这一点?我能想出的就是

my_record[:my_special_attribute]='foo'

当然不起作用。

1 个答案:

答案 0 :(得分:1)

以下两个版本可能适合您:

覆盖to_json

require 'mongoid'
Mongoid.load!("mongoid.yml", :development)

class MyClass
  include Mongoid::Document

  def to_json(options = {})
    json = JSON.parse(super)
    json['my_special_attribute'] = 'whatever you want'
    json.to_json
  end
end

p MyClass.new.to_json # => "{\"_id\":\"5155899ee44f7ba6e7000001\",\"my_special_attribute\":\"whatever you want\"}"

将参数传递给to_json(抱歉 - 为了完整起见):

require 'mongoid'
Mongoid.load!("mongoid.yml", :development)

class MyClass
  include Mongoid::Document

  def not_a_field
    "whatever you want"
  end
end

p MyClass.new.to_json(methods: :not_a_field) # => "{\"_id\":\"51558b67e44f7bddb7000001\",\"my_special_attribute\":\"whatever you want\"}"

您甚至可以将此选项传递给嵌套记录(我猜这是双重嵌套的意思):

my_record.to_json(include: {other_class: {methods: :special_field}})

您还可以将此方法添加到一个特定记录(=实例):

my_object = MyClass.new

def my_object.not_a_field
  "whatever you want"
end 
p my_object.to_json(methods: :not_a_field) # => "{\"_id\":\"51558cc8e44f7bd1f6000001\",\"not_a_field\":\"whatever you want\"}"