Question: Sinatra Display CSV entries

Question

Sinatra Display CSV entries

Answers 2
Added at 2016-12-24 22:12
Tags
Question

How do i display data from a csv file into a Sinatra-App?

Sinatra:

csv = CSV.read(data.csv)
csv.each do |entry|
 @output = "#{entry[1]},#{entry[4]}:#{entry[0]}"
end

Erb:

<%= @data %>

Wich displays only the last row of the csv file.

Answers to

Sinatra Display CSV entries

nr: #1 dodano: 2016-12-24 23:12

Problem

With this code :

csv = CSV.read(data.csv)
csv.each do |entry|
 @output = "#{entry[1]},#{entry[4]}:#{entry[0]}"
end

You iterate over all csv rows.

For each row, the block defines the @output variable.

After the first csv line, the code just keeps on overriding the @output_variable.

Possible solution

You need map, not each.

csv = CSV.read(data.csv)
@data = csv.map do |entry|
  "#{entry[1]},#{entry[4]}:#{entry[0]}"
end

You can then use

<%= @data %>

in your views. @data is now an array of strings, with one string for each csv row.

nr: #2 dodano: 2016-12-25 03:12

You probably want to move the for loop to the template file.

In sinatra

@csv_data = CSV.read(data.csv)

In erb

<% @csv_data.each do |entry| %>
  <%= entry[1] %>,<%= entry[4] %>:<%= entry[0] %>
<% end %>
Source Show
◀ Wstecz