Sunday, 15 July 2012

Parse Rails console output into Excel -


Maybe there is a strange question Model.all or I like to make some beautiful output of the array, [# & lt ; Model ID: 5, Name: "Blahblah">, # & lt; Model ID: 5, Name: "etc" & gt;] . Is it an easy way to convert it into a CSV / Excel format with properties in columns?

Yes.

Use the fast CSSV gem to create CSV from your list of models.

But this is not a good way to do it automatically. So you should add a class method to your model that produces CSV from an ARR.

Example:

  class models & lt; ActiveRecord :: Base requires 'FCSV' def self.to_csv list csv_string = FasterCSV.generate do | Csv | Attributes_for_csv = [: ID ,: Name] CSV & lt; & Lt; Attributes_for_csv.map {| One | A.to_s.titlize} list.each do | Item | CSV & LT; & Lt; Attributes_for_csv.map {| One | Item.send (a)} emd end ... end model. To_csv Model.all  

Warning: this will not be correct, you are still going to get a string and ". But starting and ending quotations is very easy.


No comments:

Post a Comment