Class: JsonToToon::ArrayNode

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

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) ⇒ ArrayNode

Returns a new instance of ArrayNode.



7
8
9
# File 'lib/json_to_toon/array_node.rb', line 7

def initialize(parent = nil)
  super
end

Instance Method Details

#single_indent(spaces = 2) ⇒ Object



32
33
34
# File 'lib/json_to_toon/array_node.rb', line 32

def single_indent(spaces = 2)
  ' ' * (@indentation_level * spaces)
end

#standard_tabular_array?Boolean

Returns:

  • (Boolean)


11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/json_to_toon/array_node.rb', line 11

def standard_tabular_array?
  arr = @children

  return true if arr.empty?

  first_node = arr[0]
  return false unless first_node.is_a?(ObjectNode)

  first_hash_keys = first_node.keys.sort

  arr.all? do |item_node|
    next false unless item_node.is_a?(ObjectNode)
    next false unless item_node.keys.sort == first_hash_keys

    item_node.children.all? do |key_value_node|
      value_node = key_value_node.value_node
      value_node.is_a?(ValueNode)
    end
  end
end

#to_sObject



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
64
65
66
67
68
69
70
# File 'lib/json_to_toon/array_node.rb', line 36

def to_s
  output = +''
  if standard_tabular_array?
    unless @children.empty?
      type = "{#{@children.first&.keys&.join(',')}}"
      output = type.to_s
    end
    output += ":\n"

    output += @children.map do |item|
      "#{indent}#{item.children.map { |c| c.to_s.chomp.lstrip }.join(',')}"
    end.join("\n")
    return output
  end

  output = +':'
  output_inline = true

  child_strings = @children.map do |child|
    output_inline = false if child.is_a?(ObjectNode) || child.is_a?(ArrayNode)
    child.to_s.chomp.lstrip
  end
  if output_inline
    output = +'' if parent.is_a?(ArrayNode)
    output << ' '
    output << child_strings.join(',')
  else
    output << "\n#{indent}- "
    output << child_strings.join("\n#{indent}- ")
  end

  output << "\n"

  output
end