Module: AngryHash::MergeString

Defined in:
lib/angry_hash/merge_string.rb

Instance Method Summary collapse

Instance Method Details

#__merge_with_op(target, op, value) ⇒ Object



30
31
32
33
34
35
36
37
# File 'lib/angry_hash/merge_string.rb', line 30

def __merge_with_op(target,op,value)
  case op
  when '='
    target.replace(value)
  when '+='
    target.replace( target + value )
  end
end

#fetch_path(segments) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/angry_hash/merge_string.rb', line 39

def fetch_path(segments)
  segments = segments.dup
  return self if segments.empty?
  ctx = self


  location = []
  while segment = segments.shift
    unless AngryHash === ctx
      raise "Path element at #{location * '.'} is #{ctx.class}, not an AngryHash. Can't descend to #{path}"
    end

    location << segment
    ctx = ctx[segment] ||= AngryHash.new
  end

  ctx
end

#merge_string(string) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/angry_hash/merge_string.rb', line 3

def merge_string(string)
  match,key,op,value = *string.match(/^([\w\.]+)(\+?=)(.*)$/)

  segments = key.split('.')

  last_segment = segments[-1]
  parent = fetch_path(segments[0..-2])

  unless AngryHash === parent
    raise "parent path element (at #{segments[0..-2] * '.'}) must be an AngryHash, not #{parent.class}"
  end

  target = parent[last_segment]

  case target
  when Array
    __merge_with_op(target,op, [value].flatten.compact)
  when Hash
    raise "not implemented"
  when String
    __merge_with_op(target,op,value.to_s)
  when NilClass
    parent[last_segment] = value
  else
  end
end