From 60d50062d7a39981942f907fc50a82d48989778b Mon Sep 17 00:00:00 2001 From: Ryan Tomayko Date: Sun, 31 Aug 2008 00:39:26 -0700 Subject: [PATCH] Fix whitespace errors across all source files and tests I can't stand this shit anymore. --- lib/sinatra.rb | 706 ++++++++++++++--------------- lib/sinatra/test/methods.rb | 14 +- lib/sinatra/test/spec.rb | 4 +- test/app_test.rb | 58 +-- test/application_test.rb | 66 +-- test/custom_error_test.rb | 37 +- test/diddy_test.rb | 10 +- test/erb_test.rb | 44 +- test/event_context_test.rb | 6 +- test/events_test.rb | 14 +- test/haml_test.rb | 62 +-- test/mapped_error_test.rb | 36 +- test/rest_test.rb | 3 +- test/sass_test.rb | 14 +- test/sessions_test.rb | 6 +- test/streaming_test.rb | 8 +- test/sym_params_test.rb | 2 +- test/template_test.rb | 20 +- test/use_in_file_templates_test.rb | 15 +- 19 files changed, 537 insertions(+), 588 deletions(-) diff --git a/lib/sinatra.rb b/lib/sinatra.rb index 65a85c4c..fdf426ad 100755 --- a/lib/sinatra.rb +++ b/lib/sinatra.rb @@ -7,7 +7,7 @@ if ENV['SWIFT'] require 'swiftcore/swiftiplied_mongrel' puts "Using Swiftiplied Mongrel" elsif ENV['EVENT'] - require 'swiftcore/evented_mongrel' + require 'swiftcore/evented_mongrel' puts "Using Evented Mongrel" end @@ -25,18 +25,19 @@ class Class end module Rack #:nodoc: - + class Request #:nodoc: - # Set of request method names allowed via the _method parameter hack. By default, - # all request methods defined in RFC2616 are included, with the exception of - # TRACE and CONNECT. + # Set of request method names allowed via the _method parameter hack. By + # default, all request methods defined in RFC2616 are included, with the + # exception of TRACE and CONNECT. POST_TUNNEL_METHODS_ALLOWED = %w( PUT DELETE OPTIONS HEAD ) - # Return the HTTP request method with support for method tunneling using the POST - # _method parameter hack. If the real request method is POST and a _method param is - # given and the value is one defined in +POST_TUNNEL_METHODS_ALLOWED+, return the value - # of the _method param instead. + # Return the HTTP request method with support for method tunneling using + # the POST _method parameter hack. If the real request method is POST and + # a _method param is given and the value is one defined in + # +POST_TUNNEL_METHODS_ALLOWED+, return the value of the _method param + # instead. def request_method if post_tunnel_method_hack? params['_method'].upcase @@ -49,38 +50,26 @@ module Rack #:nodoc: @env['HTTP_USER_AGENT'] end - private - - # Return truthfully if and only if the following conditions are met: 1.) the - # *actual* request method is POST, 2.) the request content-type is one of - # 'application/x-www-form-urlencoded' or 'multipart/form-data', 3.) there is a - # "_method" parameter in the POST body (not in the query string), and 4.) the - # method parameter is one of the verbs listed in the POST_TUNNEL_METHODS_ALLOWED - # list. - def post_tunnel_method_hack? - @env['REQUEST_METHOD'] == 'POST' && - POST_TUNNEL_METHODS_ALLOWED.include?(self.POST.fetch('_method', '').upcase) - end + private + # Return truthfully if the request is a valid verb-over-post hack. + def post_tunnel_method_hack? + @env['REQUEST_METHOD'] == 'POST' && + POST_TUNNEL_METHODS_ALLOWED.include?(self.POST.fetch('_method', '').upcase) + end end - + module Utils extend self end end + module Sinatra extend self - module Version - MAJOR = '0' - MINOR = '2' - REVISION = '3' - def self.combined - [MAJOR, MINOR, REVISION].join('.') - end - end + VERSION = '0.3.0' class NotFound < RuntimeError; end class ServerError < RuntimeError; end @@ -106,7 +95,7 @@ module Sinatra def host application.options.host end - + def env application.options.env end @@ -120,17 +109,16 @@ module Sinatra # Convert the server into the actual handler name handler = options.server.capitalize - # If the convenience conversion didn't get us anything, + # If the convenience conversion didn't get us anything, # fall back to what the user actually set. handler = options.server unless Rack::Handler.const_defined?(handler) @server ||= eval("Rack::Handler::#{handler}") end - + def run begin puts "== Sinatra has taken the stage on port #{port} for #{env} with backup by #{server.name}" - require 'pp' server.run(application, {:Port => port, :Host => host}) do |server| trap(:INT) do server.stop @@ -148,7 +136,7 @@ module Sinatra PARAM = /(:(#{URI_CHAR}+)|\*)/.freeze unless defined?(PARAM) SPLAT = /(.*?)/ attr_reader :path, :block, :param_keys, :pattern, :options - + def initialize(path, options = {}, &b) @path = URI.encode(path) @block = b @@ -168,14 +156,14 @@ module Sinatra @pattern = /^#{regex}$/ end - + def invoke(request) params = {} - if agent = options[:agent] + if agent = options[:agent] return unless request.user_agent =~ agent params[:agent] = $~[1..-1] end - if host = options[:host] + if host = options[:host] return unless host === request.host end return unless pattern =~ request.path_info.squeeze('/') @@ -187,65 +175,64 @@ module Sinatra end Result.new(block, params, 200) end - + end - + class Error - + attr_reader :code, :block - + def initialize(code, &b) @code, @block = code, b end - + def invoke(request) Result.new(block, {}, 404) end - + end - + class Static - + def invoke(request) return unless File.file?( Sinatra.application.options.public + request.path_info.http_unescape ) Result.new(block, {}, 200) end - + def block Proc.new do - send_file Sinatra.application.options.public + request.path_info.http_unescape, - :disposition => nil + send_file Sinatra.application.options.public + + request.path_info.http_unescape, :disposition => nil end end - + end - - # Adapted from actionpack + # Methods for sending files and streams to the browser instead of rendering. module Streaming DEFAULT_SEND_FILE_OPTIONS = { :type => 'application/octet-stream'.freeze, :disposition => 'attachment'.freeze, - :stream => true, + :stream => true, :buffer_size => 4096 }.freeze class MissingFile < RuntimeError; end class FileStreamer - + attr_reader :path, :options - + def initialize(path, options) @path, @options = path, options end - + def to_result(cx, *args) self end - + def each File.open(path, 'rb') do |file| while buf = file.read(options[:buffer_size]) @@ -253,143 +240,156 @@ module Sinatra end end end - + end - protected - # Sends the file by streaming it 4096 bytes at a time. This way the - # whole file doesn't need to be read into memory at once. This makes - # it feasible to send even large files. - # - # Be careful to sanitize the path parameter if it coming from a web - # page. send_file(params[:path]) allows a malicious user to - # download any file on your server. - # - # Options: - # * :filename - suggests a filename for the browser to use. - # Defaults to File.basename(path). - # * :type - specifies an HTTP content type. - # Defaults to 'application/octet-stream'. - # * :disposition - specifies whether the file will be shown inline or downloaded. - # Valid values are 'inline' and 'attachment' (default). When set to nil, the - # Content-Disposition and Content-Transfer-Encoding headers are omitted entirely. - # * :stream - whether to send the file to the user agent as it is read (true) - # or to read the entire file before sending (false). Defaults to true. - # * :buffer_size - specifies size (in bytes) of the buffer used to stream the file. - # Defaults to 4096. - # * :status - specifies the status code to send with the response. Defaults to '200 OK'. - # * :last_modified - an optional RFC 2616 formatted date value (See Time#httpdate) - # indicating the last modified time of the file. If the request includes an - # If-Modified-Since header that matches this value exactly, a 304 Not Modified response - # is sent instead of the file. Defaults to the file's last modified - # time. - # - # The default Content-Type and Content-Disposition headers are - # set to download arbitrary binary files in as many browsers as - # possible. IE versions 4, 5, 5.5, and 6 are all known to have - # a variety of quirks (especially when downloading over SSL). - # - # Simple download: - # send_file '/path/to.zip' - # - # Show a JPEG in the browser: - # send_file '/path/to.jpeg', :type => 'image/jpeg', :disposition => 'inline' - # - # Show a 404 page in the browser: - # send_file '/path/to/404.html, :type => 'text/html; charset=utf-8', :status => 404 - # - # Read about the other Content-* HTTP headers if you'd like to - # provide the user with more information (such as Content-Description). - # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11 - # - # Also be aware that the document may be cached by proxies and browsers. - # The Pragma and Cache-Control headers declare how the file may be cached - # by intermediaries. They default to require clients to validate with - # the server before releasing cached responses. See - # http://www.mnot.net/cache_docs/ for an overview of web caching and - # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9 - # for the Cache-Control header spec. - def send_file(path, options = {}) #:doc: - raise MissingFile, "Cannot read file #{path}" unless File.file?(path) and File.readable?(path) + protected - options[:length] ||= File.size(path) - options[:filename] ||= File.basename(path) - options[:type] ||= Rack::File::MIME_TYPES[File.extname(options[:filename])[1..-1]] || 'text/plain' - options[:last_modified] ||= File.mtime(path).httpdate - send_file_headers! options + # Sends the file by streaming it 4096 bytes at a time. This way the + # whole file doesn't need to be read into memory at once. This makes + # it feasible to send even large files. + # + # Be careful to sanitize the path parameter if it coming from a web + # page. send_file(params[:path]) allows a malicious user to + # download any file on your server. + # + # Options: + # * :filename - suggests a filename for the browser to use. + # Defaults to File.basename(path). + # * :type - specifies an HTTP content type. + # Defaults to 'application/octet-stream'. + # * :disposition - specifies whether the file will be shown + # inline or downloaded. Valid values are 'inline' and 'attachment' + # (default). When set to nil, the Content-Disposition and + # Content-Transfer-Encoding headers are omitted entirely. + # * :stream - whether to send the file to the user agent as it + # is read (true) or to read the entire file before sending (false). + # Defaults to true. + # * :buffer_size - specifies size (in bytes) of the buffer used + # to stream the file. Defaults to 4096. + # * :status - specifies the status code to send with the + # response. Defaults to '200 OK'. + # * :last_modified - an optional RFC 2616 formatted date value + # (See Time#httpdate) indicating the last modified time of the file. + # If the request includes an If-Modified-Since header that matches this + # value exactly, a 304 Not Modified response is sent instead of the file. + # Defaults to the file's last modified time. + # + # The default Content-Type and Content-Disposition headers are + # set to download arbitrary binary files in as many browsers as + # possible. IE versions 4, 5, 5.5, and 6 are all known to have + # a variety of quirks (especially when downloading over SSL). + # + # Simple download: + # send_file '/path/to.zip' + # + # Show a JPEG in the browser: + # send_file '/path/to.jpeg', + # :type => 'image/jpeg', + # :disposition => 'inline' + # + # Show a 404 page in the browser: + # send_file '/path/to/404.html, + # :type => 'text/html; charset=utf-8', + # :status => 404 + # + # Read about the other Content-* HTTP headers if you'd like to + # provide the user with more information (such as Content-Description). + # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11 + # + # Also be aware that the document may be cached by proxies and browsers. + # The Pragma and Cache-Control headers declare how the file may be cached + # by intermediaries. They default to require clients to validate with + # the server before releasing cached responses. See + # http://www.mnot.net/cache_docs/ for an overview of web caching and + # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9 + # for the Cache-Control header spec. + def send_file(path, options = {}) #:doc: + raise MissingFile, "Cannot read file #{path}" unless File.file?(path) and File.readable?(path) - if options[:stream] - throw :halt, [options[:status] || 200, FileStreamer.new(path, options)] - else - File.open(path, 'rb') { |file| throw :halt, [options[:status] || 200, file.read] } - end + options[:length] ||= File.size(path) + options[:filename] ||= File.basename(path) + options[:type] ||= Rack::File::MIME_TYPES[File.extname(options[:filename])[1..-1]] || 'text/plain' + options[:last_modified] ||= File.mtime(path).httpdate + send_file_headers! options + + if options[:stream] + throw :halt, [options[:status] || 200, FileStreamer.new(path, options)] + else + File.open(path, 'rb') { |file| throw :halt, [options[:status] || 200, file.read] } + end + end + + # Send binary data to the user as a file download. May set content type, + # apparent file name, and specify whether to show data inline or download + # as an attachment. + # + # Options: + # * :filename - Suggests a filename for the browser to use. + # * :type - specifies an HTTP content type. + # Defaults to 'application/octet-stream'. + # * :disposition - specifies whether the file will be shown inline + # or downloaded. Valid values are 'inline' and 'attachment' (default). + # * :status - specifies the status code to send with the response. + # Defaults to '200 OK'. + # * :last_modified - an optional RFC 2616 formatted date value (See + # Time#httpdate) indicating the last modified time of the response entity. + # If the request includes an If-Modified-Since header that matches this + # value exactly, a 304 Not Modified response is sent instead of the data. + # + # Generic data download: + # send_data buffer + # + # Download a dynamically-generated tarball: + # send_data generate_tgz('dir'), :filename => 'dir.tgz' + # + # Display an image Active Record in the browser: + # send_data image.data, + # :type => image.content_type, + # :disposition => 'inline' + # + # See +send_file+ for more information on HTTP Content-* headers and caching. + def send_data(data, options = {}) #:doc: + send_file_headers! options.merge(:length => data.size) + throw :halt, [options[:status] || 200, data] + end + + private + + def send_file_headers!(options) + options = DEFAULT_SEND_FILE_OPTIONS.merge(options) + [:length, :type, :disposition].each do |arg| + raise ArgumentError, ":#{arg} option required" unless options.key?(arg) end - # Send binary data to the user as a file download. May set content type, apparent file name, - # and specify whether to show data inline or download as an attachment. - # - # Options: - # * :filename - Suggests a filename for the browser to use. - # * :type - specifies an HTTP content type. - # Defaults to 'application/octet-stream'. - # * :disposition - specifies whether the file will be shown inline or downloaded. - # Valid values are 'inline' and 'attachment' (default). - # * :status - specifies the status code to send with the response. Defaults to '200 OK'. - # * :last_modified - an optional RFC 2616 formatted date value (See Time#httpdate) - # indicating the last modified time of the response entity. If the request includes an - # If-Modified-Since header that matches this value exactly, a 304 Not Modified response - # is sent instead of the data. - # - # Generic data download: - # send_data buffer - # - # Download a dynamically-generated tarball: - # send_data generate_tgz('dir'), :filename => 'dir.tgz' - # - # Display an image Active Record in the browser: - # send_data image.data, :type => image.content_type, :disposition => 'inline' - # - # See +send_file+ for more information on HTTP Content-* headers and caching. - def send_data(data, options = {}) #:doc: - send_file_headers! options.merge(:length => data.size) - throw :halt, [options[:status] || 200, data] + # Send a "304 Not Modified" if the last_modified option is provided and + # matches the If-Modified-Since request header value. + if last_modified = options[:last_modified] + header 'Last-Modified' => last_modified + throw :halt, [ 304, '' ] if last_modified == request.env['HTTP_IF_MODIFIED_SINCE'] end - private - def send_file_headers!(options) - options = DEFAULT_SEND_FILE_OPTIONS.merge(options) - [:length, :type, :disposition].each do |arg| - raise ArgumentError, ":#{arg} option required" unless options.key?(arg) - end + headers( + 'Content-Length' => options[:length].to_s, + 'Content-Type' => options[:type].strip # fixes a problem with extra '\r' with some browsers + ) - # Send a "304 Not Modified" if the last_modified option is provided and matches - # the If-Modified-Since request header value. - if last_modified = options[:last_modified] - header 'Last-Modified' => last_modified - throw :halt, [ 304, '' ] if last_modified == request.env['HTTP_IF_MODIFIED_SINCE'] - end - - headers( - 'Content-Length' => options[:length].to_s, - 'Content-Type' => options[:type].strip # fixes a problem with extra '\r' with some browsers - ) - - # Omit Content-Disposition and Content-Transfer-Encoding headers if - # the :disposition option set to nil. - if !options[:disposition].nil? - disposition = options[:disposition].dup || 'attachment' - disposition <<= %(; filename="#{options[:filename]}") if options[:filename] - headers 'Content-Disposition' => disposition, 'Content-Transfer-Encoding' => 'binary' - end - - # Fix a problem with IE 6.0 on opening downloaded files: - # If Cache-Control: no-cache is set (which Rails does by default), - # IE removes the file it just downloaded from its cache immediately - # after it displays the "open/save" dialog, which means that if you - # hit "open" the file isn't there anymore when the application that - # is called for handling the download is run, so let's workaround that - header('Cache-Control' => 'private') if headers['Cache-Control'] == 'no-cache' + # Omit Content-Disposition and Content-Transfer-Encoding headers if + # the :disposition option set to nil. + if !options[:disposition].nil? + disposition = options[:disposition].dup || 'attachment' + disposition <<= %(; filename="#{options[:filename]}") if options[:filename] + headers 'Content-Disposition' => disposition, 'Content-Transfer-Encoding' => 'binary' end + + # Fix a problem with IE 6.0 on opening downloaded files: + # If Cache-Control: no-cache is set (which Rails does by default), + # IE removes the file it just downloaded from its cache immediately + # after it displays the "open/save" dialog, which means that if you + # hit "open" the file isn't there anymore when the application that + # is called for handling the download is run, so let's workaround that + header('Cache-Control' => 'private') if headers['Cache-Control'] == 'no-cache' + end end @@ -525,101 +525,104 @@ module Sinatra end result end - + def determine_layout(renderer, template, options) return if options[:layout] == false layout_from_options = options[:layout] || :layout resolve_template(renderer, layout_from_options, options, false) end - private - - def resolve_template(renderer, template, options, scream = true) - case template - when String - template - when Proc - template.call - when Symbol - if proc = templates[template] - resolve_template(renderer, proc, options, scream) - else - read_template_file(renderer, template, options, scream) - end + private + + def resolve_template(renderer, template, options, scream = true) + case template + when String + template + when Proc + template.call + when Symbol + if proc = templates[template] + resolve_template(renderer, proc, options, scream) else - nil + read_template_file(renderer, template, options, scream) end + else + nil end - - def read_template_file(renderer, template, options, scream = true) - path = File.join( - options[:views_directory] || Sinatra.application.options.views, - "#{template}.#{renderer}" - ) - unless File.exists?(path) - raise Errno::ENOENT.new(path) if scream - nil - else - File.read(path) - end + end + + def read_template_file(renderer, template, options, scream = true) + path = File.join( + options[:views_directory] || Sinatra.application.options.views, + "#{template}.#{renderer}" + ) + unless File.exists?(path) + raise Errno::ENOENT.new(path) if scream + nil + else + File.read(path) end - - def templates - Sinatra.application.templates - end - + end + + def templates + Sinatra.application.templates + end + end module Erb - + def erb(content, options={}) require 'erb' render(:erb, content, options) end - - private - - def render_erb(content, options = {}) - locals_opt = options.delete(:locals) || {} - locals_code = "" - locals_hash = {} - locals_opt.each do |key, value| - locals_code << "#{key} = locals_hash[:#{key}]\n" - locals_hash[:"#{key}"] = value - end - - body = ::ERB.new(content).src - eval("#{locals_code}#{body}", binding) + private + + def render_erb(content, options = {}) + locals_opt = options.delete(:locals) || {} + + locals_code = "" + locals_hash = {} + locals_opt.each do |key, value| + locals_code << "#{key} = locals_hash[:#{key}]\n" + locals_hash[:"#{key}"] = value end + body = ::ERB.new(content).src + eval("#{locals_code}#{body}", binding) + end + end module Haml - + def haml(content, options={}) require 'haml' render(:haml, content, options) end - - private - - def render_haml(content, options = {}, &b) - haml_options = (options[:options] || {}).merge(Sinatra.options.haml || {}) - ::Haml::Engine.new(content, haml_options).render(options[:scope] || self, options[:locals] || {}, &b) - end - + + private + + def render_haml(content, options = {}, &b) + haml_options = (options[:options] || {}). + merge(Sinatra.options.haml || {}) + ::Haml::Engine.new(content, haml_options). + render(options[:scope] || self, options[:locals] || {}, &b) + end + end # Generate valid CSS using Sass (part of Haml) # - # Sass templates can be in external files with .sass extension or can use Sinatra's - # in_file_templates. In either case, the file can be rendered by passing the name of - # the template to the +sass+ method as a symbol. + # Sass templates can be in external files with .sass extension + # or can use Sinatra's in_file_templates. In either case, the file can + # be rendered by passing the name of the template to the +sass+ method + # as a symbol. # - # Unlike Haml, Sass does not support a layout file, so the +sass+ method will ignore both - # the default layout.sass file and any parameters passed in as :layout in - # the options hash. + # Unlike Haml, Sass does not support a layout file, so the +sass+ method + # will ignore both the default layout.sass file and any parameters + # passed in as :layout in the options hash. # # === Sass Template Files # @@ -633,7 +636,7 @@ module Sinatra # end # # The "views/stylesheet.sass" file might contain the following: - # + # # body # #admin # :background-color #CCC @@ -649,51 +652,50 @@ module Sinatra # background-color: #CCC; } # body #main { # background-color: #000; } - # + # # #form { # border-color: #AAA; # border-width: 10px; } - # + # # # NOTE: Haml must be installed or a LoadError will be raised the first time an # attempt is made to render a Sass template. # # See http://haml.hamptoncatlin.com/docs/rdoc/classes/Sass.html for comprehensive documentation on Sass. - - module Sass - + def sass(content, options = {}) require 'sass' - + # Sass doesn't support a layout, so we override any possible layout here options[:layout] = false - + render(:sass, content, options) end - - private - - def render_sass(content, options = {}) - ::Sass::Engine.new(content).render - end + + private + + def render_sass(content, options = {}) + ::Sass::Engine.new(content).render + end + end # Generating conservative XML content using Builder templates. # - # Builder templates can be inline by passing a block to the builder method, or in - # external files with +.builder+ extension by passing the name of the template - # to the +builder+ method as a Symbol. + # Builder templates can be inline by passing a block to the builder method, + # or in external files with +.builder+ extension by passing the name of the + # template to the +builder+ method as a Symbol. # # === Inline Rendering # - # If the builder method is given a block, the block is called directly with an - # +XmlMarkup+ instance and the result is returned as String: + # If the builder method is given a block, the block is called directly with + # an +XmlMarkup+ instance and the result is returned as String: # get '/who.xml' do # builder do |xml| # xml.instruct! # xml.person do - # xml.name "Francis Albert Sinatra", + # xml.name "Francis Albert Sinatra", # :aka => "Frank Sinatra" # xml.email 'frank@capitolrecords.com' # end @@ -709,9 +711,9 @@ module Sinatra # # === Builder Template Files # - # Builder templates can be stored in separate files with a +.builder+ - # extension under the view path. An +XmlMarkup+ object named +xml+ is automatically - # made available to template. + # Builder templates can be stored in separate files with a +.builder+ + # extension under the view path. An +XmlMarkup+ object named +xml+ is + # automatically made available to template. # # Example: # get '/bio.xml' do @@ -742,10 +744,11 @@ module Sinatra # # # - # NOTE: Builder must be installed or a LoadError will be raised the first time an - # attempt is made to render a builder template. + # NOTE: Builder must be installed or a LoadError will be raised the first + # time an attempt is made to render a builder template. # - # See http://builder.rubyforge.org/ for comprehensive documentation on Builder. + # See http://builder.rubyforge.org/ for comprehensive documentation on + # Builder. module Builder def builder(content=nil, options={}, &block) @@ -754,24 +757,24 @@ module Sinatra render(:builder, content, options) end - private + private - def render_builder(content, options = {}, &b) - require 'builder' - xml = ::Builder::XmlMarkup.new(:indent => 2) - case content - when String - eval(content, binding, '', 1) - when Proc - content.call(xml) - end - xml.target! + def render_builder(content, options = {}, &b) + require 'builder' + xml = ::Builder::XmlMarkup.new(:indent => 2) + case content + when String + eval(content, binding, '', 1) + when Proc + content.call(xml) end + xml.target! + end end class EventContext - + include ResponseHelpers include Streaming include RenderingHelpers @@ -779,20 +782,20 @@ module Sinatra include Haml include Builder include Sass - + attr_accessor :request, :response - + dslify_writer :status, :body - + def initialize(request, response, route_params) @request = request @response = response @route_params = route_params @response.body = nil end - + def params - @params ||= begin + @params ||= begin h = Hash.new {|h,k| h[k.to_s] if Symbol === k} h.merge(@route_params.merge(@request.params)) end @@ -801,25 +804,25 @@ module Sinatra def data @data ||= params.keys.first end - + def stop(*args) throw :halt, args end - + def complete(returned) @response.body || returned end - + def session request.env['rack.session'] ||= {} end - - private - def method_missing(name, *args, &b) - @response.send(name, *args, &b) - end - + private + + def method_missing(name, *args, &b) + @response.send(name, *args, &b) + end + end @@ -1043,7 +1046,6 @@ module Sinatra errors[NotFound].invoke(request) end - # Define a named template. The template may be referenced from # event handlers by passing the name as a Symbol to rendering # methods. The block is executed each time the template is rendered @@ -1249,7 +1251,7 @@ module Sinatra end not_found { '

