Class: Kiba::Extend::Transforms::Take::First

Inherits:
Object
  • Object
show all
Defined in:
lib/kiba/extend/transforms/take.rb

Overview

Take the first value from given fields and put then in the given target fields.

If no target fields are given, values in the original fields will be replaced with first values.

If nil or `` are passed in as targets, the original field(s) corresponding to those targets will be replaced by their first values, while other targets will be created as new fields.

The “first value” of a nil field is nil. The “first value” of an empty string field is an empty string.

Examples

Input table:

| a   | b   |
|-----------|
| c|d | e|j |
|     | nil |
| |f  | g|  |
| h   | i   |

Used in pipeline as:

transform Take::First, fields: %i[a b], targets: %i[y z], delim: '|'

Results in:

| a   | b   | y | z   |
|---------------------|
| c|d | e|j | c | e   |
|     | nil |   | nil |
| |f  | g|  |   | g   |
| h   | i   | h | i   |

Instance Method Summary collapse

Constructor Details

#initialize(fields:, delim:, targets: []) ⇒ First

Returns a new instance of First.



53
54
55
56
57
58
59
# File 'lib/kiba/extend/transforms/take.rb', line 53

def initialize(fields:, delim:, targets: [])
  @fields = [fields].flatten
  @targets = targets
  @delim = delim
  build_targets
  @field_map = @fields.zip(@targets).to_h
end

Instance Method Details

#process(row) ⇒ Object

Parameters:

  • row (Hash{ Symbol => String, nil })


62
63
64
65
66
67
68
# File 'lib/kiba/extend/transforms/take.rb', line 62

def process(row)
  @field_map.each do |field, target|
    field_val = row.fetch(field, nil)
    row[target] = first_val(field_val)
  end
  row
end