I have the following hash in my controller.
@order = {
:id => "somestringid",
:user_id => "someotherstringid",
:amount => 19.99,
:metadata => [
{
:type => :shipping_data,
:address => "line 1 of address, line 2 of address, city, state, pincode"
},
{
:type => :payment,
:stripe_customer_id => "somestringid",
:stripe_card_id => "someotherstringid"
},
{
:type => :contact,
:email => "[email protected]",
:phone => "1231231231"
}
]
}
Notes:
- The "metadata" is a list of objects.
- There can be 0, 1 or more metadata objects.
- Each metadata object has a different structure.
- The only common key for all metadata objects is the "type" key.
I want to use rabl to generate the following json, but cannot figure out what I should put into my template.
The JSON output that I want should look like the following.
{
"id": "somestringid",
"user_id": "someotherstringid",
"amount": 19.99,
"metadata": [
{
"type": "shipping_data",
"address": "line 1 of address, line 2 of address, city, state, pincode"
},
{
"type": "payment",
"stripe_customer_id": "somestringid",
"stripe_card_id": "someotherstringid"
},
{
"type": "contact",
"email": "[email protected]",
"phone": "1231231231"
}
]
}
What should I put into my template, so that I get the desired output?
Note
I am not sure whether by rabl you mean you are using standard rabl gem OR rabl-rails because you haven't provided any details about the nature of your application and it is built using what all libraries.
But my solution below is in context of a Rails application using rabl-rails gem. And the rabl-rails gem's README says following:
So I guess it should not be a problem to adapt this solution in context of standard rabl gem whether the application is built Rails or Non-Rails based. My aim is to provide a guidance on the approach which can be used to achieve your desired output.
Now coming to the solution approach:
Using some abstractions you can design a flexible and maintainable solution. Let me elaborate:
Assuming you have a plain ruby-class
Orderlike following or if you don't have any such class you can define it easily using virtus gem which provides some handy out-of-the-box features for a class:app/models/order.rb
app/models/order_metadata.rb
app/models/shipping_data.rb
app/models/payment_data.rb
app/models/contact_data.rb
/app/json_views/orders/metadata/shipping.rabl
/app/json_views/orders/metadata/payment.rabl
/app/json_views/orders/metadata/contact.rabl
/app/json_views/orders/order_metadata.rabl
/app/json_views/order.rabl
Then in your controller do this
/app/controllers/my_controller.rb
Hope this helps.
Thanks.