nesquena / rabl

General ruby templating with json, bson, xml, plist and msgpack support
http://blog.codepath.com/2011/06/27/building-a-platform-api-on-rails/
MIT License
3.64k stars 334 forks source link

How do I render free form metadata #714

Closed kapad closed 4 months ago

kapad commented 6 years ago

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 => "someone@example.com",
      :phone => "1231231231"
    }
  ]
}
# 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. 

Note: I have simplified the hash to make this question easier to write out.

I want to be able to render this hash to json using rabl but cannot figure out how. The json that I want to render should be as below

{
  "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": "someone@example.com",
      "phone": "1231231231"
    }
  ]
}
kapad commented 6 years ago

Note: I am using OpenStruct.new(@order) to convert my hash to an object. So in my controller, I call render_with(OpenStruct.new(@object), default_template: :show) to create my json response.