Class: Utopia::Redirection::Errors

Inherits:
Object
  • Object
show all
Defined in:
lib/utopia/redirection.rb

Overview

A middleware which performs internal redirects based on error status codes.

Instance Method Summary collapse

Constructor Details

#initialize(app, codes = {}) ⇒ Errors

Returns a new instance of Errors.

Parameters:

  • codes (Hash<Integer,String>) (defaults to: {})

    The redirection path for a given error code.



27
28
29
30
# File 'lib/utopia/redirection.rb', line 27

def initialize(app, codes = {})
  @app = app
  @codes = codes
end

Instance Method Details

#call(env) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/utopia/redirection.rb', line 44

def call(env)
  response = @app.call(env)
  
  if unhandled_error?(response) && location = @codes[response[0]]
    error_request = env.merge(Rack::PATH_INFO => location, Rack::REQUEST_METHOD => Rack::GET)
    error_response = @app.call(error_request)
    
    if error_response[0] >= 400
      raise RequestFailure.new(env[Rack::PATH_INFO], response[0], location, error_response[0])
    else
      # Feed the error code back with the error document:
      error_response[0] = response[0]
      return error_response
    end
  else
    return response
  end
end

#freezeObject



32
33
34
35
36
37
38
# File 'lib/utopia/redirection.rb', line 32

def freeze
  return self if frozen?
  
  @codes.freeze
  
  super
end

#unhandled_error?(response) ⇒ Boolean

Returns:

  • (Boolean)


40
41
42
# File 'lib/utopia/redirection.rb', line 40

def unhandled_error?(response)
  response[0] >= 400 && response[1].empty?
end