0

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!

0xSina
  • 20,973
  • 34
  • 136
  • 253

1 Answers1

2

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]
mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • Thanks! I will accept your answer if you can answer my last question 'What's the difference between to_json and as_json' – 0xSina Nov 28 '12 at 04:39
  • 1
    @0xSina: `as_json` is a pre-JSON serializer that produces a simple nested Array/Hash/... structure, `to_json` produces actual JSON strings, I covered some of this awhile ago over here http://stackoverflow.com/a/6880638/479863 – mu is too short Nov 28 '12 at 04:45