Class: Console::Format::Safe

Inherits:
Object
  • Object
show all
Defined in:
lib/console/format/safe.rb

Overview

A safe format for converting objects to strings.

Handles issues like circular references, encoding errors, excessive nesting depth, and excessive output size.

Constant Summary collapse

TRUNCATED =

The JSON fragment used as the truncation marker when dropped fields cannot be named.

"\"truncated\":true"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(format: ::JSON, depth_limit: 12, size_limit: 16 * 1024, encoding: ::Encoding::UTF_8, limit: nil) ⇒ Safe

Create a new safe format.



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/console/format/safe.rb', line 25

def initialize(format: ::JSON, depth_limit: 12, size_limit: 16 * 1024, encoding: ::Encoding::UTF_8, limit: nil)
	if limit
		warn "Console::Format::Safe `limit:` is deprecated, use `depth_limit:` instead.", uplevel: 1, category: :deprecated
		depth_limit = limit
	end
	
	@format = format
	@depth_limit = depth_limit
	@size_limit = size_limit
	@encoding = encoding
end

Instance Attribute Details

#depth_limitObject (readonly)

Returns the value of attribute depth_limit.



38
39
40
# File 'lib/console/format/safe.rb', line 38

def depth_limit
  @depth_limit
end

#size_limitObject (readonly)

Returns the value of attribute size_limit.



41
42
43
# File 'lib/console/format/safe.rb', line 41

def size_limit
  @size_limit
end

#The maximum byte size of the serialized output.(maximumbytesizeoftheserializedoutput.) ⇒ Object (readonly)



41
# File 'lib/console/format/safe.rb', line 41

attr :size_limit

#The maximum depth to recurse into objects.(maximumdepthtorecurseintoobjects.) ⇒ Object (readonly)



38
# File 'lib/console/format/safe.rb', line 38

attr :depth_limit

Instance Method Details

#dump(object) ⇒ Object

Dump the given object to a string.

The common case is a single fast serialization. If that fails (e.g. circular references, excessive nesting, or encoding errors) or its output exceeds #size_limit, it falls back to #safe_dump, which rebuilds the record field-by-field within the limit.



52
53
54
55
56
57
58
59
60
61
62
# File 'lib/console/format/safe.rb', line 52

def dump(object)
	buffer = @format.dump(object, @depth_limit)
	
	if @size_limit and buffer.bytesize > @size_limit
		return safe_dump(object)
	end
	
	return buffer
rescue SystemStackError, StandardError
	return safe_dump(object)
end