Not Found

'} end - + configures :development do get '/sinatra_custom_images/:image.png' do @@ -1259,18 +1261,8 @@ module Sinatra not_found do %Q( @@ -1278,9 +1270,7 @@ module Sinatra
Try this: -
#{request.request_method.downcase} "#{request.path_info}" do
-  .. do something ..
-end
+                
#{request.request_method.downcase} "#{request.path_info}" do\n  .. do something ..\n  end
               
@@ -1289,52 +1279,29 @@ end
 
         error do
           @error = request.env['sinatra.error']
-          %Q(
+          (<<-HTML).sub(/ {12}/, '')
           
-          	
-          		
-          		
- -
+ + +
+ +
Params:
#{params.inspect}
-            		
-
-

#{Rack::Utils.escape_html(@error.class.name + ' - ' + @error.message.to_s)}

-
#{Rack::Utils.escape_html(@error.backtrace.join("\n"))}
-
- +
+
+

#{Rack::Utils.escape_html(@error.class.name + ' - ' + @error.message.to_s)}

+
#{Rack::Utils.escape_html(@error.backtrace.join("\n"))}
+
+ - ) + HTML end end end @@ -1381,14 +1348,12 @@ end ### Misc Core Extensions module Kernel - def silence_warnings old_verbose, $VERBOSE = $VERBOSE, nil yield ensure $VERBOSE = old_verbose end - end class String @@ -1399,58 +1364,47 @@ class String Rack::Utils.escape(self) end alias :http_escape :to_param - + # Converts +self+ from an escaped URI parameter value # 'Foo%20Bar'.from_param # => 'Foo Bar' def from_param Rack::Utils.unescape(self) end alias :http_unescape :from_param - + end class Hash - def to_params map { |k,v| "#{k}=#{URI.escape(v)}" }.join('&') end - def symbolize_keys self.inject({}) { |h,(k,v)| h[k.to_sym] = v; h } end - def pass(*keys) reject { |k,v| !keys.include?(k) } end - end class Symbol - - def to_proc + def to_proc Proc.new { |*args| args.shift.__send__(self, *args) } end - end class Array - def to_hash self.inject({}) { |h, (k, v)| h[k] = v; h } end - def to_proc Proc.new { |*args| args.shift.__send__(self[0], *(args + self[1..-1])) } end - end module Enumerable - def eject(&block) find { |e| result = block[e] and break result } end - end ### Core Extension results for throw :halt @@ -1497,7 +1451,7 @@ end at_exit do raise $! if $! if Sinatra.application.options.run - Sinatra.run + Sinatra.run end end diff --git a/lib/sinatra/test/methods.rb b/lib/sinatra/test/methods.rb index 6fec510b..1c741b32 100644 --- a/lib/sinatra/test/methods.rb +++ b/lib/sinatra/test/methods.rb @@ -1,7 +1,7 @@ module Sinatra - + module Test - + module Methods def easy_env_map @@ -13,12 +13,12 @@ module Sinatra :cookies => "HTTP_COOKIE" } end - + def session(data, key = 'rack.session') data = data.from_params if data.respond_to?(:from_params) "#{Rack::Utils.escape(key)}=#{[Marshal.dump(data)].pack("m*")}" end - + def map_easys(params) easy_env_map.inject(params.dup) do |m, (from, to)| m[to] = m.delete(from) if m.has_key?(from); m @@ -37,7 +37,7 @@ module Sinatra @response = @request.request(m.upcase, path, {:input => input}.merge(env || {})) end end - + def follow! get_it(@response.location) end @@ -45,9 +45,9 @@ module Sinatra def method_missing(name, *args) @response.send(name, *args) rescue super end - + end end - + end diff --git a/lib/sinatra/test/spec.rb b/lib/sinatra/test/spec.rb index 5785e55a..73a429be 100644 --- a/lib/sinatra/test/spec.rb +++ b/lib/sinatra/test/spec.rb @@ -2,9 +2,9 @@ require File.dirname(__FILE__) + '/unit' require 'test/spec' class Test::Unit::TestCase - + def should @response.should end - + end diff --git a/test/app_test.rb b/test/app_test.rb index cc94839a..3f784e61 100644 --- a/test/app_test.rb +++ b/test/app_test.rb @@ -1,7 +1,7 @@ require File.dirname(__FILE__) + '/helper' context "Sinatra" do - + setup do Sinatra.application = nil end @@ -17,32 +17,32 @@ context "Sinatra" do get '/' do nil end - + get_it '/' should.be.ok body.should == '' end - + specify "handles events" do get '/:name' do 'Hello ' + params["name"] end - + get_it '/Blake' - + should.be.ok body.should.equal 'Hello Blake' end - + specify "handles splats" do get '/hi/*' do params["splat"].kind_of?(Array).should.equal true params["splat"].first end - + get_it '/hi/Blake' - + should.be.ok body.should.equal 'Blake' end @@ -51,9 +51,9 @@ context "Sinatra" do get '/say/*/to/*' do params["splat"].join(' ') end - + get_it '/say/hello/to/world' - + should.be.ok body.should.equal 'hello world' end @@ -62,14 +62,14 @@ context "Sinatra" do get '/say/*/to*/*' do params["splat"].join(' ') end - + get_it '/say/hello/to/world' - + should.be.ok body.should.equal 'hello world' # second splat is empty get_it '/say/hello/tomy/world' - + should.be.ok body.should.equal 'hello my world' end @@ -93,20 +93,20 @@ context "Sinatra" do get '/' do redirect '/blake' end - + get '/blake' do 'Mizerany' end - + get_it '/' should.be.redirection body.should.equal '' - + follow! should.be.ok body.should.equal 'Mizerany' end - + specify "renders a body with a redirect" do Sinatra::EventContext.any_instance.expects(:foo).returns('blah') get "/" do @@ -130,34 +130,34 @@ context "Sinatra" do end specify "body sets content and ends event" do - + Sinatra::EventContext.any_instance.expects(:foo).never - + get '/set_body' do stop 'Hello!' stop 'World!' foo end - + get_it '/set_body' - + should.be.ok body.should.equal 'Hello!' - + end - + specify "should set status then call helper with a var" do Sinatra::EventContext.any_instance.expects(:foo).once.with(1).returns('bah!') - + get '/set_body' do stop [404, [:foo, 1]] end - + get_it '/set_body' - + should.be.not_found body.should.equal 'bah!' - + end specify "should easily set response Content-Type" do @@ -235,7 +235,7 @@ context "Sinatra" do body.should.equal '' end - + specify "put'n with POST" do put '/' do 'puted' @@ -252,7 +252,7 @@ context "Sinatra" do assert_equal 'puted', body end - # Some Ajax libraries downcase the _method parameter value. Make + # Some Ajax libraries downcase the _method parameter value. Make # sure we can handle that. specify "put'n with POST and lowercase _method param" do put '/' do diff --git a/test/application_test.rb b/test/application_test.rb index 57a67bbf..a753821f 100644 --- a/test/application_test.rb +++ b/test/application_test.rb @@ -19,49 +19,49 @@ context "Looking up a request" do specify "returns what's at the end" do block = Proc.new { 'Hello' } get '/', &block - + result = Sinatra.application.lookup( Rack::Request.new( 'REQUEST_METHOD' => 'GET', 'PATH_INFO' => '/' ) ) - + result.should.not.be.nil result.block.should.be block end - + specify "takes params in path" do block = Proc.new { 'Hello' } get '/:foo', &block - + result = Sinatra.application.lookup( Rack::Request.new( 'REQUEST_METHOD' => 'GET', 'PATH_INFO' => '/bar' ) ) - + result.should.not.be.nil result.block.should.be block result.params.should.equal "foo" => 'bar' end - + end context "An app returns" do - + setup do Sinatra.application = nil end - + specify "404 if no events found" do request = Rack::MockRequest.new(@app) get_it '/' should.be.not_found body.should.equal '

