Class: Appfuel::ResponseHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/appfuel/response_handler.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(response_class = Response) ⇒ ResponseHandler



5
6
7
# File 'lib/appfuel/response_handler.rb', line 5

def initialize(response_class = Response)
  @response_class = response_class
end

Instance Attribute Details

#response_classObject (readonly)

Returns the value of attribute response_class.



3
4
5
# File 'lib/appfuel/response_handler.rb', line 3

def response_class
  @response_class
end

Instance Method Details

#create_response(data) ⇒ Object



9
10
11
12
13
# File 'lib/appfuel/response_handler.rb', line 9

def create_response(data)
  return data        if response?(data)
  return error(data) if error_data?(data)
  ok(data)
end

#error(*args) ⇒ Object

Convert a number of different error formats into hash and use that to build the response



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/appfuel/response_handler.rb', line 49

def error(*args)
  error = args.shift
  case
  when error.kind_of?(ActiveModel::Errors)
    messages = error.messages
  when error.kind_of?(StandardError)
    key = error.class.to_s.underscore.to_sym
    backtrace_key = "#{key}_backtrace".to_sym
    messages = {
      errors: {
        key => [error.message],
        backtrace_key => error.backtrace || []
      }
    }
  when error.is_a?(Hash)
    messages = error.key?(:errors) ? error : {errors: error}
  when error.is_a?(Errors)
    messages = error.to_h

  when args.length >= 1
    messages = {errors: {error => args}}
  when error.is_a?(response_class)
    return error
  else
    messages = {errors: {general_error: [error.to_s]}}
  end

  response_class.error(messages)
end

#error_data?(data) ⇒ Boolean

Determine if the data given is an error by looking at its class or checking if it is a hash with the key :errors



24
25
26
27
28
29
30
31
32
33
# File 'lib/appfuel/response_handler.rb', line 24

def error_data?(data)
  case
  when data.kind_of?(::StandardError) || data.is_a?(Errors)
    true
  when data.is_a?(Hash)
    data.key?(:errors)
  else
    false
  end
end

#ok(value = nil) ⇒ Object

This is used when returning results back to the action handler. We use this to indicate it was a successful response



40
41
42
# File 'lib/appfuel/response_handler.rb', line 40

def ok(value = nil)
  response_class.ok(value)
end

#response?(data) ⇒ Boolean



15
16
17
# File 'lib/appfuel/response_handler.rb', line 15

def response?(data)
  data.is_a?(response_class)
end