Permalink
Browse files

wrap sinatra stack for nicer handling, fixes #496

  • Loading branch information...
1 parent 97e1bd2 commit f9b1c60ae4686ea2991f4644f92733d271d61072 @rkh rkh committed May 13, 2012
Showing with 47 additions and 1 deletion.
  1. +5 −0 CHANGES
  2. +24 −1 lib/sinatra/base.rb
  3. +18 −0 test/base_test.rb
View
5 CHANGES
@@ -17,6 +17,11 @@
* Status, headers and body will be set correctly in an after filter when using
halt in a before filter or route. (Konstantin Haase)
+ * Sinatra::Base.new now returns a Sinatra::Wrapper instance, exposing
+ #settings and #helpers, yet going through the middleware stack on #call.
+ It also implements a nice #inspect, so it plays nice with Rails' `rake
+ routes`. (Konstantin Haase)
+
= 1.3.3 / Not Yet Released
* When keeping a stream open, set up callback/errback correctly to deal with
View
25 lib/sinatra/base.rb
@@ -1409,7 +1409,8 @@ def prototype
# pipeline. The object is guaranteed to respond to #call but may not be
# an instance of the class new was called on.
def new(*args, &bk)
- build(new!(*args, &bk)).to_app
+ instance = new!(*args, &bk)
+ Wrapper.new(build(instance).to_app, instance)
end
# Creates a Rack::Builder instance with all the middleware set up and
@@ -1724,6 +1725,28 @@ class << self
self.target = Application
end
+ class Wrapper
+ def initialize(stack, instance)
+ @stack, @instance = stack, instance
+ end
+
+ def settings
+ @instance.settings
+ end
+
+ def helpers
+ @instance
+ end
+
+ def call(env)
+ @stack.call(env)
+ end
+
+ def inspect
+ "#<#{@instance.class} app_file=#{settings.app_file.inspect}>"
+ end
+ end
+
# Create a new Sinatra application. The block is evaluated in the new app's
# class scope.
def self.new(base=Base, options={}, &block)
View
18 test/base_test.rb
@@ -56,6 +56,24 @@ class TestApp < Sinatra::Base
end
end
+ describe "Sinatra::Base#new" do
+ it 'returns a wrapper' do
+ assert_equal Sinatra::Wrapper, Sinatra::Base.new.class
+ end
+
+ it 'implements a nice inspect' do
+ assert_equal '#<Sinatra::Base app_file=nil>', Sinatra::Base.new.inspect
+ end
+
+ it 'exposes settings' do
+ assert_equal Sinatra::Base.settings, Sinatra::Base.new.settings
+ end
+
+ it 'expses helpers' do
+ assert_equal 'image/jpeg', Sinatra::Base.new.helpers.mime_type(:jpg)
+ end
+ end
+
describe "Sinatra::Base as Rack middleware" do
app = lambda { |env|
headers = {'X-Downstream' => 'true'}

0 comments on commit f9b1c60

Please sign in to comment.