Class: KeyValueParser

Inherits:
Object
  • Object
show all
Defined in:
lib/key_value_parser.rb

Instance Method Summary collapse

Constructor Details

#initialize(defaults = {}, options = {}) ⇒ KeyValueParser

Returns a new instance of KeyValueParser.



3
4
5
6
7
8
9
10
11
# File 'lib/key_value_parser.rb', line 3

def initialize defaults={}, options={}
  @defaults = defaults
  @options = {
    separator: /\s*[=:]\s*/,
    normalize_keys: true,
    typecast_values: true,
    array_values: true
  }.merge(options)
end

Instance Method Details

#parse(kvs) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/key_value_parser.rb', line 13

def parse kvs
  @defaults.merge(
    Hash[
      kvs.map do |a| 
        k, *v = a.split(@options[:separator], @options[:array_values] ? 0 : 2)
        if v.size==1
          v = v[0]
        elsif v.size==0
          v = nil
        end
        [
          @options[:normalize_keys] ? normalize_key(k) : k, 
          @options[:typecast_values] ? typecast(v) : v
        ]
      end
    ]
  )
end