Not Found

' end - + specify "200 if success" do get '/' do 'Hello World' @@ -70,32 +70,32 @@ context "An app returns" do should.be.ok body.should.equal 'Hello World' end - + specify "an objects result from each if it has it" do - + get '/' do TesterWithEach.new end - + get_it '/' should.be.ok body.should.equal 'foobarbaz' end - + specify "the body set if set before the last" do - + get '/' do body 'Blake' 'Mizerany' end - + get_it '/' should.be.ok body.should.equal 'Blake' end - + end context "Application#configure blocks" do @@ -145,43 +145,43 @@ context "Default Application Configuration" do end context "Events in an app" do - + setup do Sinatra.application = nil end - + specify "evaluate in a clean context" do helpers do def foo 'foo' end end - + get '/foo' do foo end - + get_it '/foo' should.be.ok body.should.equal 'foo' end - + specify "get access to request, response, and params" do get '/:foo' do params["foo"] + params["bar"] end - + get_it '/foo?bar=baz' should.be.ok body.should.equal 'foobaz' end - + specify "can filters by agent" do - + get '/', :agent => /Windows/ do request.env['HTTP_USER_AGENT'] end - + get_it '/', :env => { :agent => 'Windows' } should.be.ok body.should.equal 'Windows' @@ -192,30 +192,30 @@ context "Events in an app" do end specify "can use regex to get parts of user-agent" do - + get '/', :agent => /Windows (NT)/ do params[:agent].first end - + get_it '/', :env => { :agent => 'Windows NT' } body.should.equal 'NT' end - + specify "can deal with spaces in paths" do - + path = '/path with spaces' - + get path do "Look ma, a path with spaces!" end - + get_it URI.encode(path) - + body.should.equal "Look ma, a path with spaces!" end - + end diff --git a/test/custom_error_test.rb b/test/custom_error_test.rb index e479d6b3..7923345d 100644 --- a/test/custom_error_test.rb +++ b/test/custom_error_test.rb @@ -5,63 +5,58 @@ context "Custom Errors (in general)" do setup do Sinatra.application = nil end - + specify "override the default 404" do - + get_it '/' should.be.not_found body.should.equal '

Not Found

' - + error Sinatra::NotFound do 'Custom 404' end - + get_it '/' should.be.not_found body.should.equal 'Custom 404' - + end - + specify "override the default 500" do Sinatra.application.options.raise_errors = false - + get '/' do raise 'asdf' end - + get_it '/' status.should.equal 500 body.should.equal '

Internal Server Error

' - - + + error do 'Custom 500 for ' + request.env['sinatra.error'].message end - + get_it '/' - + get_it '/' status.should.equal 500 body.should.equal 'Custom 500 for asdf' - + Sinatra.application.options.raise_errors = true end - + class UnmappedError < RuntimeError; end - + specify "should bring unmapped error back to the top" do get '/' do raise UnmappedError, 'test' end - + assert_raises(UnmappedError) do get_it '/' end end end - - - - - diff --git a/test/diddy_test.rb b/test/diddy_test.rb index a6a1cfbe..27e4b664 100644 --- a/test/diddy_test.rb +++ b/test/diddy_test.rb @@ -11,11 +11,11 @@ context "Diddy" do get '/' do 'asdf' end - + get_it '/' assert ok? assert_equal('asdf', body) - + get '/foo', :host => 'foo.sinatrarb.com' do 'in foo!' end @@ -23,7 +23,7 @@ context "Diddy" do get '/foo', :host => 'bar.sinatrarb.com' do 'in bar!' end - + get_it '/foo', {}, 'HTTP_HOST' => 'foo.sinatrarb.com' assert ok? assert_equal 'in foo!', body @@ -31,10 +31,10 @@ context "Diddy" do get_it '/foo', {}, 'HTTP_HOST' => 'bar.sinatrarb.com' assert ok? assert_equal 'in bar!', body - + get_it '/foo' assert not_found? - + end end diff --git a/test/erb_test.rb b/test/erb_test.rb index 36c1e239..51a79593 100644 --- a/test/erb_test.rb +++ b/test/erb_test.rb @@ -5,19 +5,19 @@ context "Erb" do setup do Sinatra.application = nil end - + context "without layouts" do - + setup do Sinatra.application = nil end - + specify "should render" do - + get '/no_layout' do erb '<%= 1 + 1 %>' end - + get_it '/no_layout' should.be.ok body.should == '2' @@ -44,62 +44,62 @@ context "Erb" do body.should == 'foo' end end - + context "with layouts" do setup do Sinatra.application = nil end - + specify "can be inline" do - + layout do %Q{This is <%= yield %>!} end - + get '/lay' do erb 'Blake' end - + get_it '/lay' should.be.ok body.should.equal 'This is Blake!' end - + specify "can use named layouts" do - + layout :pretty do %Q{

<%= yield %>

} end - + get '/pretty' do erb 'Foo', :layout => :pretty end - + get '/not_pretty' do erb 'Bar' end - + get_it '/pretty' body.should.equal '

Foo

' - + get_it '/not_pretty' body.should.equal 'Bar' - + end - + specify "can be read from a file if they're not inlined" do - + get '/foo' do @title = 'Welcome to the Hello Program' erb 'Blake', :layout => :foo_layout, :views_directory => File.dirname(__FILE__) + "/views" end - + get_it '/foo' body.should.equal "Welcome to the Hello Program\nHi Blake\n" - + end end @@ -132,5 +132,5 @@ context "Erb" do end end - + end diff --git a/test/event_context_test.rb b/test/event_context_test.rb index b9f9a69b..538d0082 100644 --- a/test/event_context_test.rb +++ b/test/event_context_test.rb @@ -3,13 +3,13 @@ require File.dirname(__FILE__) + '/helper' context "EventContext" do specify "DSLified setters" do - + cx = Sinatra::EventContext.new(stub_everything, Rack::Response.new, {}) lambda { cx.status 404 }.should.not.raise(ArgumentError) - + end - + end diff --git a/test/events_test.rb b/test/events_test.rb index 5c1c1021..d37c0872 100644 --- a/test/events_test.rb +++ b/test/events_test.rb @@ -13,7 +13,7 @@ context "Simple Events" do event = Sinatra::Event.new(path, &b) event.invoke(simple_request_hash(:get, request_path)) end - + specify "return last value" do block = Proc.new { 'Simple' } result = invoke_simple('/', '/', &block) @@ -21,27 +21,27 @@ context "Simple Events" do result.block.should.be block result.params.should.equal Hash.new end - + specify "takes params in path" do result = invoke_simple('/:foo/:bar', '/a/b') result.should.not.be.nil result.params.should.equal "foo" => 'a', "bar" => 'b' - + # unscapes result = invoke_simple('/:foo/:bar', '/a/blake%20mizerany') result.should.not.be.nil result.params.should.equal "foo" => 'a', "bar" => 'blake mizerany' end - + specify "ignores to many /'s" do result = invoke_simple('/x/y', '/x//y') result.should.not.be.nil end - + specify "understands splat" do invoke_simple('/foo/*', '/foo/bar').should.not.be.nil invoke_simple('/foo/*', '/foo/bar/baz').should.not.be.nil invoke_simple('/foo/*', '/foo/baz').should.not.be.nil - end - + end + end diff --git a/test/haml_test.rb b/test/haml_test.rb index 44e278ad..4e738ba7 100644 --- a/test/haml_test.rb +++ b/test/haml_test.rb @@ -5,95 +5,95 @@ context "Haml" do setup do Sinatra.application = nil end - + context "without layouts" do - + setup do Sinatra.application = nil end - + specify "should render" do - + get '/no_layout' do haml '== #{1+1}' end - + get_it '/no_layout' should.be.ok body.should == "2\n" end end - + context "with layouts" do setup do Sinatra.application = nil end - + specify "can be inline" do - + layout do '== This is #{yield}!' end - + get '/lay' do haml 'Blake' end - + get_it '/lay' should.be.ok body.should.equal "This is Blake\n!\n" end - + specify "can use named layouts" do - + layout :pretty do '%h1== #{yield}' end - + get '/pretty' do haml 'Foo', :layout => :pretty end - + get '/not_pretty' do haml 'Bar' end - + get_it '/pretty' body.should.equal "

Foo

\n" - + get_it '/not_pretty' body.should.equal "Bar\n" - + end - + specify "can be read from a file if they're not inlined" do - + get '/foo' do @title = 'Welcome to the Hello Program' haml 'Blake', :layout => :foo_layout, :views_directory => File.dirname(__FILE__) + "/views" end - + get_it '/foo' body.should.equal "Welcome to the Hello Program\nHi Blake\n" - + end - + specify "can be read from file and layout from text" do get '/foo' do haml 'Test', :layout => '== Foo #{yield}' end - + get_it '/foo' - + body.should.equal "Foo Test\n" end end - + context "Templates (in general)" do setup do @@ -136,21 +136,21 @@ context "Haml" do body.should.equal "

No Layout!

\n" end - + specify "can render with no layout" do layout do "X\n= yield\nX" end - + get '/' do haml 'blake', :layout => false end - + get_it '/' - + body.should.equal "blake\n" end - + specify "raises error if template not found" do get '/' do haml :not_found @@ -175,7 +175,7 @@ context "Haml" do body.should.equal "asdf\n" end - + end describe 'Options passed to the HAML interpreter' do diff --git a/test/mapped_error_test.rb b/test/mapped_error_test.rb index 918af061..e664b104 100644 --- a/test/mapped_error_test.rb +++ b/test/mapped_error_test.rb @@ -3,59 +3,59 @@ require File.dirname(__FILE__) + '/helper' class FooError < RuntimeError; end context "Mapped errors" do - + setup do Sinatra.application = nil end - + specify "are rescued and run in context" do - + error FooError do 'MAPPED ERROR!' end - + get '/' do raise FooError.new end - + get_it '/' - + should.be.server_error body.should.equal 'MAPPED ERROR!' - + end specify "renders empty if no each method on result" do - + error FooError do nil end - + get '/' do raise FooError.new end - + get_it '/' - + should.be.server_error body.should.be.empty - + end specify "doesn't override status if set" do - + error FooError do status(200) end - + get '/' do raise FooError.new end - + get_it '/' - + should.be.ok - + end - + end diff --git a/test/rest_test.rb b/test/rest_test.rb index 8a126ad8..5c24e9c4 100644 --- a/test/rest_test.rb +++ b/test/rest_test.rb @@ -1,12 +1,13 @@ require File.dirname(__FILE__) + '/helper' +# XXX: How does any of this have anything to do with REST? context "RESTful tests" do specify "should take xml" do post '/foo.xml' do request.body.string end - + post_it '/foo.xml', '' assert ok? assert_equal('', body) diff --git a/test/sass_test.rb b/test/sass_test.rb index b24762b5..ee6d4f41 100644 --- a/test/sass_test.rb +++ b/test/sass_test.rb @@ -5,7 +5,7 @@ context "Sass" do setup do Sinatra.application = nil end - + context "Templates (in general)" do setup do @@ -23,7 +23,7 @@ context "Sass" do body.should.equal "#sass {\n background_color: #FFF; }\n" end - + specify "raise an error if template not found" do get '/' do sass :not_found @@ -31,27 +31,27 @@ context "Sass" do lambda { get_it '/' }.should.raise(Errno::ENOENT) end - + specify "ignore default layout file with .sass extension" do get '/' do sass :foo, :views_directory => File.dirname(__FILE__) + "/views/layout_test" end - + get_it '/' should.be.ok body.should.equal "#sass {\n background_color: #FFF; }\n" end - + specify "ignore explicitly specified layout file" do get '/' do sass :foo, :layout => :layout, :views_directory => File.dirname(__FILE__) + "/views/layout_test" end - + get_it '/' should.be.ok body.should.equal "#sass {\n background_color: #FFF; }\n" end - + end end diff --git a/test/sessions_test.rb b/test/sessions_test.rb index 37912304..b50cb8fb 100644 --- a/test/sessions_test.rb +++ b/test/sessions_test.rb @@ -13,7 +13,7 @@ context "Sessions" do get '/test' do session[:test] == true ? "true" : "false" end - + get_it '/asdf', {}, 'HTTP_HOST' => 'foo.sinatrarb.com' assert ok? assert !include?('Set-Cookie') @@ -33,7 +33,7 @@ context "Sessions" do get_it '/foo', :env => { :host => 'foo.sinatrarb.com' } assert ok? - assert include?('Set-Cookie') + assert include?('Set-Cookie') end - + end diff --git a/test/streaming_test.rb b/test/streaming_test.rb index 998bbc66..d507f1be 100644 --- a/test/streaming_test.rb +++ b/test/streaming_test.rb @@ -86,7 +86,7 @@ context "Static files (by default)" do end context "SendData" do - + setup do Sinatra.application = nil end @@ -95,13 +95,13 @@ context "SendData" do get '/' do send_data 'asdf', :status => 500 end - + get_it '/' - + should.be.server_error body.should.equal 'asdf' end - + specify "should include a Content-Disposition header" do get '/' do send_file File.dirname(__FILE__) + '/public/foo.xml' diff --git a/test/sym_params_test.rb b/test/sym_params_test.rb index 3f398444..2172be0c 100644 --- a/test/sym_params_test.rb +++ b/test/sym_params_test.rb @@ -10,7 +10,7 @@ context "Symbol Params" do get '/' do params[:foo] + params['foo'] end - + get_it '/', :foo => "X" assert_equal('XX', body) end diff --git a/test/template_test.rb b/test/template_test.rb index cafac91a..41b439b8 100644 --- a/test/template_test.rb +++ b/test/template_test.rb @@ -1,30 +1,30 @@ require File.dirname(__FILE__) + '/helper' context "Templates (in general)" do - + specify "are read from files if Symbols" do - + get '/from_file' do @name = 'Alena' erb :foo, :views_directory => File.dirname(__FILE__) + "/views" end - + get_it '/from_file' - + body.should.equal 'You rock Alena!' - + end - + specify "use layout.ext by default if available" do - + get '/layout_from_file' do erb :foo, :views_directory => File.dirname(__FILE__) + "/views/layout_test" end - + get_it '/layout_from_file' should.be.ok body.should.equal "x This is foo! x \n" - + end - + end diff --git a/test/use_in_file_templates_test.rb b/test/use_in_file_templates_test.rb index ca61a051..265f07de 100644 --- a/test/use_in_file_templates_test.rb +++ b/test/use_in_file_templates_test.rb @@ -6,34 +6,33 @@ context "Rendering in file templates" do Sinatra.application = nil use_in_file_templates! end - + specify "should set template" do assert Sinatra.application.templates[:foo] end - + specify "should set layout" do assert Sinatra.application.templates[:layout] end - + specify "should render without layout if specified" do get '/' do haml :foo, :layout => false end - + get_it '/' assert_equal "this is foo\n", body end - + specify "should render with layout if specified" do get '/' do haml :foo end - + get_it '/' assert_equal "X\nthis is foo\nX\n", body end - - + end __END__