Class: TsonRails::Encoder

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

Overview

Encodes Ruby values into the TSON text data format.

The encoder intentionally targets the schemaless data-format layer. It emits records for string/symbol-keyed hashes, maps for other hashes, and built-in TSON annotations for Ruby temporal and exact numeric values.

Constant Summary collapse

SERIALIZATION_OPTION_KEYS =
%i[only except methods include].freeze
SAFE_UNQUOTED =
/\A[A-Za-z0-9_+.\-]+\z/.freeze
DECIMAL_DIGITS =
"[0-9](?:_?[0-9])*"
DECIMAL_INTEGER =
"(?:0|[1-9](?:_?[0-9])*)"
BASED_INTEGER =
"(?:0[xX][0-9A-Fa-f](?:_?[0-9A-Fa-f])*|0[oO][0-7](?:_?[0-7])*|0[bB][01](?:_?[01])*)"
EXPONENT =
"[eE][+-]?#{DECIMAL_DIGITS}"
FLOAT =
"(?:(?:#{DECIMAL_DIGITS})?\.(?:#{DECIMAL_DIGITS})(?:#{EXPONENT})?|#{DECIMAL_DIGITS}#{EXPONENT})"
NUMBER_TOKEN =
/\A[+-]?(?:#{DECIMAL_INTEGER}|#{BASED_INTEGER}|#{FLOAT})\z/.freeze
SPECIAL_FLOAT_TOKEN =
/\A[+-]?\.(?:inf|infinity|nan)\z/.freeze

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Encoder

Returns a new instance of Encoder.



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/tson_rails/encoder.rb', line 25

def initialize(options = {})
  options = options.to_h

  @pretty = !!options.fetch(:pretty, false)
  @indent = options.fetch(:indent, "  ").to_s
  @omit_absent = !!options.fetch(:omit_absent, false)
  @hash_mode = (options[:hash_mode] || options[:map_mode] || :auto).to_sym
  @time_precision = Integer(options.fetch(:time_precision, 9))
  @serialization_options = serialization_options_for(options)
  @active_path = {}

  unless %i[auto record map].include?(@hash_mode)
    raise ArgumentError, "hash_mode must be :auto, :record, or :map"
  end

  if @time_precision.negative? || @time_precision > 9
    raise ArgumentError, "time_precision must be between 0 and 9"
  end
end

Instance Method Details

#encode(value) ⇒ Object



45
46
47
# File 'lib/tson_rails/encoder.rb', line 45

def encode(value)
  encode_value(value, 0)
end