class TTY::Logger::Formatters::JSON

Format data suitable for data exchange

Constants

ELLIPSIS

Public Instance Methods

dump(obj, max_bytes: 2**12, max_depth: 3) click to toggle source

Dump data into a JSON formatted string

@param [Hash] obj

the object to serialize as JSON

@return [String]

@api public

# File lib/tty/logger/formatters/json.rb, line 20
def dump(obj, max_bytes: 2**12, max_depth: 3)
  bytesize = 0

  hash = obj.each_with_object({}) do |(k, v), acc|
    str = (k.to_json + v.to_json)
    items = acc.keys.size - 1

    if bytesize + str.bytesize + items + ELLIPSIS.bytesize > max_bytes
      acc[k] = ELLIPSIS
      break acc
    else
      bytesize += str.bytesize
      acc[k] = dump_val(v, max_depth)
    end
  end
  ::JSON.generate(hash)
end

Private Instance Methods

dump_val(val, depth) click to toggle source
# File lib/tty/logger/formatters/json.rb, line 40
def dump_val(val, depth)
  case val
  when Hash then enc_obj(val, depth - 1)
  when Array then enc_arr(val, depth - 1)
  else
    val
  end
end
enc_arr(obj, depth) click to toggle source
# File lib/tty/logger/formatters/json.rb, line 55
def enc_arr(obj, depth)
  return ELLIPSIS if depth.zero?

  obj.each_with_object([]) { |v, acc| acc << dump_val(v, depth) }
end
enc_obj(obj, depth) click to toggle source
# File lib/tty/logger/formatters/json.rb, line 49
def enc_obj(obj, depth)
  return ELLIPSIS if depth.zero?

  obj.each_with_object({}) { |(k, v), acc| acc[k] = dump_val(v, depth) }
end