Class: JsonToToon::ValueNode

Inherits:
DataNode show all
Defined in:
lib/json_to_toon/value_node.rb

Instance Attribute Summary collapse

Attributes inherited from DataNode

#indentation_level, #parent

Instance Method Summary collapse

Methods inherited from DataNode

#indent, #root

Constructor Details

#initialize(value, parent = nil) ⇒ ValueNode

Returns a new instance of ValueNode.



9
10
11
12
# File 'lib/json_to_toon/value_node.rb', line 9

def initialize(value, parent = nil)
  super(parent)
  @value = value
end

Instance Attribute Details

#valueObject (readonly)

Returns the value of attribute value.



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

def value
  @value
end

Instance Method Details

#add_child(_child) ⇒ Object

Raises:

  • (NoMethodError)


40
41
42
# File 'lib/json_to_toon/value_node.rb', line 40

def add_child(_child)
  raise NoMethodError, "A #{self.class} cannot have children."
end

#escape(value) ⇒ Object



14
15
16
17
18
19
20
21
22
23
# File 'lib/json_to_toon/value_node.rb', line 14

def escape(value)
  return 'null' if value.nil?
  return value unless value.is_a?(String)
  return "\"#{value.gsub('"', '\"')}\"" if value.match(/"/)
  return "\"#{value}\"" if value.match(/,/)
  return "\"#{value}\"" if value.match(/^(-\s)/)
  return "\"#{value.gsub("\n", '\n')}\"" if value.match(/\n/)

  value
end

#to_sObject



25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/json_to_toon/value_node.rb', line 25

def to_s
  formatted_value = case @value
                    when String
                      escape(@value)
                    when Numeric, TrueClass, FalseClass
                      @value.to_s
                    when NilClass
                      'null'
                    else
                      @value.to_s
                    end

  "#{indent}#{formatted_value}"
end