Search code examples
ruby-on-railsjsonnodesrabl

Node as Hash not Array in RABL


I have this RABL template:

object :@pollution => nil
attributes :id, :time
node :components do |p|
  p.components.map do |component|
    { component.name => { level: component.level, main: component.main } }
  end
end

It renders

{ "id":820,
  "time":"2017-05-12 20:00:00 UTC",
  "components": [ # I don't need this array
    { "component1": { "level": 3, "main": false } },
    { "component2": { "level": 5, "main": false } },
  ]
}

And I want this

{ "id":820,
  "time":"2017-05-12 20:00:00 UTC",
  "components": {
    "component1": { "level": 3, "main" :false },
    "component2": { "level": 5, "main" :false },
  }
}

So, instead of array of components, I need a hash, where keys will be components names and value — hash with components data (level(Int) and main(Bool)).

I tried to render child :components, but it also renders an array.

Thanks for any help!


Solution

  • To get what you want, you need to change these lines:

    p.components.map do |component|
      { component.name => { level: component.level, main: component.main } }
    end
    

    which are returning an array, to something like:

    p.components.inject({}) do |components, component|
      components[component.name] = { level: component.level, main: component.main }
      components
    end
    

    that will build a hash instead of an array.