Class: ToonMyJson::Encoder

Inherits:
Object
  • Object
show all
Defined in:
lib/toon_my_json/encoder.rb

Overview

Encodes Ruby objects to TOON format

Constant Summary collapse

RESERVED_CHARS =
/[,:\[\]{}#\n\r\t]/
NEEDS_QUOTES =
/\A\s|\s\z|#{RESERVED_CHARS}/

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(indent: 2, delimiter: ',', length_marker: true) ⇒ Encoder

Returns a new instance of Encoder.



11
12
13
14
15
# File 'lib/toon_my_json/encoder.rb', line 11

def initialize(indent: 2, delimiter: ',', length_marker: true)
  @indent_size = indent
  @delimiter = delimiter
  @length_marker = length_marker
end

Instance Attribute Details

#delimiterObject (readonly)

Returns the value of attribute delimiter.



9
10
11
# File 'lib/toon_my_json/encoder.rb', line 9

def delimiter
  @delimiter
end

#indent_sizeObject (readonly)

Returns the value of attribute indent_size.



9
10
11
# File 'lib/toon_my_json/encoder.rb', line 9

def indent_size
  @indent_size
end

#length_markerObject (readonly)

Returns the value of attribute length_marker.



9
10
11
# File 'lib/toon_my_json/encoder.rb', line 9

def length_marker
  @length_marker
end

Instance Method Details

#encode(value, depth = 0) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/toon_my_json/encoder.rb', line 17

def encode(value, depth = 0)
  case value
  when Hash
    encode_hash(value, depth)
  when Array
    encode_array(value, depth)
  when nil
    'null'
  when true, false
    value.to_s
  when Numeric
    value.to_s
  when String
    encode_string(value)
  else
    encode_string(value.to_s)
  end
end