Class: Sunrise::Utils::CsvDocument

Inherits:
Object
  • Object
show all
Defined in:
lib/sunrise/utils/csv_document.rb

Instance Method Summary collapse

Constructor Details

#initialize(source, options = {}) ⇒ CsvDocument

Returns a new instance of CsvDocument.



8
9
10
11
12
# File 'lib/sunrise/utils/csv_document.rb', line 8

def initialize(source, options = {})
  @source = source
  @options = options
  @klass = (@options.delete(:klass) || extract_klass)
end

Instance Method Details

#columns_names ⇒ Object



14
15
16
# File 'lib/sunrise/utils/csv_document.rb', line 14

def columns_names
  @columns_names ||= (@options[:columns] || @klass.column_names)
end

#each_with_index ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/sunrise/utils/csv_document.rb', line 40

def each_with_index
  count = 0

  if @source.respond_to?(:find_each)
    @source.find_each do |item|
      yield item, count
      count += 1
    end
  else
    Array.wrap(@source).each do |item|
      yield item, count
      count += 1
    end
  end
end

#filename ⇒ Object



22
23
24
# File 'lib/sunrise/utils/csv_document.rb', line 22

def filename
  @filename ||= [(@options[:filename] || @klass.model_name.plural || 'document'), '.csv'].join
end

#human_columns_names ⇒ Object



18
19
20
# File 'lib/sunrise/utils/csv_document.rb', line 18

def human_columns_names
  @human_columns_names ||= columns_names.map { |column| @klass.human_attribute_name(column.to_s) }
end

#render ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/sunrise/utils/csv_document.rb', line 26

def render
  csv_string = ::CSV.generate do |csv|
    csv << human_columns_names

    each_with_index do |record, _index|
      row = columns_names.each_with_object([]) do |column, result|
        result << record.send(column)
      end

      csv << row
    end
  end
end