Rails to Excel
How do you go from a Rails model to a Comma Seperated Value (CSV) file that you can import to Excel?
First install
Ruports (Ruby Reports)
$ sudo gem install ruportThen just extend ActiveRecord:
# in config/environment.rb
class ActiveRecord::Base
def self.to_csv
data_set = Ruport::DataSet.new(self.column_names)
self.find_all.each do |row|
data_set << row.attributes
end
data_set.to_csv
end
end
Now you, too, can do magic!
>> Contact.to_csv #=> A string of CSV data
🙂
I had no idea about acts_as_reportable. Is their any documentation on it besides RDoc?
I guess either way this proves the idiom that anything you think is elegant in ruby can be done easier and with less lines of code.
http://reporting.stonecode.org/ruport-cookbook-pre.pdf
I will actually release this document when I finish it 🙂
to_ds and formatted_table work with ActiveRecord.find, too 🙂