Class: RocketPants::Errors

Inherits:
Object
  • Object
show all
Defined in:
lib/rocket_pants/errors.rb

Overview

A simple map of data about errors that the rocket pants system can handle.

Constant Summary collapse

@@errors =
{}

Class Method Summary collapse

Class Method Details

.[](name) ⇒ Error?

Looks up a specific error from the given name, returning nil if none are found.

Parameters:

  • name (#to_sym)

    the name of the error to look up.

Returns:

  • (Error, nil)

    the error class if found, otherwise nil.



19
20
21
# File 'lib/rocket_pants/errors.rb', line 19

def self.[](name)
  @@errors[name.to_sym]
end

.add(error) ⇒ Object

Adds a given Error class in the list of all errors, making it suitable for lookup via [].

Parameters:

  • error (Error)

    the error to register.

See Also:

  • Errors[]


27
28
29
# File 'lib/rocket_pants/errors.rb', line 27

def self.add(error)
  @@errors[error.error_name] = error
end

.allHash{Symbol => RocketPants::Error}

Returns a hash of all known errors, keyed by their error name.

Returns:



12
13
14
# File 'lib/rocket_pants/errors.rb', line 12

def self.all
  @@errors.dup
end

.register!(name, options = {}) ⇒ Object

Creates an error class to represent a given error state.

Examples:

Adding a RocketPants::NinjasUnavailable class w/ ‘:service_unavailable` as the status code:

register! :ninjas_unavailable, :http_status => :service_unavailable

Parameters:

  • name (Symbol)

    the name of the given error

  • options (Hash) (defaults to: {})

    the options used to create the error class.

Options Hash (options):

  • :class_name (Symbol)

    the name of the class (under ‘RocketPants`), defaulting to the classified name.

  • :error_name (Symbol)

    the name of the error, defaulting to the name parameter.

  • :http_status (Symbol)

    the status code for the given error, doing nothing if absent.

Raises:

  • (ArgumentError)


39
40
41
42
43
44
45
46
47
48
49
# File 'lib/rocket_pants/errors.rb', line 39

def self.register!(name, options = {})
  klass_name = (options[:class_name] || name.to_s.classify).to_sym
  base_klass = options[:base] || Error
  raise ArgumentError, ":base must be a subclass of RocketPants::Error" unless base_klass <= Error
  klass = Class.new(base_klass)
  klass.error_name(options[:error_name] || name.to_s.underscore)
  klass.http_status(options[:http_status]) if options[:http_status].present?
  (options[:under] || RocketPants).const_set klass_name, klass
  add klass
  klass
end