0xSina
0xSina

Reputation: 21553

to_json/as_json overriding

I am overriding to_json in my ActiveRecord class:

def to_json(options={})
    puts options
    options.merge :methods => [:shortened_id, :quote]
    puts options
    super(options)
end

It's not doing anything to the options hash, i.e. it's not changing it.

I am calling it via

obj.to_json

I call puts to see if it's modifying options hash and it prints

{}
{}

Also, i tried this with as_json, no luck. What's the difference between to_json and as_json and why isn't this working? Thanks!

Upvotes: 0

Views: 1067

Answers (1)

mu is too short
mu is too short

Reputation: 434615

Hash#merge returns the merged Hash:

merge(other_hash) → new_hash
merge(other_hash){|key, oldval, newval| block} → new_hash

Returns a new hash containing the contents of other_hash and the contents of hsh.

So you want:

options = options.merge :methods => [:shortened_id, :quote]

or use merge! which modifies the Hash in-place:

options.merge! :methods => [:shortened_id, :quote]

Upvotes: 2

Related Questions