Skip to content

Instantly share code, notes, and snippets.

@0xradical
Created November 13, 2012 13:01
Show Gist options
  • Save 0xradical/4065654 to your computer and use it in GitHub Desktop.
Save 0xradical/4065654 to your computer and use it in GitHub Desktop.
CSV streamer
# controller method
def csv_export
respond_to do |format|
format.csv {
@filename = "responses-#{Date.today.to_s(:db)}.csv"
self.response.headers["Content-Type"] ||= 'text/csv'
self.response.headers["Content-Disposition"] = "attachment; filename=#{@filename}"
self.response.headers['Last-Modified'] = Time.now.ctime.to_s
self.response_body = Enumerator.new do |y|
i = 0
Model.find_each do |m|
if i == 0
y << Model.csv_header.to_csv
end
y << sr.csv_array.to_csv
i = i+1
GC.start if i%500==0
end
end
}
end
end
# model.rb
def self.csv_header
["ID", "Route", "username"]
end
def csv_array
[id, route, username]
end
# model.rb (outra versao)
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
# response headers
self.response.headers["Content-Type"] = "application/octet-stream"
self.response.headers["Content-Disposition"] = "attachment; filename=#{filename}"
self.response.headers['Last-Modified'] = Time.now.ctime.to_s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment