Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/acts_as_csv.rb

Instance Method Summary collapse

Instance Method Details

#to_csv(options = {}) ⇒ Object

Convert an array of objects into a CSV String.



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/acts_as_csv.rb', line 67

def to_csv(options = {})
  column_options    = {
    :only    => options.delete(:only),
    :exclude => options.delete(:exclude) || [],
    :methods => options.delete(:methods) || []
  }

  options = {
    :col_sep => "\t" # Appease Excel Gods
  }.merge(options)

  if all? { |e| e.respond_to?(:to_csv) }
    header_row = first.class.csv_columns(column_options).to_csv

    content_rows = map { |e|
      # Get all the values of non-excluded rows
      e.to_csv(column_options)
    }.map{|r|
      # Call to_csv on the array of row-level values, this will join them into a CSV row
      r.to_csv(column_options)
    }

    ([header_row] + content_rows).join
  else
    FasterCSV.generate_line(self, options)
  end
end