Class: CsvPiper::Processors::Translate
- Inherits:
-
Object
- Object
- CsvPiper::Processors::Translate
- Defined in:
- lib/csv_piper/processors/translate.rb
Overview
Used to convert the values in the transformed hash according a provided mapping hash. { key => { ‘value’ => ‘new_value’, ‘value2’ => ‘new_value2’ } }
Instance Method Summary collapse
-
#initialize(mapping:, add_error_on_missing_translation: false, pass_through_on_no_match: false) ⇒ Translate
constructor
A new instance of Translate.
- #process(_source, transformed, errors) ⇒ Object
Constructor Details
#initialize(mapping:, add_error_on_missing_translation: false, pass_through_on_no_match: false) ⇒ Translate
Returns a new instance of Translate.
11 12 13 14 15 |
# File 'lib/csv_piper/processors/translate.rb', line 11 def initialize(mapping: , add_error_on_missing_translation: false, pass_through_on_no_match: false) @add_error = add_error_on_missing_translation @pass_through = pass_through_on_no_match @mapping = mapping end |
Instance Method Details
#process(_source, transformed, errors) ⇒ Object
17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/csv_piper/processors/translate.rb', line 17 def process(_source, transformed, errors) mappings_to_apply = @mapping.select { |key,_| transformed.has_key?(key) } transformed = mappings_to_apply.each_with_object(transformed) do |(key, translation), memo| new_value = translation[memo[key]] errors.add(key, "No mapping for value #{memo[key]}") if @add_error && new_value.nil? new_value = new_value || memo[key] if @pass_through memo[key] = new_value end [transformed, errors] end |