Class: Mongrel::RedirectHandler

Inherits:
HttpHandler show all
Defined in:
lib/mongrel/handlers.rb

Overview

This handler allows you to redirect one url to another. You can use it like String#gsub, where the string is the REQUEST_URI. REQUEST_URI is the full path with GET parameters.

Eg. /test/something?help=true&disclaimer=false

Examples

h = Mongrel::HttpServer.new('0.0.0.0')
h.register '/test', Mongrel::RedirectHandler.new('/to/there') # simple
h.register '/to',   Mongrel::RedirectHandler.new(/t/, 'w') # regexp
# and with a block
h.register '/hey',  Mongrel::RedirectHandler.new(/(\w+)/) { |match| ... }

Instance Attribute Summary

Attributes inherited from HttpHandler

#listener, #request_notify

Instance Method Summary collapse

Methods inherited from HttpHandler

#request_begins, #request_progress

Constructor Details

#initialize(pattern, replacement = nil, &block) ⇒ RedirectHandler

You set the rewrite rules when building the object.

pattern => What to look for or replacement if used alone

replacement, block => One of them is used to replace the found text


446
447
448
449
450
451
452
# File 'lib/mongrel/handlers.rb', line 446

def initialize(pattern, replacement = nil, &block)
  unless replacement or block
    @pattern, @replacement = nil, pattern
  else
    @pattern, @replacement, @block = pattern, replacement, block
  end
end

Instance Method Details

#process(request, response) ⇒ Object

Process the request and return a redirect response


455
456
457
458
459
460
461
462
463
464
465
466
# File 'lib/mongrel/handlers.rb', line 455

def process(request, response)
  unless @pattern
    response.socket.write(Mongrel::Const::REDIRECT % @replacement)
  else
    if @block
      new_path = request.params['REQUEST_URI'].gsub(@pattern, &@block)
    else
      new_path = request.params['REQUEST_URI'].gsub(@pattern, @replacement)
    end
    response.socket.write(Mongrel::Const::REDIRECT % new_path)
  end
end