Created
August 4, 2011 15:55
-
-
Save timuruski/1125503 to your computer and use it in GitHub Desktop.
Different ways to stack Rack middleware
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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]) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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