Skip to content

Commit

Permalink
I knew I shoulda taken that left turn at Hoboken
Browse files Browse the repository at this point in the history
This is a fairly large reworking of Sinatra's innards. Although
most of the internal implementation has been modified, it
provides the same basic feature set and is meant to be compatible
with Sinatra 0.3.2.

* The Event and EventContext classes have been removed. Sinatra
  applications are now defined within the class context of a
  Sinatra::Base subclass; each request is processed within a new
  instance.

* Sinatra::Base can be used as a base class for multiple
  Rack applications within a single process and can be used as
  Rack middleware.

* The routing and result type processing implementation has been
  simplified and enhanced a bit. There's a new route conditions
  system for things like :agent/:host matching and a request
  level #pass method has been added to allow an event handler to
  exit immediately, passing control to the next matching route.

* Regular expressions may now be used in route patterns. Captures
  are available as an array from "params[:captures]".

* The #body helper method now takes a block. The block is not
  evaluated until an attempt is made to read the body.

* Options are now dynamically generated class attributes on the
  Sinatra::Base subclass (instead of OpenStruct); options are
  inherited by subclasses and may be overridden up the
  inheritance hierarchy. The Base.set manages all option related
  stuff.

* The application file (app_file) detection heuristics are bit
  more sane now. This fixes some bugs with reloading and
  public/views directory detection. All thin / passenger issues
  of these type should be better now.

* Error mappings are now split into to distinct layers: exception
  mappings and custom error pages. Exception mappings are registered
  with 'error(Exception)' and are run only when the app raises an
  exception. Custom error pages are registered with error(status_code)
  and are run any time the response has the status code specified.
  It's also possible to register an error page for a range of status
  codes: 'error(500..599)'.

* The spec and unit testing extensions have been modified to take
  advantage of the ability to have multiple Sinatra applications.
  The Sinatra::Test module must be included within the TestCase
  in order to take advantage of these methods (unless the
  'sinatra/compat' library has been required).

* Rebuilt specs from scratch for better coverage and
  organization. Sinatra 3.2 unit tests have been retained
  under ./compat to ensure a baseline level of compatibility with
  previous versions; use the 'rake compat' task to run these.

A large number of existing Sinatra idioms have been deprecated but
continue to be supported through the 'sinatra/compat' library.

* The "set_option" and "set_options" methods have been deprecated
  due to redundancy; use "set".

