Raphael Onofre Raphael Onofre - 5 months ago 19
Ruby Question

Dynamically display hashes/data/JSON in the view

I'm trying to dynamically insert headers and tbody into the HTML using Ruby and Sinatra. Until the moment i've got the headers but i'm not having success on the body.

Here's my code:

get '/list' do
urlData = "http://localhost:3000/data"
responseData = RestClient.get urlData

@banks = JSON.parse(responseData.body)
@keys = @banks[0].keys # OK
@values = @banks.map(&:values) # Trying to put in the html

erb :list


The view, as follows:

<% @keys.each do |key| %>
<th><%= key %></th>
<% end %>

<% @values.each do |value| %>
<td><%= value %></td>
<% end %>

The JSON format:

"ID": 247,
"Code": "246",
"Name": "ABC BANK S.A."
"ID": 248,
"Code": "25",
"Name": "Beta Bank"
}, ...

How is showing:
enter image description here
A way to solve it is to put kind of a increment, like

<%= value[0] %>

but i can't find an elegant way.


If I understand you correctly, you want to show the values in separate td tags, you can do that like this. The @values is an array of arrays (the rows) which contain the cell values.

 <% @values.each do |row| %>
    <% row.each do |value| %>
     <td><%= value %></td>
 <% end %>

EDIT: you get your array of arrays like this

banks.map{|x| x.values}
#[[247, "246", "ABC BANK S.A."], [248, "25", "Beta Bank"]]

and you pass it to your view like this, not sure if necessary

erb :list, :locals => {values: @values, keys: @keys}