Class: Sus::Output::Variable::Formatter

Inherits:
Object
  • Object
show all
Defined in:
lib/sus/output/variable.rb

Overview

Walks a value and emits styled tokens to an output, aborting once the character budget is exhausted.

Defined Under Namespace

Classes: Truncated

Instance Method Summary collapse

Constructor Details

#initialize(output, limit:) ⇒ Formatter

Returns a new instance of Formatter.



44
45
46
47
48
# File 'lib/sus/output/variable.rb', line 44

def initialize(output, limit:)
	@output = output
	@remaining = limit
	@seen = nil
end

Instance Method Details

#emit(text) ⇒ Object

Emit a token in the variable style, truncating and aborting once the budget is exceeded.

Raises:



53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/sus/output/variable.rb', line 53

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

#format(value) ⇒ Object

Format a value, emitting styled tokens to the output.



70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/sus/output/variable.rb', line 70

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