Created
November 15, 2008 01:06
-
-
Save bmizerany/25168 to your computer and use it in GitHub Desktop.
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 "rubygems" | |
| require "rack" | |
| require "delegate" | |
| module Sinatra | |
| class Builder < Rack::Builder | |
| Fall = 99 | |
| class EventContext < DelegateClass(Hash) | |
| attr_reader :request, :response | |
| def initialize(env) | |
| @request = Rack::Request.new(env) | |
| @response = Rack::Response.new | |
| super(env) | |
| end | |
| def fall | |
| response.status = Fall | |
| self.body | |
| end | |
| def method_missing(s, *args, &blk) | |
| @response.send(s, *args, &blk) | |
| end | |
| end | |
| attr_reader :context | |
| def initialize(&blk) | |
| @cascade = Rack::Cascade.new([], Fall) | |
| super(&blk) | |
| run @cascade | |
| end | |
| def raw_filter(&blk) | |
| @cascade << blk | |
| end | |
| def filter(&blk) | |
| raw_filter do |cx| | |
| cx.status = 200 if cx.status == Fall | |
| cx.body = cx.instance_eval(&blk) | |
| cx.finish | |
| end | |
| end | |
| def get(match_path, &blk) | |
| filter do | |
| if match_path == request.path_info | |
| instance_eval(&blk) | |
| else | |
| fall | |
| end | |
| end | |
| end | |
| def map2(path = '*', &blk) | |
| instance_eval(&blk) | |
| end | |
| alias :group :map2 | |
| def call(env) | |
| status, *_ = *super(EventContext.new(env)) | |
| [status == Fall ? 404 : status, *_] | |
| end | |
| end | |
| end | |
| ## ~ 3200 req/sec | |
| # R = Rack::Builder.new do | |
| # | |
| # app1 = lambda { |env| | |
| # req = Rack::Request.new(env) | |
| # res = Rack::Response.new | |
| # if req.path_info == '/' | |
| # res.body = 'rack' | |
| # res.finish | |
| # else | |
| # res.status = 404 | |
| # res.body = '' | |
| # res.finish | |
| # end | |
| # } | |
| # | |
| # run Rack::Cascade.new([app1]) | |
| # | |
| # end | |
| ## ~ 2200 req/sec | |
| class MW | |
| end | |
| R = Sinatra::Builder.new do | |
| use Rack::CommonLogger | |
| get '/bar' do | |
| 'rack' | |
| end | |
| end | |
| R.get '/foo' do | |
| 'foobar!' | |
| end | |
| if $0 == __FILE__ | |
| require File.dirname(__FILE__) + "/helper" | |
| p R.call(Rack::MockRequest.env_for('/')) | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment