Class: ToeTag::CategorySpec

Inherits:
ExceptionSpec show all
Defined in:
lib/toe_tag.rb

Overview

Aggregates multiple exception classes into one single logical type. Intended to be used in rescue clauses, for cases where different underlying implementations may bubble up different exceptions meaning the same thing.

The recommended usage is to assign these to constants and treat them as a sort of meta-exception. This may be useful in combination with ExceptionMessageCatcher.

Examples:

ErrorA = Class.new(StandardError)
ErrorB = Class.new(StandardError)
ErrorC = Class.new(StandardError)

ErrorsABC = ToeTag.category ErrorA, ErrorB, ErrorC

begin
  # some stuff
rescue ErrorsABC => err
  # err is either ErrorA, ErrorB, or ErrorC
end

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ExceptionBehavior

#with_message

Constructor Details

#initialize(*exceptions) ⇒ CategorySpec

Returns a new instance of CategorySpec.



50
51
52
# File 'lib/toe_tag.rb', line 50

def initialize(*exceptions)
  self.exceptions = exceptions.flatten.freeze
end

Instance Attribute Details

#exceptionsObject

Returns the value of attribute exceptions.



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

def exceptions
  @exceptions
end

Class Method Details

.category(*names) ⇒ Object

Accepts a list of exception classes or names of exception classes and returns an ExceptionCategory covering those exception classes. If a name is provided, it is converted to a constant. If the constant doesn’t exist, the name is ignored. This allows the creation of an ExceptionCategory covering multiple exception types that may not all be loaded in a given environment.

Examples:

DatabaseError = ExceptionCategory.category %w[ActiveRecord::JDBCError PG::Error]


66
67
68
69
70
71
72
73
74
75
# File 'lib/toe_tag.rb', line 66

def self.category(*names)
  names = names.flatten.map{|except_name|
    if except_name.kind_of?(String)
      Util.try_constantize(except_name)
    else
      except_name
    end
  }.compact
  new(*names)
end

Instance Method Details

#===(except) ⇒ Object



54
55
56
# File 'lib/toe_tag.rb', line 54

def ===(except)
  exceptions.any?{|exc| exc === except }
end