Skip to content

Instantly share code, notes, and snippets.

@bsodmike
Created April 19, 2012 10:17
Show Gist options
  • Save bsodmike/2420108 to your computer and use it in GitHub Desktop.
Save bsodmike/2420108 to your computer and use it in GitHub Desktop.
Streaming CSV file to the Client with Rails 3.1
format.csv do
@scheduled_session = Session.find(params[:id])
@applicants = @scheduled_session.applicant_signups
filename = "#{@scheduled_session.title.parameterize.downcase}_applicant_list_#{Time.now.strftime('%d%m%Y')}.csv"
headers['Content-Disposition'] = 'attachment; filename="' + filename + '"'
titles = [
"Title", "First Name", "Last Name", "DOB Day", "DOB Month", "DOB Year", "Nationality", \
"Email", "Mobile Number", "Address Line 1", "Address Line 2", "Place of Work", \
"Discipline/Speciality", "Job Title", "Key Responsibilities", "Payment Ref."
]
attribs = [
lambda {|r, event| r.title},
lambda {|r, event| r.first_name},
lambda {|r, event| r.last_name},
lambda {|r, event| r.dob_day},
lambda {|r, event| r.dob_month},
lambda {|r, event| r.dob_year},
lambda {|r, event| r.nationality},
lambda {|r, event| r.email},
lambda {|r, event| r.phone_number},
lambda {|r, event| r.address_line1},
lambda {|r, event| r.address_line2},
lambda {|r, event| r.work_place},
lambda {|r, event| r.speciality},
lambda {|r, event| r.occupation}, # job title
lambda {|r, event| r.responsibilities},
lambda {|r, event| "#{event.code}R000#{r.id}"}
]
self.response_body = CSVStreamer.new(@applicants, @scheduled_session, titles, attribs)
end
class CSVStreamer
attr_reader :records, :event, :titles, :attribs
def initialize(records, event, titles, attribs)
@event = event
@records = records
@titles = titles
@attribs = attribs
end
def each
yield CSV.generate_line(titles)
records.each do |r|
yield csv_row(r)
end
end
def csv_row(r)
CSV.generate_line(attribs.map{|a| a.call(r,event)})
end
end

Here's some code from a session of hacking no where close to being DRY.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment