Class: JsonToGraphql::Parser

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

Defined Under Namespace

Classes: Node

Constant Summary collapse

SPACES_PER_TAB =
2

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input_hash) ⇒ Parser



6
7
8
9
10
# File 'lib/json_to_graphql/parser.rb', line 6

def initialize(input_hash)
  self.input_hash = input_hash
  self.root = Node.new(name: :root, args: {}, attrs: [])
  build_nodes(self.input_hash, self.root)
end

Instance Attribute Details

#input_hashObject

Returns the value of attribute input_hash.



3
4
5
# File 'lib/json_to_graphql/parser.rb', line 3

def input_hash
  @input_hash
end

#rootObject

Returns the value of attribute root.



3
4
5
# File 'lib/json_to_graphql/parser.rb', line 3

def root
  @root
end

Instance Method Details

#build_nodes(hash, parent_node) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/json_to_graphql/parser.rb', line 12

def build_nodes(hash, parent_node)
  hash.each do |key, value|
    node = Node.new(name: key,
                    args: value.delete('_args') || {},
                    attrs: value.delete('_attrs') || [])

    node.variables = (value.delete("_variables") || {}) if parent_node.name == :root
    parent_node.children << node
    build_nodes(value || {}, node)
  end
end


24
25
26
27
28
# File 'lib/json_to_graphql/parser.rb', line 24

def print
  root.children.each_with_object("{\n") do |child, query|
    query.concat("#{child.print("", 1)}")
  end.concat("}")
end