Top Level Namespace

Instance Method Summary collapse

Instance Method Details

#export_csv(klass, options = {}) ⇒ Object



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/export_csv.rb', line 1

def export_csv(klass, options = {})
  require 'ruport'

  opts = { :filename => klass, :parameters => {} }.merge(options)

  records = klass.find(:all, opts[:parameters])
  headers = klass.columns.collect{ |a| a.name }
  data = []
  records.each do |r|
    record = []
    headers.each do |h|
      record << r[h]
    end
    data << record
  end
  table = Ruport::Data::Table(:column_names => headers.collect{ |h| h.humanize }, :data => data)
  csv = table.to_csv
  time = Time.now
  filename = "#{opts[:filename]}-#{time.strftime('%m%d%Y-%H%M')}.csv"
  send_data csv, :filename => filename, :type => 'text/csv; charset=iso-8859-1; header=present', :disposition => "attachment; #{filename}"
end