Skip to content

Instantly share code, notes, and snippets.

@erikeldridge
Created March 9, 2011 08:15
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save erikeldridge/861870 to your computer and use it in GitHub Desktop.
Save erikeldridge/861870 to your computer and use it in GitHub Desktop.
require 'router'
use Rack::CommonLogger
use Rack::ShowExceptions
use Rack::Lint
use Rack::Static, :urls => ["/static"]
run Router.new
require 'mustache'
class Default
def self.call(env)
markup = 'Hi {{name}}'
data = {:name => 'Fred'}
html = Mustache.render markup, data
[200, {'Content-Type' => 'text/html'}, html]
end
end
class Foo
def self.call(env)
[200, {'Content-Type' => 'text/plain'}, 'foo']
end
end
class Router
def initialize(path='routes.yaml')
@routes = YAML.load_file path
end
def call(env)
# Lookup path in routes hash.
path = env['PATH_INFO']
until @routes.has_key? path do
# Chop off nested directories until we have a hit or ...
path = path.rpartition('/').first
# ... path is empty, in which case, default to root
path = '/' if path.empty?
end
# Load controller definition.
require @routes[path]
# Resolve controller's class name, eg '/foo : foo' --> "Foo".
class_name = @routes[path].capitalize
# Controller must be a valid Rack app.
Kernel.const_get(class_name).call env
end
end
---
/ : default
/foo : foo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment