Hi,
I want to create a tab delimited text file from model data. How can I
achieve this ?
Thanks
vnac
Hi,
I want to create a tab delimited text file from model data. How can I
achieve this ?
Thanks
vnac
The code below should at least help get you on the right track.
Best,
Kevin S.
http://www.nullislove.com
def some_action
field_names = custom_field_name_array ||= MyModel.column_names
models = MyModel.find(:all, :select => field_names)
data_string = generate_tsv(field_names, models)
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
Thanks Kevin! I will try to implement this…
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 forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs