[DRE-commits] [SCM] ruby-sinatra.git branch, upstream, updated. upstream/1.2.6

Youhei SASAKI uwabami at gfd-dennou.org
Tue Jul 26 07:31:23 UTC 2011


The following commit has been merged in the upstream branch:
commit 4c4d0d8581ebe2899a0eced8ae07f8a1a7f3b0cb
Author: Youhei SASAKI <uwabami at gfd-dennou.org>
Date:   Tue Jul 26 00:52:18 2011 +0900

    Imported Upstream version 1.2.6

diff --git a/CHANGES b/CHANGES
index ef5b2df..1d78b8d 100644
--- a/CHANGES
+++ b/CHANGES
@@ -1,3 +1,36 @@
+= 1.2.6 / 2011-05-01
+
+ * Fix broken delegation, backport delegation tests from Sinatra 1.3.
+   (Konstantin Haase)
+
+= 1.2.5 / 2011-04-30
+
+ * Restore compatibility with Ruby 1.8.6. (Konstantin Haase)
+
+= 1.2.4 / 2011-04-30
+
+ * Sinatra::Application (classic style) does not use a session secret in
+   development mode, so sessions are not invalidated after every request when
+   using Shotgun. (Konstantin Haase)
+
+ * The request object was shared between multiple Sinatra instances in the
+   same middleware chain. This caused issues if any non-sinatra routing
+   happend in-between two of those instances, or running a request twice
+   against an application (described in the README). The caching was reverted.
+   See GH#239 and GH#256 for more infos. (Konstantin Haase)
+
+ * Fixes issues where the top level DSL was interfering with method_missing
+   proxies. This issue surfaced when Rails 3 was used with older Sass versions
+   and Sinatra >= 1.2.0. (Konstantin Haase)
+
+ * Sinatra::Delegator.delegate is now able to delegate any method names, even
+   those containing special characters. This allows better integration into
+   other programming languages on Rubinius (probably on the JVM, too), like
+   Fancy. (Konstantin Haase)
+
+ * Remove HEAD request logic and let Rack::Head handle it instead. (Paolo
+   "Nusco" Perrotta)
+
 = 1.2.3 / 2011-04-13
 
  * This release is compatible with Tilt 1.3, it will still work with Tilt 1.2.2,
diff --git a/Gemfile b/Gemfile
index 89ae28e..383eba1 100644
--- a/Gemfile
+++ b/Gemfile
@@ -17,7 +17,7 @@ gem 'rack-test', '>= 0.5.6'
 
 # Allows stuff like `tilt=1.2.2 bundle install` or `tilt=master ...`.
 # Used by the CI.
-tilt = ENV['tilt'].dup || 'stable'
+tilt = (ENV['tilt'] || 'stable').dup
 tilt.sub! 'tilt-', ''
 if tilt != 'stable'
   tilt = {:git => TILT_REPO, :branch => tilt} unless tilt =~ /(\d+\.)+\d+/
diff --git a/LICENSE b/LICENSE
index 7e38bc4..270661f 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2007, 2008, 2009, 2010 Blake Mizerany
+Copyright (c) 2007, 2008, 2009, 2010, 2011 Blake Mizerany
 
 Permission is hereby granted, free of charge, to any person
 obtaining a copy of this software and associated documentation
diff --git a/README.de.rdoc b/README.de.rdoc
index 8d15d32..3993687 100644
--- a/README.de.rdoc
+++ b/README.de.rdoc
@@ -903,8 +903,8 @@ Manchmal entspricht +pass+ nicht den Anforderungen, wenn das Ergebnis einer
 anderen Route gefordert wird. Um das zu erreichen, lässt sich +call+ nutzen:
 
   get '/foo' do
-    status, headers, body = call request.env.merge("PATH_INFO" => '/bar')
-    [status, body.upcase]
+    status, headers, body = call env.merge("PATH_INFO" => '/bar')
+    [status, headers, body.map(&:upcase)]
   end
 
   get '/bar' do
@@ -1357,7 +1357,7 @@ Routen-Block oder in einem Filter geworfen wurde. Die Exception kann über die
 Benutzerdefinierte Fehler:
 
   error MeinFehler do
