Class: CsvExporter::Base

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

Instance Method Summary collapse

Instance Method Details

#csv_file(collection, hash, filename) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/csv_exporter/base.rb', line 7

def csv_file(collection, hash, filename)
  CSV.open(CsvExporter.file(filename), 'w') do |csv|

    collection.each_with_index do |element, index|

      case element.class.to_s.downcase
      when 'hash'
        csv << element.keys if index == 0
        csv << element.values
      when 'array'
        csv << element
      when 'openstruct'
        csv << element.to_h.keys.map(&:capitalize) if index == 0
        csv << element.to_h.values
      else
        if hash.is_a?(Hash)
          hash.symbolize_keys!
          if hash[:export_fields].present?
            csv << hash[:export_fields].map(&:capitalize) if index == 0
            csv << custom_rows(element, hash[:export_fields])
          else
            csv << hash.keys.map(&:capitalize) if index == 0
            csv << custom_rows(element, hash.values)
          end
        elsif hash.is_a?(Array)
          csv << hash.map(&:capitalize) if index == 0
          csv << custom_rows(element, hash)
        end
      end

    end

  end
end