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:

  • (defaults to: {})

    The redirection path for a given error code.



44
45
46
47
# File 'lib/utopia/redirection.rb', line 44

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

Instance Method Details

#call(env) ⇒ Object



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

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



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

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

#unhandled_error?(response) ⇒ Boolean

Returns:



59
60
61
# File 'lib/utopia/redirection.rb', line 59

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