Class: TPTree::Formatters::BaseFormatter

Inherits:
Object
  • Object
show all
Defined in:
lib/tp_tree/formatters/base_formatter.rb

Overview

BaseFormatter provides common formatting methods for parameters, values, and timing. Subclasses must implement the colorize method for their specific output format.

Direct Known Subclasses

AnsiFormatter, XmlFormatter

Constant Summary collapse

DEPTH_COLORS =

Color codes for different depth levels in the call tree

[:green, :blue, :yellow, :magenta, :cyan, :red].freeze

Instance Method Summary collapse

Instance Method Details

#color_for_depth(depth) ⇒ Object



82
83
84
# File 'lib/tp_tree/formatters/base_formatter.rb', line 82

def color_for_depth(depth)
  DEPTH_COLORS[depth % DEPTH_COLORS.length]
end

#colorize(text, color) ⇒ Object

Abstract method - must be implemented by subclasses

Raises:

  • (NotImplementedError)


12
13
14
# File 'lib/tp_tree/formatters/base_formatter.rb', line 12

def colorize(text, color)
  raise NotImplementedError, "Subclasses must implement colorize method"
end

#format_parameters(parameters) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/tp_tree/formatters/base_formatter.rb', line 30

def format_parameters(parameters)
  return '' if parameters.nil? || parameters.empty?

  parameters.map { |param_type, param_name, param_value|
    case param_type
    when :req, :opt
      "#{param_name} = #{format_value(param_value)}"
    when :keyreq, :key
      if param_value.nil?
        "#{param_name}:"
      else
        "#{param_name} = #{format_value(param_value)}"
      end
    when :rest
      "*#{param_name}"
    when :keyrest
      "**#{param_name}"
    when :block
      "&#{param_name}"
    else
      param_name.to_s
    end
  }.join(', ')
end

#format_return_value(return_value) ⇒ Object



78
79
80
# File 'lib/tp_tree/formatters/base_formatter.rb', line 78

def format_return_value(return_value)
  format_value(return_value)
end

#format_timing(duration) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/tp_tree/formatters/base_formatter.rb', line 16

def format_timing(duration)
  return '' if duration.nil?

  formatted_time = if duration < 0.001
    "#{(duration * 1_000_000).round(1)}μs"
  elsif duration < 1.0
    "#{(duration * 1000).round(1)}ms"
  else
    "#{duration.round(3)}s"
  end

  colorize(" [#{formatted_time}]", :cyan)
end

#format_value(value) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/tp_tree/formatters/base_formatter.rb', line 55

def format_value(value)
  case value
  when String
    value.inspect
  when Symbol
    ":#{value}"
  when NilClass
    'nil'
  when TrueClass, FalseClass
    value.to_s
  when Numeric
    value.to_s
  when Array
    "[#{value.map { |v| format_value(v) }.join(', ')}]"
  when Hash
    "{#{value.map { |k, v| "#{format_value(k)} => #{format_value(v)}" }.join(', ')}}"
  when Proc
    'Proc'
  else
    value.inspect
  end
end