Class: SmarterJSON::Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/smarter_json/generator.rb

Constant Summary collapse

ESCAPE =
{
  '"' => '\\"', "\\" => "\\\\", "\b" => "\\b", "\f" => "\\f",
  "\n" => "\\n", "\r" => "\\r", "\t" => "\\t"
}.freeze
ESCAPE_RE =

“, backslash, and control chars 0x00-0x1F must be escaped; everything else (including multi-byte UTF-8) is emitted raw — valid JSON.

/["\\\x00-\x1f]/.freeze

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Generator

Returns a new instance of Generator.



33
34
35
36
37
38
# File 'lib/smarter_json/generator.rb', line 33

def initialize(options = {})
  @format = options.fetch(:format, :json)
  unless %i[json ndjson].include?(@format)
    raise ArgumentError, "unknown writer format: #{@format.inspect} (expected :json or :ndjson)"
  end
end

Instance Method Details

#generate(obj) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/smarter_json/generator.rb', line 40

def generate(obj)
  buf = +""
  if @format == :ndjson
    if obj.is_a?(Array)
      obj.each do |v|
        emit(v, buf)
        buf << "\n"
      end
    else
      emit(obj, buf)
      buf << "\n"
    end
  else
    emit(obj, buf)
  end
  buf
end