Guest User

Untitled

a guest
Feb 20th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. require "rubygems"
  2. require "rack"
  3. require "delegate"
  4.  
  5. module Sinatra
  6.  
  7. class Builder < Rack::Builder
  8. Fall = 99
  9.  
  10. class EventContext < DelegateClass(Hash)
  11.  
  12. attr_reader :request, :response
  13.  
  14. def initialize(env)
  15. @request = Rack::Request.new(env)
  16. @response = Rack::Response.new
  17. super(env)
  18. end
  19.  
  20. def fall
  21. response.status = Fall
  22. self.body
  23. end
  24.  
  25. def method_missing(s, *args, &blk)
  26. @response.send(s, *args, &blk)
  27. end
  28. end
  29.  
  30. attr_reader :context
  31.  
  32. def initialize(&blk)
  33. @cascade = Rack::Cascade.new([], Fall)
  34. super(&blk)
  35. run @cascade
  36. end
  37.  
  38. def raw_filter(&blk)
  39. @cascade << blk
  40. end
  41.  
  42. def filter(&blk)
  43. raw_filter do |cx|
  44. cx.status = 200 if cx.status == Fall
  45. cx.body = cx.instance_eval(&blk)
  46. cx.finish
  47. end
  48. end
  49.  
  50. def get(match_path, &blk)
  51. filter do
  52. if match_path == request.path_info
  53. instance_eval(&blk)
  54. else
  55. fall
  56. end
  57. end
  58. end
  59.  
  60. def map2(path = '*', &blk)
  61. instance_eval(&blk)
  62. end
  63. alias :group :map2
  64.  
  65. def call(env)
  66. status, *_ = *super(EventContext.new(env))
  67. [status == Fall ? 404 : status, *_]
  68. end
  69. end
  70. end
  71.  
  72. ## ~ 3200 req/sec
  73. # R = Rack::Builder.new do
  74. #
  75. # app1 = lambda { |env|
  76. # req = Rack::Request.new(env)
  77. # res = Rack::Response.new
  78. # if req.path_info == '/'
  79. # res.body = 'rack'
  80. # res.finish
  81. # else
  82. # res.status = 404
  83. # res.body = ''
  84. # res.finish
  85. # end
  86. # }
  87. #
  88. # run Rack::Cascade.new([app1])
  89. #
  90. # end
  91.  
  92. ## ~ 2200 req/sec
  93.  
  94. class MW
  95.  
  96. end
  97.  
  98. R = Sinatra::Builder.new do
  99.  
  100. use Rack::CommonLogger
  101.  
  102. get '/bar' do
  103. 'rack'
  104. end
  105.  
  106. end
  107.  
  108. R.get '/foo' do
  109. 'foobar!'
  110. end
  111.  
  112. if $0 == __FILE__
  113. require File.dirname(__FILE__) + "/helper"
  114. p R.call(Rack::MockRequest.env_for('/'))
  115. end
Add Comment
Please, Sign In to add comment