Class: Kiba::Extend::Transforms::Merge::MultivalueConstant

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

Overview

Adds a specified value to new target field for every value found in on_field

Examples

Input table:

| name                 |
|----------------------|
| Weddy                |
| NULL                 |
|                      |
| nil                  |
| Earlybird;Divebomber |
| ;Niblet              |
| Hunter;              |
| NULL;Earhart         |

Used in pipeline as:

 transform Merge::MultivalueConstant, on_field: :name, target: :species, value: 'guinea fowl', sep: ';',
   placeholder: 'NULL'

Results in:

| name                 | species                 |
|----------------------+-------------------------|
| Weddy                | guinea fowl             |
| NULL                 | NULL                    |
|                      | NULL                    |
| nil                  | NULL                    |
| Earlybird;Divebomber | guinea fowl;guinea fowl |
| ;Niblet              | NULL;guinea fowl        |
| Hunter;              | guinea fowl;NULL        |
| NULL;Earhart         | NULL;guinea fowl        |

Instance Method Summary collapse

Constructor Details

#initialize(on_field:, target:, value:, sep:, placeholder:) ⇒ MultivalueConstant

Returns a new instance of MultivalueConstant.

Parameters:

  • on_field (Symbol)

    field the new field’s values will be based on

  • target (Symbol)

    name of new field

  • value (String)

    value to add to target for each existing value in on_field

  • sep (String)

    multivalue separator

  • placeholder (String)

    value to add to target for empty/nil values in on_field



55
56
57
58
59
60
61
# File 'lib/kiba/extend/transforms/merge/multivalue_constant.rb', line 55

def initialize(on_field:, target:, value:, sep:, placeholder:)
  @on_field = on_field
  @target = target
  @value = value
  @sep = sep
  @placeholder = placeholder
end

Instance Method Details

#process(row) ⇒ Object

Parameters:

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


64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/kiba/extend/transforms/merge/multivalue_constant.rb', line 64

def process(row)
  field_val = row.fetch(@on_field, nil)
  if field_val.blank?
    row[@target] = @placeholder
    return row
  end

  merge_vals = []
  field_val.split(@sep, -1).each do |field_val|
    merge_vals << if field_val == @placeholder || field_val.blank?
      @placeholder
    else
      @value
    end
  end

  row[@target] = merge_vals.join(@sep)
  row
end