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, empty_value: '') ⇒ String

Extract the value for this column from a record

Parameters:

  • record (Hash, Object)

    the source record

  • empty_value (String) (defaults to: '')

    placeholder for nil / missing values

Returns:

  • (String)

    the extracted and converted value



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/philiprehberger/csv_builder/column.rb', line 27

def extract(record, empty_value: '')
  value = if @transform
            @transform.call(record)
          elsif record.is_a?(Hash)
            if record.key?(@name)
              record[@name]
            else
              record[@name.to_s]
            end
          elsif record.respond_to?(@name)
            record.send(@name)
          end

  return empty_value if value.nil?

  str = value.to_s
  str.empty? ? empty_value : str
end

#headerString

Return the header label for this column

Returns:

  • (String)


49
50
51
# File 'lib/philiprehberger/csv_builder/column.rb', line 49

def header
  @custom_header || @name.to_s
end