class Formatter
Walks a value and emits styled tokens to an output, aborting once the character budget is exhausted.
Nested
Definitions
def initialize(output, limit:)
Signature
-
parameter
outputOutput The output target to write tokens to.
-
parameter
limitInteger The maximum number of characters to emit.
Implementation
def initialize(output, limit:)
@output = output
@remaining = limit
@seen = nil
end
def emit(text)
Emit a token in the variable style, truncating and aborting once the budget is exceeded.
Signature
-
parameter
textString The token text to emit.
Implementation
def emit(text)
truncated = false
if text.length > @remaining
text = text[0, @remaining]
truncated = true
end
@remaining -= text.length
@output.write(:variable, text, :reset)
raise Truncated if truncated
end
def format(value)
Format a value, emitting styled tokens to the output.
Signature
-
parameter
valueObject The value to format.
Implementation
def format(value)
case value
when String
# Inspect only a prefix so we never escape a huge string:
slice = value.length > @remaining ? value[0, @remaining] : value
emit(slice.inspect)
when Array
format_array(value)
when Hash
format_hash(value)
else
format_object(value)
end
end