Class: Ucode::Audit::Formatters::TextFormatter

Inherits:
Object
  • Object
show all
Defined in:
lib/ucode/audit/formatters/text_formatter.rb

Overview

Shared utilities for the text-rendering formatters. Owns the column helpers, list truncation, byte formatting, and ANSI color hook that the audit/diff/library renderers all use.

Formatters instantiate this class and delegate common formatting chores to it; the renderer classes own the section shape and model-walking logic.

Constant Summary collapse

LIST_LIMIT =
10
LABEL_WIDTH =
18

Instance Method Summary collapse

Instance Method Details

#format_bytes(bytes) ⇒ String

Format an integer byte count as B / KB / MB.

Parameters:

  • bytes (Integer, nil)

Returns:

  • (String)


54
55
56
57
58
59
60
61
62
63
64
# File 'lib/ucode/audit/formatters/text_formatter.rb', line 54

def format_bytes(bytes)
  return "0 B" if bytes.nil? || bytes.zero?

  if bytes < 1024
    "#{bytes} B"
  elsif bytes < 1024 * 1024
    format("%<v>.2f KB", v: bytes / 1024.0)
  else
    format("%<v>.2f MB", v: bytes / (1024.0 * 1024))
  end
end

#row(label, value, width: LABEL_WIDTH) ⇒ String?

Right-pad a label to a column width, then append the value. Returns nil if value is nil or empty-string (signal to skip).

Parameters:

  • label (String, Symbol)
  • value (Object)

Returns:

  • (String, nil)


72
73
74
75
76
77
78
79
# File 'lib/ucode/audit/formatters/text_formatter.rb', line 72

def row(label, value, width: LABEL_WIDTH)
  return if value.nil?
  return if value.is_a?(String) && value.empty?

  label_s = label.to_s
  padding = " " * [(width - label_s.length - 1), 1].max
  "  #{label_s}:#{padding}#{value}"
end

#truncate_list(items, limit: LIST_LIMIT) ⇒ String

Format a list of arbitrary items as a single-line truncated comma-separated string. Returns "(none)" for empty input.

Parameters:

  • items (Enumerable)

Returns:

  • (String)


22
23
24
25
26
27
28
29
30
31
32
# File 'lib/ucode/audit/formatters/text_formatter.rb', line 22

def truncate_list(items, limit: LIST_LIMIT)
  list = Array(items)
  return "(none)" if list.empty?

  shown = list.first(limit).join(", ")
  if list.size > limit
    "#{shown}, … (+#{list.size - limit} more)"
  else
    shown
  end
end

#truncate_ranges(ranges, limit: LIST_LIMIT) ⇒ String

Format a codepoint range list as U+XXXX-U+XXXX, …, truncated.

Parameters:

Returns:

  • (String)


38
39
40
41
42
43
44
45
46
47
48
# File 'lib/ucode/audit/formatters/text_formatter.rb', line 38

def truncate_ranges(ranges, limit: LIST_LIMIT)
  list = Array(ranges)
  return "(none)" if list.empty?

  shown = list.first(limit).join(", ")
  if list.size > limit
    "#{shown}, … (+#{list.size - limit} more)"
  else
    shown
  end
end