Module: JSONAPIonify::Api::Resource::ErrorHandling::ClassMethods

Defined in:
lib/jsonapionify/api/resource/error_handling.rb

Instance Method Summary collapse

Instance Method Details

#error(name, &block) ⇒ Object



29
30
31
# File 'lib/jsonapionify/api/resource/error_handling.rb', line 29

def error(name, &block)
  self.error_definitions = self.error_definitions.merge name.to_sym => block
end

#error_definitionsObject



55
56
57
58
59
60
61
62
# File 'lib/jsonapionify/api/resource/error_handling.rb', line 55

def error_definitions
  @error_definitions ||= {}
  if superclass.respond_to?(:error_definitions)
    superclass.error_definitions.merge(@error_definitions)
  else
    @error_definitions
  end
end

#error_definitions=(hash) ⇒ Object



51
52
53
# File 'lib/jsonapionify/api/resource/error_handling.rb', line 51

def error_definitions=(hash)
  @error_definitions = hash
end

#register_exception(*klasses, callbacks: false, error:, &block) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/jsonapionify/api/resource/error_handling.rb', line 33

def register_exception(*klasses, callbacks: false, error:, &block)
  block ||= proc {}
  rescue_from(*klasses) do |exception, context|
    evaluate = proc {
      errors.evaluate(
        error_block:   lookup_error(error),
        runtime_block: proc { instance_exec exception, context, &block },
        backtrace:     exception.backtrace
      )
    }
    if callbacks
      run_callbacks :exception, exception, &evaluate
    else
      evaluate.call
    end
  end
end

#sorted_rescue_handlersObject



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/jsonapionify/api/resource/error_handling.rb', line 64

def sorted_rescue_handlers
  handlers           = self.rescue_handlers.dup
  # logic to find invalid order
  out_of_order_class = lambda do |klasses|
    klass_index  = nil
    parent_index = nil
    sort_class   = klasses.find do |klass|
      klass_index  = klasses.find_index { |k| k == klass }
      parent_index = klasses[0..klass_index].find_index { |k| k < klass }
    end
    sort_class ? [klass_index, parent_index] : nil
  end

  # Map handler classes
  klasses            = handlers.map do |klass_name, _|
    klass = self.class.const_get(klass_name) rescue nil
    klass ||= klass_name.constantize rescue nil
    klass
  end.compact

  # Loop until things are ordered
  while (result = out_of_order_class[klasses])
    klass_index, parent_index = result
    handler                   = klasses.delete_at klass_index
    handlers                  = [*handlers[0..parent_index-1], handler, *handlers[parent_index..-1]]
  end
  handlers.reverse
end