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.

Constant Summary collapse

CONTENT_TYPE =
'Content-Type'.freeze

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.



42
43
44
45
# File 'lib/utopia/redirection.rb', line 42

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

Instance Method Details

#call(env) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/utopia/redirection.rb', line 61

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



47
48
49
50
51
52
53
# File 'lib/utopia/redirection.rb', line 47

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

#unhandled_error?(response) ⇒ Boolean

Returns:

  • (Boolean)


57
58
59
# File 'lib/utopia/redirection.rb', line 57

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