Class: ToonFu::Encoder
- Inherits:
-
Object
- Object
- ToonFu::Encoder
- Defined in:
- lib/toon_fu/encoder.rb
Overview
Encodes values with one set of options, for callers that encode many.
Constant Summary collapse
- DELIMITERS =
[",", "\t", "|"].freeze
Instance Method Summary collapse
-
#encode(value) ⇒ String
Encodes a value as TOON.
-
#initialize(delimiter: ",", indent_size: 2) ⇒ Encoder
constructor
A new instance of Encoder.
Constructor Details
#initialize(delimiter: ",", indent_size: 2) ⇒ Encoder
Returns a new instance of Encoder.
13 14 15 16 17 18 19 |
# File 'lib/toon_fu/encoder.rb', line 13 def initialize(delimiter: ",", indent_size: 2) raise ArgumentError, "delimiter must be one of #{DELIMITERS.inspect}, got #{delimiter.inspect}" unless DELIMITERS.include?(delimiter) raise ArgumentError, "indent_size must be a positive Integer, got #{indent_size.inspect}" unless indent_size.is_a?(Integer) && indent_size.positive? @delimiter = delimiter @indent = " " * indent_size end |
Instance Method Details
#encode(value) ⇒ String
Encodes a value as TOON.
Accepts the JSON data model plus these Ruby types, nested in any combination:
Hashwith String, Symbol or Integer keys, which become strings;Array;Setas an arrayStringin UTF-8, in an encoding that transcodes to it, or binary bytes that are valid UTF-8;Symbolas its nameIntegerof any size as its exact digits;FloatandBigDecimal, with NaN and infinities asnull,BigDecimalas its exact digits;true,false,nilDateas an ISO 8601 date;TimeandDateTimeas ISO 8601 timestamps keeping their offset, fraction digits up to the last non-zero one- objects that declare themselves a Hash, Array or String through
Ruby's implicit conversions:
to_hash,to_ary,to_str - any object responding to
as_toon: its result is encoded instead, ahead of the mappings above
48 49 50 51 52 |
# File 'lib/toon_fu/encoder.rb', line 48 def encode(value) Writer.new(@delimiter, @indent).write(Normalizer.new.call(value)) rescue SystemStackError raise Error, "cannot encode a circular reference or nesting too deep" end |