Module: CustomExceptions

Defined in:
lib/custom_exceptions.rb,
lib/custom_exceptions/base.rb

Defined Under Namespace

Classes: Base

Constant Summary collapse

VERSION =
"0.0.1"

Class Method Summary collapse

Class Method Details

.define_exceptionsObject



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/custom_exceptions.rb', line 22

def define_exceptions
  error_constants.each do |name, error_body|
    klass = Class.new(CustomExceptions::Base)
    klass.send(:define_method, :initialize) do |options={}|
      @metadata = options[:metadata]
      @code = options[:code]
      @message = options[:message]
      @status = options[:status]
    end
    klass.send(:define_method, :metadata) { @metadata || error_body["metadata"] }
    klass.send(:define_method, :code) { @code || error_body["code"]}
    klass.send(:define_method, :message) { @message || error_body["message"] }
    klass.send(:define_method, :status) { @status || error_body["status"]}
    CustomExceptions.send(:remove_const, name.to_s.classify) if CustomExceptions.const_defined?(name.to_s.classify)
    CustomExceptions.const_set(name.to_s.classify, klass)
  end
end

.error_constantsObject



16
17
18
19
20
# File 'lib/custom_exceptions.rb', line 16

def error_constants
  @config.each_with_object({}) do |const, hash|
    hash[const.first] = const.last
  end
end

.exception(class_name) ⇒ Object



40
41
42
43
44
45
46
# File 'lib/custom_exceptions.rb', line 40

def exception(class_name)
  if const_defined?(class_name)
    CustomExceptions.const_get(class_name)
  else
    runtime_exception(class_name)
  end
end

.load(file) ⇒ Object



11
12
13
14
# File 'lib/custom_exceptions.rb', line 11

def load(file)
 @config = YAML.load_file(file)
 define_exceptions
end

.runtime_exception(name) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/custom_exceptions.rb', line 48

def runtime_exception(name)
  klass = Class.new(CustomExceptions::Base)
  klass.send(:define_method, :initialize) do |options={}|
    @metadata = options[:metadata]
    @code = options[:code]
    @message = options[:message] || name.to_s.split("_").join(' ').downcase.capitalize
    @status = options[:status] || 500
  end
  klass.send(:define_method, :metadata) { @metadata }
  klass.send(:define_method, :code) { @code }
  klass.send(:define_method, :message) { @message }
  klass.send(:define_method, :status) { @status }
  CustomExceptions.send(:remove_const, name.to_s.classify) if CustomExceptions.const_defined?(name.to_s.classify)
  CustomExceptions.const_set(name.to_s.classify, klass)
end