-    'Au weia, ' + request.env['sinatra.error'].message
+    'Au weia, ' + env['sinatra.error'].message
   end
 
 Dann, wenn das passiert:
@@ -1819,10 +1819,10 @@ die so installiert werden:
 === Mit Bundler
 
 Wenn die Applikation mit der neuesten Version von Sinatra und
-{Bundler}[http://gembundler.com/] genutzt werden soll, schlagen wir folgenden
-Weg vor:
+{Bundler}[http://gembundler.com/] genutzt werden soll, empfehlen wir den
+nachfolgenden Weg.
 
-Soweit Bundler noch nicht installiert ist, folgendes:
+Soweit Bundler noch nicht installiert ist:
 
   gem install bundler
 
@@ -1897,9 +1897,13 @@ SemVer und SemVerTag.
 * {Projekt-Website}[http://sinatra.github.com/] - Ergänzende Dokumentation,
   News und Links zu anderen Ressourcen.
 * {Hilfe beisteuern}[http://sinatra.github.com/contributing.html] - Einen
-Fehler gefunden? Brauchst du Hilfe? Hast du einen Patch?
+  Fehler gefunden? Brauchst du Hilfe? Hast du einen Patch?
 * {Issue-Tracker}[http://github.com/sinatra/sinatra/issues]
 * {Twitter}[http://twitter.com/sinatra]
 * {Mailing-Liste}[http://groups.google.com/group/sinatrarb]
 * {IRC: #sinatra}[irc://chat.freenode.net/#sinatra] auf http://freenode.net
 
+* API Dokumentation für die {aktuelle Version}[http://rubydoc.info/gems/sinatra]	
+  oder für {HEAD}[http://rubydoc.info/github/sinatra/sinatra] auf 
+  http://rubydoc.info
+
diff --git a/README.es.rdoc b/README.es.rdoc
index aeca7e8..8814306 100644
--- a/README.es.rdoc
+++ b/README.es.rdoc
@@ -874,8 +874,8 @@ Cuando querés obtener el resultado de la llamada a una ruta, +pass+ no te va a
 servir.  Para lograr esto, podés usar +call+:
 
   get '/foo' do
-    status, headers, body = call request.env.merge("PATH_INFO" => '/bar')
-    [status, body.upcase]
+    status, headers, body = call env.merge("PATH_INFO" => '/bar')
+    [status, headers, body.map(&:upcase)]
   end
 
   get '/bar' do
@@ -1331,9 +1331,11 @@ Podés acceder a estas opciones utilizando el método <tt>settings</tt>:
 [static]              define si Sinatra debe encargarse de servir archivos
                       estáticos.
 
-                      Deshabilitala cuando usés un servidor capaz de hacerlo
-                      por sí solo, porque mejorará el rendimiento.  Se encuentra
-                      habilitada por defecto.
+                      Deshabilitala cuando usés un servidor capaz de
+                      hacerlo por sí solo, porque mejorará el
+                      rendimiento.  Se encuentra habilitada por
+                      defecto en el estilo clásico y desactivado en el
+                      el modular.
 
 [views]               directorio de las vistas.
 
@@ -1365,7 +1367,7 @@ obtener de la variable Rack <tt>sinatra.error</tt>:
 Errores personalizados:
 
   error MiErrorPersonalizado do
-    'Lo que pasó fue...' request.env['sinatra.error'].message
+    'Lo que pasó fue...' + env['sinatra.error'].message
   end
 
 Entonces, si pasa esto:
@@ -1534,6 +1536,7 @@ entre sus configuraciones:
   logging             true                         false
   method_override     true                         false
   inline_templates    true                         false
+  static              true                         false
 
 === Sirviendo una Aplicación Modular
 
@@ -1633,7 +1636,7 @@ aplicación basada en Rack (Rails/Ramaze/Camping/...):
 
 Puede que en algunas ocasiones quieras crear nuevas aplicaciones en
 tiempo de ejecución sin tener que asignarlas a una constante.  Para
-esto tenés `Sinatra.new`:
+esto tenés <tt>Sinatra.new</tt>:
 
   require 'sinatra/base'
   mi_app = Sinatra.new { get('/') { "hola" } }
@@ -1909,3 +1912,7 @@ siguiendo las especificaciones SemVer y SemVerTag.
 * {Twitter}[http://twitter.com/sinatra]
 * {Lista de Correo}[http://groups.google.com/group/sinatrarb/topics]
 * {IRC: #sinatra}[irc://chat.freenode.net/#sinatra] en http://freenode.net
+* Documentación de la API para la
+  {última versión liberada}[http://rubydoc.info/gems/sinatra] o para la
+  {rama de desarrollo actual}[http://rubydoc.info/github/sinatra/sinatra]
+  en http://rubydoc.info/
diff --git a/README.fr.rdoc b/README.fr.rdoc
index 7f2d986..627f035 100644
--- a/README.fr.rdoc
+++ b/README.fr.rdoc
@@ -894,8 +894,8 @@ souhaitez obtenir le résultat d'une autre route. Pour cela, utilisez
 simplement +call+ :
 
   get '/foo' do
-    status, headers, body = call request.env.merge("PATH_INFO" => '/bar')
-    [status, body.upcase]
+    status, headers, body = call env.merge("PATH_INFO" => '/bar')
+    [status, headers, body.map(&:upcase)]
   end
 
   get '/bar' do
@@ -1399,7 +1399,7 @@ variable Rack <tt>sinatra.error</tt>:
 Erreur sur mesure:
 
   error MonErreurSurMesure do
-    'Donc il est arrivé ceci...' + request.env['sinatra.error'].message
+    'Donc il est arrivé ceci...' + env['sinatra.error'].message
   end
 
 Donc si ceci arrive:
diff --git a/README.hu.rdoc b/README.hu.rdoc
index d30c382..e6deeca 100644
--- a/README.hu.rdoc
+++ b/README.hu.rdoc
@@ -399,7 +399,7 @@ előszűrő kivételt vált ki. A kivétel objektum lehívható a
 Egyéni hibakezelés:
 
   error MyCustomError do
-    'Szóval az van, hogy...' + request.env['sinatra.error'].message
+    'Szóval az van, hogy...' + env['sinatra.error'].message
   end
 
 És amikor fellép:
diff --git a/README.jp.rdoc b/README.jp.rdoc
index c479706..5e5d414 100644
--- a/README.jp.rdoc
+++ b/README.jp.rdoc
@@ -700,7 +700,7 @@ body部を指定することもできます ...
 エラーをカスタマイズする場合は、
 
   error MyCustomError do
-    'エラーメッセージ...' + request.env['sinatra.error'].message
+    'エラーメッセージ...' + env['sinatra.error'].message
   end
 
 と書いておいて,下記のように呼び出します。
diff --git a/README.pt-br.rdoc b/README.pt-br.rdoc
index 12dc259..5a3e7e7 100644
--- a/README.pt-br.rdoc
+++ b/README.pt-br.rdoc
@@ -431,7 +431,7 @@ Rack <tt>sinatra.error</tt>:
 Erros customizados:
 
   error MeuErroCustomizado do
-    'Então que aconteceu foi...' + request.env['sinatra.error'].message
+    'Então que aconteceu foi...' + env['sinatra.error'].message
   end
 
 Então, se isso acontecer:
diff --git a/README.pt-pt.rdoc b/README.pt-pt.rdoc
index e72f7be..f8a8872 100644
--- a/README.pt-pt.rdoc
+++ b/README.pt-pt.rdoc
@@ -430,7 +430,7 @@ Rack <tt>sinatra.error</tt>:
 Erros personalizados:
 
   error MeuErroPersonalizado do
-    'O que aconteceu foi...' + request.env['sinatra.error'].message
+    'O que aconteceu foi...' + env['sinatra.error'].message
   end
 
 Então, se isso acontecer:
diff --git a/README.rdoc b/README.rdoc
index f6fd03c..301b066 100644
--- a/README.rdoc
+++ b/README.rdoc
@@ -854,8 +854,8 @@ Sometimes +pass+ is not what you want, instead you would like to get the result
 of calling another route. Simply use +call+ to achieve this:
 
   get '/foo' do
-    status, headers, body = call request.env.merge("PATH_INFO" => '/bar')
-    [status, body.upcase]
+    status, headers, body = call env.merge("PATH_INFO" => '/bar')
+    [status, headers, body.map(&:upcase)]
   end
 
   get '/bar' do
@@ -1325,7 +1325,7 @@ block or a filter. The exception object can be obtained from the
 Custom errors:
 
   error MyCustomError do
-    'So what happened was...' + request.env['sinatra.error'].message
+    'So what happened was...' + env['sinatra.error'].message
   end
 
 Then, if this happens:
@@ -1478,8 +1478,8 @@ There are only two downsides compared with modular style:
 
 There is no reason you cannot mix modular and classic style.
 
-If switching from one style to the other, you should be aware of slight
-differences in the setting:
+If switching from one style to the other, you should be aware of slightly
+different default settings:
 
   Setting             Classic                 Modular
 
@@ -1587,7 +1587,7 @@ application (Rails/Ramaze/Camping/...):
 === Dynamic Application Creation
 
 Sometimes you want to create new applications at runtime without having to
-assign them to a constant, you can do this with `Sinatra.new`:
+assign them to a constant, you can do this with <tt>Sinatra.new</tt>:
 
   require 'sinatra/base'
   my_app = Sinatra.new { get('/') { "hi" } }
@@ -1855,6 +1855,8 @@ SemVerTag.
 * {Twitter}[http://twitter.com/sinatra]
 * {Mailing List}[http://groups.google.com/group/sinatrarb/topics]
 * {IRC: #sinatra}[irc://chat.freenode.net/#sinatra] on http://freenode.net
+* {Sinatra Book}[http://sinatra-book.gittr.com] Cookbook Tutorial
+* {Sinatra Book Contrib}[http://sinatra-book-contrib.com/] Community contributed recipes
 * API documentation for the {latest release}[http://rubydoc.info/gems/sinatra]
   or the {current HEAD}[http://rubydoc.info/github/sinatra/sinatra] on
   http://rubydoc.info/
diff --git a/README.zh.rdoc b/README.zh.rdoc
index 53c9227..649f985 100644
--- a/README.zh.rdoc
+++ b/README.zh.rdoc
@@ -843,8 +843,8 @@ Session被用来在请求之间保持状态。如果被激活,每一个用户
 。简单的使用 +call+ 可以做到这一点:
 
   get '/foo' do
-    status, headers, body = call request.env.merge("PATH_INFO" => '/bar')
-    [status, body.upcase]
+    status, headers, body = call env.merge("PATH_INFO" => '/bar')
+    [status, headers, body.map(&:upcase)]
   end
 
   get '/bar' do
@@ -1314,7 +1314,7 @@ Sinatra会自动处理range请求。
 自定义错误:
 
   error MyCustomError do
-    'So what happened was...' + request.env['sinatra.error'].message
+    'So what happened was...' + env['sinatra.error'].message
   end
 
 那么,当这个发生的时候:
diff --git a/lib/sinatra/base.rb b/lib/sinatra/base.rb
index 18f4c1e..52115e7 100644
--- a/lib/sinatra/base.rb
+++ b/lib/sinatra/base.rb
@@ -7,15 +7,11 @@ require 'sinatra/showexceptions'
 require 'tilt'
 
 module Sinatra
-  VERSION = '1.2.3'
+  VERSION = '1.2.6'
 
   # The request object. See Rack::Request for more info:
   # http://rack.rubyforge.org/doc/classes/Rack/Request.html
   class Request < Rack::Request
-    def self.new(env)
-      env['sinatra.request'] ||= super
-    end
-
     # Returns an array of acceptable media types for the response
     def accept
       @env['sinatra.accept'] ||= begin
@@ -63,7 +59,7 @@ module Sinatra
     def accept_entry(entry)
       type, *options = entry.gsub(/\s/, '').split(';')
       quality = 0 # we sort smalles first
-      options.delete_if { |e| quality = 1 - e[2..-1].to_f if e.start_with? 'q=' }
+      options.delete_if { |e| quality = 1 - e[2..-1].to_f if e =~ /^q=/ }
       [type, [quality, type.count('*'), 1 - options.size]]
     end
   end
@@ -371,7 +367,7 @@ module Sinatra
       time = time_for time
       response['Last-Modified'] = time.httpdate
       # compare based on seconds since epoch
-      halt 304 if Time.httpdate(request.env['HTTP_IF_MODIFIED_SINCE']).to_i >= time.to_i
+      halt 304 if Time.httpdate(env['HTTP_IF_MODIFIED_SINCE']).to_i >= time.to_i
     rescue ArgumentError
     end
 
@@ -655,17 +651,7 @@ module Sinatra
         end
       end
 
-      status, header, body = @response.finish
-
-      # Never produce a body on HEAD requests. Do retain the Content-Length
-      # unless it's "0", in which case we assume it was calculated erroneously
-      # for a manual HEAD response and remove it entirely.
-      if @env['REQUEST_METHOD'] == 'HEAD'
-        body = []
-        header.delete('Content-Length') if header['Content-Length'] == '0'
-      end
-
-      [status, header, body]
+      @response.finish
     end
 
     # Access settings defined with Base.set.
@@ -700,7 +686,7 @@ module Sinatra
     # Forward the request to the downstream app -- middleware only.
     def forward
       fail "downstream app not set" unless @app.respond_to? :call
-      status, headers, body = @app.call(@request.env)
+      status, headers, body = @app.call env
       @response.status = status
       @response.body = body
       @response.headers.merge! headers
@@ -953,14 +939,15 @@ module Sinatra
 
       # Sets an option to the given value.  If the value is a proc,
       # the proc will be called every time the option is accessed.
-      def set(option, value=self, &block)
-        raise ArgumentError if block && value != self
+      def set(option, value = (not_set = true), &block)
+        raise ArgumentError if block and !not_set
         value = block if block
         if value.kind_of?(Proc)
           metadef(option, &value)
           metadef("#{option}?") { !!__send__(option) }
           metadef("#{option}=") { |val| metadef(option, &Proc.new{val}) }
-        elsif value == self && option.respond_to?(:each)
+        elsif not_set
+          raise ArgumentError unless option.respond_to?(:each)
           option.each { |k,v| set(k, v) }
         elsif respond_to?("#{option}=")
           __send__ "#{option}=", value
@@ -1274,6 +1261,7 @@ module Sinatra
         builder.use Rack::MethodOverride if method_override?
         builder.use ShowExceptions       if show_exceptions?
         builder.use Rack::CommonLogger   if logging?
+        builder.use Rack::Head
         setup_sessions builder
         middleware.each { |c,a,b| builder.use(c, *a, &b) }
         builder.run new!(*args, &bk)
@@ -1440,7 +1428,7 @@ module Sinatra
           </style>
         </head>
         <body>
-          <h2>Sinatra doesn't know this ditty.</h2>
+          <h2>Sinatra doesn’t know this ditty.</h2>
           <img src='#{uri "/__sinatra__/404.png"}'>
           <div id="c">
             Try this:
@@ -1464,6 +1452,7 @@ module Sinatra
     set :logging, Proc.new { ! test? }
     set :method_override, true
     set :run, Proc.new { ! test? }
+    set :session_secret, Proc.new { super() unless development? }
 
     def self.register(*extensions, &block) #:nodoc:
       added_methods = extensions.map {|m| m.public_instance_methods }.flatten
@@ -1476,14 +1465,28 @@ module Sinatra
   # methods to be delegated to the Sinatra::Application class. Used primarily
   # at the top-level.
   module Delegator #:nodoc:
+    TEMPLATE = <<-RUBY
+      def %1$s(*args, &b)
+        return super if respond_to? :%1$s
+        ::Sinatra::Delegator.target.send("%2$s", *args, &b)
+      end
+    RUBY
+
     def self.delegate(*methods)
       methods.each do |method_name|
-        eval <<-RUBY, binding, '(__DELEGATE__)', 1
-          def #{method_name}(*args, &b)
-            ::Sinatra::Application.send(#{method_name.inspect}, *args, &b)
-          end
-          private #{method_name.inspect}
-        RUBY
+        # Replaced with way shorter and better implementation in 1.3.0
+        # using define_method instead, however, blocks cannot take block
+        # arguments on 1.8.6.
+        begin
+          code = TEMPLATE % [method_name, method_name]
+          eval code, binding, '(__DELEGATE__)', 1
+        rescue SyntaxError
+          code  = TEMPLATE % [:_delegate, method_name]
+          eval code, binding, '(__DELEGATE__)', 1
+          alias_method method_name, :_delegate
+          undef_method :_delegate
+        end
+        private method_name
       end
     end
 
@@ -1491,6 +1494,12 @@ module Sinatra
              :before, :after, :error, :not_found, :configure, :set, :mime_type,
              :enable, :disable, :use, :development?, :test?, :production?,
              :helpers, :settings
+
+    class << self
+      attr_accessor :target
+    end
+
+    self.target = Application
   end
 
   # Create a new Sinatra application. The block is evaluated in the new app's
@@ -1503,11 +1512,11 @@ module Sinatra
 
   # Extend the top-level DSL with the modules provided.
   def self.register(*extensions, &block)
-    Application.register(*extensions, &block)
+    Delegator.target.register(*extensions, &block)
   end
 
   # Include the helper modules provided in Sinatra's request context.
   def self.helpers(*extensions, &block)
-    Application.helpers(*extensions, &block)
+    Delegator.target.helpers(*extensions, &block)
   end
 end
diff --git a/metadata.yml b/metadata.yml
index ad46d3d..a05c029 100644
--- a/metadata.yml
+++ b/metadata.yml
@@ -2,7 +2,7 @@
 name: sinatra
 version: !ruby/object:Gem::Version 
   prerelease: 
-  version: 1.2.3
+  version: 1.2.6
 platform: ruby
 authors: 
 - Blake Mizerany
@@ -13,8 +13,7 @@ autorequire:
 bindir: bin
 cert_chain: []
 
-date: 2011-04-13 00:00:00 +02:00
-default_executable: 
+date: 2011-05-01 00:00:00 Z
 dependencies: 
 - !ruby/object:Gem::Dependency 
   name: rack
@@ -94,6 +93,7 @@ files:
 - test/builder_test.rb
 - test/coffee_test.rb
 - test/contest.rb
+- test/delegator_test.rb
 - test/encoding_test.rb
 - test/erb_test.rb
 - test/erubis_test.rb
@@ -169,7 +169,6 @@ files:
 - test/views/layout2.test
 - test/views/nested.str
 - test/views/utf8.erb
-has_rdoc: true
 homepage: http://sinatra.rubyforge.org
 licenses: []
 
@@ -188,7 +187,7 @@ required_ruby_version: !ruby/object:Gem::Requirement
   requirements: 
   - - ">="
     - !ruby/object:Gem::Version 
-      hash: -4509942912649873200
+      hash: -2370709599790999687
       segments: 
       - 0
       version: "0"
@@ -201,7 +200,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
 requirements: []
 
 rubyforge_project: sinatra
-rubygems_version: 1.6.2
+rubygems_version: 1.7.2
 signing_key: 
 specification_version: 2
 summary: Classy web-development dressed in a DSL
@@ -209,6 +208,7 @@ test_files:
 - test/base_test.rb
 - test/builder_test.rb
 - test/coffee_test.rb
+- test/delegator_test.rb
 - test/encoding_test.rb
 - test/erb_test.rb
 - test/erubis_test.rb
diff --git a/sinatra.gemspec b/sinatra.gemspec
index c860a69..ada5d90 100644
--- a/sinatra.gemspec
+++ b/sinatra.gemspec
@@ -3,8 +3,8 @@ Gem::Specification.new do |s|
   s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
 
   s.name = 'sinatra'
-  s.version = '1.2.3'
-  s.date = '2011-04-13'
+  s.version = '1.2.6'
+  s.date = '2011-05-01'
 
   s.description = "Classy web-development dressed in a DSL"
   s.summary     = "Classy web-development dressed in a DSL"
@@ -40,6 +40,7 @@ Gem::Specification.new do |s|
     test/builder_test.rb
     test/coffee_test.rb
     test/contest.rb
+    test/delegator_test.rb
     test/encoding_test.rb
     test/erb_test.rb
     test/erubis_test.rb
diff --git a/test/delegator_test.rb b/test/delegator_test.rb
new file mode 100644
index 0000000..e35b738
--- /dev/null
+++ b/test/delegator_test.rb
@@ -0,0 +1,153 @@
+class DelegatorTest < Test::Unit::TestCase
+  class Mirror
+    attr_reader :last_call
+    def method_missing(*a, &b)
+      @last_call = [*a.map(&:to_s)]
+      @last_call << b if b
+    end
+  end
+
+  def self.delegates(name)
+    it "delegates #{name}" do
+      m = mirror { send name }
+      assert_equal m.last_call, [name.to_s]
+    end
+
+    it "delegates #{name} with arguments" do
+      m = mirror { send name, "foo", "bar" }
+      assert_equal m.last_call, [name.to_s, "foo", "bar"]
+    end
+
+    it "delegates #{name} with block" do
+      block = proc { }
+      m = mirror { send(name, &block) }
+      assert_equal m.last_call, [name.to_s, block]
+    end
+  end
+
+  setup do
+    @target_was = Sinatra::Delegator.target
+  end
+
+  def teardown
+    Sinatra::Delegator.target = @target_was
+  end
+
+  def delegation_app(&block)
+    mock_app { Sinatra::Delegator.target = self }
+    delegate(&block)
+  end
+
+  def mirror(&block)
+    mirror = Mirror.new
+    Sinatra::Delegator.target = mirror
+    delegate(&block)
+  end
+
+  def delegate(&block)
+    assert Sinatra::Delegator.target != Sinatra::Application
+    Object.new.extend(Sinatra::Delegator).instance_eval(&block) if block
+    Sinatra::Delegator.target
+  end
+
+  def target
+    Sinatra::Delegator.target
+  end
+
+  it 'defaults to Sinatra::Application as target' do
+    assert_equal Sinatra::Delegator.target, Sinatra::Application
+  end
+
+  %w[get put post delete options].each do |verb|
+    it "delegates #{verb} correctly" do
+      delegation_app do
+        send verb, '/hello' do
+          'Hello World'
+        end
+      end
+
+      request = Rack::MockRequest.new(@app)
+      response = request.request(verb.upcase, '/hello', {})
+      assert response.ok?
+      assert_equal 'Hello World', response.body
+    end
+  end
+
+  it "delegates head correctly" do
+    delegation_app do
+      head '/hello' do
+        response['X-Hello'] = 'World!'
+        'remove me'
+      end
+    end
+
+    request = Rack::MockRequest.new(@app)
+    response = request.request('HEAD', '/hello', {})
+    assert response.ok?
+    assert_equal 'World!', response['X-Hello']
+    assert_equal '', response.body
+  end
+
+  it "registers extensions with the delegation target" do
+    app, mixin = mirror, Module.new
+    Sinatra.register mixin
+    assert_equal app.last_call, ["register", mixin.to_s ]
+  end
+
+  it "registers helpers with the delegation target" do
+    app, mixin = mirror, Module.new
+    Sinatra.helpers mixin
+    assert_equal app.last_call, ["helpers", mixin.to_s ]
+  end
+
+  it "should work with method_missing proxies for options" do
+    mixin = Module.new do
+      def respond_to?(method, *)
+        method.to_sym == :options or super
+      end
+
+      def method_missing(method, *args, &block)
+        return super unless method.to_sym == :options
+        {:some => :option}
+      end
+    end
+
+    value = nil
+    mirror do
+      extend mixin
+      value = options
+    end
+
+    assert_equal({:some => :option}, value)
+  end
+
+  it "delegates crazy method names" do
+    Sinatra::Delegator.delegate "foo:bar:"
+    method = mirror { send "foo:bar:" }.last_call.first
+    assert_equal "foo:bar:", method
+  end
+
+  delegates 'get'
+  delegates 'put'
+  delegates 'post'
+  delegates 'delete'
+  delegates 'head'
+  delegates 'options'
+  delegates 'template'
+  delegates 'layout'
+  delegates 'before'
+  delegates 'after'
+  delegates 'error'
+  delegates 'not_found'
+  delegates 'configure'
+  delegates 'set'
+  delegates 'mime_type'
+  delegates 'enable'
+  delegates 'disable'
+  delegates 'use'
+  delegates 'development?'
+  delegates 'test?'
+  delegates 'production?'
+  delegates 'helpers'
+  delegates 'settings'
+end
diff --git a/test/routing_test.rb b/test/routing_test.rb
index d85010d..f1b5c6b 100644
--- a/test/routing_test.rb
+++ b/test/routing_test.rb
@@ -686,10 +686,10 @@ class RoutingTest < Test::Unit::TestCase
   it "filters by accept header" do
     mock_app {
       get '/', :provides => :xml do
-        request.env['HTTP_ACCEPT']
+        env['HTTP_ACCEPT']
       end
       get '/foo', :provides => :html do
-        request.env['HTTP_ACCEPT']
+        env['HTTP_ACCEPT']
       end
     }
 
@@ -714,7 +714,7 @@ class RoutingTest < Test::Unit::TestCase
 
     mock_app {
       get '/', :provides => types do
-        request.env['HTTP_ACCEPT']
+        env['HTTP_ACCEPT']
       end
     }
 
@@ -729,7 +729,7 @@ class RoutingTest < Test::Unit::TestCase
   it 'degrades gracefully when optional accept header is not provided' do
     mock_app {
       get '/', :provides => :xml do
-        request.env['HTTP_ACCEPT']
+        env['HTTP_ACCEPT']
       end
       get '/' do
         'default'
@@ -1042,4 +1042,35 @@ class RoutingTest < Test::Unit::TestCase
     get '/foo'
     assert not_found?
   end
+
+  it 'allows using call to fire another request internally' do
+    mock_app do
+      get '/foo' do
+        status, headers, body = call env.merge("PATH_INFO" => '/bar')
+        [status, headers, body.map(&:upcase)]
+      end
+
+      get '/bar' do
+        "bar"
+      end
+    end
+
+    get '/foo'
+    assert ok?
+    assert_body "BAR"
+  end
+
+  it 'plays well with other routing middleware' do
+    middleware = Sinatra.new
+    inner_app  = Sinatra.new { get('/foo') { 'hello' } }
+    builder    = Rack::Builder.new do
+      use middleware
+      map('/test') { run inner_app }
+    end
+
+    @app = builder.to_app
+    get '/test/foo'
+    assert ok?
+    assert_body 'hello'
+  end
 end
diff --git a/test/settings_test.rb b/test/settings_test.rb
index b8c9788..71ceb84 100644
--- a/test/settings_test.rb
+++ b/test/settings_test.rb
@@ -34,6 +34,24 @@ class SettingsTest < Test::Unit::TestCase
     assert !@base.respond_to?(:fiz)
   end
 
+  it 'raises an error without value and block' do
+    assert_raise(ArgumentError) { @base.set(:fiz) }
+    assert !@base.respond_to?(:fiz)
+  end
+
+  it 'allows setting a value to the app class' do
+    @base.set :base, @base
+    assert @base.respond_to?(:base)
+    assert_equal @base, @base.base
+  end
+
+  it 'raises an error with the app class as value and a block' do
+    assert_raise ArgumentError do
+      @base.set(:fiz, @base) { 'baz' }
+    end
+    assert !@base.respond_to?(:fiz)
+  end
+
   it "sets multiple settings with a Hash" do
     @base.set :foo => 1234,
         :bar => 'Hello World',

-- 
ruby-sinatra.git



More information about the Pkg-ruby-extras-commits mailing list