Class: Kiba::Extend::Transforms::Rename::Field
- Inherits:
-
Object
- Object
- Kiba::Extend::Transforms::Rename::Field
- Includes:
- SingleWarnable
- Defined in:
- lib/kiba/extend/transforms/rename/field.rb
Overview
Renames one field
Example notes
1 - :from field exists
:from field renamed to :to field. Not much to see here.
2 - :to field already exists
:sex is renamed to :gender, overwriting the existing value of :gender (unknown) with value of :sex (m). The transform emits a warning about this unless you suppress_overwrite_warnings
3 - :from field does not exist
Row is passed through unchanged, and the transform emits a warning about not being able to rename a field that doesn’t exist, unless you suppress_missing_key_warnings
4 - :from and :to field are the same
This seems like a real weird edge case from the perspective of defining transforms manually, but it can happen when transform definitions are programmatically generated from configuration.
Instance Method Summary collapse
-
#initialize(from:, to:, suppress_missing_key_warnings: false, suppress_overwrite_warnings: false) ⇒ Field
constructor
A new instance of Field.
-
#process(row) ⇒ Hash{ Symbol => String, nil }
Methods included from SingleWarnable
Constructor Details
#initialize(from:, to:, suppress_missing_key_warnings: false, suppress_overwrite_warnings: false) ⇒ Field
Returns a new instance of Field.
175 176 177 178 179 180 181 182 183 184 |
# File 'lib/kiba/extend/transforms/rename/field.rb', line 175 def initialize(from:, to:, suppress_missing_key_warnings: false, suppress_overwrite_warnings: false) @from = from @to = to @suppress_missing_key_warnings = suppress_missing_key_warnings @suppress_overwrite_warnings = suppress_overwrite_warnings setup_single_warning unless suppress_missing_key_warnings && suppress_overwrite_warnings end |
Instance Method Details
#process(row) ⇒ Hash{ Symbol => String, nil }
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 |
# File 'lib/kiba/extend/transforms/rename/field.rb', line 188 def process(row) return row if from == to unless row.key?(from) unless suppress_missing_key_warnings add_single_warning("Cannot rename field: `#{from}` does not "\ "exist in row") end return row end if row.key?(to) && !suppress_overwrite_warnings add_single_warning("Renaming `#{from}` to `#{to}` overwrites "\ "existing `#{to}` field data") end row[to] = row.fetch(from) row.delete(from) row end |