Class: Koi::Middleware::UrlRedirect

Inherits:
Object
  • Object
show all
Defined in:
lib/koi/middleware/url_redirect.rb

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ UrlRedirect

Returns a new instance of UrlRedirect.



6
7
8
# File 'lib/koi/middleware/url_redirect.rb', line 6

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/koi/middleware/url_redirect.rb', line 10

def call(env)
  status, headers, body = @app.call(env)

  current_path = env["REQUEST_URI"]

  if status.to_i == 404 && (redirect = UrlRewrite.active.find_by(from: current_path))
    request = ActionDispatch::Request.new(env)

    # Close the body as we will not use it for a 301 redirect
    body.close

    # Return a redirect response
    [redirect.status_code, { "Location" => new_location(current_path, redirect.to, request) },
     ["#{redirect.from} moved. The document has moved to #{redirect.to}"]]
  else
    # Not a 404 or no redirect found, just send the response as is
    [status, headers, body]
  end
end