Class: Openra::MiniYAML

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

Constant Summary collapse

MATCHER =
/(?<indentation>\t+)?(?<key>[^\:]+)?\:?\s?(?<value>.+)?/.freeze

Class Method Summary collapse

Class Method Details

.load(yaml_string) ⇒ 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
33
34
35
36
37
38
39
# File 'lib/openra/mini_yaml.rb', line 7

def self.load(yaml_string)
  last_indentation = -1
  last_key = nil
  data = {}
  structs = []

  yaml_string.split("\n").inject(data) do |struct, line|
    next if line =~ /^\s+$/

    matchdata = line.match(MATCHER)
    indentation = matchdata[:indentation].to_s.bytesize
    key = matchdata[:key]
    value = matchdata[:value]

    if indentation > last_indentation
      struct[last_key] = {}
      structs.push(struct[last_key])
      struct = struct[last_key]
    elsif indentation < last_indentation
      diff = last_indentation - indentation
      structs = structs.slice(0..-diff.next)
      struct = structs.last
    end

    struct[key] = value unless key.nil? || value.nil?

    last_key = key
    last_indentation = indentation
    struct
  end

  data[nil]
end