* The "env" option (Sinatra::Base.env) has been renamed to "environment"
  and deprecated because it's too easy to confuse with the request-level
  Rack environment Hash (Sinatra::Base#env).

* The request level "stop" method has been renamed "halt" and
  deprecated. This is for consistency with `throw :halt`.

* The request level "entity_tag" method has been renamed "etag" and
  deprecated. Both versions were previously supported.

* The request level "headers" method has been deprecated. Use
  response['Header-Name'] to access and modify response headers.

* Sinatra.application is deprecated. Use Sinatra::Application instead.

* Setting Sinatra.application = nil to reset an application is
  deprecated. You shouldn't have to reset objects anymore.

* The Sinatra.default_options Hash is deprecated. Modifying this object now
  results in "set(key, value)" invocations on the Sinatra::Base
  subclass.

* The "body.to_result" convention has been deprecated.

* The ServerError exception has been deprecated. Any Exception is now
  considered a ServerError.
  • Loading branch information
rtomayko committed Dec 21, 2008
1 parent d25e020 commit a734cf3
Show file tree
Hide file tree
Showing 77 changed files with 3,297 additions and 2,237 deletions.
73 changes: 27 additions & 46 deletions README.rdoc
Expand Up @@ -36,16 +36,12 @@ Run with <tt>ruby myapp.rb</tt> and view at <tt>http://localhost:4567</tt>

end

NOTE: <tt>put</tt> and <tt>delete</tt> are also triggered when a
<tt>_method</tt> parameter is set to PUT or DELETE and the HTTP request method
is POST

== Routes

Routes are matched based on the order of declaration. The first route that
matches the request is invoked.

Simple:
Basic routes:

get '/hi' do
...
Expand All @@ -54,19 +50,20 @@ Simple:
Named parameters:

get '/:name' do
# matches /sinatra and the like and sets params[:name]
# matches "GET /foo" and "GET /bar"
# params[:name] is 'foo' or 'bar'
end

Splat parameters:

get '/say/*/to/*' do
# matches /say/hello/to/world
params["splat"] # => ["hello", "world"]
params[:splat] # => ["hello", "world"]
end

get '/download/*.*' do
# matches /download/path/to/file.xml
params["splat"] # => ["path/to/file", "xml"]
params[:splat] # => ["path/to/file", "xml"]
end

User agent matching:
Expand All @@ -76,25 +73,29 @@ User agent matching:
end

get '/foo' do
# matches non-songbird browsers
# Matches non-songbird browsers
end

== Static files
== Static Files

Put all of your static content in the ./public directory

root
\ public

If a file exists that maps to the REQUEST_PATH then it is served and the
request ends. Otherwise, Sinatra will look for an event that matches the
path.
To use a different static directory:

set :public, File.dirname(__FILE__) + '/static'

== Views

Views are searched for in a "views" directory in the same location as
Views are searched for in a ./views directory in the same location as
your main application.

To use a different views directory:

set :views, File.dirname(__FILE__) + '/templates'

=== Haml Templates

get '/' do
Expand Down Expand Up @@ -190,8 +191,7 @@ method:

== Helpers

The top-level <tt>helpers</tt> method takes a block and extends all
EventContext instances with the methods defined:
The top-level <tt>helpers</tt> method

helpers do
def bar(name)
Expand All @@ -205,27 +205,27 @@ EventContext instances with the methods defined:

== Filters

These are run in Sinatra::EventContext before every event.
Before filters are evaluated in request context before routing is performed:

before do
.. this code will run before each event ..
@note = 'Hi!'
request.path_info = '/foo/bar/baz'
end

get '/foo/*' do
@note #=> 'Hi!'
params[:splat] #=> 'bar/baz'
end

Before filters can modify the request and response; instance variables are
available to routes.

== Halt!

To immediately stop a request during a before filter or event use:

throw :halt

Set the body to the result of a helper method

throw :halt, :helper_method

Set the body to the result of a helper method after sending it parameters from
the local scope

throw :halt, [:helper_method, foo, bar]

Set the body to a simple string

throw :halt, 'this will be the body'
Expand All @@ -234,30 +234,11 @@ Set status then the body

throw :halt, [401, 'go away!']

Set the status then call a helper method with params from local scope

throw :halt, [401, [:helper_method, foo, bar]]

Run a proc inside the Sinatra::EventContext instance and set the body to the
result

throw :halt, lambda { puts 'In a proc!'; 'I just wrote to $stdout!' }

Create you own to_result

class MyResultObject
def to_result(event_context, *args)
event_context.body = 'This will be the body!
end
end

get '/' do
throw :halt, MyResultObject.new
end

Get the gist? If you want more fun with this then checkout <tt>to_result</tt>
on Array, Symbol, Fixnum, NilClass.

== Configuration and Reloading

Sinatra supports multiple environments and reloading. Reloading happens
Expand Down
14 changes: 10 additions & 4 deletions Rakefile
Expand Up @@ -8,13 +8,19 @@ task :default => :test

desc 'Run specs with story style output'
task :spec do
sh 'specrb --specdox -Ilib:test test/*_test.rb'
pattern = ENV['TEST'] || '.*'
sh "specrb --testcase '#{pattern}' --specdox -Ilib:test test/*_test.rb"
end

desc 'Run specs with unit test style output'
task :test => FileList['test/*_test.rb'] do |t|
suite = t.prerequisites.map{|f| "-r#{f.chomp('.rb')}"}.join(' ')
sh "ruby -Ilib:test #{suite} -e ''", :verbose => false
task :test do |t|
sh "specrb -Ilib:test test/*_test.rb"
end

desc 'Run compatibility specs'
task :compat do |t|
pattern = ENV['TEST'] || '.*'
sh "specrb --testcase '#{pattern}' -Ilib:test compat/*_test.rb"
end

# PACKAGING ============================================================
Expand Down
21 changes: 11 additions & 10 deletions test/app_test.rb → compat/app_test.rb
Expand Up @@ -108,7 +108,9 @@
end

specify "renders a body with a redirect" do
Sinatra::EventContext.any_instance.expects(:foo).returns('blah')
helpers do
def foo ; 'blah' ; end
end
get "/" do
redirect 'foo', :foo
end
Expand All @@ -130,13 +132,10 @@
end

specify "stop sets content and ends event" do

Sinatra::EventContext.any_instance.expects(:foo).never

get '/set_body' do
stop 'Hello!'
stop 'World!'
foo
fail 'stop should have halted'
end

get_it '/set_body'
Expand All @@ -146,8 +145,13 @@

end

specify "should set status then call helper with a var" do
Sinatra::EventContext.any_instance.expects(:foo).once.with(1).returns('bah!')
# Deprecated. WTF was going on here? What's the 1 in [:foo, 1] do?
xspecify "should set status then call helper with a var" do
helpers do
def foo
'bah!'
end
end

get '/set_body' do
stop [404, [:foo, 1]]
Expand Down Expand Up @@ -252,8 +256,6 @@
assert_equal 'puted', body
end

# Some Ajax libraries downcase the _method parameter value. Make
# sure we can handle that.
specify "rewrites POSTs with lowercase _method param to PUT" do
put '/' do
'puted'
Expand All @@ -262,7 +264,6 @@
body.should.equal 'puted'
end

# Ignore any _method parameters specified in GET requests or on the query string in POST requests.
specify "does not rewrite GETs with _method param to PUT" do
get '/' do
'getted'
Expand Down
15 changes: 10 additions & 5 deletions test/application_test.rb → compat/application_test.rb
Expand Up @@ -16,7 +16,8 @@ def each
Sinatra.application = nil
end

specify "returns what's at the end" do
# Deprecated. The lookup method is no longer used.
xspecify "returns what's at the end" do
block = Proc.new { 'Hello' }
get '/', &block

Expand All @@ -31,7 +32,8 @@ def each
result.block.should.be block
end

specify "takes params in path" do
# Deprecated. The lookup method is no longer used.
xspecify "takes params in path" do
block = Proc.new { 'Hello' }
get '/:foo', &block

Expand Down Expand Up @@ -83,7 +85,8 @@ def each

end

specify "the body set if set before the last" do
# Deprecated. The body method no longer halts.
xspecify "the body set if set before the last" do

get '/' do
body 'Blake'
Expand Down Expand Up @@ -142,14 +145,16 @@ def each

context "Default Application Configuration" do

specify "includes 404 and 500 error handlers" do
# Sinatra::ServerError is no longer used
xspecify "includes 404 and 500 error handlers" do
Sinatra.application.errors.should.include(Sinatra::ServerError)
Sinatra.application.errors[Sinatra::ServerError].should.not.be.nil
Sinatra.application.errors.should.include(Sinatra::NotFound)
Sinatra.application.errors[Sinatra::NotFound].should.not.be.nil
end

specify "includes Static event" do
# Deprecated. No such thing as a Static event anymore.
xspecify "includes Static event" do
assert Sinatra.application.events[:get].any? { |e| Sinatra::Static === e }
end

Expand Down
101 changes: 101 additions & 0 deletions compat/builder_test.rb
@@ -0,0 +1,101 @@
require File.dirname(__FILE__) + '/helper'

context "Builder" do

setup do
Sinatra.application = nil
end

context "without layouts" do

setup do
Sinatra.application = nil
end

specify "should render" do

get '/no_layout' do
builder 'xml.instruct!'
end

get_it '/no_layout'
should.be.ok
body.should == %(<?xml version="1.0" encoding="UTF-8"?>\n)

end

specify "should render inline block" do

get '/no_layout_and_inlined' do
@name = "Frank & Mary"
builder do |xml|
xml.couple @name
end
end

get_it '/no_layout_and_inlined'
should.be.ok
body.should == %(<couple>Frank &amp; Mary</couple>\n)

end

end



context "Templates (in general)" do

setup do
Sinatra.application = nil
end

specify "are read from files if Symbols" do

get '/from_file' do
@name = 'Blue'
builder :foo, :views_directory => File.dirname(__FILE__) + "/views"
end

get_it '/from_file'
should.be.ok
body.should.equal %(<exclaim>You rock Blue!</exclaim>\n)

end

specify "use layout.ext by default if available" do

get '/' do
builder :foo, :views_directory => File.dirname(__FILE__) + "/views/layout_test"
end

get_it '/'
should.be.ok
body.should.equal "<layout>\n<this>is foo!</this>\n</layout>\n"

end

specify "renders without layout" do

get '/' do
builder :no_layout, :views_directory => File.dirname(__FILE__) + "/views/no_layout"
end

get_it '/'
should.be.ok
body.should.equal "<foo>No Layout!</foo>\n"

end

specify "raises error if template not found" do

get '/' do
builder :not_found
end

lambda { get_it '/' }.should.raise(Errno::ENOENT)

end

end

end
File renamed without changes.

0 comments on commit a734cf3

Please sign in to comment.