Skip to content

Instantly share code, notes, and snippets.

@pooya-raz
Forked from erikeldridge/config.ru
Created September 8, 2011 06:26
Show Gist options
  • Save pooya-raz/1202770 to your computer and use it in GitHub Desktop.
Save pooya-raz/1202770 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