Render CSV in Rails

First I read the docs at: rubydoc.info to understand how FasterCSV is now in the ruby standard library.

Then, I set up the following code:

#config/initializers/csv_renderer.rb
require 'csv'
class Array
alias old_to_csv to_csv #keep reference to original to_csv method
def to_csv
# override only if first element actually has as_csv method
return old_to_csv unless first.respond_to? :as_csv
# use keys from first row as header columns
out = first.as_csv.keys.to_csv
self.each { |r| out << r.as_csv.values.to_csv }
out
end
end
ActionController::Renderers.add :csv do |csv, options|
self.content_type ||= Mime::CSV
csv.respond_to?(:to_csv) ? csv.to_csv : csv
end

view raw
csv_renderer.rb
hosted with ❤ by GitHub

class Backend::TimeSlotsController < Backend::ResourceController
nested_belongs_to :location, :fitness_camp
def attendance_sheet
# here we need a list of all users in a time slot
ts = TimeSlot.find(params[:time_slot_id])
@campers = ts.all_campers
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @campers}
format.csv { render :csv => @campers}
end
end
end

# This is a Device-User-Class extended with ROLES, Avatar-handling, and more
class User
include Mongoid::Document
def as_csv
{name: self.full_name}
end
end

view raw
user.rb
hosted with ❤ by GitHub

This gives me a pretty flexible solution to render csv, but I’m really interested to see if this is a good way to go. Your comments are appreciated.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.