From 874a44880b06873f45b34771c1ada10b34ca7055 Mon Sep 17 00:00:00 2001 From: Kristina Spurgin Date: Mon, 12 Aug 2024 16:19:34 -0400 Subject: [PATCH] Add delim param to trigger multival treatment --- CHANGELOG.adoc | 1 + .../transforms/append/to_field_value.rb | 33 +++++++++++++++++-- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.adoc b/CHANGELOG.adoc index ccf5dafc..21a89e40 100644 --- a/CHANGELOG.adoc +++ b/CHANGELOG.adoc @@ -40,6 +40,7 @@ These changes are merged into the `main` branch, but have not been released. Aft === Added * `MARC::LanguageCodeLookup` transform * Ability to pass `find` argument to `Clean::RegexpFindReplaceFieldVals` as a `Regexp` object. Not sure why this was not the default initial behavior, but here we are! (PR#196) +* Ability to pass `delim` argument to `Append::ToFieldValue` to trigger multi-value treatment (PR#200) === Changed diff --git a/lib/kiba/extend/transforms/append/to_field_value.rb b/lib/kiba/extend/transforms/append/to_field_value.rb index 2ede43cf..210e7f6f 100644 --- a/lib/kiba/extend/transforms/append/to_field_value.rb +++ b/lib/kiba/extend/transforms/append/to_field_value.rb @@ -26,12 +26,39 @@ module Append # {name: ""} # ] # expect(result).to eq(expected) + # + # @example 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) class ToFieldValue # @param field [Symbol] name of field to append to # @param value [String] value to append to existing field values - def initialize(field:, value:) + # @param delim [String, nil] indicates multivalue delimiter on which + # to split values, if given + def initialize(field:, value:, delim: nil) @field = field @value = value + @delim = delim end # @param row [Hash{ Symbol => String, nil }] @@ -39,7 +66,9 @@ def process(row) fv = row.fetch(@field, nil) return row if fv.blank? - row[@field] = "#{fv}#{@value}" + vals = @delim ? fv.split(@delim) : [fv] + row[@field] = vals.map { |fieldval| "#{fieldval}#{@value}" } + .join(@delim) row end end