rabl icon indicating copy to clipboard operation
rabl copied to clipboard

How do I render free form metadata

Open kapad opened this issue 6 years ago • 1 comments

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"
    }
  ]
}
# 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": "[email protected]",
      "phone": "1231231231"
    }
  ]
}

kapad avatar Jul 20 '18 09:07 kapad

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.

kapad avatar Jul 20 '18 11:07 kapad