Motivation

Requirements/Environment

Code

[sourcecode lang=“ruby”] class Router def initialize(routes) @routes = routes end def default [ 404, {‘Content-Type’ => ’text/plain’}, ‘file not found’ ] end def call(env) @routes.each do |route| match = env[‘REQUEST_PATH’].match(route[:pattern]) if match return route[:controller].call( env, match ) end end default end end [/sourcecode]

Usage

[sourcecode lang=“ruby”] # assumes router code is in router.rb require ‘router’

use Rack::CommonLogger use Rack::ShowExceptions use Rack::Lint use Rack::Static, :urls => ["/static"]

run Router.new([ { :pattern => %r{^/page1$}, :controller => lambda do |env, match|

[ 200, {‘Content-Type’ => ’text/html’}, ‘page 1’ ]

end }, { :pattern => %r{^/}, :controller => lambda do |env, match|

[ 200, {‘Content-Type’ => ’text/html’}, ‘index!’ ]

end }

]); [/sourcecode]

Run it on the command line using Rack’s native Rackup ( $ rackup config.ru) or via Ryan Tomayko’s shotgun, which conveniently auto-reloads.

Reference

Update Mar 5, 2011

Update Mar 9, 2011