Skip to content

Instantly share code, notes, and snippets.

@jamiehodge
Forked from rkh/gist:1900123
Created February 24, 2012 11:20
Show Gist options
  • Save jamiehodge/1900263 to your computer and use it in GitHub Desktop.
Save jamiehodge/1900263 to your computer and use it in GitHub Desktop.
require 'sinatra/base'
module Sinatra
module Exchange
RESPONSE = Struct.new(:status, :headers, :body)
def get_local(path, params={})
r = env['operator'].call(
env.merge(
'SCRIPT_NAME' => '',
'PATH_INFO' => path,
'REQUEST_METHOD' => 'GET',
'QUERY_STRING' => params.collect {|k,v| "#{k}=#{v}"}.join('&')
)
)
RESPONSE.new(*r)
end
end
helpers Exchange
end
class Foo < Sinatra::Base
helpers Sinatra::Exchange
get '/' do
bar = get_local '/bar', fud: 'dud'
"foo says: #{bar.body.join}"
end
end
class Bar < Sinatra::Base
get '/' do
"I am here: #{url('/')}, with these params: #{params}"
end
end
class Operator
def initialize(app, key = 'operator')
@app, @key = app, key
end
def call(env)
@app.call env.merge(@key => @app)
end
end
require 'rack/test'
require 'minitest/autorun'
describe 'App' do
include Rack::Test::Methods
def app
Rack::Builder.new do
use Operator
map '/foo' do
run Foo
end
map '/bar' do
run Bar
end
end
end
it 'must return bar from foo' do
get '/foo'
last_response.body.must_equal 'foo says: I am here: http://example.org/bar/, with these params: {"fud"=>"dud"}'
end
end
require 'sinatra/base'
class TrackMiddleware
def initialize(app, key = "track.middleware") @app, @key = app, key end
def call(env) @app.call env.merge(@key => @app) end
end
class Foo < Sinatra::Base
get '/' do
env['track.middleware'].call(env.merge('SCRIPT_NAME' => '/', 'PATH_INFO' => '/bar'))
end
end
class Bar < Sinatra::Base
get '/' do
'bar'
end
end
builder = Rack::Builder.new do
use TrackMiddleware
map('/foo') { run Foo }
map('/bar') { run Bar }
end
Rack::Handler::Thin.run builder
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment