Archive for May 5th, 2007

CSV in Ruby

To Create CSV file in Rails:

    @models = Model.find(:all, :conditions => ['...'])    rawdata = StringIO.new    CSV::Writer.generate(rawdata, ',') do |csv|      csv << %w(Title Total)      @models.each do |model|        csv << [model.title, model.total]      end    end

    rawdata.rewind    send_data(rawdata.read,      :type => 'text/csv; charset=iso-8859-1; header=present',      :filename => 'rawdata.csv')

To retrieve, here is the lib…

FasterCSV is intended as a
replacement to Ruby‘s standard CSV library. It was designed to
address concerns users of that library had and it has three primary goals:

  1. Be significantly faster than CSV while remaining a pure Ruby library.

  2. Use a smaller and easier to maintain code base. (FasterCSV is larger now, but
    considerably richer in features. The parsing core remains quite small.)

  3. Improve on the CSV interface.
  4. def retrieve_csv
       csv_file = params[:csv_file]    begin    Record.transaction do       fastercsv = FasterCSV.new( csv_file )      while row = fastercsv.readline        foo, bar = row        Record.create!( :foo => foo, :bar => bar )      end    end    redirect_to success_action_path  rescue     # do something with the error    flash[:error] = "CSV import failed"    redirect_to retrieve_path  endend