Module: Cargobull::Dispatch

Defined in:
lib/cargobull/dispatch.rb

Constant Summary collapse

METHOD_MAP =
{
  "GET" => :read,
  "POST" => :create,
  "PATCH" => :update,
  "PUT" => :update,
  "DELETE" => :delete
}

Class Method Summary collapse

Class Method Details

.call(env, method, action, *params) ⇒ Object



22
23
24
25
# File 'lib/cargobull/dispatch.rb', line 22

def self.call(env, method, action, *params)
  dispatch(env, env[:transform_in], env[:transform_out], method, action,
    *params)
end

.dispatch(env, tfin, tfout, method, action, *params) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/cargobull/dispatch.rb', line 27

def self.dispatch(env, tfin, tfout, method, action, *params)
  klass = translate_action_call(env, action)
  return klass if klass.is_a?(Array) # break on error
  klass = klass.constantize

  method = translate_method_call(env, method)
  return method if method.is_a?(Array) # break on error

  params = tfin.call(*params) if tfin

  obj = klass.is_a?(Class) ? klass.new : klass

  return obj.respond_to?(method) ?
    transform(env, obj.send(method, *params), &tfout) :
    [404, { "Content-Type" => env[:ctype] }, env[:e404]]
end

.transform(env, data) ⇒ Object



44
45
46
47
48
# File 'lib/cargobull/dispatch.rb', line 44

def self.transform(env, data)
  data = yield(data) if block_given?
  return data.is_a?(Array) && data.count == 3 ? data :
    [200, { "Content-Type" => env[:ctype] }, data]
end

.translate_action_call(env, action) ⇒ Object



17
18
19
20
# File 'lib/cargobull/dispatch.rb', line 17

def self.translate_action_call(env, action)
  Service.dispatch_to(action) ||
    [404, { "Content-Type" => env[:ctype] }, env[:e404] ]
end

.translate_method_call(env, method) ⇒ Object



12
13
14
15
# File 'lib/cargobull/dispatch.rb', line 12

def self.translate_method_call(env, method)
  METHOD_MAP[method.to_s] ||
    [405, { "Content-Type" => env[:ctype] }, env[:e405] ]
end