Forum: Ruby on Rails create tab delimited text file

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
2ebaeddec042b2723ab6a9fb1308ff40?d=identicon&s=25 Varsha Nachane (vnac)
on 2007-07-31 20:29
Hi,

   I want to create a tab delimited text file from model data. How can I
achieve this ?

Thanks
vnac
67b18e0e6de269790dee456a33ea1d31?d=identicon&s=25 Kevin Skoglund (Guest)
on 2007-08-01 00:27
(Received via mailing list)
The code below should at least help get you on the right track.

Best,
Kevin Skoglund
http://www.nullislove.com

-----

def some_action
  # find the data
  field_names = custom_field_name_array ||= MyModel.column_names
  models = MyModel.find(:all, :select => field_names)
  # get the data into tab-delimited format
  data_string = generate_tsv(field_names, models)
  # export the data as a file
  send_data(data_string, :type => 'text/tab-separated-values;
charset=utf-8; header=present',
    :disposition => 'attachment',
    :filename => "my_model_export.tsv")
end

def generate_tsv( field_names, data_rows )
  tsv = field_names.map {|fn| fn.humanize.titleize }.join("\t") << "\r"
  data_rows.each do |row|
    tsv << row.map {|field| clean_for_tsv(field)}.join("\t") << "\r"
  end
  return tsv
end

def clean_for_tsv( string )
  return string.gsub(/(\t|\\t)/, '  ')
end
2ebaeddec042b2723ab6a9fb1308ff40?d=identicon&s=25 Varsha Nachane (vnac)
on 2007-08-01 22:58
Thanks Kevin! I will try to implement this..
Db7238007950074e9e73b76a81910406?d=identicon&s=25 tonypm (Guest)
on 2007-08-04 09:57
(Received via mailing list)
Or you could use CSV or FasterCSV with the option :col_sep=>"\t"


eg.

@orders=Order.find :all,

    @report= FasterCSV.generate({:col_sep=>"\t"}) do |csv|
      csv << ["order-id","quantity","ship-date"]  # title row
      for o in @orders
        csv << [o.order_ref,o.quantity, o.ship_date]
      end
    end

Tonypm
This topic is locked and can not be replied to.