Class: SimpleHdGraph::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/simple-hd-graph/parser.rb

Overview

parse for YAML string

Constant Summary collapse

KEYWORD_ID =
"id".freeze
KEYWORD_RESOURCES =
"resources".freeze
KEYWORD_DEPENDS =
"depends".freeze

Instance Method Summary collapse

Instance Method Details

#pack_depends_into_context(depends, context) ⇒ Object

Parameters:



52
53
54
# File 'lib/simple-hd-graph/parser.rb', line 52

def pack_depends_into_context(depends, context)
  context.set_depends depends
end

#pack_resources_into_context(resources, context) ⇒ Object

Parameters:



60
61
62
63
64
65
66
# File 'lib/simple-hd-graph/parser.rb', line 60

def pack_resources_into_context(resources, context)
  resources.each { |key, resource|
    rn = ResourceNode.new
    rn.load_with_context({id: context.id}, {key => resource})
    context << rn
  }
end

#parse(document) ⇒ Object

Parameters:

  • document (String)


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
40
41
42
43
44
45
46
# File 'lib/simple-hd-graph/parser.rb', line 15

def parse(document)
  contexts = []

  YAML.load_stream(document) do |node|
    next unless node

    context = nil
    resources = nil
    depends = nil

    node.each_pair { |key, value|
      case key
      when KEYWORD_ID
        context = ContextNode.new
        context.load({id: value})
      when KEYWORD_DEPENDS
        depends = value
      when KEYWORD_RESOURCES
        resources = value
      end
    }

    pack_depends_into_context(depends, context) if depends
    pack_resources_into_context(resources, context) if resources

    contexts << context
  end
  refill_relation(contexts)
  refill_depends(contexts)

  contexts.map { |context| context.freeze }.freeze
end

#refill_depends(contexts) ⇒ Object

Parameters:

  • context (Array)


80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/simple-hd-graph/parser.rb', line 80

def refill_depends(contexts)
  contexts.map { |context|
    if context.depends
      regularized = context.depends.map { |dependee|
        d = contexts.find { |c|
          c.alias == dependee
        }

        {
          context.id => d ? d.id : dependee
        }
      }
      context.set_depends regularized
    else
      context.set_depends []
    end
  }
end

#refill_relation(contexts) ⇒ Object

Parameters:

  • contexts (Array)


71
72
73
74
75
# File 'lib/simple-hd-graph/parser.rb', line 71

def refill_relation(contexts)
  contexts.each { |context|
    context.refill_relation
  }
end