Class: Necromancer::HashConverters::StringToHashConverter

Inherits:
Converter
  • Object
show all
Defined in:
lib/necromancer/converters/hash.rb

Overview

An object that converts a String to a Hash

Constant Summary collapse

DEFAULT_CONVERSION =
->(val, *_rest) { val }

Instance Attribute Summary

Attributes inherited from Converter

#config, #convert, #source, #target

Instance Method Summary collapse

Methods inherited from Converter

create, #initialize, #raise_conversion_type

Constructor Details

This class inherits a constructor from Necromancer::Converter

Instance Method Details

#call(value, strict: config.strict, value_converter: DEFAULT_CONVERSION) ⇒ Object

Convert string value to hash

Examples:

converter.call("a:1 b:2 c:3")
# => {a: "1", b: "2", c: "3"}
converter.call("a=1 & b=3 & c=3")
# => {a: "1", b: "2", c: "3"}


24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/necromancer/converters/hash.rb', line 24

def call(value, strict: config.strict, value_converter: DEFAULT_CONVERSION)
  values = value.split(/\s*[& ]\s*/)
  values.each_with_object({}) do |pair, pairs|
    key, value = pair.split(/[=:]/, 2)
    value_converted = value_converter.(value, strict: strict)
    if current = pairs[key.to_sym]
      pairs[key.to_sym] = Array(current) << value_converted
    else
      pairs[key.to_sym] = value_converted
    end
    pairs
  end
end