Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering a simple Ruby hash with RABL

Tags:

I have a ruby hash that I'd like to render using RABL. The hash looks something like this:

@my_hash = {
    :c => {
        :d => "e"
    }
}

I'm trying to render this with some RABL code:

object @my_hash => :some_object
attributes :d
node(:c) { |n| n[:d] }

but I'm receiving {"c":null}

How can I render this with RABL?

like image 425
SundayMonday Avatar asked Jan 20 '12 03:01

SundayMonday


2 Answers

This works for arbitrary hash values.

object false

@values.keys.each do |key|
  node(key){ @values[key] }
end

Worked for me using Rails 3.2.13 and Ruby 2.0.0-p195

like image 161
rharriso Avatar answered Oct 05 '22 19:10

rharriso


Currently RABL doesn't play too nicely with hashes. I was able to work around this by converting my hash to an OpenStruct format (which uses a more RABL-friendly dot-notation). Using your example:

your_controller.rb

require 'ostruct'
@my_hash = OpenStruct.new
@my_hash.d = 'e'

your_view.rabl

object false
child @my_hash => :c do
    attributes :d
end

results

{
  "c":{
    "d":"e"
  }
}
like image 23
jbnunn Avatar answered Oct 05 '22 20:10

jbnunn