Class: JsonToToon::ObjectNode

Inherits:
ContainerNode show all
Defined in:
lib/json_to_toon/object_node.rb

Defined Under Namespace

Classes: KeyedValue

Instance Attribute Summary

Attributes inherited from ContainerNode

#children

Attributes inherited from DataNode

#indentation_level, #parent

Instance Method Summary collapse

Methods inherited from ContainerNode

#add_child

Methods inherited from DataNode

#add_child, #indent, #root

Constructor Details

#initialize(parent = nil) ⇒ ObjectNode

Returns a new instance of ObjectNode.



20
21
22
# File 'lib/json_to_toon/object_node.rb', line 20

def initialize(parent = nil)
  super
end

Instance Method Details

#add_key_value(key, value_node) ⇒ Object

Raises:

  • (ArgumentError)


28
29
30
31
32
# File 'lib/json_to_toon/object_node.rb', line 28

def add_key_value(key, value_node)
  raise ArgumentError, 'Can only add DataNode objects as values.' unless value_node.is_a?(DataNode)

  @children << KeyedValue.new(key, value_node)
end

#keysObject



24
25
26
# File 'lib/json_to_toon/object_node.rb', line 24

def keys
  @children.map(&:key)
end

#to_sObject



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/json_to_toon/object_node.rb', line 34

def to_s
  return indent.to_s if @children.empty?

  output = if parent
             "#{indent}\n"
           else
             String.new(encoding: Encoding::UTF_8)
           end

  child_strings = @children.map do |keyed_value|
    value_indent = '  ' * @indentation_level
    value_string = keyed_value.value_node.to_s.chomp
    if keyed_value.value_node.is_a?(ArrayNode)
      "#{value_indent}#{keyed_value.key}[#{keyed_value.value_node.children.size}]#{value_string.lstrip}"

    else

      newline = ''
      if keyed_value.value_node.is_a?(ObjectNode) && !keyed_value.value_node.children.empty?
        newline = "\n#{'  ' * keyed_value.value_node.indentation_level}"
      end

      "#{value_indent}#{keyed_value.key}: #{newline}#{value_string.lstrip}"
    end
  end

  output << child_strings.join("\n")

  output
end