NoBrainerORM / nobrainer

Ruby ORM for RethinkDB
http://nobrainer.io/
Other
387 stars 49 forks source link

Custom JSON serialization #169

Closed kethomassen closed 8 years ago

kethomassen commented 8 years ago
class User
    include NoBrainer::Document
    field :key, :type => String

    def to_json
        { :key => key, :lol => "bam" }.to_json
    end
end

User.insert_all([{ :key => "a" }, { :key => "b"}])

puts User.all.to_json
# => { "key": "a", "lol": "bam"}
# => { "key": "b", "lol": "bam"}

Is there a way to override to_json like this as such? Would be convenient!

nviennot commented 8 years ago

Put .to_a after .all. Also override as_json instead.

nviennot commented 8 years ago

If you override as_json you shouldn't need to_a

kethomassen commented 8 years ago

@nviennot

/site/models/item.rb:13:in `as_json': wrong number of arguments (1 for 0) (ArgumentError)

when using

    def as_json
        {
            :id => id,
            :image => price.image,
            :price => price.latest_price,
            :name => price.name
        }.to_json
    end
nviennot commented 8 years ago

def as_json(options={})

nviennot commented 8 years ago

And you should not call to_json, just return a hash

kethomassen commented 8 years ago

Thanks! @nviennot