Class: AbAdmin::Utils::CsvDocument

Inherits:
Object
  • Object
show all
Includes:
EvalHelpers
Defined in:
lib/ab_admin/utils/csv_document.rb

Instance Method Summary collapse

Methods included from EvalHelpers

#call_method_or_proc_on, #evaluate_method

Constructor Details

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

Returns a new instance of CsvDocument


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

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

Instance Method Details

#column_dataObject


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

def column_data
  @columns_names ||= @options[:column_data] || default_columns
end

#columns_namesObject


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

def columns_names
  (@options[:column_names] || default_columns).map { |column| column.is_a?(Symbol) ? @klass.human_attribute_name(column) : column }
end

#default_columnsObject


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

def default_columns
  @default_columns ||= @klass.column_names
end

#each_recordObject


40
41
42
43
44
45
46
47
48
49
50
# File 'lib/ab_admin/utils/csv_document.rb', line 40

def each_record
  if @source.respond_to?(:find_each)
    @source.find_each do |item|
      yield item
    end
  else
    Array(@source).each do |item|
      yield item
    end
  end
end

#filenameObject


26
27
28
# File 'lib/ab_admin/utils/csv_document.rb', line 26

def filename
  @filename ||= [@options[:filename] || "#{@klass.model_name.plural}-#{Time.now.strftime('%Y-%m-%d')}", '.csv'].join
end

#renderObject


30
31
32
33
34
35
36
37
38
# File 'lib/ab_admin/utils/csv_document.rb', line 30

def render
  ::CSV.generate(col_sep: @options[:column_separator] || ',') do |csv|
    csv << columns_names

    each_record do |item|
      csv << column_data.map { |column| AbAdmin.pretty_data call_method_or_proc_on(item, column, exec: false) }
    end
  end
end