Class: Morphix::Transformer
- Inherits:
-
Object
- Object
- Morphix::Transformer
- Defined in:
- lib/morphix/transformer.rb
Overview
The Transformer class provides a DSL for transforming data structures like hashes and JSON. It allows you to define transformation rules that can be applied to input data, making it perfect for API response normalization, JSON reshaping, and ETL pipelines.
Instance Method Summary collapse
-
#apply(input) ⇒ Hash
Applies the transformations to the input hash.
-
#initialize ⇒ Transformer
constructor
Creates a new transformer with the given block.
-
#map(key, &block) ⇒ self
Transforms a value while preserving its key.
-
#map_collection(key, &block) ⇒ self
Transforms an array of hashes.
-
#reject(key) ⇒ self
Removes a key from the hash.
-
#rename(old_key, to:, &block) ⇒ self
Renames a key to a new name, optionally transforming its value.
-
#reshape(key, &block) ⇒ self
Transforms a nested hash structure.
Constructor Details
#initialize ⇒ Transformer
Creates a new transformer with the given block
10 11 12 13 |
# File 'lib/morphix/transformer.rb', line 10 def initialize(&) @transformations = [] instance_eval(&) if block_given? end |
Instance Method Details
#apply(input) ⇒ Hash
Applies the transformations to the input hash
63 64 65 66 67 |
# File 'lib/morphix/transformer.rb', line 63 def apply(input) result = input.dup @transformations.each { |transformation| apply_transformation(result, transformation) } result end |
#map(key, &block) ⇒ self
Transforms a value while preserving its key
29 30 31 32 |
# File 'lib/morphix/transformer.rb', line 29 def map(key, &block) @transformations << { type: :map, key:, block: } self end |
#map_collection(key, &block) ⇒ self
Transforms an array of hashes
55 56 57 58 |
# File 'lib/morphix/transformer.rb', line 55 def map_collection(key, &block) @transformations << { type: :map_collection, key:, block: } self end |
#reject(key) ⇒ self
Removes a key from the hash
37 38 39 40 |
# File 'lib/morphix/transformer.rb', line 37 def reject(key) @transformations << { type: :reject, key: } self end |
#rename(old_key, to:, &block) ⇒ self
Renames a key to a new name, optionally transforming its value
20 21 22 23 |
# File 'lib/morphix/transformer.rb', line 20 def rename(old_key, to:, &block) @transformations << { type: :rename, old_key:, new_key: to, block: } self end |
#reshape(key, &block) ⇒ self
Transforms a nested hash structure
46 47 48 49 |
# File 'lib/morphix/transformer.rb', line 46 def reshape(key, &block) @transformations << { type: :reshape, key:, block: } self end |