开发者

Parse Rails console output into Excel

Perhaps an oddball question. Doing a Model.all or the like gets me a somewhat pretty output of the array, 开发者_Python百科[#<Model id:5, name:"Blahblah">,#<Model id:5, name:"Etc">]. Is there an easy way to convert this into a CSV/Excel format with the attributes as columns?


Yes.

Use the FasterCSV gem to generate a CSV from a list of your models.

But there's no good way to do this automatically. So you should add a class method to your model that produces the CSV from an array.

example:

class Model < ActiveRecord::Base

  require 'FCSV'
  def self.to_csv list 
  csv_string = FasterCSV.generate do |csv|
    attributes_for_csv = [:id, :name]
    csv << attributes_for_csv.map{|a| a.to_s.titlize}
    list.each do |item|
      csv << attributes_for_csv.map{|a| item.send(a)}
    emd
  end

  ...
end

Model.to_csv Model.all

Warning: it's not going to be perfect, you're still going to get a string that starts and ends with ". But it's pretty easy to remove the start and end quotes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