Skip to content

Instantly share code, notes, and snippets.

@timuruski
Created August 4, 2011 15:55
Show Gist options
  • Select an option

  • Save timuruski/1125503 to your computer and use it in GitHub Desktop.

Select an option

Save timuruski/1125503 to your computer and use it in GitHub Desktop.
Different ways to stack Rack middleware
require 'sinatra'
class AppBase < Sinatra::Base
def body
<<-EOS
<pre>
request_path: #{request.env['REQUEST_PATH']}
path_info: #{request.path_info}
</pre>
EOS
end
end
require './app_base'
class AppA < AppBase
get '/test' do
body
end
end
class AppB < AppBase
get '/test' do
body
end
end
# Use the Rack::Builder DSL to construct a router,
# mapping each prefix to the desired app.
app = Rack::Builder.new do
map '/a' do
run AppA.new
end
map '/b' do
run AppB.new
end
end
run app
require './app_base'
class AppA < AppBase
before do
if request.path_info.start_with?('/a/')
request.path_info = request.path_info.sub(/^\/a\//, '/')
else
halt 404
end
end
get '/test' do
body
end
end
class AppB < AppBase
before do
if request.path_info.start_with?('/b/')
request.path_info = request.path_info.sub(/^\/b\//, '/')
else
halt 404
end
end
get '/test' do
body
end
end
# Each app explicitly handles a prefix, the
# Rack::Cascade tries each app until something
# doesn't return 404
run Rack::Cascade.new([AppA,AppB])
require './app_base'
class AppA < AppBase
get '/test' do
body
end
end
class AppB < AppBase
get '/test' do
body
end
end
# Manually map each app to a prefix route.
map '/a' do
run AppA.new
end
map '/b' do
run AppB.new
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment