Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using different key for to_json :methods

When using :methods in to_json, is there a way to rename the key? I'm trying to replace the real id with a base62 version of it, and I want the value of base62_id to have the key :id.

@obj.to_json(
    :except => :id
    :methods => :base62_id
)

I tried to do

@obj.to_json(
    :except => :id
    :methods => { :id => :base62_id }
)

but that didn't work.

Any advice?

like image 544
fphilipe Avatar asked Mar 15 '10 17:03

fphilipe


1 Answers

The to_json serializer uses the name of the method as the key for serialization. So you can't use the methods option for this. Unfortunately to_json method doesnt acceptblock` parameter, otherwise you could have done something similar to

@obj.to_json(:except => :id) {|json| json.id = base62_id }

So that leaves us with a ugly hack such as:

def to_json(options={})
  oid, self.id  = self.id, self.base62_id(self.id) 
  super
ensure
  self.id = oid
end

Now to_json will return the expected result.

like image 142
Harish Shetty Avatar answered Oct 05 '22 23:10

Harish Shetty