Method: Array#write_csv

Defined in:
lib/crudboy/ext/array.rb

#write_csv(filename, *fields, **options) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/crudboy/ext/array.rb', line 76

def write_csv(filename, *fields, **options)
  generate_csv(filename, **options) do |csv|
    if size > 0 && first.is_a?(ActiveRecord::Base)
      if fields.empty?
        fields = first.attributes.keys
      else
        fields = fields.map(&:to_s)
      end
      csv << fields
    end
    if size > 0 && first.is_a?(Hash)
      if fields.empty?
        fields = first.keys
      end
      csv << fields
    end
    each do |row|
      if row.is_a?(Array)
        csv << row.map(&:to_s)
      else
        csv << row.slice(*fields).values.map(&:to_s)
      end
    end
  end
end