Created
December 19, 2012 08:51
-
-
Save amolpujari/4335376 to your computer and use it in GitHub Desktop.
quick write csv files CSVReports::Base.new objects, columns=[ :attr1, :attr2]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'csv' | |
module CSVReports | |
class Base | |
attr_accessor :columns, :column_separator, :row_separator | |
def initialize items, columns=[] | |
@items = items | |
self.columns = columns | |
self.column_separator = ',' | |
self.row_separator = "\n" | |
end | |
def to_s | |
rows.join @row_separator | |
end | |
def to_csv_file | |
csv_file = "#{Rails.root.to_s}/tmp/#{Time.now.utc.to_s.gsub('-', '').gsub(':', '').delete(' ')}.csv" | |
CSV.open(csv_file, "w") do |csv| | |
rows.each { |row| csv << [row] } | |
end | |
csv_file | |
end | |
def rows | |
@items.collect{ |item| row item} | |
end | |
private | |
def row item | |
data = @columns.collect{ |column| eval("item.#{column.to_s}")} | |
data = data.join @column_separator | |
end | |
end | |
end | |
class MyCSVReport < CSVReports::Base | |
def initialize objects | |
super objects, [:id, :name] | |
end | |
end | |
# CSVReports::Base.new objects, columns=[ :attr1, :attr2] | |
# MyCSVReport.new objects | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment