Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

No longer need to use vendor'd sinatra.

  • Loading branch information...
commit 8b923aec62821a90d1840ab784130b67e4f81d6b 1 parent 15ea2c6
@funkaoshi authored
Showing with 2 additions and 7,463 deletions.
  1. +1 −1  config.ru
  2. +0 −1  dreamhost.rb
  3. +1 −1  groupviewer.rb
  4. +0 −9 vendor/sinatra/.gitignore
  5. +0 −43 vendor/sinatra/AUTHORS
  6. +0 −467 vendor/sinatra/CHANGES
  7. +0 −22 vendor/sinatra/LICENSE
  8. +0 −552 vendor/sinatra/README.jp.rdoc
  9. +0 −581 vendor/sinatra/README.rdoc
  10. +0 −129 vendor/sinatra/Rakefile
  11. +0 −7 vendor/sinatra/lib/sinatra.rb
  12. +0 −1,148 vendor/sinatra/lib/sinatra/base.rb
  13. BIN  vendor/sinatra/lib/sinatra/images/404.png
  14. BIN  vendor/sinatra/lib/sinatra/images/500.png
  15. +0 −28 vendor/sinatra/lib/sinatra/main.rb
  16. +0 −303 vendor/sinatra/lib/sinatra/showexceptions.rb
  17. +0 −509 vendor/sinatra/lib/sinatra/tilt.rb
  18. +0 −88 vendor/sinatra/sinatra.gemspec
  19. +0 −160 vendor/sinatra/test/base_test.rb
  20. +0 −65 vendor/sinatra/test/builder_test.rb
  21. +0 −64 vendor/sinatra/test/contest.rb
  22. +0 −3  vendor/sinatra/test/data/reload_app_file.rb
  23. +0 −81 vendor/sinatra/test/erb_test.rb
  24. +0 −82 vendor/sinatra/test/erubis_test.rb
  25. +0 −100 vendor/sinatra/test/extensions_test.rb
  26. +0 −195 vendor/sinatra/test/filter_test.rb
  27. +0 −90 vendor/sinatra/test/haml_test.rb
  28. +0 −76 vendor/sinatra/test/helper.rb
  29. +0 −560 vendor/sinatra/test/helpers_test.rb
  30. +0 −186 vendor/sinatra/test/mapped_error_test.rb
  31. +0 −68 vendor/sinatra/test/middleware_test.rb
  32. +0 −33 vendor/sinatra/test/request_test.rb
  33. +0 −42 vendor/sinatra/test/response_test.rb
  34. +0 −98 vendor/sinatra/test/result_test.rb
  35. +0 −59 vendor/sinatra/test/route_added_hook_test.rb
  36. +0 −834 vendor/sinatra/test/routing_test.rb
  37. +0 −79 vendor/sinatra/test/sass_test.rb
  38. +0 −47 vendor/sinatra/test/server_test.rb
  39. +0 −365 vendor/sinatra/test/settings_test.rb
  40. +0 −13 vendor/sinatra/test/sinatra_test.rb
  41. +0 −87 vendor/sinatra/test/static_test.rb
  42. +0 −155 vendor/sinatra/test/templates_test.rb
  43. +0 −3  vendor/sinatra/test/views/error.builder
  44. +0 −3  vendor/sinatra/test/views/error.erb
  45. +0 −3  vendor/sinatra/test/views/error.erubis
  46. +0 −3  vendor/sinatra/test/views/error.haml
  47. +0 −2  vendor/sinatra/test/views/error.sass
  48. +0 −1  vendor/sinatra/test/views/foo/hello.test
  49. +0 −1  vendor/sinatra/test/views/hello.builder
  50. +0 −1  vendor/sinatra/test/views/hello.erb
  51. +0 −1  vendor/sinatra/test/views/hello.erubis
  52. +0 −1  vendor/sinatra/test/views/hello.haml
  53. +0 −2  vendor/sinatra/test/views/hello.sass
  54. +0 −1  vendor/sinatra/test/views/hello.test
  55. +0 −3  vendor/sinatra/test/views/layout2.builder
  56. +0 −2  vendor/sinatra/test/views/layout2.erb
  57. +0 −2  vendor/sinatra/test/views/layout2.erubis
  58. +0 −2  vendor/sinatra/test/views/layout2.haml
  59. +0 −1  vendor/sinatra/test/views/layout2.test
View
2  config.ru
@@ -1,6 +1,6 @@
require 'dreamhost.rb' # loads rubygems on Dreamhost.
-require 'vendor/sinatra/lib/sinatra.rb'
+require 'sinatra'
Sinatra::Base.set(:run, false)
Sinatra::Base.set(:env, :production);
View
1  dreamhost.rb
@@ -3,4 +3,3 @@
ENV['GEM_PATH'] = '$GEM_HOME:/usr/lib/ruby/gems/1.8'
require 'rubygems'
Gem.clear_paths
-
View
2  groupviewer.rb
@@ -1,4 +1,4 @@
-require File.dirname(__FILE__) + '/vendor/sinatra/lib/sinatra.rb'
+require 'sinatra'
require 'flickraw'
require 'haml'
View
9 vendor/sinatra/.gitignore
@@ -1,9 +0,0 @@
-*.log
-.DS_Store
-/pkg
-/book
-/doc/api
-/doc/*.html
-.#*
-\#*
-.emacs*
View
43 vendor/sinatra/AUTHORS
@@ -1,43 +0,0 @@
-Sinatra was designed and developed by Blake Mizerany (bmizerany) in
-California. Continued development would not be possible without the ongoing
-financial support provided by [Heroku](http://heroku.com) and the emotional
-support provided by Adam Wiggins (adamwiggins) of Heroku, Chris Wanstrath (defunkt),
-PJ Hyett (pjhyett), and the rest of the GitHub crew.
-
-Special thanks to the following extraordinary individuals, who-out which
-Sinatra would not be possible:
-
-* Ryan Tomayko (rtomayko) for constantly fixing whitespace errors 60d5006
-* Ezra Zygmuntowicz (ezmobius) for initial help and letting Blake steal
- some of merbs internal code.
-* Ari Lerner (http://xnot.org/) for his evangelism, spirit, and gumption
- that got Sinatra recognized from Day 1.
-* Christopher Schneid (cschneid) for The Book, the blog (gittr.com),
- irclogger.com, and a bunch of useful patches.
-* Markus Prinz (cypher) for patches over the years, caring about
- the README, and hanging in there when times were rough.
-* Simon Rozet (sr) for a ton of doc patches, HAML options, and all that
- advocacy stuff he's going to do for 1.0.
-* Erik Kastner (kastner) for fixing `MIME_TYPES` under Rack 0.5.
-* Ben Bleything (bleything) for caring about HTTP status codes and doc fixes.
-* Igal Koshevoy (igal) for root path detection under Thin/Passenger.
-* Jon Crosby (jcrosby) for coffee breaks, doc fixes, and just because, man.
-* Karel Minarik (karmi) for screaming until the website came back up.
-* Jeremy Evans (jeremyevans) for unbreaking optional path params (twice!)
-* The GitHub guys for stealing Blake's table.
-* Nickolas Means (nmeans) for Sass template support.
-* Victor Hugo Borja (vic) for splat'n routes specs and doco.
-* Avdi Grimm (avdi) for basic RSpec support.
-* Jack Danger Canty for a more accurate root directory and for making me
- watch [this](http://www.youtube.com/watch?v=ueaHLHgskkw) just now.
-* Mathew Walker for making escaped paths work with static files.
-* Millions of Us for having the problem that led to Sinatra's conception.
-* Songbird for the problems that helped Sinatra's future become realized.
-* Rick Olson (technoweenie) for the killer plug at RailsConf '08.
-* Steven Garcia for the amazing custom artwork you see on 404's and 500's
-* Pat Nakajima (nakajima) for fixing non-nested params in nested params Hash's.
-
-and last but not least:
-
-* Frank Sinatra (chairman of the board) for having so much class he
- deserves a web-framework named after him.
View
467 vendor/sinatra/CHANGES
@@ -1,467 +0,0 @@
-= 1.0 / unreleased
-
- * It's now possible to register blocks to run after each request using
- after filters. After filters run at the end of each request, after
- routes and error handlers.
-
- * Sinatra now uses Tilt <http://github.com/rtomayko/tilt> for rendering
- templates. This adds support for template caching, consistent
- template backtraces, and support for new template engines, like
- mustache and liquid.
-
- * New 'settings' method gives access to options in both class and request
- scopes. This replaces the 'options' method.
-
- * New 'erubis' helper method for rendering Erubis templates.
-
- * New 'expires' helper method is like cache_control but takes an
- integer number of seconds or Time object:
- expires 300, :public, :must_revalidate
-
- * New 'cache_control' helper method provides a convenient way of
- setting the Cache-Control response header. Takes a variable number
- of boolean directives followed by a hash of value directives, like
- this:
- cache_control :public, :must_revalidate, :max_age => 60
-
- * Sinatra apps can now be run with a `-h <addr>` argument to specify
- the address to bind to.
-
- * Rack::Session::Cookie is now added to the middleware pipeline when
- running in test environments if the :sessions option is set.
-
- * Route handlers, before filters, templates, error mappings, and
- middleware are now resolved dynamically up the inheritance hierarchy
- when needed instead of duplicating the superclass's version when
- a new Sinatra::Base subclass is created. This should fix a variety
- of issues with extensions that need to add any of these things
- to the base class.
-
-The following Sinatra features have been obsoleted in the 1.0 release:
-
- * The `sinatra/test` library is obsolete. This includes the
- `Sinatra::Test` module, the `Sinatra::TestHarness` class,
- and the `get_it`, `post_it`, `put_it`, `delete_it`, and `head_it`
- helper methods. The
- [`Rack::Test` library](http://gitrdoc.com/brynary/rack-test) should
- be used instead.
-
- * Test framework specific libraries (`sinatra/test/spec`,
- `sinatra/test/bacon`,`sinatra/test/rspec`, etc.) are obsolete.
- See http://www.sinatrarb.com/testing.html for instructions on
- setting up a testing environment under each of these frameworks.
-
- * Auto-requiring template libraries in the `erb`, `builder`, `haml`,
- and `sass` methods is obsolete due to thread-safety issues. You must
- require the template libraries explicitly in your app.
-
- * The `:views_directory` option to rendering methods is obsolete; use
- `:views` instead.
-
- * The `:haml` and `:sass` options to rendering methods are obsolete.
- Template engine options should be passed in the second Hash argument
- instead.
-
- * The 'media_type' helper method is obsolete. Use 'mime_type' instead.
-
- * The request-level `send_data` method is no longer supported.
-
- * The `Sinatra::Event` and `Sinatra::EventContext` classes are no longer
- supported. This may effect extensions written for versions prior to 0.9.2.
- See [Writing Sinatra Extensions](http://www.sinatrarb.com/extensions.html)
- for the officially supported extensions API.
-
- * The `set_option` and `set_options` methods are obsolete; use `set`
- instead.
-
- * The `:env` setting (`settings.env`) is obsolete; use `:environment`
- instead.
-
- * The request level `stop` method is obsolete; use `halt` instead.
-
- * The request level `entity_tag` method is obsolete; use `etag`
- instead.
-
- * The request level `headers` method (HTTP response headers) is obsolete;
- use `response['Header-Name']` instead.
-
- * `Sinatra.application` is obsolete; use `Sinatra::Application` instead.
-
- * Using `Sinatra.application = nil` to reset an application is obsolete.
- This should no longer be necessary.
-
- * Using `Sinatra.default_options` to set base configuration items is
- obsolete; use `Sinatra::Base.set(key, value)` instead.
-
- * The `Sinatra::ServerError` exception is obsolete. All exceptions raised
- within a request are now treated as internal server errors and result in
- a 500 response status.
-
-= 0.9.2 / 2009-05-18
-
- * This version is compatible with Rack 1.0. [Rein Henrichs]
-
- * The development-mode unhandled exception / error page has been
- greatly enhanced, functionally and aesthetically. The error
- page is used when the :show_exceptions option is enabled and an
- exception propagates outside of a route handler or before filter.
- [Simon Rozet / Matte Noble / Ryan Tomayko]
-
- * Backtraces that move through templates now include filenames and
- line numbers where possible. [#51 / S. Brent Faulkner]
-
- * All templates now have an app-level option for setting default
- template options (:haml, :sass, :erb, :builder). The app-level
- option value must be a Hash if set and is merged with the
- template options specified to the render method (Base#haml,
- Base#erb, Base#builder). [S. Brent Faulkner, Ryan Tomayko]
-
- * The method signature for all template rendering methods has
- been unified: "def engine(template, options={}, locals={})".
- The options Hash now takes the generic :views, :layout, and
- :locals options but also any template-specific options. The
- generic options are removed before calling the template specific
- render method. Locals may be specified using either the
- :locals key in the options hash or a second Hash option to the
- rendering method. [#191 / Ryan Tomayko]
-
- * The receiver is now passed to "configure" blocks. This
- allows for the following idiom in top-level apps:
- configure { |app| set :foo, app.root + '/foo' }
- [TJ Holowaychuck / Ryan Tomayko]
-
- * The "sinatra/test" lib is deprecated and will be removed in
- Sinatra 1.0. This includes the Sinatra::Test module and
- Sinatra::TestHarness class in addition to all the framework
- test helpers that were deprecated in 0.9.1. The Rack::Test
- lib should be used instead: http://gitrdoc.com/brynary/rack-test
- [#176 / Simon Rozet]
-
- * Development mode source file reloading has been removed. The
- "shotgun" (http://rtomayko.github.com/shotgun/) program can be
- used to achieve the same basic functionality in most situations.
- Passenger users should use the "tmp/always_restart.txt"
- file (http://tinyurl.com/c67o4h). [#166 / Ryan Tomayko]
-
- * Auto-requiring template libs in the erb, builder, haml, and
- sass methods is deprecated due to thread-safety issues. You must
- require the template libs explicitly in your app file. [Simon Rozet]
-
- * A new Sinatra::Base#route_missing method was added. route_missing
- is sent when no route matches the request or all route handlers
- pass. The default implementation forwards the request to the
- downstream app when running as middleware (i.e., "@app" is
- non-nil), or raises a NotFound exception when no downstream app
- is defined. Subclasses can override this method to perform custom
- route miss logic. [Jon Crosby]
-
- * A new Sinatra::Base#route_eval method was added. The method
- yields to the block and throws :halt with the result. Subclasses
- can override this method to tap into the route execution logic.
- [TJ Holowaychuck]
-
- * Fix the "-x" (enable request mutex / locking) command line
- argument. Passing -x now properly sets the :lock option.
- [S. Brent Faulkner, Ryan Tomayko]
-
- * Fix writer ("foo=") and predicate ("foo?") methods in extension
- modules not being added to the registering class.
- [#172 / Pat Nakajima]
-
- * Fix in-file templates when running alongside activesupport and
- fatal errors when requiring activesupport before sinatra
- [#178 / Brian Candler]
-
- * Fix various issues running on Google AppEngine.
- [Samuel Goebert, Simon Rozet]
-
- * Fix in-file templates __END__ detection when __END__ exists with
- other stuff on a line [Yoji Shidara]
-
-= 0.9.1.1 / 2009-03-09
-
- * Fix directory traversal vulnerability in default static files
- route. See [#177] for more info.
-
-= 0.9.1 / 2009-03-01
-
- * Sinatra now runs under Ruby 1.9.1 [#61]
-
- * Route patterns (splats, :named, or Regexp captures) are now
- passed as arguments to the block. [#140]
-
- * The "helpers" method now takes a variable number of modules
- along with the normal block syntax. [#133]
-
- * New request-level #forward method for middleware components: passes
- the env to the downstream app and merges the response status, headers,
- and body into the current context. [#126]
-
- * Requests are now automatically forwarded to the downstream app when
- running as middleware and no matching route is found or all routes
- pass.
-
- * New simple API for extensions/plugins to add DSL-level and
- request-level methods. Use Sinatra.register(mixin) to extend
- the DSL with all public methods defined in the mixin module;
- use Sinatra.helpers(mixin) to make all public methods defined
- in the mixin module available at the request level. [#138]
- See http://www.sinatrarb.com/extensions.html for details.
-
- * Named parameters in routes now capture the "." character. This makes
- routes like "/:path/:filename" match against requests like
- "/foo/bar.txt"; in this case, "params[:filename]" is "bar.txt".
- Previously, the route would not match at all.
-
- * Added request-level "redirect back" to redirect to the referring
- URL.
-
- * Added a new "clean_trace" option that causes backtraces dumped
- to rack.errors and displayed on the development error page to
- omit framework and core library backtrace lines. The option is
- enabled by default. [#77]
-
- * The ERB output buffer is now available to helpers via the @_out_buf
- instance variable.
-
- * It's now much easier to test sessions in unit tests by passing a
- ":session" option to any of the mock request methods. e.g.,
- get '/', {}, :session => { 'foo' => 'bar' }
-
- * The testing framework specific files ('sinatra/test/spec',
- 'sinatra/test/bacon', 'sinatra/test/rspec', etc.) have been deprecated.
- See http://sinatrarb.com/testing.html for instructions on setting up
- a testing environment with these frameworks.
-
- * The request-level #send_data method from Sinatra 0.3.3 has been added
- for compatibility but is deprecated.
-
- * Fix :provides causing crash on any request when request has no
- Accept header [#139]
-
- * Fix that ERB templates were evaluated twice per "erb" call.
-
- * Fix app-level middleware not being run when the Sinatra application is
- run as middleware.
-
- * Fixed some issues with running under Rack's CGI handler caused by
- writing informational stuff to stdout.
-
- * Fixed that reloading was sometimes enabled when starting from a
- rackup file [#110]
-
- * Fixed that "." in route patterns erroneously matched any character
- instead of a literal ".". [#124]
-
-= 0.9.0.4 / 2009-01-25
-
- * Using halt with more than 1 args causes ArgumentError [#131]
- * using halt in a before filter doesn't modify response [#127]
- * Add deprecated Sinatra::EventContext to unbreak plugins [#130]
- * Give access to GET/POST params in filters [#129]
- * Preserve non-nested params in nested params hash [#117]
- * Fix backtrace dump with Rack::Lint [#116]
-
-= 0.9.0.3 / 2009-01-21
-
- * Fall back on mongrel then webrick when thin not found. [#75]
- * Use :environment instead of :env in test helpers to
- fix deprecation warnings coming from framework.
- * Make sinatra/test/rspec work again [#113]
- * Fix app_file detection on windows [#118]
- * Fix static files with Rack::Lint in pipeline [#121]
-
-= 0.9.0.2 / 2009-01-18
-
- * Halting a before block should stop processing of routes [#85]
- * Fix redirect/halt in before filters [#85]
-
-= 0.9.0 / 2009-01-18
-
- * Works with and requires Rack >= 0.9.1
-
- * Multiple Sinatra applications can now co-exist peacefully within a
- single process. The new "Sinatra::Base" class can be subclassed to
- establish a blank-slate Rack application or middleware component.
- Documentation on using these features is forth-coming; the following
- provides the basic gist: http://gist.github.com/38605
-
- * Parameters with subscripts are now parsed into a nested/recursive
- Hash structure. e.g., "post[title]=Hello&post[body]=World" yields
- params: {'post' => {'title' => 'Hello', 'body' => 'World'}}.
-
- * Regular expressions may now be used in route pattens; captures are
- available at "params[:captures]".
-
- * New ":provides" route condition takes an array of mime types and
- matches only when an Accept request header is present with a
- corresponding type. [cypher]
-
- * New request-level "pass" method; immediately exits the current block
- and passes control to the next matching route.
-
- * The request-level "body" method now takes a block; evaluation is
- deferred until an attempt is made to read the body. The block must
- return a String or Array.
-
- * New "route conditions" system for attaching rules for when a route
- matches. The :agent and :host route options now use this system.
-
- * New "dump_errors" option controls whether the backtrace is dumped to
- rack.errors when an exception is raised from a route. The option is
- enabled by default for top-level apps.
-
- * Better default "app_file", "root", "public", and "views" location
- detection; changes to "root" and "app_file" automatically cascade to
- other options that depend on them.
-
- * Error mappings are now split into two 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)",
- where "status_code" is an integer, 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)".
-
- * In-file templates are now automatically imported from the file that
- requires 'sinatra'. The use_in_file_templates! method is still available
- for loading templates from other files.
-
- * Sinatra's testing support is no longer dependent on Test::Unit. Requiring
- 'sinatra/test' adds the Sinatra::Test module and Sinatra::TestHarness
- class, which can be used with any test framework. The 'sinatra/test/unit',
- 'sinatra/test/spec', 'sinatra/test/rspec', or 'sinatra/test/bacon' files
- can be required to setup a framework-specific testing environment. See the
- README for more information.
-
- * Added support for Bacon (test framework). The 'sinatra/test/bacon' file
- can be required to setup Sinatra test helpers on Bacon::Context.
-
- * Deprecated "set_option" and "set_options"; use "set" instead.
-
- * Deprecated the "env" option ("options.env"); use "environment" instead.
-
- * Deprecated the request level "stop" method; use "halt" instead.
-
- * Deprecated the request level "entity_tag" method; use "etag" instead.
- Both "entity_tag" and "etag" were previously supported.
-
- * Deprecated the request level "headers" method (HTTP response headers);
- use "response['Header-Name']" instead.
-
- * Deprecated "Sinatra.application"; use "Sinatra::Application" instead.
-
- * Deprecated setting Sinatra.application = nil to reset an application.
- This should no longer be necessary.
-
- * Deprecated "Sinatra.default_options"; use
- "Sinatra::Default.set(key, value)" instead.
-
- * Deprecated the "ServerError" exception. All Exceptions are now
- treated as internal server errors and result in a 500 response
- status.
-
- * Deprecated the "get_it", "post_it", "put_it", "delete_it", and "head_it"
- test helper methods. Use "get", "post", "put", "delete", and "head",
- respectively, instead.
-
- * Removed Event and EventContext classes. Applications are defined in a
- subclass of Sinatra::Base; each request is processed within an
- instance.
-
-= 0.3.3 / 2009-01-06
-
- * Pin to Rack 0.4.0 (this is the last release on Rack 0.4)
-
- * Log unhandled exception backtraces to rack.errors.
-
- * Use RACK_ENV environment variable to establish Sinatra
- environment when given. Thin sets this when started with
- the -e argument.
-
- * BUG: raising Sinatra::NotFound resulted in a 500 response
- code instead of 404.
-
- * BUG: use_in_file_templates! fails with CR/LF (#45)
-
- * BUG: Sinatra detects the app file and root path when run under
- thin/passenger.
-
-= 0.3.2
-
- * BUG: Static and send_file read entire file into String before
- sending. Updated to stream with 8K chunks instead.
-
- * Rake tasks and assets for building basic documentation website.
- See http://sinatra.rubyforge.org
-
- * Various minor doc fixes.
-
-= 0.3.1
-
- * Unbreak optional path parameters [jeremyevans]
-
-= 0.3.0
-
- * Add sinatra.gemspec w/ support for github gem builds. Forks can now
- enable the build gem option in github to get free username-sinatra.gem
- builds: gem install username-sinatra.gem --source=http://gems.github.com/
-
- * Require rack-0.4 gem; removes frozen rack dir.
-
- * Basic RSpec support; require 'sinatra/test/rspec' instead of
- 'sinatra/test/spec' to use. [avdi]
-
- * before filters can modify request environment vars used for
- routing (e.g., PATH_INFO, REQUEST_METHOD, etc.) for URL rewriting
- type functionality.
-
- * In-file templates now uses @@ instead of ## as template separator.
-
- * Top-level environment test predicates: development?, test?, production?
-
- * Top-level "set", "enable", and "disable" methods for tweaking
- app options. [rtomayko]
-
- * Top-level "use" method for building Rack middleware pipelines
- leading to app. See README for usage. [rtomayko]
-
- * New "reload" option - set false to disable reloading in development.
-
- * New "host" option - host/ip to bind to [cschneid]
-
- * New "app_file" option - override the file to reload in development
- mode [cschneid]
-
- * Development error/not_found page cleanup [sr, adamwiggins]
-
- * Remove a bunch of core extensions (String#to_param, String#from_param,
- Hash#from_params, Hash#to_params, Hash#symbolize_keys, Hash#pass)
-
- * Various grammar and formatting fixes to README; additions on
- community and contributing [cypher]
-
- * Build RDoc using Hanna template: http://sinatrarb.rubyforge.org/api
-
- * Specs, documentation and fixes for splat'n routes [vic]
-
- * Fix whitespace errors across all source files. [rtomayko]
-
- * Fix streaming issues with Mongrel (body not closed). [bmizerany]
-
- * Fix various issues with environment not being set properly (configure
- blocks not running, error pages not registering, etc.) [cypher]
-
- * Fix to allow locals to be passed to ERB templates [cschneid]
-
- * Fix locking issues causing random errors during reload in development.
-
- * Fix for escaped paths not resolving static files [Matthew Walker]
-
-= 0.2.1
-
- * File upload fix and minor tweaks.
-
-= 0.2.0
-
- * Initial gem release of 0.2 codebase.
View
22 vendor/sinatra/LICENSE
@@ -1,22 +0,0 @@
-Copyright (c) 2007, 2008, 2009 Blake Mizerany
-
-Permission is hereby granted, free of charge, to any person
-obtaining a copy of this software and associated documentation
-files (the "Software"), to deal in the Software without
-restriction, including without limitation the rights to use,
-copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the
-Software is furnished to do so, subject to the following
-conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-OTHER DEALINGS IN THE SOFTWARE.
View
552 vendor/sinatra/README.jp.rdoc
@@ -1,552 +0,0 @@
-= Sinatra
-
-SinatraはRubyで下記のような最小労力で手早くウェブアプリケーションを作成するためのDSLです。
-
- # myapp.rb
- require 'rubygems'
- require 'sinatra'
- get '/' do
- 'Hello world!'
- end
-
-gemをインストールして動かしてみる。
-
- sudo gem install sinatra
- ruby myapp.rb
-
-http://localhost:4567 を見る。
-
-== ルート
-
-Sinatraでは、ルートはHTTPメソッドとURLマッチングパターンがペアになっています。
-ルートはブロックに結び付けられています。
-
- get '/' do
- .. 何か見せる ..
- end
-
- post '/' do
- .. 何か生成する ..
- end
-
- put '/' do
- .. 何か更新する ..
- end
-
- delete '/' do
- .. 何か削除する ..
- end
-
-ルートは定義された順番にマッチします。 リクエストに最初にマッチしたルートが呼び出されます。
-
-ルートのパターンは名前付きパラメータを含むことができ、
-<tt>params</tt>ハッシュで取得できます。
-
- get '/hello/:name' do
- # matches "GET /hello/foo" and "GET /hello/bar"
- # params[:name] is 'foo' or 'bar'
- "Hello #{params[:name]}!"
- end
-
-また、ブロックパラメータで名前付きパラメータにアクセスすることもできます。
-
- get '/hello/:name' do |n|
- "Hello #{n}!"
- end
-
-ルートパターンはsplat(またはワイルドカード)を含むこともでき、
-<tt>params[:splat]</tt> で取得できます。
-
- get '/say/*/to/*' do
- # matches /say/hello/to/world
- params[:splat] # => ["hello", "world"]
- end
-
- get '/download/*.*' do
- # matches /download/path/to/file.xml
- params[:splat] # => ["path/to/file", "xml"]
- end
-
-正規表現を使ったルート:
-
- get %r{/hello/([\w]+)} do
- "Hello, #{params[:captures].first}!"
- end
-
-ブロックパラーメータを使用した場合:
-
- get %r{/hello/([\w]+)} do |c|
- "Hello, #{c}!"
- end
-
-ルートにはユーザエージェントのようなさまざまな条件を含めることができます。
-
- get '/foo', :agent => /Songbird (\d\.\d)[\d\/]*?/ do
- "You're using Songbird version #{params[:agent][0]}"
- end
-
- get '/foo' do
- # Matches non-songbird browsers
- end
-
-== 静的ファイル
-
-静的ファイルは<tt>./public</tt>ディレクトリから配信されます。
-<tt>:public</tt>オプションを指定することで別の場所を指定することができます。
-
- set :public, File.dirname(__FILE__) + '/static'
-
-注意: この静的ファイル用のディレクトリ名はURL中に含まれません。
-例えば、<tt>./public/css/style.css</tt>は<tt>http://example.com/css/style.css</tt>でアクセスできます。
-
-== ビュー / テンプレート
-
-テンプレートは<tt>./views</tt>ディレクトリ下に配置されています。
-他のディレクトリを使用する場合の例:
-
- set :views, File.dirname(__FILE__) + '/templates'
-
-テンプレートはシンボルを使用して参照させることを覚えておいて下さい。
-サブデレクトリでもこの場合は<tt>:'subdir/template'</tt>のようにします。
-レンダリングメソッドは文字列が渡されると、そのまま文字列を出力します。
-
-=== Haml テンプレート
-
-hamlを使うにはhamlライブラリが必要です:
-
- ## hamlを読み込みます
- require 'haml'
-
- get '/' do
- haml :index
- end
-
-<tt>./views/index.haml</tt>を表示します。
-
-{Haml's options}[http://haml.hamptoncatlin.com/docs/rdoc/classes/Haml.html]
-はSinatraの設定でグローバルに設定することができます。
-{Options and Configurations}[http://www.sinatrarb.com/configuration.html],
-を参照してそれぞれ設定を上書きして下さい。
-
- set :haml, {:format => :html5 } # デフォルトのフォーマットは:xhtml
-
- get '/' do
- haml :index, :haml_options => {:format => :html4 } # 上書き
- end
-
-
-=== Erb テンプレート
-
- ## erbを読み込みます
- require 'erb'
-
- get '/' do
- erb :index
- end
-
-<tt>./views/index.erb</tt>を表示します。
-
-=== Builder テンプレート
-
-builderを使うにはbuilderライブラリが必要です:
-
- ## builderを読み込みます
- require 'builder'
-
- get '/' do
- content_type 'application/xml', :charset => 'utf-8'
- builder :index
- end
-
-<tt>./views/index.builder</tt>を表示します。
-
-=== Sass テンプレート
-
-Sassテンプレートを使うにはsassライブラリが必要です:
-
- ## hamlかsassを読み込みます
- require 'sass'
-
- get '/stylesheet.css' do
- content_type 'text/css', :charset => 'utf-8'
- sass :stylesheet
- end
-
-<tt>./views/stylesheet.sass</tt>を表示します。
-
-{Sass' options}[http://haml.hamptoncatlin.com/docs/rdoc/classes/Sass.html]
-はSinatraの設定でグローバルに設定することができます。
-see {Options and Configurations}[http://www.sinatrarb.com/configuration.html],
-を参照してそれぞれ設定を上書きして下さい。
-
- set :sass, {:style => :compact } # デフォルトのSass styleは :nested
-
- get '/stylesheet.css' do
- content_type 'text/css', :charset => 'utf-8'
- sass :stylesheet, :sass_options => {:style => :expanded } # 上書き
- end
-
-
-=== インラインテンプレート
-
- get '/' do
- haml '%div.title Hello World'
- end
-
-文字列をテンプレートとして表示します。
-
-=== テンプレート内で変数にアクセスする
-
-テンプレートはルートハンドラと同じコンテキストの中で評価されます。. ルートハンドラでセットされたインスタンス変数は
-テンプレート内で直接使うことができます。
-
- get '/:id' do
- @foo = Foo.find(params[:id])
- haml '%h1= @foo.name'
- end
-
-ローカル変数を明示的に定義することもできます。
-
- get '/:id' do
- foo = Foo.find(params[:id])
- haml '%h1= foo.name', :locals => { :foo => foo }
- end
-
-このやり方は他のテンプレート内で部分テンプレートとして表示する時に典型的に使用されます。
-
-=== ファイル内テンプレート
-
-テンプレートはソースファイルの最後で定義することもできます。
-
- require 'rubygems'
- require 'sinatra'
-
- get '/' do
- haml :index
- end
-
- __END__
-
- @@ layout
- %html
- = yield
-
- @@ index
- %div.title Hello world!!!!!
-
-注意: sinatraをrequireするファイル内で定義されたファイル内テンプレートは自動的に読み込まれます。
-他のファイルで定義されているテンプレートを使うには <tt>use_in_file_templates!</tt>メソッドで指定します。
-
-=== 名前付きテンプレート
-
-テンプレートはトップレベルの<tt>template</tt>メソッドで定義することができます。
-
- template :layout do
- "%html\n =yield\n"
- end
-
- template :index do
- '%div.title Hello World!'
- end
-
- get '/' do
- haml :index
- end
-
-「layout」というテンプレートが存在する場合、そのテンプレートファイルは他のテンプレートが
-表示される度に使用されます。<tt>:layout => false</tt>.することでlayoutsを無効にできます。
-
- get '/' do
- haml :index, :layout => !request.xhr?
- end
-
-== ヘルパー
-
-トップレベルの<tt>helpers</tt>を使用してルートハンドラやテンプレートで使うヘルパメソッドを
-定義できます。
-
- helpers do
- def bar(name)
- "#{name}bar"
- end
- end
-
- get '/:name' do
- bar(params[:name])
- end
-
-== フィルタ
-
-beforeフィルタはリクエストされたコンテキストを実行する前に評価され、
-リクエストとレスポンスを変更することができます。フィルタ内でセットされた
-インスタンス変数はルーティングとテンプレートで使用できます。
-
- before do
- @note = 'Hi!'
- request.path_info = '/foo/bar/baz'
- end
-
- get '/foo/*' do
- @note #=> 'Hi!'
- params[:splat] #=> 'bar/baz'
- end
-
-== 強制終了
-
-ルートかbeforeフィルタ内で直ちに実行を終了する方法:
-
- halt
-
-body部を指定することもできます ...
-
- halt 'ここにbodyを書く'
-
-ステータスとbody部を指定する ...
-
- halt 401, '立ち去れ!'
-
-== パッシング(Passing)
-
-ルートは<tt>pass</tt>を使って次のルートに飛ばすことができます:
-
- get '/guess/:who' do
- pass unless params[:who] == 'Frank'
- "見つかっちゃった!"
- end
-
- get '/guess/*' do
- "はずれです!"
- end
-
-ルートブロックからすぐに抜け出し、次にマッチするルートを実行します。
-マッチするルートが見当たらない場合は404が返されます。
-
-== 設定
-
-どの環境でも起動時に1回だけ実行されます。
-
- configure do
- ...
- end
-
-環境変数<tt>:production</tt>(RACK_ENV環境変数) がセットされている時だけ実行する方法:
-
- configure :production do
- ...
- end
-
-環境変数<tt>:production</tt> か<tt>:test</tt>の場合に設定する方法:
-
- configure :production, :test do
- ...
- end
-
-== エラーハンドリング
-
-エラーハンドラーはルートコンテキストとbeforeフィルタ内で実行します。
-<tt>haml</tt>、<tt>erb</tt>、<tt>halt</tt>などを使うこともできます。
-
-=== Not Found
-
-<tt>Sinatra::NotFound</tt>が起きた時か レスポンスのステータスコードが
-404の時に<tt>not_found</tt>ハンドラーが発動します。
-
- not_found do
- 'ファイルが存在しません'
- end
-
-=== エラー
-
-+error+ ハンドラーはルートブロックかbeforeフィルタ内で例外が発生した時はいつでも発動します。
-block or before filter. 例外オブジェクトはRack変数<tt>sinatra.error</tt>から取得されます。
-
- error do
- 'エラーが発生しました。 - ' + env['sinatra.error'].name
- end
-
-エラーをカスタマイズする場合は、
-
- error MyCustomError do
- 'エラーメッセージ...' + request.env['sinatra.error'].message
- end
-
-と書いておいて,下記のように呼び出します。
-
- get '/' do
- raise MyCustomError, '何かがまずかったようです'
- end
-
-そうするとこうなります:
-
- エラーメッセージ... 何かがまずかったようです
-
-開発環境として実行している場合、Sinatraは特別な<tt>not_found</tt>と<tt>error</tt>ハンドラーを
-インストールしています。
-
-== MIMEタイプ
-
-<tt>send_file</tt>か静的ファイルを使う時、Sinatraが理解でいないMIMEタイプがある場合があります。
-その時は +mime_type+ を使ってファイル拡張子毎に登録して下さい。
-
- mime_type :foo, 'text/foo'
-
-== Rackミドルウェア
-
-SinatraはRack[http://rack.rubyforge.org/]というRubyのWEBフレームワーク用の
-最小限の標準インターフェース 上で動作しています。Rack中でもアプリケーションデベロッパー
-向けに一番興味深い機能はミドルウェア(サーバとアプリケーション間に介在し、モニタリング、HTTPリクエストとレスポンス
-の手動操作ができるなど、一般的な機能のいろいろなことを提供するもの)をサポートすることです。
-
-Sinatraではトップレベルの+user+ メソッドを使ってRackにパイプラインを構築します。
-
- require 'sinatra'
- require 'my_custom_middleware'
-
- use Rack::Lint
- use MyCustomMiddleware
-
- get '/hello' do
- 'Hello World'
- end
-
-<tt>use</tt> の意味は{Rack::Builder}[http://rack.rubyforge.org/doc/classes/Rack/Builder.html] DSLで定義されていることと全て一致します。
-例えば +use+ メソッドはブロック構文のように複数の引数を受け取ることができます。
-
- use Rack::Auth::Basic do |username, password|
- username == 'admin' && password == 'secret'
- end
-
-Rackはログ、デバッギング、URLルーティング、認証、セッションなどいろいろな機能を備えた標準的ミドルウェアです。
-Sinatraはその多くのコンポーネントを自動で使うよう基本設定されているため、+use+で明示的に指定する必要はありません。
-
-== テスト
-
-SinatraでのテストはRack-basedのテストライブラリかフレームワークを使って書くことができます。
-{Rack::Test}[http://gitrdoc.com/brynary/rack-test] をおすすめします。やり方:
-
- require 'my_sinatra_app'
- require 'rack/test'
-
- class MyAppTest < Test::Unit::TestCase
- include Rack::Test::Methods
-
- def app
- Sinatra::Application
- end
-
- def test_my_default
- get '/'
- assert_equal 'Hello World!', last_response.body
- end
-
- def test_with_params
- get '/meet', :name => 'Frank'
- assert_equal 'Hello Frank!', last_response.body
- end
-
- def test_with_rack_env
- get '/', {}, 'HTTP_USER_AGENT' => 'Songbird'
- assert_equal "あなたはSongbirdを使ってますね!", last_response.body
- end
- end
-
-注意: ビルトインのSinatra::TestモジュールとSinatra::TestHarnessクラスは
-0.9.2リリース以降、廃止予定になっています。
-
-== Sinatra::Base - ミドルウェア、ライブラリ、 モジュラーアプリ
-
-トップレベル(グローバル領域)上でいろいろ定義していくのは軽量アプリならうまくいきますが、
-RackミドルウェアやRails metal、サーバのコンポーネントを含んだシンプルな
-ライブラリやSinatraの拡張プログラムを考慮するような場合はそうとは限りません。
-トップレベルのDSLがネームスペースを汚染したり、設定を変えてしまうこと(例:./publicや./view)がありえます。
-そこでSinatra::Baseの出番です。
-
- require 'sinatra/base'
-
- class MyApp < Sinatra::Base
- set :sessions, true
- set :foo, 'bar'
-
- get '/' do
- 'Hello world!'
- end
- end
-
-このMyAppは独立したRackコンポーネントで、RackミドルウェアやRackアプリケーション
-Rails metalとして使用することができます。<tt>config.ru</tt>ファイル内で +use+ か、または
-+run+ でこのクラスを指定するか、ライブラリとしてサーバコンポーネントをコントロールします。
-
- MyApp.run! :host => 'localhost', :port => 9090
-
-Sinatra::Baseのサブクラスで使えるメソッドはトップレベルのDSLを経由して確実に使うことができます。
-ほとんどのトップレベルで記述されたアプリは、以下の2点を修正することでSinatra::Baseコンポーネントに変えることができます。
-
-* +sinatra+の代わりに<tt>sinatra/base</tt>を読み込む
-(そうしない場合、SinatraのDSLメソッドの全てがメインネームスペースにインポートされます)
-* ルート、エラーハンドラー、フィルター、オプションをSinatra::Baseのサブクラスに書く
-
-<tt>Sinatra::Base</tt> はまっさらです。ビルトインサーバを含む、ほとんどのオプションがデフォルト
-で無効になっています。オプション詳細については{Options and Configuration}[http://sinatra.github.com/configuration.html]
-をご覧下さい。
-
-補足: SinatraのトップレベルDSLはシンプルな委譲(delgation)システムで実装されています。
-<tt>Sinatra::Application</tt>クラス(Sinatra::Baseの特別なサブクラス)は、トップレベルに送られる
-:get、 :put、 :post、:delete、 :before、:error、:not_found、 :configure、:set messagesのこれら
-全てを受け取ります。 詳細を閲覧されたい方はこちら(英語):
-{Sinatra::Delegator mixin}[http://github.com/sinatra/sinatra/blob/master/lib/sinatra/base.rb#L1064]
-{included into the main namespace}[http://github.com/sinatra/sinatra/blob/master/lib/sinatra/main.rb#L25].
-
-== コマンドライン
-
-Sinatraアプリケーションは直接実行できます。
-
- ruby myapp.rb [-h] [-x] [-e ENVIRONMENT] [-p PORT] [-s HANDLER]
-
-オプション:
-
- -h # ヘルプ
- -p # ポート指定(デフォルトは4567)
- -e # 環境を指定 (デフォルトはdevelopment)
- -s # rackserver/handlerを指定 (デフォルトはthin)
- -x # mutex lockを付ける (デフォルトはoff)
-
-== 最新開発版について
-
-Sinatraの開発版を使いたい場合は、ローカルに開発版を落として、
-<tt>LOAD_PATH</tt>の<tt>sinatra/lib</tt>ディレクトリを指定して実行して下さい。
-
- cd myapp
- git clone git://github.com/sinatra/sinatra.git
- ruby -Isinatra/lib myapp.rb
-
-<tt>sinatra/lib</tt>ディレクトリをto the<tt>LOAD_PATH</tt>に追加する方法もあります。
-
- $LOAD_PATH.unshift File.dirname(__FILE__) + '/sinatra/lib'
- require 'rubygems'
- require 'sinatra'
-
- get '/about' do
- "今使ってるバージョンは" + Sinatra::VERSION
- end
-
-Sinatraのソースを更新する方法:
-
- cd myproject/sinatra
- git pull
-
-== その他
-
-日本語サイト
-
-* {Greenbear Laboratory Rack日本語マニュアル}[http://mono.kmc.gr.jp/~yhara/w/?RackReferenceJa] - Rackの日本語マニュアル
-
-英語サイト
-
-* {プロジェクトサイト}[http://sinatra.github.com/] - ドキュメント、
- ニュース、他のリソースへのリンクがあります。
-* {プロジェクトに参加(貢献)する}[http://sinatra.github.com/contributing.html] - バグレポート
- パッチの送信、サポートなど
-* {Lighthouse}[http://sinatra.lighthouseapp.com] - チケット管理とリリース計画
-* {Twitter}[http://twitter.com/sinatra]
-* {メーリングリスト}[http://groups.google.com/group/sinatrarb]
-* {IRC: #sinatra}[irc://chat.freenode.net/#sinatra] on http://freenode.net
View
581 vendor/sinatra/README.rdoc
@@ -1,581 +0,0 @@
-= Sinatra
-
-Sinatra is a DSL for quickly creating web applications in Ruby with minimal
-effort:
-
- # myapp.rb
- require 'rubygems'
- require 'sinatra'
- get '/' do
- 'Hello world!'
- end
-
-Install the gem and run with:
-
- sudo gem install sinatra
- ruby myapp.rb
-
-View at: http://localhost:4567
-
-== Routes
-
-In Sinatra, a route is an HTTP method paired with an URL matching pattern.
-Each route is associated with a block:
-
- get '/' do
- .. show something ..
- end
-
- post '/' do
- .. create something ..
- end
-
- put '/' do
- .. update something ..
- end
-
- delete '/' do
- .. annihilate something ..
- end
-
-Routes are matched in the order they are defined. The first route that
-matches the request is invoked.
-
-Route patterns may include named parameters, accessible via the
-<tt>params</tt> hash:
-
- get '/hello/:name' do
- # matches "GET /hello/foo" and "GET /hello/bar"
- # params[:name] is 'foo' or 'bar'
- "Hello #{params[:name]}!"
- end
-
-You can also access named parameters via block parameters:
-
- get '/hello/:name' do |n|
- "Hello #{n}!"
- end
-
-Route patterns may also include splat (or wildcard) parameters, accessible
-via the <tt>params[:splat]</tt> array.
-
- get '/say/*/to/*' do
- # matches /say/hello/to/world
- params[:splat] # => ["hello", "world"]
- end
-
- get '/download/*.*' do
- # matches /download/path/to/file.xml
- params[:splat] # => ["path/to/file", "xml"]
- end
-
-Route matching with Regular Expressions:
-
- get %r{/hello/([\w]+)} do
- "Hello, #{params[:captures].first}!"
- end
-
-Or with a block parameter:
-
- get %r{/hello/([\w]+)} do |c|
- "Hello, #{c}!"
- end
-
-Routes may include a variety of matching conditions, such as the user agent:
-
- get '/foo', :agent => /Songbird (\d\.\d)[\d\/]*?/ do
- "You're using Songbird version #{params[:agent][0]}"
- end
-
- get '/foo' do
- # Matches non-songbird browsers
- end
-
-== Static Files
-
-Static files are served from the <tt>./public</tt> directory. You can specify
-a different location by setting the <tt>:public</tt> option:
-
- set :public, File.dirname(__FILE__) + '/static'
-
-Note that the public directory name is not included in the URL. A file
-<tt>./public/css/style.css</tt> is made available as
-<tt>http://example.com/css/style.css</tt>.
-
-== Views / Templates
-
-Templates are assumed to be located directly under the <tt>./views</tt>
-directory. To use a different views directory:
-
- set :views, File.dirname(__FILE__) + '/templates'
-
-One important thing to remember is that you always have to reference
-templates with symbols, even if they're in a subdirectory (in this
-case use <tt>:'subdir/template'</tt>). Rendering methods will render
-any strings passed to them directly.
-
-=== Haml Templates
-
-The haml gem/library is required to render HAML templates:
-
- ## You'll need to require haml in your app
- require 'haml'
-
- get '/' do
- haml :index
- end
-
-Renders <tt>./views/index.haml</tt>.
-
-{Haml's options}[http://haml.hamptoncatlin.com/docs/rdoc/classes/Haml.html]
-can be set globally through Sinatra's configurations,
-see {Options and Configurations}[http://www.sinatrarb.com/configuration.html],
-and overridden on an individual basis.
-
- set :haml, {:format => :html5 } # default Haml format is :xhtml
-
- get '/' do
- haml :index, :haml_options => {:format => :html4 } # overridden
- end
-
-
-=== Erb Templates
-
- ## You'll need to require erb in your app
- require 'erb'
-
- get '/' do
- erb :index
- end
-
-Renders <tt>./views/index.erb</tt>
-
-=== Builder Templates
-
-The builder gem/library is required to render builder templates:
-
- ## You'll need to require builder in your app
- require 'builder'
-
- get '/' do
- content_type 'application/xml', :charset => 'utf-8'
- builder :index
- end
-
-Renders <tt>./views/index.builder</tt>.
-
-=== Sass Templates
-
-The sass gem/library is required to render Sass templates:
-
- ## You'll need to require haml or sass in your app
- require 'sass'
-
- get '/stylesheet.css' do
- content_type 'text/css', :charset => 'utf-8'
- sass :stylesheet
- end
-
-Renders <tt>./views/stylesheet.sass</tt>.
-
-{Sass' options}[http://haml.hamptoncatlin.com/docs/rdoc/classes/Sass.html]
-can be set globally through Sinatra's configurations,
-see {Options and Configurations}[http://www.sinatrarb.com/configuration.html],
-and overridden on an individual basis.
-
- set :sass, {:style => :compact } # default Sass style is :nested
-
- get '/stylesheet.css' do
- content_type 'text/css', :charset => 'utf-8'
- sass :stylesheet, :sass_options => {:style => :expanded } # overridden
- end
-
-
-=== Inline Templates
-
- get '/' do
- haml '%div.title Hello World'
- end
-
-Renders the inlined template string.
-
-=== Accessing Variables in Templates
-
-Templates are evaluated within the same context as route handlers. Instance
-variables set in route handlers are direcly accessible by templates:
-
- get '/:id' do
- @foo = Foo.find(params[:id])
- haml '%h1= @foo.name'
- end
-
-Or, specify an explicit Hash of local variables:
-
- get '/:id' do
- foo = Foo.find(params[:id])
- haml '%h1= foo.name', :locals => { :foo => foo }
- end
-
-This is typically used when rendering templates as partials from within
-other templates.
-
-=== Inline Templates
-
-Templates may be defined at the end of the source file:
-
- require 'rubygems'
- require 'sinatra'
-
- get '/' do
- haml :index
- end
-
- __END__
-
- @@ layout
- %html
- = yield
-
- @@ index
- %div.title Hello world!!!!!
-
-NOTE: Inline templates defined in the source file that requires sinatra
-are automatically loaded. Call `enable :inline_templates` explicitly if you
-have inline templates in other source files.
-
-=== Named Templates
-
-Templates may also be defined using the top-level <tt>template</tt> method:
-
- template :layout do
- "%html\n =yield\n"
- end
-
- template :index do
- '%div.title Hello World!'
- end
-
- get '/' do
- haml :index
- end
-
-If a template named "layout" exists, it will be used each time a template
-is rendered. You can disable layouts by passing <tt>:layout => false</tt>.
-
- get '/' do
- haml :index, :layout => !request.xhr?
- end
-
-== Helpers
-
-Use the top-level <tt>helpers</tt> method to define helper methods for use in
-route handlers and templates:
-
- helpers do
- def bar(name)
- "#{name}bar"
- end
- end
-
- get '/:name' do
- bar(params[:name])
- end
-
-== Filters
-
-Before filters are evaluated before each request within the context of the
-request and can modify the request and response. Instance variables set in
-filters are accessible by routes and templates:
-
- before do
- @note = 'Hi!'
- request.path_info = '/foo/bar/baz'
- end
-
- get '/foo/*' do
- @note #=> 'Hi!'
- params[:splat] #=> 'bar/baz'
- end
-
-After filter are evaluated after each request within the context of the
-request and can also modify the request and response. Instance variables
-set in before filters and routes are accessible by after filters:
-
- after do
- puts response.status
- end
-
-== Halting
-
-To immediately stop a request within a filter or route use:
-
- halt
-
-You can also specify a body when halting ...
-
- halt 'this will be the body'
-
-Or set the status and body ...
-
- halt 401, 'go away!'
-
-== Passing
-
-A route can punt processing to the next matching route using <tt>pass</tt>:
-
- get '/guess/:who' do
- pass unless params[:who] == 'Frank'
- "You got me!"
- end
-
- get '/guess/*' do
- "You missed!"
- end
-
-The route block is immediately exited and control continues with the next
-matching route. If no matching route is found, a 404 is returned.
-
-== Configuration
-
-Run once, at startup, in any environment:
-
- configure do
- ...
- end
-
-Run only when the environment (RACK_ENV environment variable) is set to
-<tt>:production</tt>:
-
- configure :production do
- ...
- end
-
-Run when the environment is set to either <tt>:production</tt> or
-<tt>:test</tt>:
-
- configure :production, :test do
- ...
- end
-
-== Error handling
-
-Error handlers run within the same context as routes and before filters, which
-means you get all the goodies it has to offer, like <tt>haml</tt>, <tt>erb</tt>,
-<tt>halt</tt>, etc.
-
-=== Not Found
-
-When a <tt>Sinatra::NotFound</tt> exception is raised, or the response's status
-code is 404, the <tt>not_found</tt> handler is invoked:
-
- not_found do
- 'This is nowhere to be found'
- end
-
-=== Error
-
-The +error+ handler is invoked any time an exception is raised from a route
-block or before filter. The exception object can be obtained from the
-<tt>sinatra.error</tt> Rack variable:
-
- error do
- 'Sorry there was a nasty error - ' + env['sinatra.error'].name
- end
-
-Custom errors:
-
- error MyCustomError do
- 'So what happened was...' + request.env['sinatra.error'].message
- end
-
-Then, if this happens:
-
- get '/' do
- raise MyCustomError, 'something bad'
- end
-
-You get this:
-
- So what happened was... something bad
-
-Sinatra installs special <tt>not_found</tt> and <tt>error</tt> handlers when
-running under the development environment.
-
-== Mime types
-
-When using <tt>send_file</tt> or static files you may have mime types Sinatra
-doesn't understand. Use +mime_type+ to register them by file extension:
-
- mime_type :foo, 'text/foo'
-
-== Rack Middleware
-
-Sinatra rides on Rack[http://rack.rubyforge.org/], a minimal standard
-interface for Ruby web frameworks. One of Rack's most interesting capabilities
-for application developers is support for "middleware" -- components that sit
-between the server and your application monitoring and/or manipulating the
-HTTP request/response to provide various types of common functionality.
-
-Sinatra makes building Rack middleware pipelines a cinch via a top-level
-+use+ method:
-
- require 'sinatra'
- require 'my_custom_middleware'
-
- use Rack::Lint
- use MyCustomMiddleware
-
- get '/hello' do
- 'Hello World'
- end
-
-The semantics of +use+ are identical to those defined for the
-Rack::Builder[http://rack.rubyforge.org/doc/classes/Rack/Builder.html] DSL
-(most frequently used from rackup files). For example, the +use+ method
-accepts multiple/variable args as well as blocks:
-
- use Rack::Auth::Basic do |username, password|
- username == 'admin' && password == 'secret'
- end
-
-Rack is distributed with a variety of standard middleware for logging,
-debugging, URL routing, authentication, and session handling. Sinatra uses
-many of of these components automatically based on configuration so you
-typically don't have to +use+ them explicitly.
-
-== Testing
-
-Sinatra tests can be written using any Rack-based testing library
-or framework. {Rack::Test}[http://gitrdoc.com/brynary/rack-test] is
-recommended:
-
- require 'my_sinatra_app'
- require 'rack/test'
-
- class MyAppTest < Test::Unit::TestCase
- include Rack::Test::Methods
-
- def app
- Sinatra::Application
- end
-
- def test_my_default
- get '/'
- assert_equal 'Hello World!', last_response.body
- end
-
- def test_with_params
- get '/meet', :name => 'Frank'
- assert_equal 'Hello Frank!', last_response.body
- end
-
- def test_with_rack_env
- get '/', {}, 'HTTP_USER_AGENT' => 'Songbird'
- assert_equal "You're using Songbird!", last_response.body
- end
- end
-
-NOTE: The built-in Sinatra::Test module and Sinatra::TestHarness class
-are deprecated as of the 0.9.2 release.
-
-== Sinatra::Base - Middleware, Libraries, and Modular Apps
-
-Defining your app at the top-level works well for micro-apps but has
-considerable drawbacks when building reuseable components such as Rack
-middleware, Rails metal, simple libraries with a server component, or
-even Sinatra extensions. The top-level DSL pollutes the Object namespace
-and assumes a micro-app style configuration (e.g., a single application
-file, ./public and ./views directories, logging, exception detail page,
-etc.). That's where Sinatra::Base comes into play:
-
- require 'sinatra/base'
-
- class MyApp < Sinatra::Base
- set :sessions, true
- set :foo, 'bar'
-
- get '/' do
- 'Hello world!'
- end
- end
-
-The MyApp class is an independent Rack component that can act as
-Rack middleware, a Rack application, or Rails metal. You can +use+ or
-+run+ this class from a rackup +config.ru+ file; or, control a server
-component shipped as a library:
-
- MyApp.run! :host => 'localhost', :port => 9090
-
-The methods available to Sinatra::Base subclasses are exactly as those
-available via the top-level DSL. Most top-level apps can be converted to
-Sinatra::Base components with two modifications:
-
-* Your file should require +sinatra/base+ instead of +sinatra+;
- otherwise, all of Sinatra's DSL methods are imported into the main
- namespace.
-* Put your app's routes, error handlers, filters, and options in a subclass
- of Sinatra::Base.
-
-+Sinatra::Base+ is a blank slate. Most options are disabled by default,
-including the built-in server. See {Options and Configuration}[http://sinatra.github.com/configuration.html]
-for details on available options and their behavior.
-
-SIDEBAR: Sinatra's top-level DSL is implemented using a simple delegation
-system. The +Sinatra::Application+ class -- a special subclass of
-Sinatra::Base -- receives all :get, :put, :post, :delete, :before,
-:error, :not_found, :configure, and :set messages sent to the
-top-level. Have a look at the code for yourself: here's the
-{Sinatra::Delegator mixin}[http://github.com/sinatra/sinatra/blob/master/lib/sinatra/base.rb#L1064]
-being {included into the main namespace}[http://github.com/sinatra/sinatra/blob/master/lib/sinatra/main.rb#L25].
-
-== Command line
-
-Sinatra applications can be run directly:
-
- ruby myapp.rb [-h] [-x] [-e ENVIRONMENT] [-p PORT] [-s HANDLER]
-
-Options are:
-
- -h # help
- -p # set the port (default is 4567)
- -e # set the environment (default is development)
- -s # specify rack server/handler (default is thin)
- -x # turn on the mutex lock (default is off)
-
-== The Bleeding Edge
-
-If you would like to use Sinatra's latest bleeding code, create a local
-clone and run your app with the <tt>sinatra/lib</tt> directory on the
-<tt>LOAD_PATH</tt>:
-
- cd myapp
- git clone git://github.com/sinatra/sinatra.git
- ruby -Isinatra/lib myapp.rb
-
-Alternatively, you can add the <tt>sinatra/lib</tt> directory to the
-<tt>LOAD_PATH</tt> in your application:
-
- $LOAD_PATH.unshift File.dirname(__FILE__) + '/sinatra/lib'
- require 'rubygems'
- require 'sinatra'
-
- get '/about' do
- "I'm running version " + Sinatra::VERSION
- end
-
-To update the Sinatra sources in the future:
-
- cd myproject/sinatra
- git pull
-
-== More
-
-* {Project Website}[http://sinatra.github.com/] - Additional documentation,
- news, and links to other resources.
-* {Contributing}[http://sinatra.github.com/contributing.html] - Find a bug? Need
- help? Have a patch?
-* {Lighthouse}[http://sinatra.lighthouseapp.com] - Issue tracking and release
- planning.
-* {Twitter}[http://twitter.com/sinatra]
-* {Mailing List}[http://groups.google.com/group/sinatrarb]
-* {IRC: #sinatra}[irc://chat.freenode.net/#sinatra] on http://freenode.net
View
129 vendor/sinatra/Rakefile
@@ -1,129 +0,0 @@
-require 'rake/clean'
-require 'rake/testtask'
-require 'fileutils'
-
-task :default => :test
-task :spec => :test
-
-# SPECS ===============================================================
-
-Rake::TestTask.new(:test) do |t|
- t.test_files = FileList['test/*_test.rb']
- t.ruby_opts = ['-rubygems'] if defined? Gem
-end
-
-# PACKAGING ============================================================
-
-# Load the gemspec using the same limitations as github
-def spec
- @spec ||=
- begin
- require 'rubygems/specification'
- data = File.read('sinatra.gemspec')
- spec = nil
- Thread.new { spec = eval("$SAFE = 3\n#{data}") }.join
- spec
- end
-end
-
-def package(ext='')
- "pkg/sinatra-#{spec.version}" + ext
-end
-
-desc 'Build packages'
-task :package => %w[.gem .tar.gz].map {|e| package(e)}
-
-desc 'Build and install as local gem'
-task :install => package('.gem') do
- sh "gem install #{package('.gem')}"
-end
-
-directory 'pkg/'
-CLOBBER.include('pkg')
-
-file package('.gem') => %w[pkg/ sinatra.gemspec] + spec.files do |f|
- sh "gem build sinatra.gemspec"
- mv File.basename(f.name), f.name
-end
-
-file package('.tar.gz') => %w[pkg/] + spec.files do |f|
- sh <<-SH
- git archive \
- --prefix=sinatra-#{source_version}/ \
- --format=tar \
- HEAD | gzip > #{f.name}
- SH
-end
-
-# Rubyforge Release / Publish Tasks ==================================
-
-desc 'Publish gem and tarball to rubyforge'
-task 'release' => [package('.gem'), package('.tar.gz')] do |t|
- sh <<-end
- rubyforge add_release sinatra sinatra #{spec.version} #{package('.gem')} &&
- rubyforge add_file sinatra sinatra #{spec.version} #{package('.tar.gz')}
- end
-end
-
-# Website ============================================================
-# Building docs requires HAML and the hanna gem:
-# gem install mislav-hanna --source=http://gems.github.com
-
-task 'doc' => ['doc:api']
-
-desc 'Generate Hanna RDoc under doc/api'
-task 'doc:api' => ['doc/api/index.html']
-
-file 'doc/api/index.html' => FileList['lib/**/*.rb','README.rdoc'] do |f|
- rb_files = f.prerequisites
- sh((<<-end).gsub(/\s+/, ' '))
- hanna --charset utf8 \
- --fmt html \
- --inline-source \
- --line-numbers \
- --main README.rdoc \
- --op doc/api \
- --title 'Sinatra API Documentation' \
- #{rb_files.join(' ')}
- end
-end
-CLEAN.include 'doc/api'
-
-# Gemspec Helpers ====================================================
-
-def source_version
- line = File.read('lib/sinatra/base.rb')[/^\s*VERSION = .*/]
- line.match(/.*VERSION = '(.*)'/)[1]
-end
-
-task 'sinatra.gemspec' => FileList['{lib,test,compat}/**','Rakefile','CHANGES','*.rdoc'] do |f|
- # read spec file and split out manifest section
- spec = File.read(f.name)
- head, manifest, tail = spec.split(" # = MANIFEST =\n")
- # replace version and date
- head.sub!(/\.version = '.*'/, ".version = '#{source_version}'")
- head.sub!(/\.date = '.*'/, ".date = '#{Date.today.to_s}'")
- # determine file list from git ls-files
- files = `git ls-files`.
- split("\n").
- sort.
- reject{ |file| file =~ /^\./ }.
- reject { |file| file =~ /^doc/ }.
- map{ |file| " #{file}" }.
- join("\n")
- # piece file back together and write...
- manifest = " s.files = %w[\n#{files}\n ]\n"
- spec = [head,manifest,tail].join(" # = MANIFEST =\n")
- File.open(f.name, 'w') { |io| io.write(spec) }
- puts "updated #{f.name}"
-end
-
-# Rcov ==============================================================
-namespace :test do
- desc 'Mesures test coverage'
- task :coverage do
- rm_f "coverage"
- rcov = "rcov --text-summary --test-unit-only -Ilib"
- system("#{rcov} --no-html --no-color test/*_test.rb")
- end
-end
View
7 vendor/sinatra/lib/sinatra.rb
@@ -1,7 +0,0 @@
-libdir = File.dirname(__FILE__)
-$LOAD_PATH.unshift(libdir) unless $LOAD_PATH.include?(libdir)
-
-require 'sinatra/base'
-require 'sinatra/main'
-
-enable :inline_templates
View
1,148 vendor/sinatra/lib/sinatra/base.rb
@@ -1,1148 +0,0 @@
-require 'thread'
-require 'time'
-require 'uri'
-require 'rack'
-require 'rack/builder'
-require 'sinatra/showexceptions'
-
-# require tilt if available; fall back on bundled version.
-begin
- require 'tilt'
-rescue LoadError
- require 'sinatra/tilt'
-end
-
-module Sinatra
- VERSION = '0.10.1'
-
- # The request object. See Rack::Request for more info:
- # http://rack.rubyforge.org/doc/classes/Rack/Request.html
- class Request < Rack::Request
- def user_agent
- @env['HTTP_USER_AGENT']
- end
-
- # Returns an array of acceptable media types for the response
- def accept
- @env['HTTP_ACCEPT'].to_s.split(',').map { |a| a.strip }
- end
-
- # Override Rack 0.9.x's #params implementation (see #72 in lighthouse)
- def params
- self.GET.update(self.POST)
- rescue EOFError, Errno::ESPIPE
- self.GET
- end
-
- def secure?
- (@env['HTTP_X_FORWARDED_PROTO'] || @env['rack.url_scheme']) == 'https'
- end
- end
-
- # The response object. See Rack::Response and Rack::ResponseHelpers for
- # more info:
- # http://rack.rubyforge.org/doc/classes/Rack/Response.html
- # http://rack.rubyforge.org/doc/classes/Rack/Response/Helpers.html
- class Response < Rack::Response
- def finish
- @body = block if block_given?
- if [204, 304].include?(status.to_i)
- header.delete "Content-Type"
- [status.to_i, header.to_hash, []]
- else
- body = @body || []
- body = [body] if body.respond_to? :to_str
- if body.respond_to?(:to_ary)
- header["Content-Length"] = body.to_ary.
- inject(0) { |len, part| len + Rack::Utils.bytesize(part) }.to_s
- end
- [status.to_i, header.to_hash, body]
- end
- end
- end
-
- class NotFound < NameError #:nodoc:
- def code ; 404 ; end
- end
-
- # Methods available to routes, before/after filters, and views.
- module Helpers
- # Set or retrieve the response status code.
- def status(value=nil)
- response.status = value if value
- response.status
- end
-
- # Set or retrieve the response body. When a block is given,
- # evaluation is deferred until the body is read with #each.
- def body(value=nil, &block)
- if block_given?
- def block.each ; yield call ; end
- response.body = block
- else
- response.body = value
- end
- end
-
- # Halt processing and redirect to the URI provided.
- def redirect(uri, *args)
- status 302
- response['Location'] = uri
- halt(*args)
- end
-
- # Halt processing and return the error status provided.
- def error(code, body=nil)
- code, body = 500, code.to_str if code.respond_to? :to_str
- response.body = body unless body.nil?
- halt code
- end
-
- # Halt processing and return a 404 Not Found.
- def not_found(body=nil)
- error 404, body
- end
-
- # Set multiple response headers with Hash.
- def headers(hash=nil)
- response.headers.merge! hash if hash
- response.headers
- end
-
- # Access the underlying Rack session.
- def session
- env['rack.session'] ||= {}
- end
-
- # Look up a media type by file extension in Rack's mime registry.
- def mime_type(type)
- Base.mime_type(type)
- end
-
- # Set the Content-Type of the response body given a media type or file
- # extension.
- def content_type(type, params={})
- mime_type = self.mime_type(type)
- fail "Unknown media type: %p" % type if mime_type.nil?
- if params.any?
- params = params.collect { |kv| "%s=%s" % kv }.join(', ')
- response['Content-Type'] = [mime_type, params].join(";")
- else
- response['Content-Type'] = mime_type
- end
- end
-
- # Set the Content-Disposition to "attachment" with the specified filename,
- # instructing the user agents to prompt to save.
- def attachment(filename=nil)
- response['Content-Disposition'] = 'attachment'
- if filename
- params = '; filename="%s"' % File.basename(filename)
- response['Content-Disposition'] << params
- end
- end
-
- # Use the contents of the file at +path+ as the response body.
- def send_file(path, opts={})
- stat = File.stat(path)
- last_modified stat.mtime
-
- content_type mime_type(opts[:type]) ||
- mime_type(File.extname(path)) ||
- response['Content-Type'] ||
- 'application/octet-stream'
-
- response['Content-Length'] ||= (opts[:length] || stat.size).to_s
-
- if opts[:disposition] == 'attachment' || opts[:filename]
- attachment opts[:filename] || path
- elsif opts[:disposition] == 'inline'
- response['Content-Disposition'] = 'inline'
- end
-
- halt StaticFile.open(path, 'rb')
- rescue Errno::ENOENT
- not_found
- end
-
- # Rack response body used to deliver static files. The file contents are
- # generated iteratively in 8K chunks.
- class StaticFile < ::File #:nodoc:
- alias_method :to_path, :path
- def each
- rewind
- while buf = read(8192)
- yield buf
- end
- end
- end
-
- # Specify response freshness policy for HTTP caches (Cache-Control header).
- # Any number of non-value directives (:public, :private, :no_cache,
- # :no_store, :must_revalidate, :proxy_revalidate) may be passed along with
- # a Hash of value directives (:max_age, :min_stale, :s_max_age).
- #
- # cache_control :public, :must_revalidate, :max_age => 60
- # => Cache-Control: public, must-revalidate, max-age=60
- #
- # See RFC 2616 / 14.9 for more on standard cache control directives:
- # http://tools.ietf.org/html/rfc2616#section-14.9.1
- def cache_control(*values)
- if values.last.kind_of?(Hash)
- hash = values.pop
- hash.reject! { |k,v| v == false }
- hash.reject! { |k,v| values << k if v == true }
- else
- hash = {}
- end
-
- values = values.map { |value| value.to_s.tr('_','-') }
- hash.each { |k,v| values << [k.to_s.tr('_', '-'), v].join('=') }
-
- response['Cache-Control'] = values.join(', ') if values.any?
- end
-
- # Set the Expires header and Cache-Control/max-age directive. Amount
- # can be an integer number of seconds in the future or a Time object
- # indicating when the response should be considered "stale". The remaining
- # "values" arguments are passed to the #cache_control helper:
- #
- # expires 500, :public, :must_revalidate
- # => Cache-Control: public, must-revalidate, max-age=60
- # => Expires: Mon, 08 Jun 2009 08:50:17 GMT
- #
- def expires(amount, *values)
- values << {} unless values.last.kind_of?(Hash)
-
- if amount.respond_to?(:to_time)
- max_age = amount.to_time - Time.now
- time = amount.to_time
- else
- max_age = amount
- time = Time.now + amount
- end
-
- values.last.merge!(:max_age => max_age)
- cache_control(*values)
-
- response['Expires'] = time.httpdate
- end
-
- # Set the last modified time of the resource (HTTP 'Last-Modified' header)
- # and halt if conditional GET matches. The +time+ argument is a Time,
- # DateTime, or other object that responds to +to_time+.
- #
- # When the current request includes an 'If-Modified-Since' header that
- # matches the time specified, execution is immediately halted with a
- # '304 Not Modified' response.
- def last_modified(time)
- time = time.to_time if time.respond_to?(:to_time)
- time = time.httpdate if time.respond_to?(:httpdate)
- response['Last-Modified'] = time
- halt 304 if time == request.env['HTTP_IF_MODIFIED_SINCE']
- time
- end
-
- # Set the response entity tag (HTTP 'ETag' header) and halt if conditional
- # GET matches. The +value+ argument is an identifier that uniquely
- # identifies the current version of the resource. The +kind+ argument
- # indicates whether the etag should be used as a :strong (default) or :weak
- # cache validator.
- #
- # When the current request includes an 'If-None-Match' header with a
- # matching etag, execution is immediately halted. If the request method is
- # GET or HEAD, a '304 Not Modified' response is sent.
- def etag(value, kind=:strong)
- raise TypeError, ":strong or :weak expected" if ![:strong,:weak].include?(kind)
- value = '"%s"' % value
- value = 'W/' + value if kind == :weak
- response['ETag'] = value
-
- # Conditional GET check
- if etags = env['HTTP_IF_NONE_MATCH']
- etags = etags.split(/\s*,\s*/)
- halt 304 if etags.include?(value) || etags.include?('*')
- end
- end
-
- ## Sugar for redirect (example: redirect back)
- def back ; request.referer ; end
-
- end
-
- # Template rendering methods. Each method takes the name of a template
- # to render as a Symbol and returns a String with the rendered output,
- # as well as an optional hash with additional options.
- #
- # `template` is either the name or path of the template as symbol
- # (Use `:'subdir/myview'` for views in subdirectories), or a string
- # that will be rendered.
- #
- # Possible options are:
- # :layout If set to false, no layout is rendered, otherwise
- # the specified layout is used (Ignored for `sass`)
- # :locals A hash with local variables that should be available
- # in the template
- module Templates
- def erb(template, options={}, locals={})
- render :erb, template, options, locals
- end
-
- def erubis(template, options={}, locals={})
- render :erubis, template, options, locals
- end
-
- def haml(template, options={}, locals={})
- render :haml, template, options, locals
- end
-
- def sass(template, options={}, locals={})
- options[:layout] = false
- render :sass, template, options, locals
- end
-
- def builder(template=nil, options={}, locals={}, &block)
- options, template = template, nil if template.is_a?(Hash)
- template = Proc.new { block } if template.nil?
- render :builder, template, options, locals
- end
-
- private
- def render(engine, data, options={}, locals={}, &block)
- # merge app-level options
- options = settings.send(engine).merge(options) if settings.respond_to?(engine)
-
- # extract generic options
- locals = options.delete(:locals) || locals || {}
- views = options.delete(:views) || settings.views || "./views"
- layout = options.delete(:layout)
- layout = :layout if layout.nil? || layout == true
-
- # compile and render template
- template = compile_template(engine, data, options, views)
- output = template.render(self, locals, &block)
-
- # render layout
- if layout
- begin
- options = options.merge(:views => views, :layout => false)
- output = render(engine, layout, options, locals) { output }
- rescue Errno::ENOENT
- end
- end
-
- output
- end
-
- def compile_template(engine, data, options, views)
- @template_cache.fetch engine, data, options do
- case
- when data.is_a?(Symbol)
- body, path, line = self.class.templates[data]
- if body
- body = body.call if body.respond_to?(:call)
- Tilt[engine].new(path, line.to_i, options) { body }
- else
- path = ::File.join(views, "#{data}.#{engine}")
- Tilt[engine].new(path, 1, options)
- end
- when data.is_a?(Proc) || data.is_a?(String)
- body = data.is_a?(String) ? Proc.new { data } : data
- path, line = self.class.caller_locations.first
- Tilt[engine].new(path, line.to_i, options, &body)
- else
- raise ArgumentError
- end
- end
- end
- end
-
- # Base class for all Sinatra applications and middleware.
- class Base
- include Rack::Utils
- include Helpers
- include Templates
-
- attr_accessor :app
-
- def initialize(app=nil)
- @app = app
- @template_cache = Tilt::Cache.new
- yield self if block_given?
- end
-
- # Rack call interface.
- def call(env)
- dup.call!(env)
- end
-
- attr_accessor :env, :request, :response, :params
-
- def call!(env)
- @env = env
- @request = Request.new(env)
- @response = Response.new
- @params = indifferent_params(@request.params)
-
- invoke { dispatch! }
- invoke { error_block!(response.status) }
-
- 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]
- end
-
- # Access settings defined with Base.set.
- def settings
- self.class
- end
- alias_method :options, :settings
-
- # Exit the current block, halts any further processing
- # of the request, and returns the specified response.
- def halt(*response)
- response = response.first if response.length == 1
- throw :halt, response
- end
-
- # Pass control to the next matching route.
- # If there are no more matching routes, Sinatra will
- # return a 404 response.
- def pass(&block)
- throw :pass, block
- end
-
- # 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)
- @response.status = status
- @response.body = body
- @response.headers.merge! headers
- nil
- end
-
- private
- # Run before filters defined on the class and all superclasses.
- def before_filter!(base=self.class)
- before_filter!(base.superclass) if base.superclass.respond_to?(:before_filters)
- base.before_filters.each { |block| instance_eval(&block) }
- end
-
- # Run after filters defined on the class and all superclasses.
- def after_filter!(base=self.class)
- after_filter!(base.superclass) if base.superclass.respond_to?(:after_filters)
- base.after_filters.each { |block| instance_eval(&block) }
- end
-
- # Run routes defined on the class and all superclasses.
- def route!(base=self.class, pass_block=nil)
- if routes = base.routes[@request.request_method]
- original_params = @params
- path = unescape(@request.path_info)
-
- routes.each do |pattern, keys, conditions, block|
- if match = pattern.match(path)
- values = match.captures.to_a
- params =
- if keys.any?
- keys.zip(values).inject({}) do |hash,(k,v)|
- if k == 'splat'
- (hash[k] ||= []) << v
- else
- hash[k] = v
- end
- hash
- end
- elsif values.any?
- {'captures' => values}
- else
- {}
- end
- @params = original_params.merge(params)
- @block_params = values
-
- pass_block = catch(:pass) do
- conditions.each { |cond|
- throw :pass if instance_eval(&cond) == false }
- route_eval(&block)
- end
- end
- end
-
- @params = original_params
- end
-
- # Run routes defined in superclass.
- if base.superclass.respond_to?(:routes)
- route! base.superclass, pass_block
- return
- end
-
- route_eval(&pass_block) if pass_block
-
- route_missing
- end
-
- # Run a route block and throw :halt with the result.
- def route_eval(&block)
- throw :halt, instance_eval(&block)
- end
-
- # No matching route was found or all routes passed. The default
- # implementation is to forward the request downstream when running
- # as middleware (@app is non-nil); when no downstream app is set, raise
- # a NotFound exception. Subclasses can override this method to perform
- # custom route miss logic.
- def route_missing
- if @app
- forward
- else
- raise NotFound
- end
- end
-
- # Attempt to serve static files from public directory. Throws :halt when
- # a matching file is found, returns nil otherwise.
- def static!
- return if (public_dir = settings.public).nil?
- public_dir = File.expand_path(public_dir)
-
- path = File.expand_path(public_dir + unescape(request.path_info))
- return if path[0, public_dir.length] != public_dir
- return unless File.file?(path)
-
- send_file path, :disposition => nil
- end
-
- # Enable string or symbol key access to the nested params hash.
- def indifferent_params(params)
- params = indifferent_hash.merge(params)
- params.each do |key, value|
- next unless value.is_a?(Hash)
- params[key] = indifferent_params(value)
- end
- end
-
- def indifferent_hash
- Hash.new {|hash,key| hash[key.to_s] if Symbol === key }
- end
-
- # Run the block with 'throw :halt' support and apply result to the response.
- def invoke(&block)
- res = catch(:halt) { instance_eval(&block) }
- return if res.nil?
-
- case
- when res.respond_to?(:to_str)
- @response.body = [res]
- when res.respond_to?(:to_ary)
- res = res.to_ary
- if Fixnum === res.first
- if res.length == 3
- @response.status, headers, body = res
- @response.body = body if body
- headers.each { |k, v| @response.headers[k] = v } if headers
- elsif res.length == 2
- @response.status = res.first
- @response.body = res.last
- else
- raise TypeError, "#{res.inspect} not supported"
- end
- else
- @response.body = res
- end
- when res.respond_to?(:each)
- @response.body = res
- when (100...599) === res
- @response.status = res
- end
-
- res
- end
-
- # Dispatch a request with error handling.
- def dispatch!
- static! if settings.static? && (request.get? || request.head?)
- before_filter!
- route!
- rescue NotFound => boom
- handle_not_found!(boom)
- rescue ::Exception => boom
- handle_exception!(boom)
- ensure
- after_filter!
- end
-
- def handle_not_found!(boom)
- @env['sinatra.error'] = boom
- @response.status = 404
- @response.body = ['<h1>Not Found</h1>']
- error_block! boom.class, NotFound
- end
-
- def handle_exception!(boom)
- @env['sinatra.error'] = boom
-
- dump_errors!(boom) if settings.dump_errors?
- raise boom if settings.raise_errors? || settings.show_exceptions?
-
- @response.status = 500
- error_block! boom.class, Exception
- end
-
- # Find an custom error block for the key(s) specified.
- def error_block!(*keys)
- keys.each do |key|
- base = self.class
- while base.respond_to?(:errors)
- if block = base.errors[key]
- # found a handler, eval and return result
- res = instance_eval(&block)
- return res
- else
- base = base.superclass
- end
- end
- end
- nil
- end
-
- def dump_errors!(boom)
- backtrace = clean_backtrace(boom.backtrace)
- msg = ["#{boom.class} - #{boom.message}:",
- *backtrace].join("\n ")
- @env['rack.errors'].puts(msg)
- end
-
- def clean_backtrace(trace)
- return trace unless settings.clean_trace?
-
- trace.reject { |line|
- line =~ /lib\/sinatra.*\.rb/ ||
- (defined?(Gem) && line.include?(Gem.dir))
- }.map! { |line| line.gsub(/^\.\//, '') }
- end
-
- class << self
- attr_reader :routes, :before_filters, :after_filters, :templates, :errors
-
- def reset!
- @conditions = []
- @routes = {}
- @before_filters = []
- @after_filters = []
- @errors = {}
- @middleware = []
- @prototype = nil
- @extensions = []
-
- if superclass.respond_to?(:templates)
- @templates = Hash.new { |hash,key| superclass.templates[key] }
- else
- @templates = {}
- end
- end
-
- # Extension modules registered on this class and all superclasses.
- def extensions
- if superclass.respond_to?(:extensions)
- (@extensions + superclass.extensions).uniq
- else
- @extensions
- end
- end
-
- # Middleware used in this class and all superclasses.
- def middleware
- if superclass.respond_to?(:middleware)
- superclass.middleware + @middleware
- else
- @middleware
- end
- end
-
- # 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)
- if value.kind_of?(Proc)
- metadef(option, &value)
- metadef("#{option}?") { !!__send__(option) }
- metadef("#{option}=") { |val| set(option, Proc.new{val}) }
- elsif value == self && option.respond_to?(:to_hash)
- option.to_hash.each { |k,v| set(k, v) }
- elsif respond_to?("#{option}=")
- __send__ "#{option}=", value
- else
- set option, Proc.new{value}
- end
- self
- end
-
- # Same as calling `set :option, true` for each of the given options.
- def enable(*opts)
- opts.each { |key| set(key, true) }