Class: JsonToToon::Encoder

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

Constant Summary collapse

DEFAULT_INDENT =
2
DELIMITER_COMMA =
','
DELIMITER_TAB =
"\t"
DELIMITER_PIPE =
'|'
VALID_DELIMITERS =
[DELIMITER_COMMA, DELIMITER_TAB, DELIMITER_PIPE].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Encoder

Returns a new instance of Encoder.



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

def initialize(options = {})
  @indent_size = options[:indent] || DEFAULT_INDENT
  @delimiter = options[:delimiter] || DELIMITER_COMMA
  @length_marker = options[:length_marker] || false

  validate_options!

  @output = []
  @visited = {}
end

Instance Attribute Details

#delimiterObject (readonly)

Returns the value of attribute delimiter.



13
14
15
# File 'lib/json_to_toon/encoder.rb', line 13

def delimiter
  @delimiter
end

#indent_sizeObject (readonly)

Returns the value of attribute indent_size.



13
14
15
# File 'lib/json_to_toon/encoder.rb', line 13

def indent_size
  @indent_size
end

#length_markerObject (readonly)

Returns the value of attribute length_marker.



13
14
15
# File 'lib/json_to_toon/encoder.rb', line 13

def length_marker
  @length_marker
end

Instance Method Details

#delimiter_markerObject



39
40
41
42
43
44
45
# File 'lib/json_to_toon/encoder.rb', line 39

def delimiter_marker
  case @delimiter
  when DELIMITER_COMMA then ''
  when DELIMITER_TAB then "\t"
  when DELIMITER_PIPE then '|'
  end
end

#encode(value) ⇒ Object



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

def encode(value)
  @output = []
  @visited = {}
  result = encode_value(value, 0)

  # If encoding a primitive value at root, encode_value returns the
  # formatted string but nothing is emitted to @output. In that case
  # return the direct result.
  return result.to_s if @output.empty? && result

  @output.join("\n")
end

#length_prefixObject



47
48
49
# File 'lib/json_to_toon/encoder.rb', line 47

def length_prefix
  @length_marker == '#' ? '#' : ''
end