Reputation: 3986
I am overriding to_json
.
When I call to_json
on my model I get the following:
{ "integer1": "23", "integer2": "2", "integer3": "4", ... }
I want to_json
to return:
{ "Something": "23", "SomethingElse": "2", "AnotherThing": "4", ... }
I have an array that contains the key and its mapping:
"integer1" => "Something", "integer2" => "SomethingElse", "integer3" => "AnotherThing", ....
How can I achieve this?
Upvotes: 1
Views: 2432
Reputation: 62708
I highly advocate using draper or a similar decorator-pattern solution to create "JSON views" of objects.
You would have a decorator for your model, on which you define def as_json(options = {})
and return a hash of the data you want to use as the JSON representation of your model. This decouples it from the model, and lets you modify the "data view" of the model separately from the internal representation of the data easily.
Upvotes: 3
Reputation: 303549
Convert the hash into what you want:
h1 = { "integer1" => "23", "integer2" => "2", "integer3" => "4" }
h2 = { "integer1" => "Something", "integer2" => "SomethingElse", "integer3" => "AnotherThing" }
desired = Hash[ h1.map{ |k,v| [ h2[k], v ] } ]
Get your JSON from that:
json = desired.to_json
Upvotes: 4