Create tab delimited text file


#1

Hi,

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

Thanks
vnac


#2

The code below should at least help get you on the right track.

Best,
Kevin S.
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


#3

Thanks Kevin! I will try to implement this…


#4

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