Skip to content

Instantly share code, notes, and snippets.

@nu7hatch
Created September 30, 2010 22:42
Show Gist options
  • Save nu7hatch/605456 to your computer and use it in GitHub Desktop.
Save nu7hatch/605456 to your computer and use it in GitHub Desktop.
require "rubygems"
require "sinatra/base"
require "padrino"
class Foo < Sinatra::Base
get("/bar") {
"Hello world!"
}
end
class Bar < Padrino::Application
disable :debug
get("/bar") {
"Hello world!"
}
end
module Rack
class Mountable
attr_reader :app, :path, :host, :port, :name
def initialize(app)
@app = app
end
def to(path)
@path = "^/#{path}(.*)".gsub(%r{^\^//}, "^/")
return self
end
def as(name)
@name = name
return self
end
def bind(url)
@host, @port = url.split(":")
@host = @host.gsub('*', '.*').gsub('.', '\.')
return self
end
end
class Mounter
def initialize(&block)
@mountables = []
instance_eval(&block) if block_given?
end
def mountables
@mountables
end
def mount(app)
@mountables << (mnt = Mountable.new(app)) and return mnt
end
def call(env)
path, script, host, port, name = env.values_at \
'PATH_INFO', 'SCRIPT_NAME', 'HTTP_HOST', 'SERVER_PORT', 'SERVER_NAME'
threads = []
@mountables.each do |mnt|
next if mnt.host && (!host.match(mnt.host) || !name.match(mnt.host))
next if mnt.port && (mnt.port.to_i != port.to_i)
next if mnt.path.nil? || !(match = path.match(mnt.path))
env.merge!(
'SCRIPT_NAME' => script + match[0],
'PATH_INFO' => "/#{match[-1]}".gsub(%r{^//}, "/")
)
return mnt.app.call(env)
end
[404, {"Content-Type" => "text/plain", "X-Cascade" => "pass"}, ["Not Found: #{path}"]]
end
end
end
module Padrino
#class Mounter < Rack::Mounter
#end
class << self
def builder
@builder ||= Rack::Builder.new { run Rack::Mounter.new }
end
alias :application :builder
def mount(app)
builder.to_app.mount(app)
end
end
end
Padrino.mount(Foo).bind("localhost").to("/")
Padrino.mount(Bar).bind("*.example.com").to("/foo")
Padrino.mount(Foo).bind("example.com").to("/")
run Padrino.builder
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment