Class: Dandy::SafeExecutor

Inherits:
Object
  • Object
show all
Defined in:
lib/dandy/safe_executor.rb

Instance Method Summary collapse

Constructor Details

#initialize(container, dandy_config, view_factory) ⇒ SafeExecutor

Returns a new instance of SafeExecutor.



5
6
7
8
9
# File 'lib/dandy/safe_executor.rb', line 5

def initialize(container, dandy_config, view_factory)
  @container = container
  @dandy_config = dandy_config
  @view_factory = view_factory
end

Instance Method Details

#execute(route, headers) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/dandy/safe_executor.rb', line 11

def execute(route, headers)
  chain = Chain.new(@container, @dandy_config)

  begin
    result = chain.run_commands(route.commands, route.last_command)
    if route.view
      result = @view_factory.create(route.view, headers['Accept'], {keys_format: headers['Keys-Format'] || 'snake'})
    end

    body = result.is_a?(String) ? result : Response.format(result, headers)
  rescue Exception => error
    p error
    body = handle_error(route, headers, error)
  end

  body
end

#handle_error(route, headers, error) ⇒ Object



29
30
31
32
33
34
35
36
37
# File 'lib/dandy/safe_executor.rb', line 29

def handle_error(route, headers, error)
  @container
    .register_instance(error, :dandy_error)
    .using_lifetime(:scope)
    .bound_to(:dandy_request)

  action = @container.resolve(route.catch.name.to_sym)
  Response.format(action.call, headers)
end