Exception: Clive::Error

Inherits:
StandardError
  • Object
show all
Defined in:
lib/clive/error.rb

Overview

For general errors with Clive. It stripts most of the backtrace which you don't really want, and allows you to set nice error messages using Error.reason. Arguments can be passed and then used in messages by referencing with #n tokens, where n is the index of the argument.

A lot of this is pulled from OptionParser::ParseError see ruby-doc.org/stdlib/libdoc/optparse/rdoc/index.html.

Examples:


class MissingArgumentError < Error
  reason 'missing argument for #0'
end

raise MissingArgumentError.new(some_option)

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Error

Returns a new instance of Error.

Parameters:

  • args

    Arguments that can be accessed with '#n' in reason.


28
29
30
# File 'lib/clive/error.rb', line 28

def initialize(*args)
  @args = args
end

Instance Attribute Details

#argsObject

Returns the value of attribute args


24
25
26
# File 'lib/clive/error.rb', line 24

def args
  @args
end

Class Method Details

._reasonObject

Accessor for the reason set with reason.


48
49
50
# File 'lib/clive/error.rb', line 48

def self._reason
  @reason
end

.filter_backtrace(array) ⇒ Object

Removes all references to files which are not the file being run unless in $DEBUG mode.


34
35
36
37
38
39
# File 'lib/clive/error.rb', line 34

def self.filter_backtrace(array)
  unless $DEBUG
    array = [$0]
  end
  array
end

.reason(str) ⇒ Object

Set the reason for the error class.

Parameters:


43
44
45
# File 'lib/clive/error.rb', line 43

def self.reason(str)
  @reason = str
end

Instance Method Details

#messageObject Also known as: to_s

Build the message by substituting the arguments into the reason.


57
58
59
60
61
62
63
64
65
66
# File 'lib/clive/error.rb', line 57

def message
  self.class._reason.gsub(/#\d/) do |i|
    arg = args[i[1].to_i]
    if arg.is_a?(Array)
      arg.map(&:to_s).to_s
    else
      arg.to_s
    end
  end
end

#set_backtrace(array) ⇒ Object


52
53
54
# File 'lib/clive/error.rb', line 52

def set_backtrace(array)
  super(self.class.filter_backtrace(array))
end