Exception: Fibonaccia::Exception

Inherits:
StandardError
  • Object
show all
Defined in:
lib/fibonaccia/exceptions.rb

Overview

Define a ‘parent’ exception class for the module. All module-specific exceptions should inherit from this.

Direct Known Subclasses

NotPositiveInteger

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Exception

We cannot access the mesg ‘instance variable’ of the inherited class hierarchy, do we needs must fake it as part of our constructor.

If the first element of the argument list is a string, we set our message to it. Otherwise, we follow the practice of using the name of the class as the message.

Parameters:

  • args (Array)

    ::StandardError.method(:new).arity => -1, so we allow an undefined number of arguments here, as well. We only look at the first one, though. If it’s a string, we use it – otherwise we set the message to nil and let #to_s/#to_str apply the default at need.



45
46
47
48
# File 'lib/fibonaccia/exceptions.rb', line 45

def initialize(*args)
  @mesg		= (args[0].respond_to?(:to_str)) ? args[0] : nil
  return super
end

Instance Method Details

#to_sString

We cannot access the standard Exception hierarchical message mechanism because it store the message in a non-@ prefixed ‘instance variable.’ So we need to work around it with our own instance variable, set by the constructor.

Returns:

  • (String)

    whatever the constructor stored in the @mesg instance variable, or the class name if @mesg is nil.



61
62
63
# File 'lib/fibonaccia/exceptions.rb', line 61

def to_s
  return (@mesg || self.class.name)
end

#to_strString

Having a #to_str method tells Ruby ‘you can treat me as a String.’ This just returns the same value as #to_s.

Returns:

  • (String)

    value returned by #to_s method.



72
73
74
# File 'lib/fibonaccia/exceptions.rb', line 72

def to_str
  return self.to_s
end