module Variable
Provides a compact, truncated representation of values for output.
Rather than building a full inspect string and then truncating it, we walk
the value and stream tokens directly into an output, aborting as soon as a
character budget is exhausted. This means we never materialize the full
representation of a large subject (e.g. a big array or richly inspected
instance).
Containers (arrays and hashes) are formatted directly so we can recurse with
the budget; leaf values delegate to native inspect so their formatting
exactly matches Ruby. The value itself is emitted in a single style (matching
the rest of sus's output), and only the truncation ellipsis is highlighted
distinctly so it's clear where output was cut.
Nested
Definitions
TRUNCATION_LIMIT
The maximum length of an inspected value before it is truncated. Override
it with the SUS_OUTPUT_VARIABLE_TRUNCATION_LIMIT environment variable; a
value of 0 (or nil) disables truncation entirely.
Implementation
TRUNCATION_LIMIT = ENV.fetch("SUS_OUTPUT_VARIABLE_TRUNCATION_LIMIT", 100).then do |value|
value = Integer(value)
value.zero? ? nil : value
end
ELLIPSIS = "…"
The string appended to a truncated value.
def self.format(output, value, limit: TRUNCATION_LIMIT)
Format a value into the given output, truncating at the limit.
Signature
-
parameter
outputOutput The output target.
-
parameter
valueObject The value to format.
-
parameter
limitInteger The maximum length of the representation.
Implementation
def self.format(output, value, limit: TRUNCATION_LIMIT)
# With no limit, the formatter would produce exactly `value.inspect`, so
# we can skip walking the value and emit it directly:
unless limit
return output.write(:variable, value.inspect, :reset)
end
formatter = Formatter.new(output, limit: limit)
begin
formatter.format(value)
rescue Formatter::Truncated
output.write(:ellipsis, ELLIPSIS, :reset)
end
end
def self.buffer(value, limit: TRUNCATION_LIMIT)
Capture a value's representation into a buffer, resolving the value immediately, but deferring colour resolution until the buffer is replayed into a real output.
Signature
-
parameter
valueObject The value to capture.
-
parameter
limitInteger The maximum length of the representation.
-
returns
Buffered A buffer containing the captured representation.
Implementation
def self.buffer(value, limit: TRUNCATION_LIMIT)
buffer = Buffered.new
self.format(buffer, value, limit: limit)
return buffer
end