Class: Kiba::Extend::Transforms::Explode::FieldValuesToNewRows

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

Instance Method Summary collapse

Constructor Details

#initialize(target:, fields: [], multival: false, sep: " ", keep_nil: false, keep_empty: false) ⇒ FieldValuesToNewRows

Returns a new instance of FieldValuesToNewRows.



105
106
107
108
109
110
111
112
113
# File 'lib/kiba/extend/transforms/explode.rb', line 105

def initialize(target:, fields: [], multival: false, sep: " ",
  keep_nil: false, keep_empty: false)
  @fields = [fields].flatten
  @target = target
  @multival = multival
  @sep = sep
  @keep_nil = keep_nil
  @keep_empty = keep_empty
end

Instance Method Details

#process(row, &block) ⇒ Object



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/kiba/extend/transforms/explode.rb', line 115

def process(row, &block)
  rows = []
  other_fields = row.keys - @fields
  other_data = {}
  other_fields.each { |f| other_data[f] = row.fetch(f, nil) }

  @fields.each do |field|
    val = row.fetch(field, nil)
    vals = if val.nil?
      [nil]
    elsif val.empty?
      [""]
    elsif @multival
      val.split(@sep, -1)
    else
      [val]
    end

    vals.each do |val|
      next if !@keep_nil && val.nil?
      next if !(val.nil? || @keep_empty) && val.empty?

      new_row = other_data.clone
      new_row[@target] = val
      rows << new_row
    end
  end
  rows.each(&block)
  nil
end