Class: TTY::Option::AggregateErrors

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Enumerable, UsageWrapper
Defined in:
lib/tty/option/aggregate_errors.rb

Instance Method Summary collapse

Methods included from UsageWrapper

wrap

Constructor Details

#initialize(errors = []) ⇒ AggregateErrors

Create an intance from the passed error objects



19
20
21
# File 'lib/tty/option/aggregate_errors.rb', line 19

def initialize(errors = [])
  @errors = errors
end

Instance Method Details

#add(error) ⇒ Object

Add error



26
27
28
29
# File 'lib/tty/option/aggregate_errors.rb', line 26

def add(error)
  @errors << error
  error
end

#each(&block) ⇒ Object

Enumerate each error

Examples:

errors = AggregateErrors.new
errors.each do |error|
  # instance of TTY::Option::Error
end


40
41
42
# File 'lib/tty/option/aggregate_errors.rb', line 40

def each(&block)
  @errors.each(&block)
end

#messagesObject

All error messages

Examples:

errors = AggregateErrors.new
errors.add TTY::OptionInvalidArgument.new("invalid argument")
errors.messages
# => ["invalid argument"]


53
54
55
# File 'lib/tty/option/aggregate_errors.rb', line 53

def messages
  map(&:message)
end

#summary(width: 80, indent: 0) ⇒ String

Format errors for display in terminal

Examples:

errors = AggregateErrors.new
errors.add TTY::OptionInvalidArgument.new("invalid argument")
errors.summary
# =>
# Error: invalid argument

Parameters:

  • :width (Integer)
  • :indent (Integer)

Returns:

  • (String)


72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/tty/option/aggregate_errors.rb', line 72

def summary(width: 80, indent: 0)
  return "" if count.zero?

  output = []
  space_indent = " " * indent
  if messages.count == 1
    msg = messages.first
    label = "Error: "
    output << "#{space_indent}#{label}" \
              "#{wrap(msg, indent: indent + label.length, width: width)}"
  else
    output << "#{space_indent}Errors:"
    messages.each_with_index do |message, num|
      entry = "  #{num + 1}) "
      output << "#{space_indent}#{entry}" \
                "#{wrap(message.capitalize, indent: indent + entry.length,
                                            width: width)}"
    end
  end
  output.join("\n")
end