Class: Kiba::Extend::Transforms::Append::ToFieldValue

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

Overview

Adds the given value to the end of value of the given field. Does not affect nil/empty field values

Examples:

Treated as single value (default)

# Used in pipeline as:
# transform Append::ToFieldValue, field: :name, value: " (name)"

xform = Append::ToFieldValue.new(field: :name, value: " (name)")
input = [
    {name: "Weddy"},
    {name: "Kernel|Zipper"},
    {name: nil},
    {name: ""}
  ]
result = input.map{ |row| xform.process(row) }
expected = [
    {name: "Weddy (name)"},
    {name: "Kernel|Zipper (name)"},
    {name: nil},
    {name: ""}
  ]
expect(result).to eq(expected)

Treated as multivalue

# Used in pipeline as:
# transform Append::ToFieldValue,
#   field: :name,
#   value: " (name)",
#   delim: "|"

xform = Append::ToFieldValue.new(field: :name, value: " (name)",
  delim: "|")
input = [
    {name: "Weddy"},
    {name: "Kernel|Zipper"},
    {name: nil},
    {name: ""}
  ]
result = input.map{ |row| xform.process(row) }
expected = [
    {name: "Weddy (name)"},
    {name: "Kernel (name)|Zipper (name)"},
    {name: nil},
    {name: ""}
  ]
expect(result).to eq(expected)

Instance Method Summary collapse

Constructor Details

#initialize(field:, value:, delim: nil) ⇒ ToFieldValue

Returns a new instance of ToFieldValue.

Parameters:

  • field (Symbol)

    name of field to append to

  • value (String)

    value to append to existing field values

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

    indicates multivalue delimiter on which to split values, if given



58
59
60
61
62
# File 'lib/kiba/extend/transforms/append/to_field_value.rb', line 58

def initialize(field:, value:, delim: nil)
  @field = field
  @value = value
  @delim = delim
end

Instance Method Details

#process(row) ⇒ Object

Parameters:

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


65
66
67
68
69
70
71
72
73
# File 'lib/kiba/extend/transforms/append/to_field_value.rb', line 65

def process(row)
  fv = row.fetch(@field, nil)
  return row if fv.blank?

  vals = @delim ? fv.split(@delim) : [fv]
  row[@field] = vals.map { |fieldval| "#{fieldval}#{@value}" }
    .join(@delim)
  row
end