How to mount multiple Sinatra apps in config.ru

Language: Ruby

# A simple example of mounting multiple Sinatra apps in config.ru

# To run this example:
#   1. put this code in a config.ru file
#   2. run "shotgun" on the command line (http://github.com/rtomayko/shotgun)
#   3. go to http://localhost:9393/

require 'sinatra/base'

class MoonApp < Sinatra::Base
  get '/moon' do
    "Howard Moon"
  end
  
  # this action doesn't return an HTTP response -- it sets an env variable, 
  # and passes, so that another action in this app or another app further 
  # down the Rack pipeline has the opportunity to match this route as well
  get '/' do
    env['moon.message'] = "Hello from Moon"
    pass
  end
end

class NoirApp < Sinatra::Base
  get '/noir' do
    "Vince Noir"
  end
  
  get '/' do
    env['moon.message'] # set in MoonApp
  end
end

# We're mounting MoonApp as a middleware, and NoirApp as as an endpoint.
# This makes sense, because MoonApp is in the middle of the chain, and NoirApp
# is at the end of the line. MoonApp will be checked first for matching routes,
# followed by NoirApp.
use MoonApp
run NoirApp

# When a Sinatra app is run as a middleware, it will call the next app in the Rack
# pipeline when a route is not matched, instead of raising a NotFound error.
# For more on how this actually works, check out the code for the Rack::Builder 
# class and Sinatra::Base#initialize, #call! and #route_missing.
Reveal More
Added over 2 years ago by Devo_normal gbuesing

Refactorings

Re: How to mount multiple Sinatra apps in config.ru (Rack::Cascade example)

Refactoring of: How to mount multiple Sinatra apps in config.ru

Language: Ruby

# A simple example of mounting multiple Sinatra apps in config.ru
# MODIFIED: uses Rack::Cascade

# To run this example:
#   1. put this code in a config.ru file
#   2. run "shotgun" on the command line (http://github.com/rtomayko/shotgun)
#   3. go to http://localhost:9393/

require 'sinatra/base'

class MoonApp < Sinatra::Base
  get '/moon' do
    "Howard Moon"
  end
  
  get '/' do
    env['moon.message'] = "Hello from Moon"
    # pass
    [404, {}, []] # return 404 instead of invoking "pass"
  end
end

class NoirApp < Sinatra::Base
  get '/noir' do
    "Vince Noir"
  end
  
  get '/' do
    env['moon.message'] # set in MoonApp
  end
end

# use MoonApp
# run NoirApp
run Rack::Cascade.new [MoonApp, NoirApp]
Reveal More
Added over 2 years ago by Devo_normal gbuesing