May 05
CSV in Ruby
Cats: 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:
- Be significantly faster than CSV while remaining a pure Ruby library.
- Use a smaller and easier to maintain code base. (FasterCSV is larger now, but
considerably richer in features. The parsing core remains quite small.) - Improve on the CSV interface.
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