Module: CsvRowModel::Export

Extended by:
ActiveSupport::Concern
Includes:
DynamicColumns
Defined in:
lib/csv_row_model/export.rb,
lib/csv_row_model/export/file.rb,
lib/csv_row_model/export/file_model.rb,
lib/csv_row_model/export/dynamic_columns.rb

Overview

Include this to with Model to have a RowModel for exporting to CSVs.

Defined Under Namespace

Modules: DynamicColumns, FileModel Classes: File

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from DynamicColumns

define_dynamic_attribute_method, dynamic_column

Instance Attribute Details

#contextObject (readonly)

Returns the value of attribute context.



10
11
12
# File 'lib/csv_row_model/export.rb', line 10

def context
  @context
end

#source_modelObject (readonly)

Returns the value of attribute source_model.



10
11
12
# File 'lib/csv_row_model/export.rb', line 10

def source_model
  @source_model
end

Class Method Details

.column(column_name, options = {}) ⇒ Object



39
40
41
42
# File 'lib/csv_row_model/export.rb', line 39

def column(column_name, options={})
  super
  define_attribute_method(column_name)
end

.define_attribute_method(column_name) ⇒ Object

Define default attribute method for a column

Parameters:

  • column_name (Symbol)

    the cell's column_name



46
47
48
49
50
# File 'lib/csv_row_model/export.rb', line 46

def define_attribute_method(column_name)
  define_method(column_name) do
    self.class.format_cell(source_model.public_send(column_name), column_name, self.class.index(column_name))
  end
end

.format_cell(cell, column_name, column_index) ⇒ Object

Safe to override. Method applied to each cell by default

Parameters:

  • cell (Object)

    the cell's value



55
56
57
# File 'lib/csv_row_model/export.rb', line 55

def format_cell(cell, column_name, column_index)
  cell
end

.setup(csv, context = {}, with_headers: true) ⇒ Object



34
35
36
# File 'lib/csv_row_model/export.rb', line 34

def setup(csv, context={}, with_headers: true)
  csv << headers(context) if with_headers
end

Instance Method Details

#initialize(source_model, context = {}) ⇒ Object

Parameters:

  • source_model (Model)

    object to export to CSV

  • context (Hash) (defaults to: {})


19
20
21
22
# File 'lib/csv_row_model/export.rb', line 19

def initialize(source_model, context={})
  @source_model = source_model
  @context      = OpenStruct.new(context)
end

#to_rowArray

Returns an array of public_send(column_name) of the CSV model.

Returns:

  • (Array)

    an array of public_send(column_name) of the CSV model



29
30
31
# File 'lib/csv_row_model/export.rb', line 29

def to_row
  attributes.values
end

#to_rowsObject



24
25
26
# File 'lib/csv_row_model/export.rb', line 24

def to_rows
  [to_row]
end