Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#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
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.