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?
The
to_jsonserializer uses the name of the method as the key for serialization. So you can’t use themethodsoption for this.Unfortunately
to_jsonmethod doesnt acceptblock` parameter, otherwise you could have done something similar toSo that leaves us with a ugly hack such as:
Now
to_jsonwill return the expected result.