Class: Philiprehberger::CsvBuilder::Column

Inherits:
Object
  • Object
show all
Defined in:
lib/philiprehberger/csv_builder/column.rb

Overview

Represents a single column definition in a CSV builder

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, header: nil, &transform) ⇒ Column

Returns a new instance of Column.

Parameters:

  • name (Symbol, String)

    the column name (also used as the record key)

  • header (String, nil) (defaults to: nil)

    optional custom header label

  • transform (Proc, nil)

    optional block to transform the value



16
17
18
19
20
# File 'lib/philiprehberger/csv_builder/column.rb', line 16

def initialize(name, header: nil, &transform)
  @name = name.to_sym
  @custom_header = header
  @transform = block_given? ? transform : nil
end

Instance Attribute Details

#nameSymbol (readonly)

Returns the column name.

Returns:

  • (Symbol)

    the column name



8
9
10
# File 'lib/philiprehberger/csv_builder/column.rb', line 8

def name
  @name
end

#transformProc? (readonly)

Returns optional transform block.

Returns:

  • (Proc, nil)

    optional transform block



11
12
13
# File 'lib/philiprehberger/csv_builder/column.rb', line 11

def transform
  @transform
end

Instance Method Details

#extract(record) ⇒ String

Extract the value for this column from a record

Parameters:

  • record (Hash, Object)

    the source record

Returns:

  • (String)

    the extracted and converted value



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/philiprehberger/csv_builder/column.rb', line 26

def extract(record)
  value = if @transform
            @transform.call(record)
          elsif record.is_a?(Hash)
            record[@name] || record[@name.to_s]
          elsif record.respond_to?(@name)
            record.send(@name)
          end

  value.to_s
end

#headerString

Return the header label for this column

Returns:

  • (String)


41
42
43
# File 'lib/philiprehberger/csv_builder/column.rb', line 41

def header
  @custom_header || @name.to_s
end