Class: Hashiform
- Inherits:
-
Object
- Object
- Hashiform
- Defined in:
- lib/hashiform.rb
Instance Method Summary collapse
- #apply_mod(modifier, value) ⇒ Object
-
#initialize(original_hash, catalysts = {}) ⇒ Hashiform
constructor
A new instance of Hashiform.
- #transform(mapping) ⇒ Object
Constructor Details
#initialize(original_hash, catalysts = {}) ⇒ Hashiform
Returns a new instance of Hashiform.
2 3 4 5 |
# File 'lib/hashiform.rb', line 2 def initialize(original_hash, catalysts = {}) @original_hash = original_hash @catalysts = catalysts end |
Instance Method Details
#apply_mod(modifier, value) ⇒ Object
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/hashiform.rb', line 34 def apply_mod(modifier, value) return :_reject if modifier =~ /^if/ && value.nil? mod, arg_list = modifier.split('+') args = if arg_list arg_list =~ /^,/ ? arg_list : arg_list.split(/, ?/) end case mod when sendable(value) args ? value.public_send(mod, *args) : value.public_send(mod) when catalyst_target? @catalysts[mod][value] else value end end |
#transform(mapping) ⇒ Object
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/hashiform.rb', line 7 def transform(mapping) new_hash = {} mapping.each do |new_key, transformation| *modifiers, path = transformation.split(':') path_segments = path.split('.') value = @original_hash.dig(*path_segments) if modifiers.empty? new_hash[new_key] = value else value = modifiers.reduce(value) do |new_value, mod| new_value = apply_mod(mod, new_value) break new_value if new_value == :_reject new_value end new_hash[new_key] = value unless value == :_reject end end new_hash end |