-
-
- PAGE
-
- attr_reader :files
- attr_accessor :root, :path
-
- def initialize(root, app=nil)
- @root = F.expand_path(root)
- @app = app || Rack::File.new(@root)
- end
-
- def call(env)
- dup._call(env)
- end
-
- F = ::File
-
- def _call(env)
- @env = env
- @script_name = env['SCRIPT_NAME']
- @path_info = Utils.unescape(env['PATH_INFO'])
-
- if forbidden = check_forbidden
- forbidden
- else
- @path = F.join(@root, @path_info)
- list_path
- end
- end
-
- def check_forbidden
- return unless @path_info.include? ".."
-
- body = "Forbidden\n"
- size = Rack::Utils.bytesize(body)
- return [403, {"Content-Type" => "text/plain","Content-Length" => size.to_s}, [body]]
- end
-
- def list_directory
- @files = [['../','Parent Directory','','','']]
- glob = F.join(@path, '*')
-
- Dir[glob].sort.each do |node|
- stat = stat(node)
- next unless stat
- basename = F.basename(node)
- ext = F.extname(node)
-
- url = F.join(@script_name, @path_info, basename)
- size = stat.size
- type = stat.directory? ? 'directory' : Mime.mime_type(ext)
- size = stat.directory? ? '-' : filesize_format(size)
- mtime = stat.mtime.httpdate
- url << '/' if stat.directory?
- basename << '/' if stat.directory?
-
- @files << [ url, basename, size, type, mtime ]
- end
-
- return [ 200, {'Content-Type'=>'text/html; charset=utf-8'}, self ]
- end
-
- def stat(node, max = 10)
- F.stat(node)
- rescue Errno::ENOENT, Errno::ELOOP
- return nil
- end
-
- # TODO: add correct response if not readable, not sure if 404 is the best
- # option
- def list_path
- @stat = F.stat(@path)
-
- if @stat.readable?
- return @app.call(@env) if @stat.file?
- return list_directory if @stat.directory?
- else
- raise Errno::ENOENT, 'No such file or directory'
- end
-
- rescue Errno::ENOENT, Errno::ELOOP
- return entity_not_found
- end
-
- def entity_not_found
- body = "Entity not found: #{@path_info}\n"
- size = Rack::Utils.bytesize(body)
- return [404, {"Content-Type" => "text/plain", "Content-Length" => size.to_s}, [body]]
- end
-
- def each
- show_path = @path.sub(/^#{@root}/,'')
- files = @files.map{|f| DIR_FILE % f }*"\n"
- page = DIR_PAGE % [ show_path, show_path , files ]
- page.each_line{|l| yield l }
- end
-
- # Stolen from Ramaze
-
- FILESIZE_FORMAT = [
- ['%.1fT', 1 << 40],
- ['%.1fG', 1 << 30],
- ['%.1fM', 1 << 20],
- ['%.1fK', 1 << 10],
- ]
-
- def filesize_format(int)
- FILESIZE_FORMAT.each do |format, size|
- return format % (int.to_f / size) if int >= size
- end
-
- int.to_s + 'B'
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/file.rb b/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/file.rb
deleted file mode 100644
index fe62bd6b86..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/file.rb
+++ /dev/null
@@ -1,88 +0,0 @@
-require 'time'
-require 'rack/utils'
-require 'rack/mime'
-
-module Rack
- # Rack::File serves files below the +root+ given, according to the
- # path info of the Rack request.
- #
- # Handlers can detect if bodies are a Rack::File, and use mechanisms
- # like sendfile on the +path+.
-
- class File
- attr_accessor :root
- attr_accessor :path
-
- alias :to_path :path
-
- def initialize(root)
- @root = root
- end
-
- def call(env)
- dup._call(env)
- end
-
- F = ::File
-
- def _call(env)
- @path_info = Utils.unescape(env["PATH_INFO"])
- return forbidden if @path_info.include? ".."
-
- @path = F.join(@root, @path_info)
-
- begin
- if F.file?(@path) && F.readable?(@path)
- serving
- else
- raise Errno::EPERM
- end
- rescue SystemCallError
- not_found
- end
- end
-
- def forbidden
- body = "Forbidden\n"
- [403, {"Content-Type" => "text/plain",
- "Content-Length" => body.size.to_s},
- [body]]
- end
-
- # NOTE:
- # We check via File::size? whether this file provides size info
- # via stat (e.g. /proc files often don't), otherwise we have to
- # figure it out by reading the whole file into memory. And while
- # we're at it we also use this as body then.
-
- def serving
- if size = F.size?(@path)
- body = self
- else
- body = [F.read(@path)]
- size = Utils.bytesize(body.first)
- end
-
- [200, {
- "Last-Modified" => F.mtime(@path).httpdate,
- "Content-Type" => Mime.mime_type(F.extname(@path), 'text/plain'),
- "Content-Length" => size.to_s
- }, body]
- end
-
- def not_found
- body = "File not found: #{@path_info}\n"
- [404, {"Content-Type" => "text/plain",
- "Content-Length" => body.size.to_s},
- [body]]
- end
-
- def each
- F.open(@path, "rb") { |file|
- while part = file.read(8192)
- yield part
- end
- }
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler.rb b/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler.rb
deleted file mode 100644
index 1018af64c7..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler.rb
+++ /dev/null
@@ -1,48 +0,0 @@
-module Rack
- # *Handlers* connect web servers with Rack.
- #
- # Rack includes Handlers for Mongrel, WEBrick, FastCGI, CGI, SCGI
- # and LiteSpeed.
- #
- # Handlers usually are activated by calling MyHandler.run(myapp).
- # A second optional hash can be passed to include server-specific
- # configuration.
- module Handler
- def self.get(server)
- return unless server
-
- if klass = @handlers[server]
- obj = Object
- klass.split("::").each { |x| obj = obj.const_get(x) }
- obj
- else
- Rack::Handler.const_get(server.capitalize)
- end
- end
-
- def self.register(server, klass)
- @handlers ||= {}
- @handlers[server] = klass
- end
-
- autoload :CGI, "rack/handler/cgi"
- autoload :FastCGI, "rack/handler/fastcgi"
- autoload :Mongrel, "rack/handler/mongrel"
- autoload :EventedMongrel, "rack/handler/evented_mongrel"
- autoload :SwiftipliedMongrel, "rack/handler/swiftiplied_mongrel"
- autoload :WEBrick, "rack/handler/webrick"
- autoload :LSWS, "rack/handler/lsws"
- autoload :SCGI, "rack/handler/scgi"
- autoload :Thin, "rack/handler/thin"
-
- register 'cgi', 'Rack::Handler::CGI'
- register 'fastcgi', 'Rack::Handler::FastCGI'
- register 'mongrel', 'Rack::Handler::Mongrel'
- register 'emongrel', 'Rack::Handler::EventedMongrel'
- register 'smongrel', 'Rack::Handler::SwiftipliedMongrel'
- register 'webrick', 'Rack::Handler::WEBrick'
- register 'lsws', 'Rack::Handler::LSWS'
- register 'scgi', 'Rack::Handler::SCGI'
- register 'thin', 'Rack::Handler::Thin'
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler/cgi.rb b/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler/cgi.rb
deleted file mode 100644
index e38156c7f0..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler/cgi.rb
+++ /dev/null
@@ -1,61 +0,0 @@
-require 'rack/content_length'
-
-module Rack
- module Handler
- class CGI
- def self.run(app, options=nil)
- serve app
- end
-
- def self.serve(app)
- app = ContentLength.new(app)
-
- env = ENV.to_hash
- env.delete "HTTP_CONTENT_LENGTH"
-
- env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/"
-
- env.update({"rack.version" => [0,1],
- "rack.input" => $stdin,
- "rack.errors" => $stderr,
-
- "rack.multithread" => false,
- "rack.multiprocess" => true,
- "rack.run_once" => true,
-
- "rack.url_scheme" => ["yes", "on", "1"].include?(ENV["HTTPS"]) ? "https" : "http"
- })
-
- env["QUERY_STRING"] ||= ""
- env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"]
- env["REQUEST_PATH"] ||= "/"
-
- status, headers, body = app.call(env)
- begin
- send_headers status, headers
- send_body body
- ensure
- body.close if body.respond_to? :close
- end
- end
-
- def self.send_headers(status, headers)
- STDOUT.print "Status: #{status}\r\n"
- headers.each { |k, vs|
- vs.split("\n").each { |v|
- STDOUT.print "#{k}: #{v}\r\n"
- }
- }
- STDOUT.print "\r\n"
- STDOUT.flush
- end
-
- def self.send_body(body)
- body.each { |part|
- STDOUT.print part
- STDOUT.flush
- }
- end
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler/evented_mongrel.rb b/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler/evented_mongrel.rb
deleted file mode 100644
index 0f5cbf7293..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler/evented_mongrel.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-require 'swiftcore/evented_mongrel'
-
-module Rack
- module Handler
- class EventedMongrel < Handler::Mongrel
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler/fastcgi.rb b/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler/fastcgi.rb
deleted file mode 100644
index 6324c7d274..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler/fastcgi.rb
+++ /dev/null
@@ -1,89 +0,0 @@
-require 'fcgi'
-require 'socket'
-require 'rack/content_length'
-
-module Rack
- module Handler
- class FastCGI
- def self.run(app, options={})
- file = options[:File] and STDIN.reopen(UNIXServer.new(file))
- port = options[:Port] and STDIN.reopen(TCPServer.new(port))
- FCGI.each { |request|
- serve request, app
- }
- end
-
- module ProperStream # :nodoc:
- def each # This is missing by default.
- while line = gets
- yield line
- end
- end
-
- def read(*args)
- if args.empty?
- super || "" # Empty string on EOF.
- else
- super
- end
- end
- end
-
- def self.serve(request, app)
- app = Rack::ContentLength.new(app)
-
- env = request.env
- env.delete "HTTP_CONTENT_LENGTH"
-
- request.in.extend ProperStream
-
- env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/"
-
- env.update({"rack.version" => [0,1],
- "rack.input" => request.in,
- "rack.errors" => request.err,
-
- "rack.multithread" => false,
- "rack.multiprocess" => true,
- "rack.run_once" => false,
-
- "rack.url_scheme" => ["yes", "on", "1"].include?(env["HTTPS"]) ? "https" : "http"
- })
-
- env["QUERY_STRING"] ||= ""
- env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"]
- env["REQUEST_PATH"] ||= "/"
- env.delete "PATH_INFO" if env["PATH_INFO"] == ""
- env.delete "CONTENT_TYPE" if env["CONTENT_TYPE"] == ""
- env.delete "CONTENT_LENGTH" if env["CONTENT_LENGTH"] == ""
-
- status, headers, body = app.call(env)
- begin
- send_headers request.out, status, headers
- send_body request.out, body
- ensure
- body.close if body.respond_to? :close
- request.finish
- end
- end
-
- def self.send_headers(out, status, headers)
- out.print "Status: #{status}\r\n"
- headers.each { |k, vs|
- vs.split("\n").each { |v|
- out.print "#{k}: #{v}\r\n"
- }
- }
- out.print "\r\n"
- out.flush
- end
-
- def self.send_body(out, body)
- body.each { |part|
- out.print part
- out.flush
- }
- end
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler/lsws.rb b/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler/lsws.rb
deleted file mode 100644
index c65ba3ec8e..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler/lsws.rb
+++ /dev/null
@@ -1,55 +0,0 @@
-require 'lsapi'
-require 'rack/content_length'
-
-module Rack
- module Handler
- class LSWS
- def self.run(app, options=nil)
- while LSAPI.accept != nil
- serve app
- end
- end
- def self.serve(app)
- app = Rack::ContentLength.new(app)
-
- env = ENV.to_hash
- env.delete "HTTP_CONTENT_LENGTH"
- env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/"
- env.update({"rack.version" => [0,1],
- "rack.input" => StringIO.new($stdin.read.to_s),
- "rack.errors" => $stderr,
- "rack.multithread" => false,
- "rack.multiprocess" => true,
- "rack.run_once" => false,
- "rack.url_scheme" => ["yes", "on", "1"].include?(ENV["HTTPS"]) ? "https" : "http"
- })
- env["QUERY_STRING"] ||= ""
- env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"]
- env["REQUEST_PATH"] ||= "/"
- status, headers, body = app.call(env)
- begin
- send_headers status, headers
- send_body body
- ensure
- body.close if body.respond_to? :close
- end
- end
- def self.send_headers(status, headers)
- print "Status: #{status}\r\n"
- headers.each { |k, vs|
- vs.split("\n").each { |v|
- print "#{k}: #{v}\r\n"
- }
- }
- print "\r\n"
- STDOUT.flush
- end
- def self.send_body(body)
- body.each { |part|
- print part
- STDOUT.flush
- }
- end
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler/mongrel.rb b/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler/mongrel.rb
deleted file mode 100644
index f0c0d58330..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler/mongrel.rb
+++ /dev/null
@@ -1,84 +0,0 @@
-require 'mongrel'
-require 'stringio'
-require 'rack/content_length'
-require 'rack/chunked'
-
-module Rack
- module Handler
- class Mongrel < ::Mongrel::HttpHandler
- def self.run(app, options={})
- server = ::Mongrel::HttpServer.new(options[:Host] || '0.0.0.0',
- options[:Port] || 8080)
- # Acts like Rack::URLMap, utilizing Mongrel's own path finding methods.
- # Use is similar to #run, replacing the app argument with a hash of
- # { path=>app, ... } or an instance of Rack::URLMap.
- if options[:map]
- if app.is_a? Hash
- app.each do |path, appl|
- path = '/'+path unless path[0] == ?/
- server.register(path, Rack::Handler::Mongrel.new(appl))
- end
- elsif app.is_a? URLMap
- app.instance_variable_get(:@mapping).each do |(host, path, appl)|
- next if !host.nil? && !options[:Host].nil? && options[:Host] != host
- path = '/'+path unless path[0] == ?/
- server.register(path, Rack::Handler::Mongrel.new(appl))
- end
- else
- raise ArgumentError, "first argument should be a Hash or URLMap"
- end
- else
- server.register('/', Rack::Handler::Mongrel.new(app))
- end
- yield server if block_given?
- server.run.join
- end
-
- def initialize(app)
- @app = Rack::Chunked.new(Rack::ContentLength.new(app))
- end
-
- def process(request, response)
- env = {}.replace(request.params)
- env.delete "HTTP_CONTENT_TYPE"
- env.delete "HTTP_CONTENT_LENGTH"
-
- env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/"
-
- env.update({"rack.version" => [0,1],
- "rack.input" => request.body || StringIO.new(""),
- "rack.errors" => $stderr,
-
- "rack.multithread" => true,
- "rack.multiprocess" => false, # ???
- "rack.run_once" => false,
-
- "rack.url_scheme" => "http",
- })
- env["QUERY_STRING"] ||= ""
- env.delete "PATH_INFO" if env["PATH_INFO"] == ""
-
- status, headers, body = @app.call(env)
-
- begin
- response.status = status.to_i
- response.send_status(nil)
-
- headers.each { |k, vs|
- vs.split("\n").each { |v|
- response.header[k] = v
- }
- }
- response.send_header
-
- body.each { |part|
- response.write part
- response.socket.flush
- }
- ensure
- body.close if body.respond_to? :close
- end
- end
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler/scgi.rb b/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler/scgi.rb
deleted file mode 100644
index 9495c66374..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler/scgi.rb
+++ /dev/null
@@ -1,59 +0,0 @@
-require 'scgi'
-require 'stringio'
-require 'rack/content_length'
-require 'rack/chunked'
-
-module Rack
- module Handler
- class SCGI < ::SCGI::Processor
- attr_accessor :app
-
- def self.run(app, options=nil)
- new(options.merge(:app=>app,
- :host=>options[:Host],
- :port=>options[:Port],
- :socket=>options[:Socket])).listen
- end
-
- def initialize(settings = {})
- @app = Rack::Chunked.new(Rack::ContentLength.new(settings[:app]))
- @log = Object.new
- def @log.info(*args); end
- def @log.error(*args); end
- super(settings)
- end
-
- def process_request(request, input_body, socket)
- env = {}.replace(request)
- env.delete "HTTP_CONTENT_TYPE"
- env.delete "HTTP_CONTENT_LENGTH"
- env["REQUEST_PATH"], env["QUERY_STRING"] = env["REQUEST_URI"].split('?', 2)
- env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"]
- env["PATH_INFO"] = env["REQUEST_PATH"]
- env["QUERY_STRING"] ||= ""
- env["SCRIPT_NAME"] = ""
- env.update({"rack.version" => [0,1],
- "rack.input" => StringIO.new(input_body),
- "rack.errors" => $stderr,
-
- "rack.multithread" => true,
- "rack.multiprocess" => true,
- "rack.run_once" => false,
-
- "rack.url_scheme" => ["yes", "on", "1"].include?(env["HTTPS"]) ? "https" : "http"
- })
- status, headers, body = app.call(env)
- begin
- socket.write("Status: #{status}\r\n")
- headers.each do |k, vs|
- vs.split("\n").each { |v| socket.write("#{k}: #{v}\r\n")}
- end
- socket.write("\r\n")
- body.each {|s| socket.write(s)}
- ensure
- body.close if body.respond_to? :close
- end
- end
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler/swiftiplied_mongrel.rb b/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler/swiftiplied_mongrel.rb
deleted file mode 100644
index 4bafd0b953..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler/swiftiplied_mongrel.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-require 'swiftcore/swiftiplied_mongrel'
-
-module Rack
- module Handler
- class SwiftipliedMongrel < Handler::Mongrel
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler/thin.rb b/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler/thin.rb
deleted file mode 100644
index 3d4fedff75..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler/thin.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-require "thin"
-require "rack/content_length"
-require "rack/chunked"
-
-module Rack
- module Handler
- class Thin
- def self.run(app, options={})
- app = Rack::Chunked.new(Rack::ContentLength.new(app))
- server = ::Thin::Server.new(options[:Host] || '0.0.0.0',
- options[:Port] || 8080,
- app)
- yield server if block_given?
- server.start
- end
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler/webrick.rb b/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler/webrick.rb
deleted file mode 100644
index 829e7d6bf8..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/handler/webrick.rb
+++ /dev/null
@@ -1,67 +0,0 @@
-require 'webrick'
-require 'stringio'
-require 'rack/content_length'
-
-module Rack
- module Handler
- class WEBrick < ::WEBrick::HTTPServlet::AbstractServlet
- def self.run(app, options={})
- server = ::WEBrick::HTTPServer.new(options)
- server.mount "/", Rack::Handler::WEBrick, app
- trap(:INT) { server.shutdown }
- yield server if block_given?
- server.start
- end
-
- def initialize(server, app)
- super server
- @app = Rack::ContentLength.new(app)
- end
-
- def service(req, res)
- env = req.meta_vars
- env.delete_if { |k, v| v.nil? }
-
- env.update({"rack.version" => [0,1],
- "rack.input" => StringIO.new(req.body.to_s),
- "rack.errors" => $stderr,
-
- "rack.multithread" => true,
- "rack.multiprocess" => false,
- "rack.run_once" => false,
-
- "rack.url_scheme" => ["yes", "on", "1"].include?(ENV["HTTPS"]) ? "https" : "http"
- })
-
- env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"]
- env["QUERY_STRING"] ||= ""
- env["REQUEST_PATH"] ||= "/"
- if env["PATH_INFO"] == ""
- env.delete "PATH_INFO"
- else
- path, n = req.request_uri.path, env["SCRIPT_NAME"].length
- env["PATH_INFO"] = path[n, path.length-n]
- end
-
- status, headers, body = @app.call(env)
- begin
- res.status = status.to_i
- headers.each { |k, vs|
- if k.downcase == "set-cookie"
- res.cookies.concat vs.split("\n")
- else
- vs.split("\n").each { |v|
- res[k] = v
- }
- end
- }
- body.each { |part|
- res.body << part
- }
- ensure
- body.close if body.respond_to? :close
- end
- end
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/head.rb b/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/head.rb
deleted file mode 100644
index deab822a99..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/head.rb
+++ /dev/null
@@ -1,19 +0,0 @@
-module Rack
-
-class Head
- def initialize(app)
- @app = app
- end
-
- def call(env)
- status, headers, body = @app.call(env)
-
- if env["REQUEST_METHOD"] == "HEAD"
- [status, headers, []]
- else
- [status, headers, body]
- end
- end
-end
-
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/lint.rb b/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/lint.rb
deleted file mode 100644
index 44a33ce36e..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/lint.rb
+++ /dev/null
@@ -1,462 +0,0 @@
-require 'rack/utils'
-
-module Rack
- # Rack::Lint validates your application and the requests and
- # responses according to the Rack spec.
-
- class Lint
- def initialize(app)
- @app = app
- end
-
- # :stopdoc:
-
- class LintError < RuntimeError; end
- module Assertion
- def assert(message, &block)
- unless block.call
- raise LintError, message
- end
- end
- end
- include Assertion
-
- ## This specification aims to formalize the Rack protocol. You
- ## can (and should) use Rack::Lint to enforce it.
- ##
- ## When you develop middleware, be sure to add a Lint before and
- ## after to catch all mistakes.
-
- ## = Rack applications
-
- ## A Rack application is an Ruby object (not a class) that
- ## responds to +call+.
- def call(env=nil)
- dup._call(env)
- end
-
- def _call(env)
- ## It takes exactly one argument, the *environment*
- assert("No env given") { env }
- check_env env
-
- env['rack.input'] = InputWrapper.new(env['rack.input'])
- env['rack.errors'] = ErrorWrapper.new(env['rack.errors'])
-
- ## and returns an Array of exactly three values:
- status, headers, @body = @app.call(env)
- ## The *status*,
- check_status status
- ## the *headers*,
- check_headers headers
- ## and the *body*.
- check_content_type status, headers
- check_content_length status, headers, env
- [status, headers, self]
- end
-
- ## == The Environment
- def check_env(env)
- ## The environment must be an true instance of Hash (no
- ## subclassing allowed) that includes CGI-like headers.
- ## The application is free to modify the environment.
- assert("env #{env.inspect} is not a Hash, but #{env.class}") {
- env.instance_of? Hash
- }
-
- ##
- ## The environment is required to include these variables
- ## (adopted from PEP333), except when they'd be empty, but see
- ## below.
-
- ## REQUEST_METHOD:: The HTTP request method, such as
- ## "GET" or "POST". This cannot ever
- ## be an empty string, and so is
- ## always required.
-
- ## SCRIPT_NAME:: The initial portion of the request
- ## URL's "path" that corresponds to the
- ## application object, so that the
- ## application knows its virtual
- ## "location". This may be an empty
- ## string, if the application corresponds
- ## to the "root" of the server.
-
- ## PATH_INFO:: The remainder of the request URL's
- ## "path", designating the virtual
- ## "location" of the request's target
- ## within the application. This may be an
- ## empty string, if the request URL targets
- ## the application root and does not have a
- ## trailing slash. This information should be
- ## decoded by the server if it comes from a
- ## URL.
-
- ## QUERY_STRING:: The portion of the request URL that
- ## follows the ?, if any. May be
- ## empty, but is always required!
-
- ## SERVER_NAME, SERVER_PORT:: When combined with SCRIPT_NAME and PATH_INFO, these variables can be used to complete the URL. Note, however, that HTTP_HOST, if present, should be used in preference to SERVER_NAME for reconstructing the request URL. SERVER_NAME and SERVER_PORT can never be empty strings, and so are always required.
-
- ## HTTP_ Variables:: Variables corresponding to the
- ## client-supplied HTTP request
- ## headers (i.e., variables whose
- ## names begin with HTTP_). The
- ## presence or absence of these
- ## variables should correspond with
- ## the presence or absence of the
- ## appropriate HTTP header in the
- ## request.
-
- ## In addition to this, the Rack environment must include these
- ## Rack-specific variables:
-
- ## rack.version:: The Array [0,1], representing this version of Rack.
- ## rack.url_scheme:: +http+ or +https+, depending on the request URL.
- ## rack.input:: See below, the input stream.
- ## rack.errors:: See below, the error stream.
- ## rack.multithread:: true if the application object may be simultaneously invoked by another thread in the same process, false otherwise.
- ## rack.multiprocess:: true if an equivalent application object may be simultaneously invoked by another process, false otherwise.
- ## rack.run_once:: true if the server expects (but does not guarantee!) that the application will only be invoked this one time during the life of its containing process. Normally, this will only be true for a server based on CGI (or something similar).
-
- ## The server or the application can store their own data in the
- ## environment, too. The keys must contain at least one dot,
- ## and should be prefixed uniquely. The prefix rack.
- ## is reserved for use with the Rack core distribution and must
- ## not be used otherwise.
- ##
-
- %w[REQUEST_METHOD SERVER_NAME SERVER_PORT
- QUERY_STRING
- rack.version rack.input rack.errors
- rack.multithread rack.multiprocess rack.run_once].each { |header|
- assert("env missing required key #{header}") { env.include? header }
- }
-
- ## The environment must not contain the keys
- ## HTTP_CONTENT_TYPE or HTTP_CONTENT_LENGTH
- ## (use the versions without HTTP_).
- %w[HTTP_CONTENT_TYPE HTTP_CONTENT_LENGTH].each { |header|
- assert("env contains #{header}, must use #{header[5,-1]}") {
- not env.include? header
- }
- }
-
- ## The CGI keys (named without a period) must have String values.
- env.each { |key, value|
- next if key.include? "." # Skip extensions
- assert("env variable #{key} has non-string value #{value.inspect}") {
- value.instance_of? String
- }
- }
-
- ##
- ## There are the following restrictions:
-
- ## * rack.version must be an array of Integers.
- assert("rack.version must be an Array, was #{env["rack.version"].class}") {
- env["rack.version"].instance_of? Array
- }
- ## * rack.url_scheme must either be +http+ or +https+.
- assert("rack.url_scheme unknown: #{env["rack.url_scheme"].inspect}") {
- %w[http https].include? env["rack.url_scheme"]
- }
-
- ## * There must be a valid input stream in rack.input.
- check_input env["rack.input"]
- ## * There must be a valid error stream in rack.errors.
- check_error env["rack.errors"]
-
- ## * The REQUEST_METHOD must be a valid token.
- assert("REQUEST_METHOD unknown: #{env["REQUEST_METHOD"]}") {
- env["REQUEST_METHOD"] =~ /\A[0-9A-Za-z!\#$%&'*+.^_`|~-]+\z/
- }
-
- ## * The SCRIPT_NAME, if non-empty, must start with /
- assert("SCRIPT_NAME must start with /") {
- !env.include?("SCRIPT_NAME") ||
- env["SCRIPT_NAME"] == "" ||
- env["SCRIPT_NAME"] =~ /\A\//
- }
- ## * The PATH_INFO, if non-empty, must start with /
- assert("PATH_INFO must start with /") {
- !env.include?("PATH_INFO") ||
- env["PATH_INFO"] == "" ||
- env["PATH_INFO"] =~ /\A\//
- }
- ## * The CONTENT_LENGTH, if given, must consist of digits only.
- assert("Invalid CONTENT_LENGTH: #{env["CONTENT_LENGTH"]}") {
- !env.include?("CONTENT_LENGTH") || env["CONTENT_LENGTH"] =~ /\A\d+\z/
- }
-
- ## * One of SCRIPT_NAME or PATH_INFO must be
- ## set. PATH_INFO should be / if
- ## SCRIPT_NAME is empty.
- assert("One of SCRIPT_NAME or PATH_INFO must be set (make PATH_INFO '/' if SCRIPT_NAME is empty)") {
- env["SCRIPT_NAME"] || env["PATH_INFO"]
- }
- ## SCRIPT_NAME never should be /, but instead be empty.
- assert("SCRIPT_NAME cannot be '/', make it '' and PATH_INFO '/'") {
- env["SCRIPT_NAME"] != "/"
- }
- end
-
- ## === The Input Stream
- def check_input(input)
- ## The input stream must respond to +gets+, +each+ and +read+.
- [:gets, :each, :read].each { |method|
- assert("rack.input #{input} does not respond to ##{method}") {
- input.respond_to? method
- }
- }
- end
-
- class InputWrapper
- include Assertion
-
- def initialize(input)
- @input = input
- end
-
- def size
- @input.size
- end
-
- def rewind
- @input.rewind
- end
-
- ## * +gets+ must be called without arguments and return a string,
- ## or +nil+ on EOF.
- def gets(*args)
- assert("rack.input#gets called with arguments") { args.size == 0 }
- v = @input.gets
- assert("rack.input#gets didn't return a String") {
- v.nil? or v.instance_of? String
- }
- v
- end
-
- ## * +read+ must be called without or with one integer argument
- ## and return a string, or +nil+ on EOF.
- def read(*args)
- assert("rack.input#read called with too many arguments") {
- args.size <= 1
- }
- if args.size == 1
- assert("rack.input#read called with non-integer argument") {
- args.first.kind_of? Integer
- }
- end
- v = @input.read(*args)
- assert("rack.input#read didn't return a String") {
- v.nil? or v.instance_of? String
- }
- v
- end
-
- ## * +each+ must be called without arguments and only yield Strings.
- def each(*args)
- assert("rack.input#each called with arguments") { args.size == 0 }
- @input.each { |line|
- assert("rack.input#each didn't yield a String") {
- line.instance_of? String
- }
- yield line
- }
- end
-
- ## * +close+ must never be called on the input stream.
- def close(*args)
- assert("rack.input#close must not be called") { false }
- end
- end
-
- ## === The Error Stream
- def check_error(error)
- ## The error stream must respond to +puts+, +write+ and +flush+.
- [:puts, :write, :flush].each { |method|
- assert("rack.error #{error} does not respond to ##{method}") {
- error.respond_to? method
- }
- }
- end
-
- class ErrorWrapper
- include Assertion
-
- def initialize(error)
- @error = error
- end
-
- ## * +puts+ must be called with a single argument that responds to +to_s+.
- def puts(str)
- @error.puts str
- end
-
- ## * +write+ must be called with a single argument that is a String.
- def write(str)
- assert("rack.errors#write not called with a String") { str.instance_of? String }
- @error.write str
- end
-
- ## * +flush+ must be called without arguments and must be called
- ## in order to make the error appear for sure.
- def flush
- @error.flush
- end
-
- ## * +close+ must never be called on the error stream.
- def close(*args)
- assert("rack.errors#close must not be called") { false }
- end
- end
-
- ## == The Response
-
- ## === The Status
- def check_status(status)
- ## The status, if parsed as integer (+to_i+), must be greater than or equal to 100.
- assert("Status must be >=100 seen as integer") { status.to_i >= 100 }
- end
-
- ## === The Headers
- def check_headers(header)
- ## The header must respond to each, and yield values of key and value.
- assert("headers object should respond to #each, but doesn't (got #{header.class} as headers)") {
- header.respond_to? :each
- }
- header.each { |key, value|
- ## The header keys must be Strings.
- assert("header key must be a string, was #{key.class}") {
- key.instance_of? String
- }
- ## The header must not contain a +Status+ key,
- assert("header must not contain Status") { key.downcase != "status" }
- ## contain keys with : or newlines in their name,
- assert("header names must not contain : or \\n") { key !~ /[:\n]/ }
- ## contain keys names that end in - or _,
- assert("header names must not end in - or _") { key !~ /[-_]\z/ }
- ## but only contain keys that consist of
- ## letters, digits, _ or - and start with a letter.
- assert("invalid header name: #{key}") { key =~ /\A[a-zA-Z][a-zA-Z0-9_-]*\z/ }
-
- ## The values of the header must be Strings,
- assert("a header value must be a String, but the value of " +
- "'#{key}' is a #{value.class}") { value.kind_of? String }
- ## consisting of lines (for multiple header values) seperated by "\n".
- value.split("\n").each { |item|
- ## The lines must not contain characters below 037.
- assert("invalid header value #{key}: #{item.inspect}") {
- item !~ /[\000-\037]/
- }
- }
- }
- end
-
- ## === The Content-Type
- def check_content_type(status, headers)
- headers.each { |key, value|
- ## There must be a Content-Type, except when the
- ## +Status+ is 1xx, 204 or 304, in which case there must be none
- ## given.
- if key.downcase == "content-type"
- assert("Content-Type header found in #{status} response, not allowed") {
- not Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
- }
- return
- end
- }
- assert("No Content-Type header found") {
- Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
- }
- end
-
- ## === The Content-Length
- def check_content_length(status, headers, env)
- headers.each { |key, value|
- if key.downcase == 'content-length'
- ## There must not be a Content-Length header when the
- ## +Status+ is 1xx, 204 or 304.
- assert("Content-Length header found in #{status} response, not allowed") {
- not Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
- }
-
- bytes = 0
- string_body = true
-
- if @body.respond_to?(:to_ary)
- @body.each { |part|
- unless part.kind_of?(String)
- string_body = false
- break
- end
-
- bytes += Rack::Utils.bytesize(part)
- }
-
- if env["REQUEST_METHOD"] == "HEAD"
- assert("Response body was given for HEAD request, but should be empty") {
- bytes == 0
- }
- else
- if string_body
- assert("Content-Length header was #{value}, but should be #{bytes}") {
- value == bytes.to_s
- }
- end
- end
- end
-
- return
- end
- }
- end
-
- ## === The Body
- def each
- @closed = false
- ## The Body must respond to #each
- @body.each { |part|
- ## and must only yield String values.
- assert("Body yielded non-string value #{part.inspect}") {
- part.instance_of? String
- }
- yield part
- }
- ##
- ## If the Body responds to #close, it will be called after iteration.
- # XXX howto: assert("Body has not been closed") { @closed }
-
-
- ##
- ## If the Body responds to #to_path, it must return a String
- ## identifying the location of a file whose contents are identical
- ## to that produced by calling #each.
-
- if @body.respond_to?(:to_path)
- assert("The file identified by body.to_path does not exist") {
- ::File.exist? @body.to_path
- }
- end
-
- ##
- ## The Body commonly is an Array of Strings, the application
- ## instance itself, or a File-like object.
- end
-
- def close
- @closed = true
- @body.close if @body.respond_to?(:close)
- end
-
- # :startdoc:
-
- end
-end
-
-## == Thanks
-## Some parts of this specification are adopted from PEP333: Python
-## Web Server Gateway Interface
-## v1.0 (http://www.python.org/dev/peps/pep-0333/). I'd like to thank
-## everyone involved in that effort.
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/lobster.rb b/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/lobster.rb
deleted file mode 100644
index f63f419a49..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/lobster.rb
+++ /dev/null
@@ -1,65 +0,0 @@
-require 'zlib'
-
-require 'rack/request'
-require 'rack/response'
-
-module Rack
- # Paste has a Pony, Rack has a Lobster!
- class Lobster
- LobsterString = Zlib::Inflate.inflate("eJx9kEEOwyAMBO99xd7MAcytUhPlJyj2
- P6jy9i4k9EQyGAnBarEXeCBqSkntNXsi/ZCvC48zGQoZKikGrFMZvgS5ZHd+aGWVuWwhVF0
- t1drVmiR42HcWNz5w3QanT+2gIvTVCiE1lm1Y0eU4JGmIIbaKwextKn8rvW+p5PIwFl8ZWJ
- I8jyiTlhTcYXkekJAzTyYN6E08A+dk8voBkAVTJQ==".delete("\n ").unpack("m*")[0])
-
- LambdaLobster = lambda { |env|
- if env["QUERY_STRING"].include?("flip")
- lobster = LobsterString.split("\n").
- map { |line| line.ljust(42).reverse }.
- join("\n")
- href = "?"
- else
- lobster = LobsterString
- href = "?flip"
- end
-
- content = ["Lobstericious!",
- "
- You're seeing this error because you use Rack::ShowExceptions.
-
-
-
-
-
-HTML
-
- # :startdoc:
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/showstatus.rb b/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/showstatus.rb
deleted file mode 100644
index 28258c7c89..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/showstatus.rb
+++ /dev/null
@@ -1,106 +0,0 @@
-require 'erb'
-require 'rack/request'
-require 'rack/utils'
-
-module Rack
- # Rack::ShowStatus catches all empty responses the app it wraps and
- # replaces them with a site explaining the error.
- #
- # Additional details can be put into rack.showstatus.detail
- # and will be shown as HTML. If such details exist, the error page
- # is always rendered, even if the reply was not empty.
-
- class ShowStatus
- def initialize(app)
- @app = app
- @template = ERB.new(TEMPLATE)
- end
-
- def call(env)
- status, headers, body = @app.call(env)
- headers = Utils::HeaderHash.new(headers)
- empty = headers['Content-Length'].to_i <= 0
-
- # client or server error, or explicit message
- if (status.to_i >= 400 && empty) || env["rack.showstatus.detail"]
- req = Rack::Request.new(env)
- message = Rack::Utils::HTTP_STATUS_CODES[status.to_i] || status.to_s
- detail = env["rack.showstatus.detail"] || message
- body = @template.result(binding)
- size = Rack::Utils.bytesize(body)
- [status, headers.merge("Content-Type" => "text/html", "Content-Length" => size.to_s), [body]]
- else
- [status, headers, body]
- end
- end
-
- def h(obj) # :nodoc:
- case obj
- when String
- Utils.escape_html(obj)
- else
- Utils.escape_html(obj.inspect)
- end
- end
-
- # :stopdoc:
-
-# adapted from Django
-# Copyright (c) 2005, the Lawrence Journal-World
-# Used under the modified BSD license:
-# http://www.xfree86.org/3.3.6/COPYRIGHT2.html#5
-TEMPLATE = <<'HTML'
-
-
-
-
- <%=h message %> at <%=h req.script_name + req.path_info %>
-
-
-
-
-
-
<%=h message %> (<%= status.to_i %>)
-
-
-
Request Method:
-
<%=h req.request_method %>
-
-
-
Request URL:
-
<%=h req.url %>
-
-
-
-
-
<%= detail %>
-
-
-
-
- You're seeing this error because you use Rack::ShowStatus.
-
-
-
-
-HTML
-
- # :startdoc:
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/static.rb b/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/static.rb
deleted file mode 100644
index 168e8f83b2..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/static.rb
+++ /dev/null
@@ -1,38 +0,0 @@
-module Rack
-
- # The Rack::Static middleware intercepts requests for static files
- # (javascript files, images, stylesheets, etc) based on the url prefixes
- # passed in the options, and serves them using a Rack::File object. This
- # allows a Rack stack to serve both static and dynamic content.
- #
- # Examples:
- # use Rack::Static, :urls => ["/media"]
- # will serve all requests beginning with /media from the "media" folder
- # located in the current directory (ie media/*).
- #
- # use Rack::Static, :urls => ["/css", "/images"], :root => "public"
- # will serve all requests beginning with /css or /images from the folder
- # "public" in the current directory (ie public/css/* and public/images/*)
-
- class Static
-
- def initialize(app, options={})
- @app = app
- @urls = options[:urls] || ["/favicon.ico"]
- root = options[:root] || Dir.pwd
- @file_server = Rack::File.new(root)
- end
-
- def call(env)
- path = env["PATH_INFO"]
- can_serve = @urls.any? { |url| path.index(url) == 0 }
-
- if can_serve
- @file_server.call(env)
- else
- @app.call(env)
- end
- end
-
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/urlmap.rb b/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/urlmap.rb
deleted file mode 100644
index 0ff32df181..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/urlmap.rb
+++ /dev/null
@@ -1,55 +0,0 @@
-module Rack
- # Rack::URLMap takes a hash mapping urls or paths to apps, and
- # dispatches accordingly. Support for HTTP/1.1 host names exists if
- # the URLs start with http:// or https://.
- #
- # URLMap modifies the SCRIPT_NAME and PATH_INFO such that the part
- # relevant for dispatch is in the SCRIPT_NAME, and the rest in the
- # PATH_INFO. This should be taken care of when you need to
- # reconstruct the URL in order to create links.
- #
- # URLMap dispatches in such a way that the longest paths are tried
- # first, since they are most specific.
-
- class URLMap
- def initialize(map = {})
- remap(map)
- end
-
- def remap(map)
- @mapping = map.map { |location, app|
- if location =~ %r{\Ahttps?://(.*?)(/.*)}
- host, location = $1, $2
- else
- host = nil
- end
-
- unless location[0] == ?/
- raise ArgumentError, "paths need to start with /"
- end
- location = location.chomp('/')
-
- [host, location, app]
- }.sort_by { |(h, l, a)| [-l.size, h.to_s.size] } # Longest path first
- end
-
- def call(env)
- path = env["PATH_INFO"].to_s.squeeze("/")
- script_name = env['SCRIPT_NAME']
- hHost, sName, sPort = env.values_at('HTTP_HOST','SERVER_NAME','SERVER_PORT')
- @mapping.each { |host, location, app|
- next unless (hHost == host || sName == host \
- || (host.nil? && (hHost == sName || hHost == sName+':'+sPort)))
- next unless location == path[0, location.size]
- next unless path[location.size] == nil || path[location.size] == ?/
-
- return app.call(
- env.merge(
- 'SCRIPT_NAME' => (script_name + location),
- 'PATH_INFO' => path[location.size..-1]))
- }
- [404, {"Content-Type" => "text/plain"}, ["Not Found: #{path}"]]
- end
- end
-end
-
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/utils.rb b/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/utils.rb
deleted file mode 100644
index 0a61bce707..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack-1.0/rack/utils.rb
+++ /dev/null
@@ -1,392 +0,0 @@
-require 'set'
-require 'tempfile'
-
-module Rack
- # Rack::Utils contains a grab-bag of useful methods for writing web
- # applications adopted from all kinds of Ruby libraries.
-
- module Utils
- # Performs URI escaping so that you can construct proper
- # query strings faster. Use this rather than the cgi.rb
- # version since it's faster. (Stolen from Camping).
- def escape(s)
- s.to_s.gsub(/([^ a-zA-Z0-9_.-]+)/n) {
- '%'+$1.unpack('H2'*$1.size).join('%').upcase
- }.tr(' ', '+')
- end
- module_function :escape
-
- # Unescapes a URI escaped string. (Stolen from Camping).
- def unescape(s)
- s.tr('+', ' ').gsub(/((?:%[0-9a-fA-F]{2})+)/n){
- [$1.delete('%')].pack('H*')
- }
- end
- module_function :unescape
-
- # Stolen from Mongrel, with some small modifications:
- # Parses a query string by breaking it up at the '&'
- # and ';' characters. You can also use this to parse
- # cookies by changing the characters used in the second
- # parameter (which defaults to '&;').
- def parse_query(qs, d = '&;')
- params = {}
-
- (qs || '').split(/[#{d}] */n).each do |p|
- k, v = unescape(p).split('=', 2)
-
- if cur = params[k]
- if cur.class == Array
- params[k] << v
- else
- params[k] = [cur, v]
- end
- else
- params[k] = v
- end
- end
-
- return params
- end
- module_function :parse_query
-
- def parse_nested_query(qs, d = '&;')
- params = {}
-
- (qs || '').split(/[#{d}] */n).each do |p|
- k, v = unescape(p).split('=', 2)
- normalize_params(params, k, v)
- end
-
- return params
- end
- module_function :parse_nested_query
-
- def normalize_params(params, name, v = nil)
- name =~ %r([\[\]]*([^\[\]]+)\]*)
- k = $1 || ''
- after = $' || ''
-
- return if k.empty?
-
- if after == ""
- params[k] = v
- elsif after == "[]"
- params[k] ||= []
- raise TypeError unless params[k].is_a?(Array)
- params[k] << v
- elsif after =~ %r(^\[\]\[([^\[\]]+)\]$) || after =~ %r(^\[\](.+)$)
- child_key = $1
- params[k] ||= []
- raise TypeError unless params[k].is_a?(Array)
- if params[k].last.is_a?(Hash) && !params[k].last.key?(child_key)
- normalize_params(params[k].last, child_key, v)
- else
- params[k] << normalize_params({}, child_key, v)
- end
- else
- params[k] ||= {}
- params[k] = normalize_params(params[k], after, v)
- end
-
- return params
- end
- module_function :normalize_params
-
- def build_query(params)
- params.map { |k, v|
- if v.class == Array
- build_query(v.map { |x| [k, x] })
- else
- escape(k) + "=" + escape(v)
- end
- }.join("&")
- end
- module_function :build_query
-
- # Escape ampersands, brackets and quotes to their HTML/XML entities.
- def escape_html(string)
- string.to_s.gsub("&", "&").
- gsub("<", "<").
- gsub(">", ">").
- gsub("'", "'").
- gsub('"', """)
- end
- module_function :escape_html
-
- def select_best_encoding(available_encodings, accept_encoding)
- # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
-
- expanded_accept_encoding =
- accept_encoding.map { |m, q|
- if m == "*"
- (available_encodings - accept_encoding.map { |m2, _| m2 }).map { |m2| [m2, q] }
- else
- [[m, q]]
- end
- }.inject([]) { |mem, list|
- mem + list
- }
-
- encoding_candidates = expanded_accept_encoding.sort_by { |_, q| -q }.map { |m, _| m }
-
- unless encoding_candidates.include?("identity")
- encoding_candidates.push("identity")
- end
-
- expanded_accept_encoding.find_all { |m, q|
- q == 0.0
- }.each { |m, _|
- encoding_candidates.delete(m)
- }
-
- return (encoding_candidates & available_encodings)[0]
- end
- module_function :select_best_encoding
-
- # Return the bytesize of String; uses String#length under Ruby 1.8 and
- # String#bytesize under 1.9.
- if ''.respond_to?(:bytesize)
- def bytesize(string)
- string.bytesize
- end
- else
- def bytesize(string)
- string.size
- end
- end
- module_function :bytesize
-
- # Context allows the use of a compatible middleware at different points
- # in a request handling stack. A compatible middleware must define
- # #context which should take the arguments env and app. The first of which
- # would be the request environment. The second of which would be the rack
- # application that the request would be forwarded to.
- class Context
- attr_reader :for, :app
-
- def initialize(app_f, app_r)
- raise 'running context does not respond to #context' unless app_f.respond_to? :context
- @for, @app = app_f, app_r
- end
-
- def call(env)
- @for.context(env, @app)
- end
-
- def recontext(app)
- self.class.new(@for, app)
- end
-
- def context(env, app=@app)
- recontext(app).call(env)
- end
- end
-
- # A case-insensitive Hash that preserves the original case of a
- # header when set.
- class HeaderHash < Hash
- def initialize(hash={})
- @names = {}
- hash.each { |k, v| self[k] = v }
- end
-
- def to_hash
- inject({}) do |hash, (k,v)|
- if v.respond_to? :to_ary
- hash[k] = v.to_ary.join("\n")
- else
- hash[k] = v
- end
- hash
- end
- end
-
- def [](k)
- super @names[k.downcase]
- end
-
- def []=(k, v)
- delete k
- @names[k.downcase] = k
- super k, v
- end
-
- def delete(k)
- super @names.delete(k.downcase)
- end
-
- def include?(k)
- @names.has_key? k.downcase
- end
-
- alias_method :has_key?, :include?
- alias_method :member?, :include?
- alias_method :key?, :include?
-
- def merge!(other)
- other.each { |k, v| self[k] = v }
- self
- end
-
- def merge(other)
- hash = dup
- hash.merge! other
- end
- end
-
- # Every standard HTTP code mapped to the appropriate message.
- # Stolen from Mongrel.
- HTTP_STATUS_CODES = {
- 100 => 'Continue',
- 101 => 'Switching Protocols',
- 200 => 'OK',
- 201 => 'Created',
- 202 => 'Accepted',
- 203 => 'Non-Authoritative Information',
- 204 => 'No Content',
- 205 => 'Reset Content',
- 206 => 'Partial Content',
- 300 => 'Multiple Choices',
- 301 => 'Moved Permanently',
- 302 => 'Found',
- 303 => 'See Other',
- 304 => 'Not Modified',
- 305 => 'Use Proxy',
- 307 => 'Temporary Redirect',
- 400 => 'Bad Request',
- 401 => 'Unauthorized',
- 402 => 'Payment Required',
- 403 => 'Forbidden',
- 404 => 'Not Found',
- 405 => 'Method Not Allowed',
- 406 => 'Not Acceptable',
- 407 => 'Proxy Authentication Required',
- 408 => 'Request Timeout',
- 409 => 'Conflict',
- 410 => 'Gone',
- 411 => 'Length Required',
- 412 => 'Precondition Failed',
- 413 => 'Request Entity Too Large',
- 414 => 'Request-URI Too Large',
- 415 => 'Unsupported Media Type',
- 416 => 'Requested Range Not Satisfiable',
- 417 => 'Expectation Failed',
- 500 => 'Internal Server Error',
- 501 => 'Not Implemented',
- 502 => 'Bad Gateway',
- 503 => 'Service Unavailable',
- 504 => 'Gateway Timeout',
- 505 => 'HTTP Version Not Supported'
- }
-
- # Responses with HTTP status codes that should not have an entity body
- STATUS_WITH_NO_ENTITY_BODY = Set.new((100..199).to_a << 204 << 304)
-
- # A multipart form data parser, adapted from IOWA.
- #
- # Usually, Rack::Request#POST takes care of calling this.
-
- module Multipart
- EOL = "\r\n"
-
- def self.parse_multipart(env)
- unless env['CONTENT_TYPE'] =~
- %r|\Amultipart/form-data.*boundary=\"?([^\";,]+)\"?|n
- nil
- else
- boundary = "--#{$1}"
-
- params = {}
- buf = ""
- content_length = env['CONTENT_LENGTH'].to_i
- input = env['rack.input']
-
- boundary_size = boundary.size + EOL.size
- bufsize = 16384
-
- content_length -= boundary_size
-
- status = input.read(boundary_size)
- raise EOFError, "bad content body" unless status == boundary + EOL
-
- rx = /(?:#{EOL})?#{Regexp.quote boundary}(#{EOL}|--)/n
-
- loop {
- head = nil
- body = ''
- filename = content_type = name = nil
-
- until head && buf =~ rx
- if !head && i = buf.index("\r\n\r\n")
- head = buf.slice!(0, i+2) # First \r\n
- buf.slice!(0, 2) # Second \r\n
-
- filename = head[/Content-Disposition:.* filename="?([^\";]*)"?/ni, 1]
- content_type = head[/Content-Type: (.*)\r\n/ni, 1]
- name = head[/Content-Disposition:.* name="?([^\";]*)"?/ni, 1]
-
- if filename
- body = Tempfile.new("RackMultipart")
- body.binmode if body.respond_to?(:binmode)
- end
-
- next
- end
-
- # Save the read body part.
- if head && (boundary_size+4 < buf.size)
- body << buf.slice!(0, buf.size - (boundary_size+4))
- end
-
- c = input.read(bufsize < content_length ? bufsize : content_length)
- raise EOFError, "bad content body" if c.nil? || c.empty?
- buf << c
- content_length -= c.size
- end
-
- # Save the rest.
- if i = buf.index(rx)
- body << buf.slice!(0, i)
- buf.slice!(0, boundary_size+2)
-
- content_length = -1 if $1 == "--"
- end
-
- if filename == ""
- # filename is blank which means no file has been selected
- data = nil
- elsif filename
- body.rewind
-
- # Take the basename of the upload's original filename.
- # This handles the full Windows paths given by Internet Explorer
- # (and perhaps other broken user agents) without affecting
- # those which give the lone filename.
- filename =~ /^(?:.*[:\\\/])?(.*)/m
- filename = $1
-
- data = {:filename => filename, :type => content_type,
- :name => name, :tempfile => body, :head => head}
- else
- data = body
- end
-
- Utils.normalize_params(params, name, data) unless data.nil?
-
- break if buf.empty? || content_length == -1
- }
-
- begin
- input.rewind if input.respond_to?(:rewind)
- rescue Errno::ESPIPE
- # Handles exceptions raised by input streams that cannot be rewound
- # such as when using plain CGI under Apache
- end
-
- params
- end
- end
- end
- end
-end
diff --git a/actionpack/test/dispatch/request/multipart_params_parsing_test.rb b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
index 88b81dc493..6322cfc84a 100644
--- a/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
+++ b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
@@ -96,7 +96,7 @@ class MultipartParamsParsingTest < ActionController::IntegrationTest
# Ruby CGI doesn't handle multipart/mixed for us.
files = params['files']
- assert_kind_of String, files
+ assert_kind_of Tempfile, files
files.force_encoding('ASCII-8BIT') if files.respond_to?(:force_encoding)
assert_equal 19756, files.size
end
--
cgit v1.2.3
From 4f412a10b6125831af34d874927f891f586d0101 Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Sat, 25 Apr 2009 14:04:03 -0500
Subject: Remove RewindableInput middleware since all input MUST be rewindable
according to a recent change in the Rack 1.0 SPEC
---
.../lib/action_controller/dispatch/middlewares.rb | 1 -
actionpack/lib/action_dispatch.rb | 1 -
.../action_dispatch/middleware/rewindable_input.rb | 19 -------
.../request/multipart_params_parsing_test.rb | 61 ----------------------
.../request/url_encoded_params_parsing_test.rb | 38 --------------
5 files changed, 120 deletions(-)
delete mode 100644 actionpack/lib/action_dispatch/middleware/rewindable_input.rb
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/dispatch/middlewares.rb b/actionpack/lib/action_controller/dispatch/middlewares.rb
index b62b4f84a1..b5adbae746 100644
--- a/actionpack/lib/action_controller/dispatch/middlewares.rb
+++ b/actionpack/lib/action_controller/dispatch/middlewares.rb
@@ -7,7 +7,6 @@ use "ActionDispatch::Failsafe"
use lambda { ActionController::Base.session_store },
lambda { ActionController::Base.session_options }
-use "ActionDispatch::RewindableInput"
use "ActionDispatch::ParamsParser"
use "Rack::MethodOverride"
use "Rack::Head"
diff --git a/actionpack/lib/action_dispatch.rb b/actionpack/lib/action_dispatch.rb
index 0c915d9fd5..4f65dcadee 100644
--- a/actionpack/lib/action_dispatch.rb
+++ b/actionpack/lib/action_dispatch.rb
@@ -43,7 +43,6 @@ module ActionDispatch
autoload :Failsafe, 'action_dispatch/middleware/failsafe'
autoload :ParamsParser, 'action_dispatch/middleware/params_parser'
autoload :Reloader, 'action_dispatch/middleware/reloader'
- autoload :RewindableInput, 'action_dispatch/middleware/rewindable_input'
autoload :MiddlewareStack, 'action_dispatch/middleware/stack'
module Http
diff --git a/actionpack/lib/action_dispatch/middleware/rewindable_input.rb b/actionpack/lib/action_dispatch/middleware/rewindable_input.rb
deleted file mode 100644
index c818f28cce..0000000000
--- a/actionpack/lib/action_dispatch/middleware/rewindable_input.rb
+++ /dev/null
@@ -1,19 +0,0 @@
-module ActionDispatch
- class RewindableInput
- def initialize(app)
- @app = app
- end
-
- def call(env)
- begin
- env['rack.input'].rewind
- rescue NoMethodError, Errno::ESPIPE
- # Handles exceptions raised by input streams that cannot be rewound
- # such as when using plain CGI under Apache
- env['rack.input'] = StringIO.new(env['rack.input'].read)
- end
-
- @app.call(env)
- end
- end
-end
diff --git a/actionpack/test/dispatch/request/multipart_params_parsing_test.rb b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
index 6322cfc84a..cc81a87cb9 100644
--- a/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
+++ b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
@@ -133,46 +133,6 @@ class MultipartParamsParsingTest < ActionController::IntegrationTest
end
end
- # The lint wrapper is used in integration tests
- # instead of a normal StringIO class
- InputWrapper = Rack::Lint::InputWrapper
-
- test "parses unwindable stream" do
- InputWrapper.any_instance.stubs(:rewind).raises(Errno::ESPIPE)
- params = parse_multipart('large_text_file')
- assert_equal %w(file foo), params.keys.sort
- assert_equal 'bar', params['foo']
- end
-
- test "uploads and reads file with unwindable input" do
- InputWrapper.any_instance.stubs(:rewind).raises(Errno::ESPIPE)
-
- with_test_routing do
- post '/read', :uploaded_data => fixture_file_upload(FIXTURE_PATH + "/hello.txt", "text/plain")
- assert_equal "File: Hello", response.body
- end
- end
-
- test "passes through rack middleware and uploads file" do
- with_muck_middleware do
- with_test_routing do
- post '/read', :uploaded_data => fixture_file_upload(FIXTURE_PATH + "/hello.txt", "text/plain")
- assert_equal "File: Hello", response.body
- end
- end
- end
-
- test "passes through rack middleware and uploads file with unwindable input" do
- InputWrapper.any_instance.stubs(:rewind).raises(Errno::ESPIPE)
-
- with_muck_middleware do
- with_test_routing do
- post '/read', :uploaded_data => fixture_file_upload(FIXTURE_PATH + "/hello.txt", "text/plain")
- assert_equal "File: Hello", response.body
- end
- end
- end
-
private
def fixture(name)
File.open(File.join(FIXTURE_PATH, name), 'rb') do |file|
@@ -199,25 +159,4 @@ class MultipartParamsParsingTest < ActionController::IntegrationTest
yield
end
end
-
- class MuckMiddleware
- def initialize(app)
- @app = app
- end
-
- def call(env)
- env['rack.input'].read
- env['rack.input'].rewind
- @app.call(env)
- end
- end
-
- def with_muck_middleware
- original_middleware = ActionController::Dispatcher.middleware
- middleware = original_middleware.dup
- middleware.insert_after ActionDispatch::RewindableInput, MuckMiddleware
- ActionController::Dispatcher.middleware = middleware
- yield
- ActionController::Dispatcher.middleware = original_middleware
- end
end
diff --git a/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb b/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb
index 8de4a83d76..7167cdafac 100644
--- a/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb
+++ b/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb
@@ -126,45 +126,7 @@ class UrlEncodedParamsParsingTest < ActionController::IntegrationTest
assert_parses expected, query
end
- test "passes through rack middleware and parses params" do
- with_muck_middleware do
- assert_parses({ "a" => { "b" => "c" } }, "a[b]=c")
- end
- end
-
- # The lint wrapper is used in integration tests
- # instead of a normal StringIO class
- InputWrapper = Rack::Lint::InputWrapper
-
- test "passes through rack middleware and parses params with unwindable input" do
- InputWrapper.any_instance.stubs(:rewind).raises(Errno::ESPIPE)
- with_muck_middleware do
- assert_parses({ "a" => { "b" => "c" } }, "a[b]=c")
- end
- end
-
private
- class MuckMiddleware
- def initialize(app)
- @app = app
- end
-
- def call(env)
- env['rack.input'].read
- env['rack.input'].rewind
- @app.call(env)
- end
- end
-
- def with_muck_middleware
- original_middleware = ActionController::Dispatcher.middleware
- middleware = original_middleware.dup
- middleware.insert_after ActionDispatch::RewindableInput, MuckMiddleware
- ActionController::Dispatcher.middleware = middleware
- yield
- ActionController::Dispatcher.middleware = original_middleware
- end
-
def with_test_routing
with_routing do |set|
set.draw do |map|
--
cgit v1.2.3
From dbbe2e74ff5b6363da74fe63045b043c24041b1a Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Sun, 26 Apr 2009 10:26:53 -0500
Subject: Create a new file for response tests
---
actionpack/test/dispatch/rack_test.rb | 90 -------------------------------
actionpack/test/dispatch/response_test.rb | 83 ++++++++++++++++++++++++++++
2 files changed, 83 insertions(+), 90 deletions(-)
create mode 100644 actionpack/test/dispatch/response_test.rb
(limited to 'actionpack')
diff --git a/actionpack/test/dispatch/rack_test.rb b/actionpack/test/dispatch/rack_test.rb
index 9fad4b22ee..94eba2a24f 100644
--- a/actionpack/test/dispatch/rack_test.rb
+++ b/actionpack/test/dispatch/rack_test.rb
@@ -201,93 +201,3 @@ class RackRequestNeedsRewoundTest < BaseRackTest
assert_equal 0, request.body.pos
end
end
-
-class RackResponseTest < BaseRackTest
- def setup
- super
- @response = ActionDispatch::Response.new
- end
-
- test "simple output" do
- @response.body = "Hello, World!"
- @response.prepare!
-
- status, headers, body = @response.to_a
- assert_equal 200, status
- assert_equal({
- "Content-Type" => "text/html; charset=utf-8",
- "Cache-Control" => "private, max-age=0, must-revalidate",
- "ETag" => '"65a8e27d8879283831b664bd8b7f0ad4"',
- "Set-Cookie" => "",
- "Content-Length" => "13"
- }, headers)
-
- parts = []
- body.each { |part| parts << part }
- assert_equal ["Hello, World!"], parts
- end
-
- def test_utf8_output
- @response.body = [1090, 1077, 1089, 1090].pack("U*")
- @response.prepare!
-
- status, headers, body = @response.to_a
- assert_equal 200, status
- assert_equal({
- "Content-Type" => "text/html; charset=utf-8",
- "Cache-Control" => "private, max-age=0, must-revalidate",
- "ETag" => '"ebb5e89e8a94e9dd22abf5d915d112b2"',
- "Set-Cookie" => "",
- "Content-Length" => "8"
- }, headers)
- end
-
- def test_streaming_block
- @response.body = Proc.new do |response, output|
- 5.times { |n| output.write(n) }
- end
- @response.prepare!
-
- status, headers, body = @response.to_a
- assert_equal 200, status
- assert_equal({
- "Content-Type" => "text/html; charset=utf-8",
- "Cache-Control" => "no-cache",
- "Set-Cookie" => ""
- }, headers)
-
- parts = []
- body.each { |part| parts << part.to_s }
- assert_equal ["0", "1", "2", "3", "4"], parts
- end
-end
-
-class RackResponseHeadersTest < BaseRackTest
- def setup
- super
- @response = ActionDispatch::Response.new
- @response.status = "200 OK"
- end
-
- test "content type" do
- [204, 304].each do |c|
- @response.status = c.to_s
- assert !response_headers.has_key?("Content-Type"), "#{c} should not have Content-Type header"
- end
-
- [200, 302, 404, 500].each do |c|
- @response.status = c.to_s
- assert response_headers.has_key?("Content-Type"), "#{c} did not have Content-Type header"
- end
- end
-
- test "status" do
- assert !response_headers.has_key?('Status')
- end
-
- private
- def response_headers
- @response.prepare!
- @response.to_a[1]
- end
-end
diff --git a/actionpack/test/dispatch/response_test.rb b/actionpack/test/dispatch/response_test.rb
new file mode 100644
index 0000000000..fb593a6c31
--- /dev/null
+++ b/actionpack/test/dispatch/response_test.rb
@@ -0,0 +1,83 @@
+require 'abstract_unit'
+
+class ResponseTest < ActiveSupport::TestCase
+ def setup
+ @response = ActionDispatch::Response.new
+ end
+
+ test "simple output" do
+ @response.body = "Hello, World!"
+ @response.prepare!
+
+ status, headers, body = @response.to_a
+ assert_equal 200, status
+ assert_equal({
+ "Content-Type" => "text/html; charset=utf-8",
+ "Cache-Control" => "private, max-age=0, must-revalidate",
+ "ETag" => '"65a8e27d8879283831b664bd8b7f0ad4"',
+ "Set-Cookie" => "",
+ "Content-Length" => "13"
+ }, headers)
+
+ parts = []
+ body.each { |part| parts << part }
+ assert_equal ["Hello, World!"], parts
+ end
+
+ test "utf8 output" do
+ @response.body = [1090, 1077, 1089, 1090].pack("U*")
+ @response.prepare!
+
+ status, headers, body = @response.to_a
+ assert_equal 200, status
+ assert_equal({
+ "Content-Type" => "text/html; charset=utf-8",
+ "Cache-Control" => "private, max-age=0, must-revalidate",
+ "ETag" => '"ebb5e89e8a94e9dd22abf5d915d112b2"',
+ "Set-Cookie" => "",
+ "Content-Length" => "8"
+ }, headers)
+ end
+
+ test "streaming block" do
+ @response.body = Proc.new do |response, output|
+ 5.times { |n| output.write(n) }
+ end
+ @response.prepare!
+
+ status, headers, body = @response.to_a
+ assert_equal 200, status
+ assert_equal({
+ "Content-Type" => "text/html; charset=utf-8",
+ "Cache-Control" => "no-cache",
+ "Set-Cookie" => ""
+ }, headers)
+
+ parts = []
+ body.each { |part| parts << part.to_s }
+ assert_equal ["0", "1", "2", "3", "4"], parts
+ end
+
+ test "content type" do
+ [204, 304].each do |c|
+ @response.status = c.to_s
+ @response.prepare!
+ status, headers, body = @response.to_a
+ assert !headers.has_key?("Content-Type"), "#{c} should not have Content-Type header"
+ end
+
+ [200, 302, 404, 500].each do |c|
+ @response.status = c.to_s
+ @response.prepare!
+ status, headers, body = @response.to_a
+ assert headers.has_key?("Content-Type"), "#{c} did not have Content-Type header"
+ end
+ end
+
+ test "does not include Status header" do
+ @response.status = "200 OK"
+ @response.prepare!
+ status, headers, body = @response.to_a
+ assert !headers.has_key?('Status')
+ end
+end
--
cgit v1.2.3
From 5352a2417b9f6297d16a6baefd1994be4d1e4a12 Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Sun, 26 Apr 2009 11:12:33 -0500
Subject: Move useful response test helpers into request
---
.../lib/action_controller/testing/integration.rb | 7 ++-
.../lib/action_controller/testing/process.rb | 61 +-------------------
actionpack/lib/action_dispatch/http/response.rb | 65 +++++++++++++++++++++-
actionpack/test/dispatch/response_test.rb | 47 ++++++++++++++++
4 files changed, 116 insertions(+), 64 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/testing/integration.rb b/actionpack/lib/action_controller/testing/integration.rb
index 15d0603ac1..10260d5af2 100644
--- a/actionpack/lib/action_controller/testing/integration.rb
+++ b/actionpack/lib/action_controller/testing/integration.rb
@@ -304,8 +304,11 @@ module ActionController
@response = @controller.response
@controller.send(:set_test_assigns)
else
- @request = ::Rack::Request.new(env)
- @response = response
+ @request = Request.new(env)
+ @response = Response.new
+ @response.status = @status
+ @response.headers = @headers
+ @response.body = @body
end
# Decorate the response with the standard behavior of the
diff --git a/actionpack/lib/action_controller/testing/process.rb b/actionpack/lib/action_controller/testing/process.rb
index f5742af472..05b756fa4d 100644
--- a/actionpack/lib/action_controller/testing/process.rb
+++ b/actionpack/lib/action_controller/testing/process.rb
@@ -156,54 +156,7 @@ module ActionController #:nodoc:
# A refactoring of TestResponse to allow the same behavior to be applied
# to the "real" CgiResponse class in integration tests.
module TestResponseBehavior #:nodoc:
- # The response code of the request
- def response_code
- status.to_s[0,3].to_i rescue 0
- end
-
- # Returns a String to ensure compatibility with Net::HTTPResponse
- def code
- status.to_s.split(' ')[0]
- end
-
- def message
- status.to_s.split(' ',2)[1]
- end
-
- # Was the response successful?
- def success?
- (200..299).include?(response_code)
- end
-
- # Was the URL not found?
- def missing?
- response_code == 404
- end
-
- # Were we redirected?
- def redirect?
- (300..399).include?(response_code)
- end
-
- # Was there a server-side error?
- def error?
- (500..599).include?(response_code)
- end
-
- alias_method :server_error?, :error?
-
- # Was there a client client?
- def client_error?
- (400..499).include?(response_code)
- end
-
- # Returns the redirection location or nil
- def redirect_url
- headers['Location']
- end
-
- # Does the redirect location match this regexp pattern?
- def redirect_url_match?( pattern )
+ def redirect_url_match?(pattern)
return false if redirect_url.nil?
p = Regexp.new(pattern) if pattern.class == String
p = pattern if pattern.class == Regexp
@@ -252,18 +205,6 @@ module ActionController #:nodoc:
!template_objects[name].nil?
end
- # Returns the response cookies, converted to a Hash of (name => value) pairs
- #
- # assert_equal 'AuthorOfNewPage', r.cookies['author']
- def cookies
- cookies = {}
- Array(headers['Set-Cookie']).each do |cookie|
- key, value = cookie.split(";").first.split("=").map {|val| Rack::Utils.unescape(val)}
- cookies[key] = value
- end
- cookies
- end
-
# Returns binary content (downloadable file), converted to a String
def binary_content
raise "Response body is not a Proc: #{body_parts.inspect}" unless body_parts.kind_of?(Proc)
diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb
index ecf40b8103..7bc9c62e2c 100644
--- a/actionpack/lib/action_dispatch/http/response.rb
+++ b/actionpack/lib/action_dispatch/http/response.rb
@@ -37,6 +37,9 @@ module ActionDispatch # :nodoc:
attr_accessor :session, :assigns, :template, :layout
attr_accessor :redirected_to, :redirected_to_method_params
+ attr_writer :header
+ alias_method :headers=, :header=
+
delegate :default_charset, :to => 'ActionController::Base'
def initialize
@@ -45,6 +48,47 @@ module ActionDispatch # :nodoc:
@session, @assigns = [], []
end
+ # The response code of the request
+ def response_code
+ status.to_s[0,3].to_i rescue 0
+ end
+
+ # Returns a String to ensure compatibility with Net::HTTPResponse
+ def code
+ status.to_s.split(' ')[0]
+ end
+
+ def message
+ status.to_s.split(' ',2)[1] || StatusCodes::STATUS_CODES[response_code]
+ end
+
+ # Was the response successful?
+ def success?
+ (200..299).include?(response_code)
+ end
+
+ # Was the URL not found?
+ def missing?
+ response_code == 404
+ end
+
+ # Were we redirected?
+ def redirect?
+ (300..399).include?(response_code)
+ end
+
+ # Was there a server-side error?
+ def error?
+ (500..599).include?(response_code)
+ end
+
+ alias_method :server_error?, :error?
+
+ # Was there a client client?
+ def client_error?
+ (400..499).include?(response_code)
+ end
+
def body
str = ''
each { |part| str << part.to_s }
@@ -64,9 +108,14 @@ module ActionDispatch # :nodoc:
@body
end
- def location; headers['Location'] end
- def location=(url) headers['Location'] = url end
+ def location
+ headers['Location']
+ end
+ alias_method :redirect_url, :location
+ def location=(url)
+ headers['Location'] = url
+ end
# Sets the HTTP response's content MIME type. For example, in the controller
# you could write this:
@@ -192,6 +241,18 @@ module ActionDispatch # :nodoc:
super(key, value)
end
+ # Returns the response cookies, converted to a Hash of (name => value) pairs
+ #
+ # assert_equal 'AuthorOfNewPage', r.cookies['author']
+ def cookies
+ cookies = {}
+ Array(headers['Set-Cookie']).each do |cookie|
+ key, value = cookie.split(";").first.split("=").map { |v| Rack::Utils.unescape(v) }
+ cookies[key] = value
+ end
+ cookies
+ end
+
private
def handle_conditional_get!
if etag? || last_modified?
diff --git a/actionpack/test/dispatch/response_test.rb b/actionpack/test/dispatch/response_test.rb
index fb593a6c31..2ddc6cb2b5 100644
--- a/actionpack/test/dispatch/response_test.rb
+++ b/actionpack/test/dispatch/response_test.rb
@@ -80,4 +80,51 @@ class ResponseTest < ActiveSupport::TestCase
status, headers, body = @response.to_a
assert !headers.has_key?('Status')
end
+
+ test "response code" do
+ @response.status = "200 OK"
+ assert_equal 200, @response.response_code
+
+ @response.status = "200"
+ assert_equal 200, @response.response_code
+
+ @response.status = 200
+ assert_equal 200, @response.response_code
+ end
+
+ test "code" do
+ @response.status = "200 OK"
+ assert_equal "200", @response.code
+
+ @response.status = "200"
+ assert_equal "200", @response.code
+
+ @response.status = 200
+ assert_equal "200", @response.code
+ end
+
+ test "message" do
+ @response.status = "200 OK"
+ assert_equal "OK", @response.message
+
+ @response.status = "200"
+ assert_equal "OK", @response.message
+
+ @response.status = 200
+ assert_equal "OK", @response.message
+ end
+
+ test "cookies" do
+ @response.set_cookie("user_name", :value => "david", :path => "/")
+ @response.prepare!
+ status, headers, body = @response.to_a
+ assert_equal "user_name=david; path=/", headers["Set-Cookie"]
+ assert_equal({"user_name" => "david"}, @response.cookies)
+
+ @response.set_cookie("login", :value => "foo&bar", :path => "/", :expires => Time.utc(2005, 10, 10,5))
+ @response.prepare!
+ status, headers, body = @response.to_a
+ assert_equal "user_name=david; path=/\nlogin=foo%26bar; path=/; expires=Mon, 10-Oct-2005 05:00:00 GMT", headers["Set-Cookie"]
+ assert_equal({"login" => "foo&bar", "user_name" => "david"}, @response.cookies)
+ end
end
--
cgit v1.2.3
From 5ea8d401569323a10592d68d29b293c1ae131a8b Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Sun, 26 Apr 2009 11:16:14 -0500
Subject: Deprecate response.redirect_url_match?, use assert_match instead.
---
actionpack/lib/action_controller/testing/process.rb | 1 +
actionpack/test/controller/action_pack_assertions_test.rb | 10 ++++++----
2 files changed, 7 insertions(+), 4 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/testing/process.rb b/actionpack/lib/action_controller/testing/process.rb
index 05b756fa4d..2ad0579a30 100644
--- a/actionpack/lib/action_controller/testing/process.rb
+++ b/actionpack/lib/action_controller/testing/process.rb
@@ -157,6 +157,7 @@ module ActionController #:nodoc:
# to the "real" CgiResponse class in integration tests.
module TestResponseBehavior #:nodoc:
def redirect_url_match?(pattern)
+ ::ActiveSupport::Deprecation.warn("response.redirect_url_match? is deprecated. Use assert_match(/foo/, response.redirect_url) instead", caller)
return false if redirect_url.nil?
p = Regexp.new(pattern) if pattern.class == String
p = pattern if pattern.class == Regexp
diff --git a/actionpack/test/controller/action_pack_assertions_test.rb b/actionpack/test/controller/action_pack_assertions_test.rb
index 96f7a42c9b..f091f9b87c 100644
--- a/actionpack/test/controller/action_pack_assertions_test.rb
+++ b/actionpack/test/controller/action_pack_assertions_test.rb
@@ -378,10 +378,12 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
def test_redirect_url_match
process :redirect_external
assert @response.redirect?
- assert @response.redirect_url_match?("rubyonrails")
- assert @response.redirect_url_match?(/rubyonrails/)
- assert !@response.redirect_url_match?("phpoffrails")
- assert !@response.redirect_url_match?(/perloffrails/)
+ assert_deprecated do
+ assert @response.redirect_url_match?("rubyonrails")
+ assert @response.redirect_url_match?(/rubyonrails/)
+ assert !@response.redirect_url_match?("phpoffrails")
+ assert !@response.redirect_url_match?(/perloffrails/)
+ end
end
# check for a redirection
--
cgit v1.2.3
From 82bc768dad761df466e38ee9f1501aef766878c3 Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Sun, 26 Apr 2009 11:19:42 -0500
Subject: Fix typo in stale session check [#2404 state:resolved]
---
actionpack/lib/action_dispatch/middleware/session/abstract_store.rb | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
index 6c039cf62d..211d373208 100644
--- a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
+++ b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
@@ -74,7 +74,7 @@ module ActionDispatch
# Note that the regexp does not allow $1 to end with a ':'
$1.constantize
rescue LoadError, NameError => const_error
- raise ActionController::SessionRestoreError, "Session contains objects whose class definition isn\\'t available.\nRemember to require the classes for all objects kept in the session.\n(Original exception: \#{const_error.message} [\#{const_error.class}])\n"
+ raise ActionController::SessionRestoreError, "Session contains objects whose class definition isn't available.\nRemember to require the classes for all objects kept in the session.\n(Original exception: #{const_error.message} [#{const_error.class}])\n"
end
retry
--
cgit v1.2.3
From 3cb97aeea8837b9d2b7ed3f9806f5727ceef0e3d Mon Sep 17 00:00:00 2001
From: "Hongli Lai (Phusion)"
Date: Sun, 26 Apr 2009 11:23:10 -0500
Subject: Fix environment variable testing code in failsafe.rb.
Signed-off-by: Joshua Peek
---
actionpack/lib/action_dispatch/middleware/failsafe.rb | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_dispatch/middleware/failsafe.rb b/actionpack/lib/action_dispatch/middleware/failsafe.rb
index b5a3abcc92..5e0c479fdd 100644
--- a/actionpack/lib/action_dispatch/middleware/failsafe.rb
+++ b/actionpack/lib/action_dispatch/middleware/failsafe.rb
@@ -11,7 +11,7 @@ module ActionDispatch
@app.call(env)
rescue Exception => exception
# Reraise exception in test environment
- if defined?(Rails) && Rails.test?
+ if defined?(Rails) && Rails.env.test?
raise exception
else
failsafe_response(exception)
--
cgit v1.2.3
From 6940c0de12eedcff6529ba0dfef533513cbcd389 Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Sun, 26 Apr 2009 11:37:11 -0500
Subject: Unify functional and integration tests cookie helpers
---
.../lib/action_controller/testing/integration.rb | 33 ++++++++--------------
actionpack/test/controller/integration_test.rb | 2 +-
2 files changed, 13 insertions(+), 22 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/testing/integration.rb b/actionpack/lib/action_controller/testing/integration.rb
index 10260d5af2..be5f216e2b 100644
--- a/actionpack/lib/action_controller/testing/integration.rb
+++ b/actionpack/lib/action_controller/testing/integration.rb
@@ -285,37 +285,28 @@ module ActionController
app = Rack::Lint.new(@app)
status, headers, body = app.call(env)
response = ::Rack::MockResponse.new(status, headers, body)
+
@request_count += 1
+ @request = Request.new(env)
- @html_document = nil
+ @response = Response.new
+ @response.status = @status = response.status
+ @response.headers = @headers = response.headers
+ @response.body = @body = response.body
- @status = response.status
@status_message = ActionDispatch::StatusCodes::STATUS_CODES[@status]
- @headers = response.headers
- @body = response.body
-
- (@headers['Set-Cookie'] || "").split("\n").each do |cookie|
- name, value = cookie.match(/^([^=]*)=([^;]*);/)[1,2]
- @cookies[name] = value
- end
-
- if @controller = ActionController::Base.last_instantiation
- @request = @controller.request
- @response = @controller.response
- @controller.send(:set_test_assigns)
- else
- @request = Request.new(env)
- @response = Response.new
- @response.status = @status
- @response.headers = @headers
- @response.body = @body
- end
+ @cookies.merge!(@response.cookies)
+ @html_document = nil
# Decorate the response with the standard behavior of the
# TestResponse so that things like assert_response can be
# used in integration tests.
@response.extend(TestResponseBehavior)
+ if @controller = ActionController::Base.last_instantiation
+ @controller.send(:set_test_assigns)
+ end
+
return @status
end
diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb
index 9eeaa7b4e1..70fa41aded 100644
--- a/actionpack/test/controller/integration_test.rb
+++ b/actionpack/test/controller/integration_test.rb
@@ -297,7 +297,7 @@ class IntegrationProcessTest < ActionController::IntegrationTest
assert_response 410
assert_response :gone
assert_equal "cookie_1=; path=/\ncookie_3=chocolate; path=/", headers["Set-Cookie"]
- assert_equal({"cookie_1"=>"", "cookie_2"=>"oatmeal", "cookie_3"=>"chocolate"}, cookies)
+ assert_equal({"cookie_1"=>nil, "cookie_2"=>"oatmeal", "cookie_3"=>"chocolate"}, cookies)
assert_equal "Gone", response.body
end
end
--
cgit v1.2.3
From c8919f4c7ca13ad78987ea0c8497abe85249975b Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Sun, 26 Apr 2009 11:52:45 -0500
Subject: Require an ActionDispatch::Request to use response assertions
---
.../testing/assertions/response.rb | 24 ++++++++++++++++------
1 file changed, 18 insertions(+), 6 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/testing/assertions/response.rb b/actionpack/lib/action_controller/testing/assertions/response.rb
index ca0a9bbf52..c57cbecc44 100644
--- a/actionpack/lib/action_controller/testing/assertions/response.rb
+++ b/actionpack/lib/action_controller/testing/assertions/response.rb
@@ -22,6 +22,8 @@ module ActionController
# assert_response 401
#
def assert_response(type, message = nil)
+ validate_response!
+
clean_backtrace do
if [ :success, :missing, :redirect, :error ].include?(type) && @response.send("#{type}?")
assert_block("") { true } # to count the assertion
@@ -30,8 +32,8 @@ module ActionController
elsif type.is_a?(Symbol) && @response.response_code == ActionDispatch::StatusCodes::SYMBOL_TO_STATUS_CODE[type]
assert_block("") { true } # to count the assertion
else
- if @response.error?
- exception = @response.template.instance_variable_get(:@exception)
+ if @controller && @response.error?
+ exception = @controller.response.template.instance_variable_get(:@exception)
exception_message = exception && exception.message
assert_block(build_message(message, "Expected response to be a >, but was >\n>", type, @response.response_code, exception_message.to_s)) { false }
else
@@ -57,6 +59,8 @@ module ActionController
# assert_redirected_to @customer
#
def assert_redirected_to(options = {}, message=nil)
+ validate_response!
+
clean_backtrace do
assert_response(:redirect, message)
return true if options == @response.redirected_to
@@ -89,23 +93,25 @@ module ActionController
# assert_template :partial => false
#
def assert_template(options = {}, message = nil)
+ validate_response!
+
clean_backtrace do
case options
when NilClass, String
- rendered = @response.rendered[:template].to_s
+ rendered = @controller.response.rendered[:template].to_s
msg = build_message(message,
"expecting > but rendering with >",
options, rendered)
assert_block(msg) do
if options.nil?
- @response.rendered[:template].blank?
+ @controller.response.rendered[:template].blank?
else
rendered.to_s.match(options)
end
end
when Hash
if expected_partial = options[:partial]
- partials = @response.rendered[:partials]
+ partials = @controller.response.rendered[:partials]
if expected_count = options[:count]
found = partials.detect { |p, _| p.to_s.match(expected_partial) }
actual_count = found.nil? ? 0 : found.second
@@ -120,7 +126,7 @@ module ActionController
assert(partials.keys.any? { |p| p.to_s.match(expected_partial) }, msg)
end
else
- assert @response.rendered[:partials].empty?,
+ assert @controller.response.rendered[:partials].empty?,
"Expected no partials to be rendered"
end
end
@@ -145,6 +151,12 @@ module ActionController
@request.protocol + @request.host_with_port + after_routing
end
end
+
+ def validate_response!
+ unless @request.is_a?(ActionDispatch::Request)
+ raise ArgumentError, "@request must be an ActionDispatch::Request"
+ end
+ end
end
end
end
--
cgit v1.2.3
From 04949096797a390105c7ab9fb9b99938d5921dd4 Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Sun, 26 Apr 2009 14:33:57 -0500
Subject: Inherit TestSession from Session::AbstractStore and add indifferent
access to Session::AbstractStore.
---
actionpack/lib/action_controller/base/base.rb | 10 +--
.../lib/action_controller/testing/process.rb | 78 +++-------------------
actionpack/lib/action_dispatch/http/request.rb | 14 +---
actionpack/lib/action_dispatch/http/response.rb | 3 +-
.../middleware/session/abstract_store.rb | 28 +++++++-
.../middleware/session/cookie_store.rb | 7 +-
.../controller/http_digest_authentication_test.rb | 2 -
.../test/controller/request/test_request_test.rb | 23 ++++---
.../test/dispatch/session/cookie_store_test.rb | 3 +-
.../test/dispatch/session/test_session_test.rb | 24 +++----
10 files changed, 67 insertions(+), 125 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/base/base.rb b/actionpack/lib/action_controller/base/base.rb
index 3000b3d12f..afb9fb71cb 100644
--- a/actionpack/lib/action_controller/base/base.rb
+++ b/actionpack/lib/action_controller/base/base.rb
@@ -811,14 +811,8 @@ module ActionController #:nodoc:
end
def assign_shortcuts(request, response)
- @_request, @_params = request, request.parameters
-
- @_response = response
- @_response.session = request.session
-
- @_session = @_response.session
-
- @_headers = @_response.headers
+ @_request, @_response, @_params = request, response, request.parameters
+ @_session, @_headers = @_request.session, @_response.headers
end
def initialize_current_url
diff --git a/actionpack/lib/action_controller/testing/process.rb b/actionpack/lib/action_controller/testing/process.rb
index 2ad0579a30..16275371ad 100644
--- a/actionpack/lib/action_controller/testing/process.rb
+++ b/actionpack/lib/action_controller/testing/process.rb
@@ -1,8 +1,9 @@
require 'rack/session/abstract/id'
+
module ActionController #:nodoc:
class TestRequest < ActionDispatch::Request #:nodoc:
- attr_accessor :cookies, :session_options
- attr_accessor :query_parameters, :path, :session
+ attr_accessor :cookies
+ attr_accessor :query_parameters, :path
attr_accessor :host
def self.new(env = {})
@@ -13,18 +14,13 @@ module ActionController #:nodoc:
super(Rack::MockRequest.env_for("/").merge(env))
@query_parameters = {}
- @session = TestSession.new
- default_rack_options = Rack::Session::Abstract::ID::DEFAULT_OPTIONS
- @session_options ||= {:id => generate_sid(default_rack_options[:sidbits])}.merge(default_rack_options)
+ @env['rack.session'] = TestSession.new
+ @env['rack.session.options'] = TestSession::DEFAULT_OPTIONS.merge(:id => ActiveSupport::SecureRandom.hex(16))
initialize_default_values
initialize_containers
end
- def reset_session
- @session.reset
- end
-
# Wraps raw_post in a StringIO.
def body_stream #:nodoc:
StringIO.new(raw_post)
@@ -124,10 +120,6 @@ module ActionController #:nodoc:
end
private
- def generate_sid(sidbits)
- "%0#{sidbits / 4}x" % rand(2**sidbits - 1)
- end
-
def initialize_containers
@cookies = {}
end
@@ -235,62 +227,12 @@ module ActionController #:nodoc:
end
end
- class TestSession < Hash #:nodoc:
- attr_accessor :session_id
-
- def initialize(attributes = nil)
- reset_session_id
- replace_attributes(attributes)
- end
-
- def reset
- reset_session_id
- replace_attributes({ })
- end
-
- def data
- to_hash
- end
-
- def [](key)
- super(key.to_s)
- end
-
- def []=(key, value)
- super(key.to_s, value)
- end
-
- def update(hash = nil)
- if hash.nil?
- ActiveSupport::Deprecation.warn('use replace instead', caller)
- replace({})
- else
- super(hash)
- end
- end
-
- def delete(key = nil)
- if key.nil?
- ActiveSupport::Deprecation.warn('use clear instead', caller)
- clear
- else
- super(key.to_s)
- end
- end
-
- def close
- ActiveSupport::Deprecation.warn('sessions should no longer be closed', caller)
- end
-
- private
-
- def reset_session_id
- @session_id = ''
- end
+ class TestSession < ActionDispatch::Session::AbstractStore::SessionHash #:nodoc:
+ DEFAULT_OPTIONS = ActionDispatch::Session::AbstractStore::DEFAULT_OPTIONS
- def replace_attributes(attributes = nil)
- attributes ||= {}
- replace(attributes.stringify_keys)
+ def initialize(session = {})
+ replace(session.stringify_keys)
+ @loaded = true
end
end
diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb
index ab654b9a50..2602b344ca 100755
--- a/actionpack/lib/action_dispatch/http/request.rb
+++ b/actionpack/lib/action_dispatch/http/request.rb
@@ -451,23 +451,15 @@ EOM
@env['rack.input']
end
- def session
- @env['rack.session'] ||= {}
+ def reset_session
+ self.session_options.delete(:id)
+ self.session = {}
end
def session=(session) #:nodoc:
@env['rack.session'] = session
end
- def reset_session
- @env['rack.session.options'].delete(:id)
- @env['rack.session'] = {}
- end
-
- def session_options
- @env['rack.session.options'] ||= {}
- end
-
def session_options=(options)
@env['rack.session.options'] = options
end
diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb
index 7bc9c62e2c..77c2dd0d7a 100644
--- a/actionpack/lib/action_dispatch/http/response.rb
+++ b/actionpack/lib/action_dispatch/http/response.rb
@@ -34,12 +34,13 @@ module ActionDispatch # :nodoc:
DEFAULT_HEADERS = { "Cache-Control" => "no-cache" }
attr_accessor :request
- attr_accessor :session, :assigns, :template, :layout
+ attr_accessor :assigns, :template, :layout
attr_accessor :redirected_to, :redirected_to_method_params
attr_writer :header
alias_method :headers=, :header=
+ delegate :session, :to => :request
delegate :default_charset, :to => 'ActionController::Base'
def initialize
diff --git a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
index 211d373208..03761b10bd 100644
--- a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
+++ b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
@@ -26,12 +26,12 @@ module ActionDispatch
def [](key)
load! unless @loaded
- super
+ super(key.to_s)
end
def []=(key, value)
load! unless @loaded
- super
+ super(key.to_s, value)
end
def to_hash
@@ -40,6 +40,24 @@ module ActionDispatch
h
end
+ def update(hash = nil)
+ if hash.nil?
+ ActiveSupport::Deprecation.warn('use replace instead', caller)
+ replace({})
+ else
+ super(hash.stringify_keys)
+ end
+ end
+
+ def delete(key = nil)
+ if key.nil?
+ ActiveSupport::Deprecation.warn('use clear instead', caller)
+ clear
+ else
+ super(key.to_s)
+ end
+ end
+
def data
ActiveSupport::Deprecation.warn(
"ActionController::Session::AbstractStore::SessionHash#data " +
@@ -47,6 +65,10 @@ module ActionDispatch
to_hash
end
+ def close
+ ActiveSupport::Deprecation.warn('sessions should no longer be closed', caller)
+ end
+
def inspect
load! unless @loaded
super
@@ -61,7 +83,7 @@ module ActionDispatch
stale_session_check! do
id, session = @by.send(:load_session, @env)
(@env[ENV_SESSION_OPTIONS_KEY] ||= {})[:id] = id
- replace(session)
+ replace(session.stringify_keys)
@loaded = true
end
end
diff --git a/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb
index 433c4cc070..547a2d2062 100644
--- a/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb
+++ b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb
@@ -143,7 +143,8 @@ module ActionDispatch
request = Rack::Request.new(env)
session_data = request.cookies[@key]
data = unmarshal(session_data) || persistent_session_id!({})
- [data[:session_id], data]
+ data.stringify_keys!
+ [data["session_id"], data]
end
# Marshal a session hash into safe cookie data. Include an integrity hash.
@@ -206,12 +207,12 @@ module ActionDispatch
end
def inject_persistent_session_id(data)
- requires_session_id?(data) ? { :session_id => generate_sid } : {}
+ requires_session_id?(data) ? { "session_id" => generate_sid } : {}
end
def requires_session_id?(data)
if data
- data.respond_to?(:key?) && !data.key?(:session_id)
+ data.respond_to?(:key?) && !data.key?("session_id")
else
true
end
diff --git a/actionpack/test/controller/http_digest_authentication_test.rb b/actionpack/test/controller/http_digest_authentication_test.rb
index 00789eea38..7bebc8cd2a 100644
--- a/actionpack/test/controller/http_digest_authentication_test.rb
+++ b/actionpack/test/controller/http_digest_authentication_test.rb
@@ -111,8 +111,6 @@ class HttpDigestAuthenticationTest < ActionController::TestCase
test "authentication request with valid credential and nil session" do
@request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please')
- # session_id = "" in functional test, but is +nil+ in real life
- @request.session.session_id = nil
get :display
assert_response :success
diff --git a/actionpack/test/controller/request/test_request_test.rb b/actionpack/test/controller/request/test_request_test.rb
index 81551b4ba7..0a39feb7fe 100644
--- a/actionpack/test/controller/request/test_request_test.rb
+++ b/actionpack/test/controller/request/test_request_test.rb
@@ -10,26 +10,27 @@ class ActionController::TestRequestTest < ActiveSupport::TestCase
def test_test_request_has_session_options_initialized
assert @request.session_options
end
-
- Rack::Session::Abstract::ID::DEFAULT_OPTIONS.each_key do |option|
- test "test_rack_default_session_options_#{option}_exists_in_session_options_and_is_default" do
- assert_equal(Rack::Session::Abstract::ID::DEFAULT_OPTIONS[option],
- @request.session_options[option],
+
+ ActionDispatch::Session::AbstractStore::DEFAULT_OPTIONS.each_key do |option|
+ test "rack default session options #{option} exists in session options and is default" do
+ assert_equal(ActionDispatch::Session::AbstractStore::DEFAULT_OPTIONS[option],
+ @request.session_options[option],
"Missing rack session default option #{option} in request.session_options")
end
- test "test_rack_default_session_options_#{option}_exists_in_session_options" do
- assert(@request.session_options.has_key?(option),
+
+ test "rack default session options #{option} exists in session options" do
+ assert(@request.session_options.has_key?(option),
"Missing rack session option #{option} in request.session_options")
end
end
-
+
def test_session_id_exists_by_default
assert_not_nil(@request.session_options[:id])
end
-
+
def test_session_id_different_on_each_call
- prev_id =
+ prev_id =
assert_not_equal(@request.session_options[:id], ActionController::TestRequest.new.session_options[:id])
end
-
+
end
\ No newline at end of file
diff --git a/actionpack/test/dispatch/session/cookie_store_test.rb b/actionpack/test/dispatch/session/cookie_store_test.rb
index b9bf8cf411..3090a70244 100644
--- a/actionpack/test/dispatch/session/cookie_store_test.rb
+++ b/actionpack/test/dispatch/session/cookie_store_test.rb
@@ -10,8 +10,7 @@ class CookieStoreTest < ActionController::IntegrationTest
:key => SessionKey, :secret => SessionSecret)
Verifier = ActiveSupport::MessageVerifier.new(SessionSecret, 'SHA1')
-
- SignedBar = "BAh7BjoIZm9vIghiYXI%3D--fef868465920f415f2c0652d6910d3af288a0367"
+ SignedBar = Verifier.generate(:foo => "bar", :session_id => ActiveSupport::SecureRandom.hex(16))
class TestController < ActionController::Base
def no_session_access
diff --git a/actionpack/test/dispatch/session/test_session_test.rb b/actionpack/test/dispatch/session/test_session_test.rb
index de6539e1cc..0ff93f1c5d 100644
--- a/actionpack/test/dispatch/session/test_session_test.rb
+++ b/actionpack/test/dispatch/session/test_session_test.rb
@@ -2,37 +2,30 @@ require 'abstract_unit'
require 'stringio'
class ActionController::TestSessionTest < ActiveSupport::TestCase
-
def test_calling_delete_without_parameters_raises_deprecation_warning_and_calls_to_clear_test_session
assert_deprecated(/use clear instead/){ ActionController::TestSession.new.delete }
end
-
+
def test_calling_update_without_parameters_raises_deprecation_warning_and_calls_to_clear_test_session
assert_deprecated(/use replace instead/){ ActionController::TestSession.new.update }
end
-
+
def test_calling_close_raises_deprecation_warning
assert_deprecated(/sessions should no longer be closed/){ ActionController::TestSession.new.close }
end
-
- def test_defaults
- session = ActionController::TestSession.new
- assert_equal({}, session.data)
- assert_equal('', session.session_id)
- end
-
+
def test_ctor_allows_setting
session = ActionController::TestSession.new({:one => 'one', :two => 'two'})
assert_equal('one', session[:one])
assert_equal('two', session[:two])
end
-
+
def test_setting_session_item_sets_item
session = ActionController::TestSession.new
session[:key] = 'value'
assert_equal('value', session[:key])
end
-
+
def test_calling_delete_removes_item
session = ActionController::TestSession.new
session[:key] = 'value'
@@ -40,13 +33,13 @@ class ActionController::TestSessionTest < ActiveSupport::TestCase
session.delete(:key)
assert_nil(session[:key])
end
-
+
def test_calling_update_with_params_passes_to_attributes
session = ActionController::TestSession.new()
session.update('key' => 'value')
assert_equal('value', session[:key])
end
-
+
def test_clear_emptys_session
params = {:one => 'one', :two => 'two'}
session = ActionController::TestSession.new({:one => 'one', :two => 'two'})
@@ -54,5 +47,4 @@ class ActionController::TestSessionTest < ActiveSupport::TestCase
assert_nil(session[:one])
assert_nil(session[:two])
end
-
-end
\ No newline at end of file
+end
--
cgit v1.2.3
From be7e21a85c487b6f3bfc2e393387ada5cc52290d Mon Sep 17 00:00:00 2001
From: Jeremy Kemper
Date: Sun, 26 Apr 2009 15:05:50 -0700
Subject: Qualify toplevel constant references since we're in a BasicObject
---
actionpack/lib/action_view/helpers/prototype_helper.rb | 14 +++++++-------
1 file changed, 7 insertions(+), 7 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_view/helpers/prototype_helper.rb b/actionpack/lib/action_view/helpers/prototype_helper.rb
index fb8122af35..868c8226c4 100644
--- a/actionpack/lib/action_view/helpers/prototype_helper.rb
+++ b/actionpack/lib/action_view/helpers/prototype_helper.rb
@@ -686,7 +686,7 @@ module ActionView
# Returns an object whose to_json evaluates to +code+. Use this to pass a literal JavaScript
# expression as an argument to another JavaScriptGenerator method.
def literal(code)
- ActiveSupport::JSON::Variable.new(code.to_s)
+ ::ActiveSupport::JSON::Variable.new(code.to_s)
end
# Returns a collection reference by finding it through a CSS +pattern+ in the DOM. This collection can then be
@@ -973,7 +973,7 @@ module ActionView
def loop_on_multiple_args(method, ids)
record(ids.size>1 ?
"#{javascript_object_for(ids)}.each(#{method})" :
- "#{method}(#{ActiveSupport::JSON.encode(ids.first)})")
+ "#{method}(#{::ActiveSupport::JSON.encode(ids.first)})")
end
def page
@@ -997,7 +997,7 @@ module ActionView
end
def javascript_object_for(object)
- ActiveSupport::JSON.encode(object)
+ ::ActiveSupport::JSON.encode(object)
end
def arguments_for_call(arguments, block = nil)
@@ -1139,7 +1139,7 @@ module ActionView
class JavaScriptElementProxy < JavaScriptProxy #:nodoc:
def initialize(generator, id)
@id = id
- super(generator, "$(#{ActiveSupport::JSON.encode(id)})")
+ super(generator, "$(#{::ActiveSupport::JSON.encode(id)})")
end
# Allows access of element attributes through +attribute+. Examples:
@@ -1213,7 +1213,7 @@ module ActionView
enumerate :eachSlice, :variable => variable, :method_args => [number], :yield_args => %w(value index), :return => true, &block
else
add_variable_assignment!(variable)
- append_enumerable_function!("eachSlice(#{ActiveSupport::JSON.encode(number)});")
+ append_enumerable_function!("eachSlice(#{::ActiveSupport::JSON.encode(number)});")
end
end
@@ -1234,7 +1234,7 @@ module ActionView
def pluck(variable, property)
add_variable_assignment!(variable)
- append_enumerable_function!("pluck(#{ActiveSupport::JSON.encode(property)});")
+ append_enumerable_function!("pluck(#{::ActiveSupport::JSON.encode(property)});")
end
def zip(variable, *arguments, &block)
@@ -1298,7 +1298,7 @@ module ActionView
class JavaScriptElementCollectionProxy < JavaScriptCollectionProxy #:nodoc:\
def initialize(generator, pattern)
- super(generator, "$$(#{ActiveSupport::JSON.encode(pattern)})")
+ super(generator, "$$(#{::ActiveSupport::JSON.encode(pattern)})")
end
end
end
--
cgit v1.2.3
From 8d64085138b1a2ff36b94267d0236868b287610e Mon Sep 17 00:00:00 2001
From: Jeremy Kemper
Date: Sun, 26 Apr 2009 15:18:33 -0700
Subject: Only Object to_json alias is needed. Prefer nil options.
---
actionpack/lib/action_view/helpers/prototype_helper.rb | 2 --
1 file changed, 2 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_view/helpers/prototype_helper.rb b/actionpack/lib/action_view/helpers/prototype_helper.rb
index 868c8226c4..9cafd17004 100644
--- a/actionpack/lib/action_view/helpers/prototype_helper.rb
+++ b/actionpack/lib/action_view/helpers/prototype_helper.rb
@@ -1188,8 +1188,6 @@ module ActionView
@variable
end
- alias to_json rails_to_json
-
private
def append_to_function_chain!(call)
@generator << @variable if @empty
--
cgit v1.2.3
From c9d9bd7227b687f2162bd485b891aa2c2499adf0 Mon Sep 17 00:00:00 2001
From: Jeremy Kemper
Date: Sun, 26 Apr 2009 16:04:11 -0700
Subject: Check for to_str rather than String
---
actionpack/lib/action_dispatch/http/response.rb | 4 +---
1 file changed, 1 insertion(+), 3 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb
index 77c2dd0d7a..c2add1272e 100644
--- a/actionpack/lib/action_dispatch/http/response.rb
+++ b/actionpack/lib/action_dispatch/http/response.rb
@@ -98,7 +98,7 @@ module ActionDispatch # :nodoc:
def body=(body)
@body =
- if body.is_a?(String)
+ if body.respond_to?(:to_str)
[body]
else
body
@@ -215,8 +215,6 @@ module ActionDispatch # :nodoc:
if @body.respond_to?(:call)
@writer = lambda { |x| callback.call(x) }
@body.call(self, self)
- elsif @body.is_a?(String)
- callback.call(@body)
else
@body.each(&callback)
end
--
cgit v1.2.3
From 3f632027819ab331187ca58c014458dfcfd57a89 Mon Sep 17 00:00:00 2001
From: Jeremy Kemper
Date: Sun, 26 Apr 2009 16:04:29 -0700
Subject: Don't assume :params is a Hash
---
actionpack/lib/action_dispatch/test/mock.rb | 5 +----
1 file changed, 1 insertion(+), 4 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_dispatch/test/mock.rb b/actionpack/lib/action_dispatch/test/mock.rb
index 86269fad01..8dc048af11 100644
--- a/actionpack/lib/action_dispatch/test/mock.rb
+++ b/actionpack/lib/action_dispatch/test/mock.rb
@@ -21,10 +21,7 @@ module ActionDispatch
if method == "POST" && !opts.has_key?(:input)
opts["CONTENT_TYPE"] = "application/x-www-form-urlencoded"
- multipart = (opts[:params] || {}).any? do |k, v|
- UploadedFile === v
- end
-
+ multipart = opts[:params].respond_to?(:any?) && opts[:params].any? { |k, v| UploadedFile === v }
if multipart
opts[:input] = multipart_body(opts.delete(:params))
opts["CONTENT_LENGTH"] ||= opts[:input].length.to_s
--
cgit v1.2.3
From f7d7dc5aa8a5facc357ed291819db23e3f3df9b6 Mon Sep 17 00:00:00 2001
From: Jeremy Kemper
Date: Sun, 26 Apr 2009 17:19:14 -0700
Subject: Use session= writer methods
---
actionpack/lib/action_controller/testing/process.rb | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/testing/process.rb b/actionpack/lib/action_controller/testing/process.rb
index 16275371ad..c532a67e78 100644
--- a/actionpack/lib/action_controller/testing/process.rb
+++ b/actionpack/lib/action_controller/testing/process.rb
@@ -14,8 +14,8 @@ module ActionController #:nodoc:
super(Rack::MockRequest.env_for("/").merge(env))
@query_parameters = {}
- @env['rack.session'] = TestSession.new
- @env['rack.session.options'] = TestSession::DEFAULT_OPTIONS.merge(:id => ActiveSupport::SecureRandom.hex(16))
+ self.session = TestSession.new
+ self.session_options = TestSession::DEFAULT_OPTIONS.merge(:id => ActiveSupport::SecureRandom.hex(16))
initialize_default_values
initialize_containers
--
cgit v1.2.3
From 1850aea7fc9a1353de8e87adadf5230269b358c1 Mon Sep 17 00:00:00 2001
From: Jeremy Kemper
Date: Sun, 26 Apr 2009 18:26:06 -0700
Subject: Not sure why Request#session is missing
---
actionpack/lib/action_dispatch/http/request.rb | 8 ++++++++
1 file changed, 8 insertions(+)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb
index 2602b344ca..0b8909ced7 100755
--- a/actionpack/lib/action_dispatch/http/request.rb
+++ b/actionpack/lib/action_dispatch/http/request.rb
@@ -451,6 +451,14 @@ EOM
@env['rack.input']
end
+ def session
+ @env['rack.session']
+ end
+
+ def session_options
+ @env['rack.session.options']
+ end
+
def reset_session
self.session_options.delete(:id)
self.session = {}
--
cgit v1.2.3
From f5b4a9d02bc2292bae59e7b4fc028cce6edb91f7 Mon Sep 17 00:00:00 2001
From: Jeremy Kemper
Date: Sun, 26 Apr 2009 18:27:41 -0700
Subject: Array splitting strings on newlines is deprecated
---
actionpack/lib/action_dispatch/http/response.rb | 19 +++++++++++++++----
1 file changed, 15 insertions(+), 4 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb
index c2add1272e..6c92fb9713 100644
--- a/actionpack/lib/action_dispatch/http/response.rb
+++ b/actionpack/lib/action_dispatch/http/response.rb
@@ -245,9 +245,14 @@ module ActionDispatch # :nodoc:
# assert_equal 'AuthorOfNewPage', r.cookies['author']
def cookies
cookies = {}
- Array(headers['Set-Cookie']).each do |cookie|
- key, value = cookie.split(";").first.split("=").map { |v| Rack::Utils.unescape(v) }
- cookies[key] = value
+ if header = headers['Set-Cookie']
+ header = header.split("\n") if header.respond_to?(:to_str)
+ header.each do |cookie|
+ if pair = cookie.split(';').first
+ key, value = pair.split("=").map { |v| Rack::Utils.unescape(v) }
+ cookies[key] = value
+ end
+ end
end
cookies
end
@@ -305,7 +310,13 @@ module ActionDispatch # :nodoc:
end
def convert_cookies!
- headers['Set-Cookie'] = Array(headers['Set-Cookie']).compact
+ headers['Set-Cookie'] =
+ if header = headers['Set-Cookie']
+ header = header.split("\n") if header.respond_to?(:to_str)
+ header.compact
+ else
+ []
+ end
end
end
end
--
cgit v1.2.3
From 5cef0cbad2d1df013c74ab96c16cf7fd84040f46 Mon Sep 17 00:00:00 2001
From: Jeremy Kemper
Date: Sun, 26 Apr 2009 19:08:04 -0700
Subject: Check for to_str rather than String
---
actionpack/lib/action_controller/base/render.rb | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/base/render.rb b/actionpack/lib/action_controller/base/render.rb
index 33695cd78e..601c5429c3 100644
--- a/actionpack/lib/action_controller/base/render.rb
+++ b/actionpack/lib/action_controller/base/render.rb
@@ -254,7 +254,7 @@ module ActionController
render_for_text(js)
elsif json = options[:json]
- json = ActiveSupport::JSON.encode(json) unless json.is_a?(String)
+ json = ActiveSupport::JSON.encode(json) unless json.respond_to?(:to_str)
json = "#{options[:callback]}(#{json})" unless options[:callback].blank?
response.content_type ||= Mime::JSON
render_for_text(json)
--
cgit v1.2.3
From 678385d307559b2b5737bb2b07f633d2b9a0802c Mon Sep 17 00:00:00 2001
From: Jeremy Kemper
Date: Sun, 26 Apr 2009 19:59:22 -0700
Subject: Use javascript_object_for
---
actionpack/lib/action_view/helpers/prototype_helper.rb | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_view/helpers/prototype_helper.rb b/actionpack/lib/action_view/helpers/prototype_helper.rb
index 9cafd17004..a44c144d53 100644
--- a/actionpack/lib/action_view/helpers/prototype_helper.rb
+++ b/actionpack/lib/action_view/helpers/prototype_helper.rb
@@ -973,7 +973,7 @@ module ActionView
def loop_on_multiple_args(method, ids)
record(ids.size>1 ?
"#{javascript_object_for(ids)}.each(#{method})" :
- "#{method}(#{::ActiveSupport::JSON.encode(ids.first)})")
+ "#{method}(#{javascript_object_for(ids.first)})")
end
def page
--
cgit v1.2.3
From ee46ffedb88f812467485167036c7d254d0ce757 Mon Sep 17 00:00:00 2001
From: Jeremy Kemper
Date: Sun, 26 Apr 2009 20:04:47 -0700
Subject: Now that we have a separate internal rails_to_json, use a separate
circular reference stack instead of sticking it in the options hash
---
actionpack/lib/action_view/helpers/prototype_helper.rb | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_view/helpers/prototype_helper.rb b/actionpack/lib/action_view/helpers/prototype_helper.rb
index a44c144d53..1fbe012a95 100644
--- a/actionpack/lib/action_view/helpers/prototype_helper.rb
+++ b/actionpack/lib/action_view/helpers/prototype_helper.rb
@@ -1180,11 +1180,11 @@ module ActionView
# The JSON Encoder calls this to check for the +to_json+ method
# Since it's a blank slate object, I suppose it responds to anything.
- def respond_to?(method)
+ def respond_to?(*)
true
end
- def rails_to_json(options = nil)
+ def rails_to_json(*)
@variable
end
--
cgit v1.2.3
From e44cd416208241cd96f75574d6c454fc2101e789 Mon Sep 17 00:00:00 2001
From: Jeremy Kemper
Date: Sun, 26 Apr 2009 23:59:17 -0700
Subject: Make it clearer that session is nil
---
actionpack/test/activerecord/active_record_store_test.rb | 1 +
1 file changed, 1 insertion(+)
(limited to 'actionpack')
diff --git a/actionpack/test/activerecord/active_record_store_test.rb b/actionpack/test/activerecord/active_record_store_test.rb
index 34f18806a2..663cd259c8 100644
--- a/actionpack/test/activerecord/active_record_store_test.rb
+++ b/actionpack/test/activerecord/active_record_store_test.rb
@@ -13,6 +13,7 @@ class ActiveRecordStoreTest < ActionController::IntegrationTest
end
def set_session_value
+ raise "missing session!" unless session
session[:foo] = params[:foo] || "bar"
head :ok
end
--
cgit v1.2.3
From a88ddf8cc327279258cd68b0ad4091a5d54e3507 Mon Sep 17 00:00:00 2001
From: Jeremy Kemper
Date: Mon, 27 Apr 2009 00:00:03 -0700
Subject: Don't return bare string as rack body
---
actionpack/lib/action_dispatch/middleware/failsafe.rb | 4 ++--
actionpack/test/controller/dispatcher_test.rb | 2 +-
2 files changed, 3 insertions(+), 3 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_dispatch/middleware/failsafe.rb b/actionpack/lib/action_dispatch/middleware/failsafe.rb
index 5e0c479fdd..836098482c 100644
--- a/actionpack/lib/action_dispatch/middleware/failsafe.rb
+++ b/actionpack/lib/action_dispatch/middleware/failsafe.rb
@@ -29,9 +29,9 @@ module ActionDispatch
def failsafe_response_body
error_path = "#{self.class.error_file_path}/500.html"
if File.exist?(error_path)
- File.read(error_path)
+ [File.read(error_path)]
else
- "
500 Internal Server Error
"
+ ["
500 Internal Server Error
"]
end
end
diff --git a/actionpack/test/controller/dispatcher_test.rb b/actionpack/test/controller/dispatcher_test.rb
index 569d698a03..c3bd113b86 100644
--- a/actionpack/test/controller/dispatcher_test.rb
+++ b/actionpack/test/controller/dispatcher_test.rb
@@ -53,7 +53,7 @@ class DispatcherTest < Test::Unit::TestCase
assert_equal [
500,
{"Content-Type" => "text/html"},
- "
500 Internal Server Error
"
+ ["
500 Internal Server Error
"]
], dispatch
end
end
--
cgit v1.2.3
From c2b4da1c425dd8e1cc6606d49aea53e4f7521b91 Mon Sep 17 00:00:00 2001
From: Jeremy Kemper
Date: Mon, 27 Apr 2009 00:17:02 -0700
Subject: Sufficient to test that multipart/mixed wasn't parsed to a hash
---
actionpack/test/dispatch/request/multipart_params_parsing_test.rb | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'actionpack')
diff --git a/actionpack/test/dispatch/request/multipart_params_parsing_test.rb b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
index cc81a87cb9..aaf647e45a 100644
--- a/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
+++ b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
@@ -96,7 +96,7 @@ class MultipartParamsParsingTest < ActionController::IntegrationTest
# Ruby CGI doesn't handle multipart/mixed for us.
files = params['files']
- assert_kind_of Tempfile, files
+ assert_not_kind_of Hash, files
files.force_encoding('ASCII-8BIT') if files.respond_to?(:force_encoding)
assert_equal 19756, files.size
end
--
cgit v1.2.3
From dde063507ac40fda1a67f06a54c1a57d237f57b2 Mon Sep 17 00:00:00 2001
From: Jeremy Kemper
Date: Mon, 27 Apr 2009 09:29:01 -0700
Subject: Can't please them all
---
actionpack/test/dispatch/request/multipart_params_parsing_test.rb | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/test/dispatch/request/multipart_params_parsing_test.rb b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
index aaf647e45a..9e008a9ae8 100644
--- a/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
+++ b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
@@ -94,9 +94,8 @@ class MultipartParamsParsingTest < ActionController::IntegrationTest
assert_equal %w(files foo), params.keys.sort
assert_equal 'bar', params['foo']
- # Ruby CGI doesn't handle multipart/mixed for us.
+ # Rack doesn't handle multipart/mixed for us.
files = params['files']
- assert_not_kind_of Hash, files
files.force_encoding('ASCII-8BIT') if files.respond_to?(:force_encoding)
assert_equal 19756, files.size
end
--
cgit v1.2.3
From 21aa32692caf91f56d1c5c411baae635fa398344 Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Mon, 27 Apr 2009 13:11:17 -0500
Subject: Delegate controller.session to request.session and deprecate response
session
---
actionpack/lib/action_controller/base/base.rb | 14 +++++---------
actionpack/lib/action_controller/testing/process.rb | 2 +-
actionpack/lib/action_dispatch/http/request.rb | 8 --------
actionpack/lib/action_dispatch/http/response.rb | 6 +++++-
actionpack/test/controller/test_test.rb | 6 ------
5 files changed, 11 insertions(+), 25 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/base/base.rb b/actionpack/lib/action_controller/base/base.rb
index afb9fb71cb..1d0738588d 100644
--- a/actionpack/lib/action_controller/base/base.rb
+++ b/actionpack/lib/action_controller/base/base.rb
@@ -238,7 +238,7 @@ module ActionController #:nodoc:
cattr_reader :protected_instance_variables
# Controller specific instance variables which will not be accessible inside views.
@@protected_instance_variables = %w(@assigns @performed_redirect @performed_render @variables_added @request_origin @url @parent_controller
- @action_name @before_filter_chain_aborted @action_cache_path @_session @_headers @_params
+ @action_name @before_filter_chain_aborted @action_cache_path @_headers @_params
@_flash @_response)
# Prepends all the URL-generating helpers from AssetHelper. This makes it possible to easily move javascripts, stylesheets,
@@ -356,7 +356,9 @@ module ActionController #:nodoc:
# Holds a hash of objects in the session. Accessed like session[:person] to get the object tied to the "person"
# key. The session will hold any type of object as values, but the key should be a string or symbol.
- attr_internal :session
+ def session
+ request.session
+ end
# Holds a hash of header names and values. Accessed like headers["Cache-Control"] to get the value of the Cache-Control
# directive. Values should always be specified as strings.
@@ -787,7 +789,6 @@ module ActionController #:nodoc:
# Resets the session by clearing out all the objects stored within and initializing a new session object.
def reset_session #:doc:
request.reset_session
- @_session = request.session
end
private
@@ -812,7 +813,7 @@ module ActionController #:nodoc:
def assign_shortcuts(request, response)
@_request, @_response, @_params = request, response, request.parameters
- @_session, @_headers = @_request.session, @_response.headers
+ @_headers = @_response.headers
end
def initialize_current_url
@@ -888,10 +889,6 @@ module ActionController #:nodoc:
"#{request.protocol}#{request.host}#{request.request_uri}"
end
- def close_session
- # @_session.close if @_session && @_session.respond_to?(:close)
- end
-
def default_template(action_name = self.action_name)
self.view_paths.find_template(default_template_name(action_name), default_template_format)
end
@@ -915,7 +912,6 @@ module ActionController #:nodoc:
end
def process_cleanup
- close_session
end
end
diff --git a/actionpack/lib/action_controller/testing/process.rb b/actionpack/lib/action_controller/testing/process.rb
index c532a67e78..d073d06b19 100644
--- a/actionpack/lib/action_controller/testing/process.rb
+++ b/actionpack/lib/action_controller/testing/process.rb
@@ -165,7 +165,7 @@ module ActionController #:nodoc:
# A shortcut to the flash. Returns an empty hash if no session flash exists.
def flash
- session['flash'] || {}
+ request.session['flash'] || {}
end
# Do we have a flash?
diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb
index 0b8909ced7..2602b344ca 100755
--- a/actionpack/lib/action_dispatch/http/request.rb
+++ b/actionpack/lib/action_dispatch/http/request.rb
@@ -451,14 +451,6 @@ EOM
@env['rack.input']
end
- def session
- @env['rack.session']
- end
-
- def session_options
- @env['rack.session.options']
- end
-
def reset_session
self.session_options.delete(:id)
self.session = {}
diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb
index 6c92fb9713..ebba4eefa0 100644
--- a/actionpack/lib/action_dispatch/http/response.rb
+++ b/actionpack/lib/action_dispatch/http/response.rb
@@ -40,7 +40,11 @@ module ActionDispatch # :nodoc:
attr_writer :header
alias_method :headers=, :header=
- delegate :session, :to => :request
+ def session
+ ActiveSupport::Deprecation.warn("response.session has been deprecated. Use request.session instead", caller)
+ request.session
+ end
+
delegate :default_charset, :to => 'ActionController::Base'
def initialize
diff --git a/actionpack/test/controller/test_test.rb b/actionpack/test/controller/test_test.rb
index 124e259ef6..f68ffc7a2a 100644
--- a/actionpack/test/controller/test_test.rb
+++ b/actionpack/test/controller/test_test.rb
@@ -184,12 +184,6 @@ XML
assert_equal Hash.new, @controller.session.to_hash
end
- def test_session_is_cleared_from_response_after_reset_session
- process :set_session
- process :reset_the_session
- assert_equal Hash.new, @response.session.to_hash
- end
-
def test_session_is_cleared_from_request_after_reset_session
process :set_session
process :reset_the_session
--
cgit v1.2.3
From cecafc52ee0a4a53c903ddbaba95683261f88e5f Mon Sep 17 00:00:00 2001
From: Yehuda Katz + Carl Lerche
Date: Thu, 23 Apr 2009 15:58:38 -0700
Subject: Refactor ActionView::Template
ActionView::Template is now completely independent from template
storage, which allows different back ends such as the database.
ActionView::Template's only responsibility is to take in the
template source (passed in from ActionView::Path), compile it,
and render it.
---
actionpack/lib/action_controller/base/base.rb | 20 +-
actionpack/lib/action_controller/base/render.rb | 7 +-
.../testing/assertions/response.rb | 10 +-
actionpack/lib/action_view/base.rb | 4 +-
actionpack/lib/action_view/paths.rb | 12 +-
actionpack/lib/action_view/render/rendering.rb | 13 +-
actionpack/lib/action_view/template/error.rb | 4 +-
actionpack/lib/action_view/template/handlers.rb | 2 +-
actionpack/lib/action_view/template/path.rb | 68 +++--
actionpack/lib/action_view/template/template.rb | 336 ++++++++++++---------
actionpack/lib/action_view/test_case.rb | 7 +-
.../abstract_controller_test.rb | 2 +-
actionpack/test/controller/helper_test.rb | 2 +-
actionpack/test/controller/layout_test.rb | 24 +-
actionpack/test/controller/render_test.rb | 6 +-
actionpack/test/controller/view_paths_test.rb | 49 +--
actionpack/test/fixtures/layouts/standard.erb | 1 -
actionpack/test/fixtures/layouts/standard.html.erb | 1 +
.../test/render_file_with_locals_and_default.erb | 1 +
.../test/template/compiled_templates_test.rb | 36 +--
actionpack/test/template/render_test.rb | 14 +-
21 files changed, 338 insertions(+), 281 deletions(-)
delete mode 100644 actionpack/test/fixtures/layouts/standard.erb
create mode 100644 actionpack/test/fixtures/layouts/standard.html.erb
create mode 100644 actionpack/test/fixtures/test/render_file_with_locals_and_default.erb
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/base/base.rb b/actionpack/lib/action_controller/base/base.rb
index 1d0738588d..2063df54b4 100644
--- a/actionpack/lib/action_controller/base/base.rb
+++ b/actionpack/lib/action_controller/base/base.rb
@@ -494,8 +494,18 @@ module ActionController #:nodoc:
end
protected :filter_parameters
end
+
+ @@exempt_from_layout = [ActionView::TemplateHandlers::RJS]
+
+ def exempt_from_layout(*types)
+ types.each do |type|
+ @@exempt_from_layout <<
+ ActionView::Template.handler_class_for_extension(type)
+ end
+
+ @@exempt_from_layout
+ end
- delegate :exempt_from_layout, :to => 'ActionView::Template'
end
public
@@ -856,13 +866,13 @@ module ActionController #:nodoc:
return (performed? ? ret : default_render) if called
begin
- default_render
- rescue ActionView::MissingTemplate => e
- raise e unless e.action_name == action_name
- # If the path is the same as the action_name, the action is completely missing
+ view_paths.find_by_parts(action_name, {:formats => formats, :locales => [I18n.locale]}, controller_path)
+ rescue => e
raise UnknownAction, "No action responded to #{action_name}. Actions: " +
"#{action_methods.sort.to_sentence}", caller
end
+
+ default_render
end
# Returns true if a render or redirect has already been performed.
diff --git a/actionpack/lib/action_controller/base/render.rb b/actionpack/lib/action_controller/base/render.rb
index 601c5429c3..4286577ec5 100644
--- a/actionpack/lib/action_controller/base/render.rb
+++ b/actionpack/lib/action_controller/base/render.rb
@@ -378,13 +378,14 @@ module ActionController
# ==== Arguments
# parts::
# Example: ["show", [:html, :xml], "users", false]
- def render_for_parts(parts, layout, options = {})
+ def render_for_parts(parts, layout_details, options = {})
parts[1] = {:formats => parts[1], :locales => [I18n.locale]}
tmp = view_paths.find_by_parts(*parts)
- layout = _pick_layout(*layout) unless tmp.exempt_from_layout?
-
+ layout = _pick_layout(*layout_details) unless
+ self.class.exempt_from_layout.include?(tmp.handler)
+
render_for_text(
@template._render_template_with_layout(tmp, layout, options, parts[3]))
end
diff --git a/actionpack/lib/action_controller/testing/assertions/response.rb b/actionpack/lib/action_controller/testing/assertions/response.rb
index c57cbecc44..574b8d6825 100644
--- a/actionpack/lib/action_controller/testing/assertions/response.rb
+++ b/actionpack/lib/action_controller/testing/assertions/response.rb
@@ -98,22 +98,22 @@ module ActionController
clean_backtrace do
case options
when NilClass, String
- rendered = @controller.response.rendered[:template].to_s
+ rendered = (@controller.response.rendered[:template] || []).map { |t| t.identifier }
msg = build_message(message,
"expecting > but rendering with >",
- options, rendered)
+ options, rendered.join(', '))
assert_block(msg) do
if options.nil?
@controller.response.rendered[:template].blank?
else
- rendered.to_s.match(options)
+ rendered.any? { |t| t.match(options) }
end
end
when Hash
if expected_partial = options[:partial]
partials = @controller.response.rendered[:partials]
if expected_count = options[:count]
- found = partials.detect { |p, _| p.to_s.match(expected_partial) }
+ found = partials.detect { |p, _| p.identifier.match(expected_partial) }
actual_count = found.nil? ? 0 : found.second
msg = build_message(message,
"expecting ? to be rendered ? time(s) but rendered ? time(s)",
@@ -123,7 +123,7 @@ module ActionController
msg = build_message(message,
"expecting partial > but action rendered >",
options[:partial], partials.keys)
- assert(partials.keys.any? { |p| p.to_s.match(expected_partial) }, msg)
+ assert(partials.keys.any? { |p| p.identifier.match(expected_partial) }, msg)
end
else
assert @controller.response.rendered[:partials].empty?,
diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb
index efed19a21d..d087395361 100644
--- a/actionpack/lib/action_view/base.rb
+++ b/actionpack/lib/action_view/base.rb
@@ -196,7 +196,9 @@ module ActionView #:nodoc:
delegate :controller_path, :to => :controller, :allow_nil => true
delegate :request_forgery_protection_token, :template, :params, :session, :cookies, :response, :headers,
- :flash, :logger, :action_name, :controller_name, :to => :controller
+ :flash, :action_name, :controller_name, :to => :controller
+
+ delegate :logger, :to => :controller, :allow_nil => true
delegate :find_by_parts, :to => :view_paths
diff --git a/actionpack/lib/action_view/paths.rb b/actionpack/lib/action_view/paths.rb
index e48088f344..f6d021c92a 100644
--- a/actionpack/lib/action_view/paths.rb
+++ b/actionpack/lib/action_view/paths.rb
@@ -3,7 +3,7 @@ module ActionView #:nodoc:
def self.type_cast(obj)
if obj.is_a?(String)
cache = !Object.const_defined?(:Rails) || Rails.configuration.cache_classes
- Template::FileSystemPath.new(obj, :cache => cache)
+ Template::FileSystemPathWithFallback.new(obj, :cache => cache)
else
obj
end
@@ -34,18 +34,18 @@ module ActionView #:nodoc:
end
def find_by_parts(path, details = {}, prefix = nil, partial = false)
- template_path = path.sub(/^\//, '')
+ # template_path = path.sub(/^\//, '')
+ template_path = path
each do |load_path|
if template = load_path.find_by_parts(template_path, details, prefix, partial)
return template
end
end
-
- Template.new(path, self)
- rescue ActionView::MissingTemplate => e
+
+ # TODO: Have a fallback absolute path?
extension = details[:formats] || []
- raise ActionView::MissingTemplate.new(self, "#{prefix}/#{path}.{#{extension.join(",")}}")
+ raise ActionView::MissingTemplate.new(self, "#{prefix}/#{path} - #{details.inspect} - partial: #{!!partial}")
end
def find_by_parts?(path, extension = nil, prefix = nil, partial = false)
diff --git a/actionpack/lib/action_view/render/rendering.rb b/actionpack/lib/action_view/render/rendering.rb
index 4213b09e48..f174053b86 100644
--- a/actionpack/lib/action_view/render/rendering.rb
+++ b/actionpack/lib/action_view/render/rendering.rb
@@ -46,8 +46,8 @@ module ActionView
locals ||= {}
if controller && layout
- response.layout = layout.path_without_format_and_extension if controller.respond_to?(:response)
- logger.info("Rendering template within #{layout.path_without_format_and_extension}") if logger
+ response.layout = layout.identifier if controller.respond_to?(:response)
+ logger.info("Rendering template within #{layout.identifier}") if logger
end
begin
@@ -76,7 +76,6 @@ module ActionView
end
end
rescue Exception => e
- raise e if template.is_a?(InlineTemplate) || !template.filename
if TemplateError === e
e.sub_template_of(template)
raise e
@@ -86,7 +85,9 @@ module ActionView
end
def _render_inline(inline, layout, options)
- content = _render_template(InlineTemplate.new(options[:inline], options[:type]), options[:locals] || {})
+ handler = Template.handler_class_for_extension(options[:type] || "erb")
+ template = Template.new(options[:inline], "inline #{options[:inline].inspect}", handler, {})
+ content = _render_template(template, options[:locals] || {})
layout ? _render_content_with_layout(content, layout, options[:locals]) : content
end
@@ -96,7 +97,7 @@ module ActionView
def _render_template_with_layout(template, layout = nil, options = {}, partial = false)
if controller && logger
- logger.info("Rendering #{template.path_without_extension}" +
+ logger.info("Rendering #{template.identifier}" +
(options[:status] ? " (#{options[:status]})" : ''))
end
@@ -107,7 +108,7 @@ module ActionView
_render_template(template, options[:locals] || {})
end
- return content unless layout && !template.exempt_from_layout?
+ return content unless layout
_render_content_with_layout(content, layout, options[:locals] || {})
end
end
diff --git a/actionpack/lib/action_view/template/error.rb b/actionpack/lib/action_view/template/error.rb
index 37cb1c7c6c..a06e80b294 100644
--- a/actionpack/lib/action_view/template/error.rb
+++ b/actionpack/lib/action_view/template/error.rb
@@ -12,7 +12,7 @@ module ActionView
end
def file_name
- @template.relative_path
+ @template.identifier
end
def message
@@ -30,7 +30,7 @@ module ActionView
def sub_template_message
if @sub_templates
"Trace of template inclusion: " +
- @sub_templates.collect { |template| template.relative_path }.join(", ")
+ @sub_templates.collect { |template| template.identifier }.join(", ")
else
""
end
diff --git a/actionpack/lib/action_view/template/handlers.rb b/actionpack/lib/action_view/template/handlers.rb
index 448ab6731b..0590372d09 100644
--- a/actionpack/lib/action_view/template/handlers.rb
+++ b/actionpack/lib/action_view/template/handlers.rb
@@ -46,7 +46,7 @@ module ActionView #:nodoc:
end
def handler_class_for_extension(extension)
- registered_template_handler(extension) || @@default_template_handlers
+ (extension && registered_template_handler(extension.to_sym)) || @@default_template_handlers
end
end
end
diff --git a/actionpack/lib/action_view/template/path.rb b/actionpack/lib/action_view/template/path.rb
index 660a7e91a2..478bf96c9a 100644
--- a/actionpack/lib/action_view/template/path.rb
+++ b/actionpack/lib/action_view/template/path.rb
@@ -1,3 +1,5 @@
+require "pathname"
+
module ActionView
class Template
# Abstract super class
@@ -26,13 +28,6 @@ module ActionView
def find_templates(name, details, prefix, partial)
raise NotImplementedError
end
-
- # TODO: Refactor this to abstract out the file system
- def initialize_template(file)
- t = Template.new(file.split("#{self}/").last, self)
- t.load!
- t
- end
def valid_handlers
@valid_handlers ||= TemplateHandlers.extensions
@@ -44,10 +39,10 @@ module ActionView
/\.(?:#{e})$/
end
end
-
+
def handler_glob
- e = TemplateHandlers.extensions.join(',')
- ".{#{e}}"
+ e = TemplateHandlers.extensions.map{|h| ".#{h},"}.join
+ "{#{e}}"
end
def formats_glob
@@ -69,23 +64,19 @@ module ActionView
def initialize(path, options = {})
raise ArgumentError, "path already is a Path class" if path.is_a?(Path)
super(options)
- @path = path
+ @path = Pathname.new(path).expand_path
end
-
+
# TODO: This is the currently needed API. Make this suck less
# ====
attr_reader :path
def to_s
- if defined?(RAILS_ROOT)
- path.to_s.sub(/^#{Regexp.escape(File.expand_path(RAILS_ROOT))}\//, '')
- else
- path.to_s
- end
+ path.to_s
end
def to_str
- path.to_str
+ path.to_s
end
def ==(path)
@@ -97,11 +88,15 @@ module ActionView
end
# ====
- def find_templates(name, details, prefix, partial)
- if glob = parts_to_glob(name, details, prefix, partial)
+ def find_templates(name, details, prefix, partial, root = "#{@path}/")
+ if glob = details_to_glob(name, details, prefix, partial, root)
cached(glob) do
Dir[glob].map do |path|
- initialize_template(path) unless File.directory?(path)
+ next if File.directory?(path)
+ source = File.read(path)
+ identifier = Pathname.new(path).expand_path.to_s
+
+ Template.new(source, identifier, *path_to_details(path))
end.compact
end
end
@@ -109,7 +104,8 @@ module ActionView
private
- def parts_to_glob(name, details, prefix, partial)
+ # :api: plugin
+ def details_to_glob(name, details, prefix, partial, root)
path = ""
path << "#{prefix}/" unless prefix.empty?
path << (partial ? "_#{name}" : name)
@@ -123,8 +119,34 @@ module ActionView
end
end
- "#{@path}/#{path}#{extensions}#{handler_glob}"
+ "#{root}#{path}#{extensions}#{handler_glob}"
+ end
+
+ # TODO: fix me
+ # :api: plugin
+ def path_to_details(path)
+ # [:erb, :format => :html, :locale => :en, :partial => true/false]
+ if m = path.match(%r'/(_)?[\w-]+(\.[\w-]+)*\.(\w+)$')
+ partial = m[1] == '_'
+ details = (m[2]||"").split('.').reject { |e| e.empty? }
+ handler = Template.handler_class_for_extension(m[3])
+
+ format = Mime[details.last] && details.pop.to_sym
+ locale = details.last && details.pop.to_sym
+
+ return handler, :format => format, :locale => locale, :partial => partial
+ end
end
end
+
+ class FileSystemPathWithFallback < FileSystemPath
+
+ def find_templates(name, details, prefix, partial)
+ templates = super
+ return super(name, details, prefix, partial, '') if templates.empty?
+ templates
+ end
+
+ end
end
end
\ No newline at end of file
diff --git a/actionpack/lib/action_view/template/template.rb b/actionpack/lib/action_view/template/template.rb
index e541336613..ce6268729a 100644
--- a/actionpack/lib/action_view/template/template.rb
+++ b/actionpack/lib/action_view/template/template.rb
@@ -1,188 +1,230 @@
+# encoding: utf-8
+# This is so that templates compiled in this file are UTF-8
+
require 'set'
require "action_view/template/path"
-module ActionView #:nodoc:
+module ActionView
class Template
extend TemplateHandlers
- extend ActiveSupport::Memoizable
+ attr_reader :source, :identifier, :handler
- module Loading
- def load!
- @cached = true
- # freeze
- end
+ def initialize(source, identifier, handler, details)
+ @source = source
+ @identifier = identifier
+ @handler = handler
+ @details = details
end
- include Loading
- include Renderable
-
- # Templates that are exempt from layouts
- @@exempt_from_layout = Set.new([/\.rjs$/])
-
- # Don't render layouts for templates with the given extensions.
- def self.exempt_from_layout(*extensions)
- regexps = extensions.collect do |extension|
- extension.is_a?(Regexp) ? extension : /\.#{Regexp.escape(extension.to_s)}$/
- end
- @@exempt_from_layout.merge(regexps)
+ def render(view, locals, &blk)
+ method_name = compile(locals, view)
+ view.send(method_name, locals, &blk)
+ end
+
+ # TODO: Figure out how to abstract this
+ def variable_name
+ identifier[%r'_?(\w+)(\.\w+)*$', 1].to_sym
end
- attr_accessor :template_path, :filename, :load_path, :base_path
- attr_accessor :locale, :name, :format, :extension
- delegate :to_s, :to => :path
+ # TODO: Figure out how to abstract this
+ def counter_name
+ "#{variable_name}_counter".to_sym
+ end
+
+ # TODO: kill hax
+ def partial?
+ @details[:partial]
+ end
+
+ # TODO: Move out of Template
+ def mime_type
+ Mime::Type.lookup_by_extension(@details[:format]) if @details[:format]
+ end
+
+ private
- def initialize(template_path, load_paths = [])
- template_path = template_path.dup
- @load_path, @filename = find_full_path(template_path, load_paths)
- @base_path, @name, @locale, @format, @extension = split(template_path)
- @base_path.to_s.gsub!(/\/$/, '') # Push to split method
+ def compile(locals, view)
+ method_name = build_method_name(locals)
+
+ return method_name if view.respond_to?(method_name)
+
+ locals_code = locals.keys.map! { |key| "#{key} = local_assigns[:#{key}];" }.join
+
+ source = <<-end_src
+ def #{method_name}(local_assigns)
+ old_output_buffer = output_buffer;#{locals_code};#{@handler.call(self)}
+ ensure
+ self.output_buffer = old_output_buffer
+ end
+ end_src
+
+ begin
+ ActionView::Base::CompiledTemplates.module_eval(source, identifier, 0)
+ method_name
+ rescue Exception => e # errors from template code
+ if logger = (view && view.logger)
+ logger.debug "ERROR: compiling #{method_name} RAISED #{e}"
+ logger.debug "Function body: #{source}"
+ logger.debug "Backtrace: #{e.backtrace.join("\n")}"
+ end
- # Extend with partial super powers
- extend RenderablePartial if @name =~ /^_/
+ raise ActionView::TemplateError.new(self, {}, e)
+ end
+ end
+
+ def build_method_name(locals)
+ # TODO: is locals.keys.hash reliably the same?
+ "_render_template_#{@identifier.hash}_#{__id__}_#{locals.keys.hash}".gsub('-', "_")
end
+ end
+end
+
+if false
+ module ActionView #:nodoc:
+ class Template
+ extend TemplateHandlers
+ extend ActiveSupport::Memoizable
- def accessible_paths
- paths = []
+ module Loading
+ def load!
+ @cached = true
+ # freeze
+ end
+ end
+ include Loading
+
+ include Renderable
- if valid_extension?(extension)
- paths << path
- paths << path_without_extension
- if multipart?
- formats = format.split(".")
- paths << "#{path_without_format_and_extension}.#{formats.first}"
- paths << "#{path_without_format_and_extension}.#{formats.second}"
+ # Templates that are exempt from layouts
+ @@exempt_from_layout = Set.new([/\.rjs$/])
+
+ # Don't render layouts for templates with the given extensions.
+ def self.exempt_from_layout(*extensions)
+ regexps = extensions.collect do |extension|
+ extension.is_a?(Regexp) ? extension : /\.#{Regexp.escape(extension.to_s)}$/
end
- else
- # template without explicit template handler should only be reachable through its exact path
- paths << template_path
+ @@exempt_from_layout.merge(regexps)
end
- paths
- end
+ attr_accessor :template_path, :filename, :load_path, :base_path
+ attr_accessor :locale, :name, :format, :extension
+ delegate :to_s, :to => :path
+
+ def initialize(template_path, load_paths = [])
+ template_path = template_path.dup
+ @load_path, @filename = find_full_path(template_path, load_paths)
+ @name = template_path.to_s.split("/").last.split(".").first
+ # @base_path, @name, @locale, @format, @extension = split(template_path)
+ @base_path.to_s.gsub!(/\/$/, '') # Push to split method
+
+ # Extend with partial super powers
+ extend RenderablePartial if @name =~ /^_/
+ end
- def relative_path
- path = File.expand_path(filename)
- path.sub!(/^#{Regexp.escape(File.expand_path(RAILS_ROOT))}\//, '') if defined?(RAILS_ROOT)
- path
- end
- memoize :relative_path
+ def accessible_paths
+ paths = []
+
+ if valid_extension?(extension)
+ paths << path
+ paths << path_without_extension
+ if multipart?
+ formats = format.split(".")
+ paths << "#{path_without_format_and_extension}.#{formats.first}"
+ paths << "#{path_without_format_and_extension}.#{formats.second}"
+ end
+ else
+ # template without explicit template handler should only be reachable through its exact path
+ paths << template_path
+ end
+
+ paths
+ end
- def source
- File.read(filename)
- end
- memoize :source
+ def relative_path
+ path = File.expand_path(filename)
+ path.sub!(/^#{Regexp.escape(File.expand_path(RAILS_ROOT))}\//, '') if defined?(RAILS_ROOT)
+ path
+ end
+ memoize :relative_path
- def exempt_from_layout?
- @@exempt_from_layout.any? { |exempted| path =~ exempted }
- end
+ def source
+ File.read(filename)
+ end
+ memoize :source
- def path_without_extension
- [base_path, [name, locale, format].compact.join('.')].compact.join('/')
- end
- memoize :path_without_extension
+ def exempt_from_layout?
+ @@exempt_from_layout.any? { |exempted| path =~ exempted }
+ end
+
+ def path_without_extension
+ [base_path, [name, locale, format].compact.join('.')].compact.join('/')
+ end
+ memoize :path_without_extension
- def path_without_format_and_extension
- [base_path, [name, locale].compact.join('.')].compact.join('/')
- end
- memoize :path_without_format_and_extension
+ def path_without_format_and_extension
+ [base_path, [name, locale].compact.join('.')].compact.join('/')
+ end
+ memoize :path_without_format_and_extension
- def path
- [base_path, [name, locale, format, extension].compact.join('.')].compact.join('/')
- end
- memoize :path
+ def path
+ [base_path, [name, locale, format, extension].compact.join('.')].compact.join('/')
+ end
+ memoize :path
- def mime_type
- Mime::Type.lookup_by_extension(format) if format && defined?(::Mime)
- end
- memoize :mime_type
+ def mime_type
+ Mime::Type.lookup_by_extension(format) if format && defined?(::Mime)
+ end
+ memoize :mime_type
- def multipart?
- format && format.include?('.')
- end
+ def multipart?
+ format && format.include?('.')
+ end
- def content_type
- format && format.gsub('.', '/')
- end
+ def content_type
+ format && format.gsub('.', '/')
+ end
- private
+ private
- def format_and_extension
- (extensions = [format, extension].compact.join(".")).blank? ? nil : extensions
- end
- memoize :format_and_extension
-
- def mtime
- File.mtime(filename)
- end
- memoize :mtime
+ def format_and_extension
+ (extensions = [format, extension].compact.join(".")).blank? ? nil : extensions
+ end
+ memoize :format_and_extension
- def method_segment
- relative_path.to_s.gsub(/([^a-zA-Z0-9_])/) { $1.ord }
- end
- memoize :method_segment
+ def mtime
+ File.mtime(filename)
+ end
+ memoize :mtime
- def stale?
- File.mtime(filename) > mtime
- end
+ def method_segment
+ relative_path.to_s.gsub(/([^a-zA-Z0-9_])/) { $1.ord }
+ end
+ memoize :method_segment
- def recompile?
- !@cached
- end
+ def stale?
+ File.mtime(filename) > mtime
+ end
- def valid_extension?(extension)
- !Template.registered_template_handler(extension).nil?
- end
+ def recompile?
+ !@cached
+ end
- def valid_locale?(locale)
- I18n.available_locales.include?(locale.to_sym)
- end
+ def valid_extension?(extension)
+ !Template.registered_template_handler(extension).nil?
+ end
- def find_full_path(path, load_paths)
- load_paths = Array(load_paths) + [nil]
- load_paths.each do |load_path|
- file = load_path ? "#{load_path.to_str}/#{path}" : path
- return load_path, file if File.file?(file)
+ def valid_locale?(locale)
+ I18n.available_locales.include?(locale.to_sym)
end
- raise MissingTemplate.new(load_paths, path)
- end
- # Returns file split into an array
- # [base_path, name, locale, format, extension]
- def split(file)
- if m = file.to_s.match(/^(.*\/)?([^\.]+)\.(.*)$/)
- base_path = m[1]
- name = m[2]
- extensions = m[3]
- else
- return
- end
-
- locale = nil
- format = nil
- extension = nil
-
- if m = extensions.split(".")
- if valid_locale?(m[0]) && m[1] && valid_extension?(m[2]) # All three
- locale = m[0]
- format = m[1]
- extension = m[2]
- elsif m[0] && m[1] && valid_extension?(m[2]) # Multipart formats
- format = "#{m[0]}.#{m[1]}"
- extension = m[2]
- elsif valid_locale?(m[0]) && valid_extension?(m[1]) # locale and extension
- locale = m[0]
- extension = m[1]
- elsif valid_extension?(m[1]) # format and extension
- format = m[0]
- extension = m[1]
- elsif valid_extension?(m[0]) # Just extension
- extension = m[0]
- else # No extension
- format = m[0]
+ def find_full_path(path, load_paths)
+ load_paths = Array(load_paths) + [nil]
+ load_paths.each do |load_path|
+ file = load_path ? "#{load_path.to_str}/#{path}" : path
+ return load_path, file if File.file?(file)
end
+ raise MissingTemplate.new(load_paths, path)
end
-
- [base_path, name, locale, format, extension]
end
end
-end
+end
\ No newline at end of file
diff --git a/actionpack/lib/action_view/test_case.rb b/actionpack/lib/action_view/test_case.rb
index c8f204046b..dddd671812 100644
--- a/actionpack/lib/action_view/test_case.rb
+++ b/actionpack/lib/action_view/test_case.rb
@@ -10,9 +10,10 @@ module ActionView
alias_method :_render_template_without_template_tracking, :_render_template
def _render_template(template, local_assigns = {})
- if template.respond_to?(:path) && !template.is_a?(InlineTemplate)
- @_rendered[:partials][template] += 1 if template.is_a?(RenderablePartial)
- @_rendered[:template] ||= template
+ if template.respond_to?(:identifier)
+ @_rendered[:partials][template] += 1 if template.partial?
+ @_rendered[:template] ||= []
+ @_rendered[:template] << template
end
_render_template_without_template_tracking(template, local_assigns)
end
diff --git a/actionpack/test/abstract_controller/abstract_controller_test.rb b/actionpack/test/abstract_controller/abstract_controller_test.rb
index f1dcb39ef1..331797afcf 100644
--- a/actionpack/test/abstract_controller/abstract_controller_test.rb
+++ b/actionpack/test/abstract_controller/abstract_controller_test.rb
@@ -139,7 +139,7 @@ module AbstractController
private
def self.layout(formats)
begin
- view_paths.find_by_parts(name.underscore, {:formats => formats}t, "layouts")
+ view_paths.find_by_parts(name.underscore, {:formats => formats}, "layouts")
rescue ActionView::MissingTemplate
begin
view_paths.find_by_parts("application", {:formats => formats}, "layouts")
diff --git a/actionpack/test/controller/helper_test.rb b/actionpack/test/controller/helper_test.rb
index 5f36461b89..58addc123d 100644
--- a/actionpack/test/controller/helper_test.rb
+++ b/actionpack/test/controller/helper_test.rb
@@ -211,7 +211,7 @@ class IsolatedHelpersTest < Test::Unit::TestCase
end
def test_helper_in_a
- assert_raise(NameError) { A.process(@request, @response) }
+ assert_raise(ActionView::TemplateError) { A.process(@request, @response) }
end
def test_helper_in_b
diff --git a/actionpack/test/controller/layout_test.rb b/actionpack/test/controller/layout_test.rb
index f2721e274d..11559b4071 100644
--- a/actionpack/test/controller/layout_test.rb
+++ b/actionpack/test/controller/layout_test.rb
@@ -56,8 +56,8 @@ class LayoutAutoDiscoveryTest < ActionController::TestCase
def test_third_party_template_library_auto_discovers_layout
@controller = ThirdPartyTemplateLibraryController.new
get :hello
- assert_equal 'layouts/third_party_template_library.mab', @controller.active_layout(true).to_s
- assert_equal 'layouts/third_party_template_library', @response.layout
+ assert @controller.active_layout(true).identifier.include?('layouts/third_party_template_library.mab')
+ assert @response.layout.include?('layouts/third_party_template_library')
assert_response :success
assert_equal 'Mab', @response.body
end
@@ -72,7 +72,7 @@ class LayoutAutoDiscoveryTest < ActionController::TestCase
def test_namespaced_controllers_auto_detect_layouts
@controller = MultipleExtensions.new
get :hello
- assert_equal 'layouts/multiple_extensions.html.erb', @controller.active_layout(true).to_s
+ assert @controller.active_layout(true).identifier.include?('layouts/multiple_extensions.html.erb')
assert_equal 'multiple_extensions.html.erb hello.rhtml', @response.body.strip
end
end
@@ -116,22 +116,24 @@ class RendersNoLayoutController < LayoutTest
end
class LayoutSetInResponseTest < ActionController::TestCase
+ include ActionView::TemplateHandlers
+
def test_layout_set_when_using_default_layout
@controller = DefaultLayoutController.new
get :hello
- assert_equal 'layouts/layout_test', @response.layout
+ assert @response.layout.include?('layouts/layout_test')
end
def test_layout_set_when_set_in_controller
@controller = HasOwnLayoutController.new
get :hello
- assert_equal 'layouts/item', @response.layout
+ assert @response.layout.include?('layouts/item')
end
def test_layout_only_exception_when_included
@controller = OnlyLayoutController.new
get :hello
- assert_equal 'layouts/item', @response.layout
+ assert @response.layout.include?('layouts/item')
end
def test_layout_only_exception_when_excepted
@@ -143,7 +145,7 @@ class LayoutSetInResponseTest < ActionController::TestCase
def test_layout_except_exception_when_included
@controller = ExceptLayoutController.new
get :hello
- assert_equal 'layouts/item', @response.layout
+ assert @response.layout.include?('layouts/item')
end
def test_layout_except_exception_when_excepted
@@ -155,7 +157,7 @@ class LayoutSetInResponseTest < ActionController::TestCase
def test_layout_set_when_using_render
@controller = SetsLayoutInRenderController.new
get :hello
- assert_equal 'layouts/third_party_template_library', @response.layout
+ assert @response.layout.include?('layouts/third_party_template_library')
end
def test_layout_is_not_set_when_none_rendered
@@ -165,14 +167,14 @@ class LayoutSetInResponseTest < ActionController::TestCase
end
def test_exempt_from_layout_honored_by_render_template
- ActionController::Base.exempt_from_layout :rhtml
+ ActionController::Base.exempt_from_layout :erb
@controller = RenderWithTemplateOptionController.new
get :hello
assert_equal "alt/hello.rhtml", @response.body.strip
ensure
- ActionController::Base.exempt_from_layout.delete(/\.rhtml$/)
+ ActionController::Base.exempt_from_layout.delete(ERB)
end
def test_layout_is_picked_from_the_controller_instances_view_path
@@ -232,7 +234,7 @@ unless RUBY_PLATFORM =~ /(:?mswin|mingw|bccwin)/
@controller = LayoutSymlinkedTest.new
get :hello
assert_response 200
- assert_equal "layouts/symlinked/symlinked_layout", @response.layout
+ assert @response.layout.include?("layouts/symlinked/symlinked_layout")
end
end
end
diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb
index af7236ed26..da063710a9 100644
--- a/actionpack/test/controller/render_test.rb
+++ b/actionpack/test/controller/render_test.rb
@@ -773,7 +773,7 @@ class RenderTest < ActionController::TestCase
begin
get :render_line_offset
flunk "the action should have raised an exception"
- rescue RuntimeError => exc
+ rescue StandardError => exc
line = exc.backtrace.first
assert(line =~ %r{:(\d+):})
assert_equal "1", $1,
@@ -1736,7 +1736,7 @@ class RenderingLoggingTest < ActionController::TestCase
@controller.logger = MockLogger.new
get :layout_test
logged = @controller.logger.logged.find_all {|l| l =~ /render/i }
- assert_equal "Rendering test/hello_world", logged[0]
- assert_equal "Rendering template within layouts/standard", logged[1]
+ assert logged[0] =~ %r{Rendering.*test/hello_world}
+ assert logged[1] =~ %r{Rendering template within.*layouts/standard}
end
end
diff --git a/actionpack/test/controller/view_paths_test.rb b/actionpack/test/controller/view_paths_test.rb
index 1539f8f506..0ac10634b2 100644
--- a/actionpack/test/controller/view_paths_test.rb
+++ b/actionpack/test/controller/view_paths_test.rb
@@ -20,7 +20,7 @@ class ViewLoadPathsTest < ActionController::TestCase
layout 'test/sub'
def hello_world; render(:template => 'test/hello_world'); end
end
-
+
def setup
TestController.view_paths = nil
@@ -42,30 +42,39 @@ class ViewLoadPathsTest < ActionController::TestCase
ActiveSupport::Deprecation.behavior = @old_behavior
end
+ def expand(array)
+ array.map {|x| File.expand_path(x)}
+ end
+
+ def assert_paths(*paths)
+ controller = paths.first.is_a?(Class) ? paths.shift : @controller
+ assert_equal expand(paths), controller.view_paths.map(&:to_s)
+ end
+
def test_template_load_path_was_set_correctly
- assert_equal [FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
+ assert_paths FIXTURE_LOAD_PATH
end
def test_controller_appends_view_path_correctly
@controller.append_view_path 'foo'
- assert_equal [FIXTURE_LOAD_PATH, 'foo'], @controller.view_paths.map(&:to_s)
+ assert_paths(FIXTURE_LOAD_PATH, "foo")
@controller.append_view_path(%w(bar baz))
- assert_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz'], @controller.view_paths.map(&:to_s)
-
+ assert_paths(FIXTURE_LOAD_PATH, "foo", "bar", "baz")
+
@controller.append_view_path(FIXTURE_LOAD_PATH)
- assert_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
+ assert_paths(FIXTURE_LOAD_PATH, "foo", "bar", "baz", FIXTURE_LOAD_PATH)
end
def test_controller_prepends_view_path_correctly
@controller.prepend_view_path 'baz'
- assert_equal ['baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
+ assert_paths("baz", FIXTURE_LOAD_PATH)
@controller.prepend_view_path(%w(foo bar))
- assert_equal ['foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
+ assert_paths "foo", "bar", "baz", FIXTURE_LOAD_PATH
@controller.prepend_view_path(FIXTURE_LOAD_PATH)
- assert_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
+ assert_paths FIXTURE_LOAD_PATH, "foo", "bar", "baz", FIXTURE_LOAD_PATH
end
def test_template_appends_view_path_correctly
@@ -73,11 +82,11 @@ class ViewLoadPathsTest < ActionController::TestCase
class_view_paths = TestController.view_paths
@controller.append_view_path 'foo'
- assert_equal [FIXTURE_LOAD_PATH, 'foo'], @controller.view_paths.map(&:to_s)
+ assert_paths FIXTURE_LOAD_PATH, "foo"
@controller.append_view_path(%w(bar baz))
- assert_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz'], @controller.view_paths.map(&:to_s)
- assert_equal class_view_paths, TestController.view_paths
+ assert_paths FIXTURE_LOAD_PATH, "foo", "bar", "baz"
+ assert_paths TestController, *class_view_paths
end
def test_template_prepends_view_path_correctly
@@ -85,11 +94,11 @@ class ViewLoadPathsTest < ActionController::TestCase
class_view_paths = TestController.view_paths
@controller.prepend_view_path 'baz'
- assert_equal ['baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
+ assert_paths "baz", FIXTURE_LOAD_PATH
@controller.prepend_view_path(%w(foo bar))
- assert_equal ['foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
- assert_equal class_view_paths, TestController.view_paths
+ assert_paths "foo", "bar", "baz", FIXTURE_LOAD_PATH
+ assert_paths TestController, *class_view_paths
end
def test_view_paths
@@ -130,12 +139,12 @@ class ViewLoadPathsTest < ActionController::TestCase
A.view_paths = ['a/path']
- assert_equal ['a/path'], A.view_paths.map(&:to_s)
- assert_equal A.view_paths, B.view_paths
- assert_equal original_load_paths, C.view_paths
-
+ assert_paths A, "a/path"
+ assert_paths A, *B.view_paths
+ assert_paths C, *original_load_paths
+
C.view_paths = []
assert_nothing_raised { C.view_paths << 'c/path' }
- assert_equal ['c/path'], C.view_paths.map(&:to_s)
+ assert_paths C, "c/path"
end
end
diff --git a/actionpack/test/fixtures/layouts/standard.erb b/actionpack/test/fixtures/layouts/standard.erb
deleted file mode 100644
index 368764e6f4..0000000000
--- a/actionpack/test/fixtures/layouts/standard.erb
+++ /dev/null
@@ -1 +0,0 @@
-<%= @content_for_layout %><%= @variable_for_layout %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/layouts/standard.html.erb b/actionpack/test/fixtures/layouts/standard.html.erb
new file mode 100644
index 0000000000..368764e6f4
--- /dev/null
+++ b/actionpack/test/fixtures/layouts/standard.html.erb
@@ -0,0 +1 @@
+<%= @content_for_layout %><%= @variable_for_layout %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/render_file_with_locals_and_default.erb b/actionpack/test/fixtures/test/render_file_with_locals_and_default.erb
new file mode 100644
index 0000000000..9b4900acc5
--- /dev/null
+++ b/actionpack/test/fixtures/test/render_file_with_locals_and_default.erb
@@ -0,0 +1 @@
+<%= secret ||= 'one' %>
\ No newline at end of file
diff --git a/actionpack/test/template/compiled_templates_test.rb b/actionpack/test/template/compiled_templates_test.rb
index c75e29ed9a..b29b03f99d 100644
--- a/actionpack/test/template/compiled_templates_test.rb
+++ b/actionpack/test/template/compiled_templates_test.rb
@@ -5,37 +5,13 @@ class CompiledTemplatesTest < Test::Unit::TestCase
def setup
@compiled_templates = ActionView::Base::CompiledTemplates
@compiled_templates.instance_methods.each do |m|
- @compiled_templates.send(:remove_method, m) if m =~ /^_run_/
+ @compiled_templates.send(:remove_method, m) if m =~ /^_render_template_/
end
end
-
- def test_template_gets_compiled
- assert_equal 0, @compiled_templates.instance_methods.size
- assert_equal "Hello world!", render(:file => "test/hello_world.erb")
- assert_equal 1, @compiled_templates.instance_methods.size
- end
-
+
def test_template_gets_recompiled_when_using_different_keys_in_local_assigns
- assert_equal 0, @compiled_templates.instance_methods.size
- assert_equal "Hello world!", render(:file => "test/hello_world.erb")
- assert_equal "Hello world!", render(:file => "test/hello_world.erb", :locals => {:foo => "bar"})
- assert_equal 2, @compiled_templates.instance_methods.size
- end
-
- def test_compiled_template_will_not_be_recompiled_when_rendered_with_identical_local_assigns
- assert_equal 0, @compiled_templates.instance_methods.size
- assert_equal "Hello world!", render(:file => "test/hello_world.erb")
- ActionView::Template.any_instance.expects(:compile!).never
- assert_equal "Hello world!", render(:file => "test/hello_world.erb")
- end
-
- def test_compiled_template_will_always_be_recompiled_when_template_is_not_cached
- ActionView::Template.any_instance.expects(:recompile?).times(3).returns(true)
- assert_equal 0, @compiled_templates.instance_methods.size
- assert_equal "Hello world!", render(:file => "#{FIXTURE_LOAD_PATH}/test/hello_world.erb")
- ActionView::Template.any_instance.expects(:compile!).times(3)
- 3.times { assert_equal "Hello world!", render(:file => "#{FIXTURE_LOAD_PATH}/test/hello_world.erb") }
- assert_equal 1, @compiled_templates.instance_methods.size
+ assert_equal "one", render(:file => "test/render_file_with_locals_and_default.erb")
+ assert_equal "two", render(:file => "test/render_file_with_locals_and_default.erb", :locals => { :secret => "two" })
end
def test_template_changes_are_not_reflected_with_cached_templates
@@ -61,14 +37,12 @@ class CompiledTemplatesTest < Test::Unit::TestCase
def render_with_cache(*args)
view_paths = ActionController::Base.view_paths
- assert_equal ActionView::Template::FileSystemPath, view_paths.first.class
ActionView::Base.new(view_paths, {}).render(*args)
end
def render_without_cache(*args)
- path = ActionView::Template::FileSystemPath.new(FIXTURE_LOAD_PATH)
+ path = ActionView::Template::FileSystemPathWithFallback.new(FIXTURE_LOAD_PATH)
view_paths = ActionView::Base.process_view_paths(path)
- assert_equal ActionView::Template::FileSystemPath, view_paths.first.class
ActionView::Base.new(view_paths, {}).render(*args)
end
diff --git a/actionpack/test/template/render_test.rb b/actionpack/test/template/render_test.rb
index 7191df0dfd..71291f009c 100644
--- a/actionpack/test/template/render_test.rb
+++ b/actionpack/test/template/render_test.rb
@@ -91,10 +91,6 @@ module RenderTestCases
assert_equal "The secret is in the sauce\n", @view.render(:file => "test/dot.directory/render_file_with_ivar")
end
- def test_render_has_access_current_template
- assert_equal "test/template.erb", @view.render(:file => "test/template.erb")
- end
-
def test_render_update
# TODO: You should not have to stub out template because template is self!
@view.instance_variable_set(:@template, @view)
@@ -240,10 +236,6 @@ module RenderTestCases
end
end
- def test_template_with_malformed_template_handler_is_reachable_through_its_exact_filename
- assert_equal "Don't render me!", @view.render(:file => 'test/malformed/malformed.html.erb~')
- end
-
def test_render_with_layout
assert_equal %(\nHello world!\n),
@view.render(:file => "test/hello_world.erb", :layout => "layouts/yield")
@@ -269,7 +261,7 @@ class CachedViewRenderTest < ActiveSupport::TestCase
# Ensure view path cache is primed
def setup
view_paths = ActionController::Base.view_paths
- assert_equal ActionView::Template::FileSystemPath, view_paths.first.class
+ assert_equal ActionView::Template::FileSystemPathWithFallback, view_paths.first.class
setup_view(view_paths)
end
end
@@ -280,9 +272,9 @@ class LazyViewRenderTest < ActiveSupport::TestCase
# Test the same thing as above, but make sure the view path
# is not eager loaded
def setup
- path = ActionView::Template::FileSystemPath.new(FIXTURE_LOAD_PATH)
+ path = ActionView::Template::FileSystemPathWithFallback.new(FIXTURE_LOAD_PATH)
view_paths = ActionView::Base.process_view_paths(path)
- assert_equal ActionView::Template::FileSystemPath, view_paths.first.class
+ assert_equal ActionView::Template::FileSystemPathWithFallback, view_paths.first.class
setup_view(view_paths)
end
end
--
cgit v1.2.3
From ab83db9d069dea643eeb3588eeee634a780b6735 Mon Sep 17 00:00:00 2001
From: Yehuda Katz + Carl Lerche
Date: Mon, 27 Apr 2009 12:34:25 -0700
Subject: Fixes ActionMailer to work with the ActionView refactoring
---
actionpack/lib/action_view/template/template.rb | 152 +-----------------------
1 file changed, 1 insertion(+), 151 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_view/template/template.rb b/actionpack/lib/action_view/template/template.rb
index ce6268729a..dcc5006103 100644
--- a/actionpack/lib/action_view/template/template.rb
+++ b/actionpack/lib/action_view/template/template.rb
@@ -38,7 +38,7 @@ module ActionView
# TODO: Move out of Template
def mime_type
- Mime::Type.lookup_by_extension(@details[:format]) if @details[:format]
+ Mime::Type.lookup_by_extension(@details[:format].to_s) if @details[:format]
end
private
@@ -77,154 +77,4 @@ module ActionView
"_render_template_#{@identifier.hash}_#{__id__}_#{locals.keys.hash}".gsub('-', "_")
end
end
-end
-
-if false
- module ActionView #:nodoc:
- class Template
- extend TemplateHandlers
- extend ActiveSupport::Memoizable
-
- module Loading
- def load!
- @cached = true
- # freeze
- end
- end
- include Loading
-
- include Renderable
-
- # Templates that are exempt from layouts
- @@exempt_from_layout = Set.new([/\.rjs$/])
-
- # Don't render layouts for templates with the given extensions.
- def self.exempt_from_layout(*extensions)
- regexps = extensions.collect do |extension|
- extension.is_a?(Regexp) ? extension : /\.#{Regexp.escape(extension.to_s)}$/
- end
- @@exempt_from_layout.merge(regexps)
- end
-
- attr_accessor :template_path, :filename, :load_path, :base_path
- attr_accessor :locale, :name, :format, :extension
- delegate :to_s, :to => :path
-
- def initialize(template_path, load_paths = [])
- template_path = template_path.dup
- @load_path, @filename = find_full_path(template_path, load_paths)
- @name = template_path.to_s.split("/").last.split(".").first
- # @base_path, @name, @locale, @format, @extension = split(template_path)
- @base_path.to_s.gsub!(/\/$/, '') # Push to split method
-
- # Extend with partial super powers
- extend RenderablePartial if @name =~ /^_/
- end
-
- def accessible_paths
- paths = []
-
- if valid_extension?(extension)
- paths << path
- paths << path_without_extension
- if multipart?
- formats = format.split(".")
- paths << "#{path_without_format_and_extension}.#{formats.first}"
- paths << "#{path_without_format_and_extension}.#{formats.second}"
- end
- else
- # template without explicit template handler should only be reachable through its exact path
- paths << template_path
- end
-
- paths
- end
-
- def relative_path
- path = File.expand_path(filename)
- path.sub!(/^#{Regexp.escape(File.expand_path(RAILS_ROOT))}\//, '') if defined?(RAILS_ROOT)
- path
- end
- memoize :relative_path
-
- def source
- File.read(filename)
- end
- memoize :source
-
- def exempt_from_layout?
- @@exempt_from_layout.any? { |exempted| path =~ exempted }
- end
-
- def path_without_extension
- [base_path, [name, locale, format].compact.join('.')].compact.join('/')
- end
- memoize :path_without_extension
-
- def path_without_format_and_extension
- [base_path, [name, locale].compact.join('.')].compact.join('/')
- end
- memoize :path_without_format_and_extension
-
- def path
- [base_path, [name, locale, format, extension].compact.join('.')].compact.join('/')
- end
- memoize :path
-
- def mime_type
- Mime::Type.lookup_by_extension(format) if format && defined?(::Mime)
- end
- memoize :mime_type
-
- def multipart?
- format && format.include?('.')
- end
-
- def content_type
- format && format.gsub('.', '/')
- end
-
- private
-
- def format_and_extension
- (extensions = [format, extension].compact.join(".")).blank? ? nil : extensions
- end
- memoize :format_and_extension
-
- def mtime
- File.mtime(filename)
- end
- memoize :mtime
-
- def method_segment
- relative_path.to_s.gsub(/([^a-zA-Z0-9_])/) { $1.ord }
- end
- memoize :method_segment
-
- def stale?
- File.mtime(filename) > mtime
- end
-
- def recompile?
- !@cached
- end
-
- def valid_extension?(extension)
- !Template.registered_template_handler(extension).nil?
- end
-
- def valid_locale?(locale)
- I18n.available_locales.include?(locale.to_sym)
- end
-
- def find_full_path(path, load_paths)
- load_paths = Array(load_paths) + [nil]
- load_paths.each do |load_path|
- file = load_path ? "#{load_path.to_str}/#{path}" : path
- return load_path, file if File.file?(file)
- end
- raise MissingTemplate.new(load_paths, path)
- end
- end
- end
end
\ No newline at end of file
--
cgit v1.2.3
From afa7d7ff05a0d4787b216d50d609084649f21669 Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Tue, 28 Apr 2009 16:15:17 -0500
Subject: Fix validate_request method name
---
actionpack/lib/action_controller/testing/assertions/response.rb | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/testing/assertions/response.rb b/actionpack/lib/action_controller/testing/assertions/response.rb
index 574b8d6825..a4a3dcdec8 100644
--- a/actionpack/lib/action_controller/testing/assertions/response.rb
+++ b/actionpack/lib/action_controller/testing/assertions/response.rb
@@ -22,7 +22,7 @@ module ActionController
# assert_response 401
#
def assert_response(type, message = nil)
- validate_response!
+ validate_request!
clean_backtrace do
if [ :success, :missing, :redirect, :error ].include?(type) && @response.send("#{type}?")
@@ -59,7 +59,7 @@ module ActionController
# assert_redirected_to @customer
#
def assert_redirected_to(options = {}, message=nil)
- validate_response!
+ validate_request!
clean_backtrace do
assert_response(:redirect, message)
@@ -93,7 +93,7 @@ module ActionController
# assert_template :partial => false
#
def assert_template(options = {}, message = nil)
- validate_response!
+ validate_request!
clean_backtrace do
case options
@@ -152,7 +152,7 @@ module ActionController
end
end
- def validate_response!
+ def validate_request!
unless @request.is_a?(ActionDispatch::Request)
raise ArgumentError, "@request must be an ActionDispatch::Request"
end
--
cgit v1.2.3
From d63b42da362d696398fd371815734cb0caed48df Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Tue, 28 Apr 2009 16:25:04 -0500
Subject: Move header injection back into integration tests
---
actionpack/lib/action_controller/testing/integration.rb | 7 ++++++-
actionpack/lib/action_dispatch/test/mock.rb | 12 +-----------
2 files changed, 7 insertions(+), 12 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/testing/integration.rb b/actionpack/lib/action_controller/testing/integration.rb
index be5f216e2b..037463e489 100644
--- a/actionpack/lib/action_controller/testing/integration.rb
+++ b/actionpack/lib/action_controller/testing/integration.rb
@@ -263,7 +263,6 @@ module ActionController
opts = {
:method => method.to_s.upcase,
:params => parameters,
- :headers => headers,
"SERVER_NAME" => host,
"SERVER_PORT" => (https? ? "443" : "80"),
@@ -282,6 +281,12 @@ module ActionController
}
env = ActionDispatch::Test::MockRequest.env_for(@path, opts)
+ (headers || {}).each do |key, value|
+ key = key.to_s.upcase.gsub(/-/, "_")
+ key = "HTTP_#{key}" unless env.has_key?(key) || key =~ /^HTTP_/
+ env[key] = value
+ end
+
app = Rack::Lint.new(@app)
status, headers, body = app.call(env)
response = ::Rack::MockResponse.new(status, headers, body)
diff --git a/actionpack/lib/action_dispatch/test/mock.rb b/actionpack/lib/action_dispatch/test/mock.rb
index 8dc048af11..4042f9fbc8 100644
--- a/actionpack/lib/action_dispatch/test/mock.rb
+++ b/actionpack/lib/action_dispatch/test/mock.rb
@@ -5,8 +5,6 @@ module ActionDispatch
class << self
def env_for(path, opts)
- headers = opts.delete(:headers)
-
method = (opts[:method] || opts["REQUEST_METHOD"]).to_s.upcase
opts[:method] = opts["REQUEST_METHOD"] = method
@@ -48,15 +46,7 @@ module ActionDispatch
uri.query = requestify(params)
end
- env = ::Rack::MockRequest.env_for(uri.to_s, opts)
-
- (headers || {}).each do |key, value|
- key = key.to_s.upcase.gsub(/-/, "_")
- key = "HTTP_#{key}" unless env.has_key?(key) || key =~ /^HTTP_/
- env[key] = value
- end
-
- env
+ ::Rack::MockRequest.env_for(uri.to_s, opts)
end
private
--
cgit v1.2.3
From 8925e89c6307b8b7c8aeb0277ae5e059904b2fc6 Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Tue, 28 Apr 2009 16:32:26 -0500
Subject: Deprecate response.assigns
---
actionpack/lib/action_dispatch/http/response.rb | 8 ++++++--
1 file changed, 6 insertions(+), 2 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb
index ebba4eefa0..f570b8e8ed 100644
--- a/actionpack/lib/action_dispatch/http/response.rb
+++ b/actionpack/lib/action_dispatch/http/response.rb
@@ -34,7 +34,7 @@ module ActionDispatch # :nodoc:
DEFAULT_HEADERS = { "Cache-Control" => "no-cache" }
attr_accessor :request
- attr_accessor :assigns, :template, :layout
+ attr_accessor :template, :layout
attr_accessor :redirected_to, :redirected_to_method_params
attr_writer :header
@@ -45,12 +45,16 @@ module ActionDispatch # :nodoc:
request.session
end
+ def assigns
+ ActiveSupport::Deprecation.warn("response.assigns has been deprecated. Use controller.assigns instead", caller)
+ template.assigns
+ end
+
delegate :default_charset, :to => 'ActionController::Base'
def initialize
super
@header = Rack::Utils::HeaderHash.new(DEFAULT_HEADERS)
- @session, @assigns = [], []
end
# The response code of the request
--
cgit v1.2.3
From c0a372ba87f556769b98a6d06e8c684c3c3156df Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Tue, 28 Apr 2009 23:29:29 -0500
Subject: Deprecate template, session, assigns, and layout accessors on
response object. Instead access them through the controller instance. This
mainly affects functional test assertions.
---
actionpack/lib/action_controller/base/base.rb | 4 +-
.../lib/action_controller/base/mime_responds.rb | 2 +-
.../lib/action_controller/caching/actions.rb | 2 +-
.../testing/assertions/response.rb | 10 +-
.../lib/action_controller/testing/process.rb | 13 +-
actionpack/lib/action_dispatch/http/response.rb | 16 +-
actionpack/lib/action_view/base.rb | 2 +-
actionpack/lib/action_view/render/rendering.rb | 2 +-
actionpack/lib/action_view/test_case.rb | 5 +-
.../test/controller/action_pack_assertions_test.rb | 12 +-
actionpack/test/controller/filters_test.rb | 177 +++++++++++++--------
actionpack/test/controller/flash_test.rb | 48 +++---
actionpack/test/controller/layout_test.rb | 24 +--
actionpack/test/template/body_parts_test.rb | 2 +-
actionpack/test/template/output_buffer_test.rb | 18 +--
15 files changed, 195 insertions(+), 142 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/base/base.rb b/actionpack/lib/action_controller/base/base.rb
index 2063df54b4..14c4339c94 100644
--- a/actionpack/lib/action_controller/base/base.rb
+++ b/actionpack/lib/action_controller/base/base.rb
@@ -367,6 +367,8 @@ module ActionController #:nodoc:
# Returns the name of the action this controller is processing.
attr_accessor :action_name
+ attr_reader :template
+
class << self
def call(env)
# HACK: For global rescue to have access to the original request and response
@@ -816,7 +818,7 @@ module ActionController #:nodoc:
def initialize_template_class(response)
@template = response.template = ActionView::Base.new(self.class.view_paths, {}, self, formats)
- response.template.helpers.send :include, self.class.master_helper_module
+ @template.helpers.send :include, self.class.master_helper_module
response.redirected_to = nil
@performed_render = @performed_redirect = false
end
diff --git a/actionpack/lib/action_controller/base/mime_responds.rb b/actionpack/lib/action_controller/base/mime_responds.rb
index bac225ab2a..1003e61a0b 100644
--- a/actionpack/lib/action_controller/base/mime_responds.rb
+++ b/actionpack/lib/action_controller/base/mime_responds.rb
@@ -127,7 +127,7 @@ module ActionController #:nodoc:
@order << mime_type
@responses[mime_type] ||= Proc.new do
- @response.template.formats = [mime_type.to_sym]
+ @controller.template.formats = [mime_type.to_sym]
@response.content_type = mime_type.to_s
block_given? ? block.call : @controller.send(:render, :action => @controller.action_name)
end
diff --git a/actionpack/lib/action_controller/caching/actions.rb b/actionpack/lib/action_controller/caching/actions.rb
index b99feddf77..d95a346862 100644
--- a/actionpack/lib/action_controller/caching/actions.rb
+++ b/actionpack/lib/action_controller/caching/actions.rb
@@ -121,7 +121,7 @@ module ActionController #:nodoc:
end
def content_for_layout(controller)
- controller.response.layout && controller.response.template.instance_variable_get('@cached_content_for_layout')
+ controller.template.layout && controller.template.instance_variable_get('@cached_content_for_layout')
end
end
diff --git a/actionpack/lib/action_controller/testing/assertions/response.rb b/actionpack/lib/action_controller/testing/assertions/response.rb
index a4a3dcdec8..684fe1ffe0 100644
--- a/actionpack/lib/action_controller/testing/assertions/response.rb
+++ b/actionpack/lib/action_controller/testing/assertions/response.rb
@@ -33,7 +33,7 @@ module ActionController
assert_block("") { true } # to count the assertion
else
if @controller && @response.error?
- exception = @controller.response.template.instance_variable_get(:@exception)
+ exception = @controller.template.instance_variable_get(:@exception)
exception_message = exception && exception.message
assert_block(build_message(message, "Expected response to be a >, but was >\n>", type, @response.response_code, exception_message.to_s)) { false }
else
@@ -98,20 +98,20 @@ module ActionController
clean_backtrace do
case options
when NilClass, String
- rendered = (@controller.response.rendered[:template] || []).map { |t| t.identifier }
+ rendered = (@controller.template.rendered[:template] || []).map { |t| t.identifier }
msg = build_message(message,
"expecting > but rendering with >",
options, rendered.join(', '))
assert_block(msg) do
if options.nil?
- @controller.response.rendered[:template].blank?
+ @controller.template.rendered[:template].blank?
else
rendered.any? { |t| t.match(options) }
end
end
when Hash
if expected_partial = options[:partial]
- partials = @controller.response.rendered[:partials]
+ partials = @controller.template.rendered[:partials]
if expected_count = options[:count]
found = partials.detect { |p, _| p.identifier.match(expected_partial) }
actual_count = found.nil? ? 0 : found.second
@@ -126,7 +126,7 @@ module ActionController
assert(partials.keys.any? { |p| p.identifier.match(expected_partial) }, msg)
end
else
- assert @controller.response.rendered[:partials].empty?,
+ assert @controller.template.rendered[:partials].empty?,
"Expected no partials to be rendered"
end
end
diff --git a/actionpack/lib/action_controller/testing/process.rb b/actionpack/lib/action_controller/testing/process.rb
index d073d06b19..16a8f66bc4 100644
--- a/actionpack/lib/action_controller/testing/process.rb
+++ b/actionpack/lib/action_controller/testing/process.rb
@@ -160,7 +160,8 @@ module ActionController #:nodoc:
# Returns the template of the file which was used to
# render this response (or nil)
def rendered
- template.instance_variable_get(:@_rendered)
+ ActiveSupport::Deprecation.warn("response.rendered has been deprecated. Use tempate.rendered instead", caller)
+ @template.instance_variable_get(:@_rendered)
end
# A shortcut to the flash. Returns an empty hash if no session flash exists.
@@ -190,11 +191,13 @@ module ActionController #:nodoc:
# A shortcut to the template.assigns
def template_objects
- template.assigns || {}
+ ActiveSupport::Deprecation.warn("response.template_objects has been deprecated. Use tempate.assigns instead", caller)
+ @template.assigns || {}
end
# Does the specified template object exist?
def has_template_object?(name=nil)
+ ActiveSupport::Deprecation.warn("response.has_template_object? has been deprecated. Use tempate.assigns[name].nil? instead", caller)
!template_objects[name].nil?
end
@@ -317,9 +320,9 @@ module ActionController #:nodoc:
def assigns(key = nil)
if key.nil?
- @response.template.assigns
+ @controller.template.assigns
else
- @response.template.assigns[key.to_s]
+ @controller.template.assigns[key.to_s]
end
end
@@ -431,7 +434,7 @@ module ActionController #:nodoc:
(instance_variable_names - self.class.protected_instance_variables).each do |var|
name, value = var[1..-1], instance_variable_get(var)
@assigns[name] = value
- response.template.assigns[name] = value if response
+ @template.assigns[name] = value if response
end
end
end
diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb
index f570b8e8ed..d104dcb8a0 100644
--- a/actionpack/lib/action_dispatch/http/response.rb
+++ b/actionpack/lib/action_dispatch/http/response.rb
@@ -34,20 +34,30 @@ module ActionDispatch # :nodoc:
DEFAULT_HEADERS = { "Cache-Control" => "no-cache" }
attr_accessor :request
- attr_accessor :template, :layout
attr_accessor :redirected_to, :redirected_to_method_params
attr_writer :header
alias_method :headers=, :header=
+ def template
+ ActiveSupport::Deprecation.warn("response.template has been deprecated. Use controller.template instead", caller)
+ @template
+ end
+ attr_writer :template
+
def session
ActiveSupport::Deprecation.warn("response.session has been deprecated. Use request.session instead", caller)
- request.session
+ @request.session
end
def assigns
ActiveSupport::Deprecation.warn("response.assigns has been deprecated. Use controller.assigns instead", caller)
- template.assigns
+ @template.controller.assigns
+ end
+
+ def layout
+ ActiveSupport::Deprecation.warn("response.layout has been deprecated. Use template.layout instead", caller)
+ @template.layout
end
delegate :default_charset, :to => 'ActionController::Base'
diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb
index d087395361..44bd401631 100644
--- a/actionpack/lib/action_view/base.rb
+++ b/actionpack/lib/action_view/base.rb
@@ -191,7 +191,7 @@ module ActionView #:nodoc:
ActionController::Base.allow_concurrency || (cache_template_loading.nil? ? !ActiveSupport::Dependencies.load? : cache_template_loading)
end
- attr_internal :request
+ attr_internal :request, :layout
delegate :controller_path, :to => :controller, :allow_nil => true
diff --git a/actionpack/lib/action_view/render/rendering.rb b/actionpack/lib/action_view/render/rendering.rb
index f174053b86..6e368f27eb 100644
--- a/actionpack/lib/action_view/render/rendering.rb
+++ b/actionpack/lib/action_view/render/rendering.rb
@@ -46,7 +46,7 @@ module ActionView
locals ||= {}
if controller && layout
- response.layout = layout.identifier if controller.respond_to?(:response)
+ @_layout = layout.identifier
logger.info("Rendering template within #{layout.identifier}") if logger
end
diff --git a/actionpack/lib/action_view/test_case.rb b/actionpack/lib/action_view/test_case.rb
index dddd671812..50bed67f7d 100644
--- a/actionpack/lib/action_view/test_case.rb
+++ b/actionpack/lib/action_view/test_case.rb
@@ -7,7 +7,8 @@ module ActionView
@_rendered = { :template => nil, :partials => Hash.new(0) }
initialize_without_template_tracking(*args)
end
-
+
+ attr_internal :rendered
alias_method :_render_template_without_template_tracking, :_render_template
def _render_template(template, local_assigns = {})
if template.respond_to?(:identifier)
@@ -16,7 +17,7 @@ module ActionView
@_rendered[:template] << template
end
_render_template_without_template_tracking(template, local_assigns)
- end
+ end
end
class TestCase < ActiveSupport::TestCase
diff --git a/actionpack/test/controller/action_pack_assertions_test.rb b/actionpack/test/controller/action_pack_assertions_test.rb
index f091f9b87c..dd59999a0c 100644
--- a/actionpack/test/controller/action_pack_assertions_test.rb
+++ b/actionpack/test/controller/action_pack_assertions_test.rb
@@ -292,14 +292,14 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
# make sure that the template objects exist
def test_template_objects_alive
process :assign_this
- assert !@response.has_template_object?('hi')
- assert @response.has_template_object?('howdy')
+ assert !@controller.template.assigns['hi']
+ assert @controller.template.assigns['howdy']
end
# make sure we don't have template objects when we shouldn't
def test_template_object_missing
process :nothing
- assert_nil @response.template_objects['howdy']
+ assert_nil @controller.template.assigns['howdy']
end
# check the empty flashing
@@ -328,11 +328,11 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
# check if we were rendered by a file-based template?
def test_rendered_action
process :nothing
- assert_nil @response.rendered[:template]
+ assert_nil @controller.template.rendered[:template]
process :hello_world
- assert @response.rendered[:template]
- assert 'hello_world', @response.rendered[:template].to_s
+ assert @controller.template.rendered[:template]
+ assert 'hello_world', @controller.template.rendered[:template].to_s
end
# check the redirection location
diff --git a/actionpack/test/controller/filters_test.rb b/actionpack/test/controller/filters_test.rb
index e83fde2349..aca7a821c8 100644
--- a/actionpack/test/controller/filters_test.rb
+++ b/actionpack/test/controller/filters_test.rb
@@ -165,11 +165,11 @@ class FilterTest < Test::Unit::TestCase
def index
render :text => 'ok'
end
-
+
def public
end
end
-
+
class SkippingAndReorderingController < TestController
skip_before_filter :ensure_login
before_filter :find_record
@@ -450,7 +450,8 @@ class FilterTest < Test::Unit::TestCase
def test_empty_filter_chain
assert_equal 0, EmptyFilterChainController.filter_chain.size
- assert test_process(EmptyFilterChainController).template.assigns['action_executed']
+ test_process(EmptyFilterChainController)
+ assert @controller.template.assigns['action_executed']
end
def test_added_filter_to_inheritance_graph
@@ -466,88 +467,109 @@ class FilterTest < Test::Unit::TestCase
end
def test_running_filters
- assert_equal %w( wonderful_life ensure_login ), test_process(PrependingController).template.assigns["ran_filter"]
+ test_process(PrependingController)
+ assert_equal %w( wonderful_life ensure_login ), @controller.template.assigns["ran_filter"]
end
def test_running_filters_with_proc
- assert test_process(ProcController).template.assigns["ran_proc_filter"]
+ test_process(ProcController)
+ assert @controller.template.assigns["ran_proc_filter"]
end
def test_running_filters_with_implicit_proc
- assert test_process(ImplicitProcController).template.assigns["ran_proc_filter"]
+ test_process(ImplicitProcController)
+ assert @controller.template.assigns["ran_proc_filter"]
end
def test_running_filters_with_class
- assert test_process(AuditController).template.assigns["was_audited"]
+ test_process(AuditController)
+ assert @controller.template.assigns["was_audited"]
end
def test_running_anomolous_yet_valid_condition_filters
- response = test_process(AnomolousYetValidConditionController)
- assert_equal %w( ensure_login ), response.template.assigns["ran_filter"]
- assert response.template.assigns["ran_class_filter"]
- assert response.template.assigns["ran_proc_filter1"]
- assert response.template.assigns["ran_proc_filter2"]
+ test_process(AnomolousYetValidConditionController)
+ assert_equal %w( ensure_login ), @controller.template.assigns["ran_filter"]
+ assert @controller.template.assigns["ran_class_filter"]
+ assert @controller.template.assigns["ran_proc_filter1"]
+ assert @controller.template.assigns["ran_proc_filter2"]
- response = test_process(AnomolousYetValidConditionController, "show_without_filter")
- assert_equal nil, response.template.assigns["ran_filter"]
- assert !response.template.assigns["ran_class_filter"]
- assert !response.template.assigns["ran_proc_filter1"]
- assert !response.template.assigns["ran_proc_filter2"]
+ test_process(AnomolousYetValidConditionController, "show_without_filter")
+ assert_equal nil, @controller.template.assigns["ran_filter"]
+ assert !@controller.template.assigns["ran_class_filter"]
+ assert !@controller.template.assigns["ran_proc_filter1"]
+ assert !@controller.template.assigns["ran_proc_filter2"]
end
def test_running_conditional_options
- response = test_process(ConditionalOptionsFilter)
- assert_equal %w( ensure_login ), response.template.assigns["ran_filter"]
+ test_process(ConditionalOptionsFilter)
+ assert_equal %w( ensure_login ), @controller.template.assigns["ran_filter"]
end
def test_running_collection_condition_filters
- assert_equal %w( ensure_login ), test_process(ConditionalCollectionFilterController).template.assigns["ran_filter"]
- assert_equal nil, test_process(ConditionalCollectionFilterController, "show_without_filter").template.assigns["ran_filter"]
- assert_equal nil, test_process(ConditionalCollectionFilterController, "another_action").template.assigns["ran_filter"]
+ test_process(ConditionalCollectionFilterController)
+ assert_equal %w( ensure_login ), @controller.template.assigns["ran_filter"]
+ test_process(ConditionalCollectionFilterController, "show_without_filter")
+ assert_equal nil, @controller.template.assigns["ran_filter"]
+ test_process(ConditionalCollectionFilterController, "another_action")
+ assert_equal nil, @controller.template.assigns["ran_filter"]
end
def test_running_only_condition_filters
- assert_equal %w( ensure_login ), test_process(OnlyConditionSymController).template.assigns["ran_filter"]
- assert_equal nil, test_process(OnlyConditionSymController, "show_without_filter").template.assigns["ran_filter"]
+ test_process(OnlyConditionSymController)
+ assert_equal %w( ensure_login ), @controller.template.assigns["ran_filter"]
+ test_process(OnlyConditionSymController, "show_without_filter")
+ assert_equal nil, @controller.template.assigns["ran_filter"]
- assert test_process(OnlyConditionProcController).template.assigns["ran_proc_filter"]
- assert !test_process(OnlyConditionProcController, "show_without_filter").template.assigns["ran_proc_filter"]
+ test_process(OnlyConditionProcController)
+ assert @controller.template.assigns["ran_proc_filter"]
+ test_process(OnlyConditionProcController, "show_without_filter")
+ assert !@controller.template.assigns["ran_proc_filter"]
- assert test_process(OnlyConditionClassController).template.assigns["ran_class_filter"]
- assert !test_process(OnlyConditionClassController, "show_without_filter").template.assigns["ran_class_filter"]
+ test_process(OnlyConditionClassController)
+ assert @controller.template.assigns["ran_class_filter"]
+ test_process(OnlyConditionClassController, "show_without_filter")
+ assert !@controller.template.assigns["ran_class_filter"]
end
def test_running_except_condition_filters
- assert_equal %w( ensure_login ), test_process(ExceptConditionSymController).template.assigns["ran_filter"]
- assert_equal nil, test_process(ExceptConditionSymController, "show_without_filter").template.assigns["ran_filter"]
+ test_process(ExceptConditionSymController)
+ assert_equal %w( ensure_login ), @controller.template.assigns["ran_filter"]
+ test_process(ExceptConditionSymController, "show_without_filter")
+ assert_equal nil, @controller.template.assigns["ran_filter"]
- assert test_process(ExceptConditionProcController).template.assigns["ran_proc_filter"]
- assert !test_process(ExceptConditionProcController, "show_without_filter").template.assigns["ran_proc_filter"]
+ test_process(ExceptConditionProcController)
+ assert @controller.template.assigns["ran_proc_filter"]
+ test_process(ExceptConditionProcController, "show_without_filter")
+ assert !@controller.template.assigns["ran_proc_filter"]
- assert test_process(ExceptConditionClassController).template.assigns["ran_class_filter"]
- assert !test_process(ExceptConditionClassController, "show_without_filter").template.assigns["ran_class_filter"]
+ test_process(ExceptConditionClassController)
+ assert @controller.template.assigns["ran_class_filter"]
+ test_process(ExceptConditionClassController, "show_without_filter")
+ assert !@controller.template.assigns["ran_class_filter"]
end
def test_running_before_and_after_condition_filters
- assert_equal %w( ensure_login clean_up_tmp), test_process(BeforeAndAfterConditionController).template.assigns["ran_filter"]
- assert_equal nil, test_process(BeforeAndAfterConditionController, "show_without_filter").template.assigns["ran_filter"]
+ test_process(BeforeAndAfterConditionController)
+ assert_equal %w( ensure_login clean_up_tmp), @controller.template.assigns["ran_filter"]
+ test_process(BeforeAndAfterConditionController, "show_without_filter")
+ assert_equal nil, @controller.template.assigns["ran_filter"]
end
def test_around_filter
- controller = test_process(AroundFilterController)
- assert controller.template.assigns["before_ran"]
- assert controller.template.assigns["after_ran"]
+ test_process(AroundFilterController)
+ assert @controller.template.assigns["before_ran"]
+ assert @controller.template.assigns["after_ran"]
end
def test_before_after_class_filter
- controller = test_process(BeforeAfterClassFilterController)
- assert controller.template.assigns["before_ran"]
- assert controller.template.assigns["after_ran"]
+ test_process(BeforeAfterClassFilterController)
+ assert @controller.template.assigns["before_ran"]
+ assert @controller.template.assigns["after_ran"]
end
def test_having_properties_in_around_filter
- controller = test_process(AroundFilterController)
- assert_equal "before and after", controller.template.assigns["execution_log"]
+ test_process(AroundFilterController)
+ assert_equal "before and after", @controller.template.assigns["execution_log"]
end
def test_prepending_and_appending_around_filter
@@ -560,7 +582,7 @@ class FilterTest < Test::Unit::TestCase
def test_rendering_breaks_filtering_chain
response = test_process(RenderingController)
assert_equal "something else", response.body
- assert !response.template.assigns["ran_action"]
+ assert !@controller.template.assigns["ran_action"]
end
def test_filters_with_mixed_specialization_run_in_order
@@ -586,40 +608,53 @@ class FilterTest < Test::Unit::TestCase
def test_running_prepended_before_and_after_filter
assert_equal 3, PrependingBeforeAndAfterController.filter_chain.length
- response = test_process(PrependingBeforeAndAfterController)
- assert_equal %w( before_all between_before_all_and_after_all after_all ), response.template.assigns["ran_filter"]
+ test_process(PrependingBeforeAndAfterController)
+ assert_equal %w( before_all between_before_all_and_after_all after_all ), @controller.template.assigns["ran_filter"]
end
-
+
def test_skipping_and_limiting_controller
- assert_equal %w( ensure_login ), test_process(SkippingAndLimitedController, "index").template.assigns["ran_filter"]
- assert_nil test_process(SkippingAndLimitedController, "public").template.assigns["ran_filter"]
+ test_process(SkippingAndLimitedController, "index")
+ assert_equal %w( ensure_login ), @controller.template.assigns["ran_filter"]
+ test_process(SkippingAndLimitedController, "public")
+ assert_nil @controller.template.assigns["ran_filter"]
end
def test_skipping_and_reordering_controller
- assert_equal %w( find_record ensure_login ), test_process(SkippingAndReorderingController, "index").template.assigns["ran_filter"]
+ test_process(SkippingAndReorderingController, "index")
+ assert_equal %w( find_record ensure_login ), @controller.template.assigns["ran_filter"]
end
def test_conditional_skipping_of_filters
- assert_nil test_process(ConditionalSkippingController, "login").template.assigns["ran_filter"]
- assert_equal %w( ensure_login find_user ), test_process(ConditionalSkippingController, "change_password").template.assigns["ran_filter"]
+ test_process(ConditionalSkippingController, "login")
+ assert_nil @controller.template.assigns["ran_filter"]
+ test_process(ConditionalSkippingController, "change_password")
+ assert_equal %w( ensure_login find_user ), @controller.template.assigns["ran_filter"]
- assert_nil test_process(ConditionalSkippingController, "login").template.controller.instance_variable_get("@ran_after_filter")
- assert_equal %w( clean_up ), test_process(ConditionalSkippingController, "change_password").template.controller.instance_variable_get("@ran_after_filter")
+ test_process(ConditionalSkippingController, "login")
+ assert_nil @controller.template.controller.instance_variable_get("@ran_after_filter")
+ test_process(ConditionalSkippingController, "change_password")
+ assert_equal %w( clean_up ), @controller.template.controller.instance_variable_get("@ran_after_filter")
end
def test_conditional_skipping_of_filters_when_parent_filter_is_also_conditional
- assert_equal %w( conditional_in_parent conditional_in_parent ), test_process(ChildOfConditionalParentController).template.assigns['ran_filter']
- assert_nil test_process(ChildOfConditionalParentController, 'another_action').template.assigns['ran_filter']
+ test_process(ChildOfConditionalParentController)
+ assert_equal %w( conditional_in_parent conditional_in_parent ), @controller.template.assigns['ran_filter']
+ test_process(ChildOfConditionalParentController, 'another_action')
+ assert_nil @controller.template.assigns['ran_filter']
end
def test_condition_skipping_of_filters_when_siblings_also_have_conditions
- assert_equal %w( conditional_in_parent conditional_in_parent ), test_process(ChildOfConditionalParentController).template.assigns['ran_filter'], "1"
- assert_equal nil, test_process(AnotherChildOfConditionalParentController).template.assigns['ran_filter']
- assert_equal %w( conditional_in_parent conditional_in_parent ), test_process(ChildOfConditionalParentController).template.assigns['ran_filter']
+ test_process(ChildOfConditionalParentController)
+ assert_equal %w( conditional_in_parent conditional_in_parent ), @controller.template.assigns['ran_filter'], "1"
+ test_process(AnotherChildOfConditionalParentController)
+ assert_equal nil, @controller.template.assigns['ran_filter']
+ test_process(ChildOfConditionalParentController)
+ assert_equal %w( conditional_in_parent conditional_in_parent ), @controller.template.assigns['ran_filter']
end
def test_changing_the_requirements
- assert_equal nil, test_process(ChangingTheRequirementsController, "go_wild").template.assigns['ran_filter']
+ test_process(ChangingTheRequirementsController, "go_wild")
+ assert_equal nil, @controller.template.assigns['ran_filter']
end
def test_a_rescuing_around_filter
@@ -638,7 +673,8 @@ class FilterTest < Test::Unit::TestCase
request = ActionController::TestRequest.new
request.action = action
controller = controller.new if controller.is_a?(Class)
- controller.process_with_test(request, ActionController::TestResponse.new)
+ @controller = controller
+ @controller.process_with_test(request, ActionController::TestResponse.new)
end
end
@@ -819,9 +855,9 @@ class YieldingAroundFiltersTest < Test::Unit::TestCase
end
def test_with_proc
- controller = test_process(ControllerWithProcFilter,'no_raise')
- assert controller.template.assigns['before']
- assert controller.template.assigns['after']
+ test_process(ControllerWithProcFilter,'no_raise')
+ assert @controller.template.assigns['before']
+ assert @controller.template.assigns['after']
end
def test_nested_filters
@@ -841,13 +877,13 @@ class YieldingAroundFiltersTest < Test::Unit::TestCase
end
def test_filter_order_with_all_filter_types
- controller = test_process(ControllerWithAllTypesOfFilters,'no_raise')
- assert_equal 'before around (before yield) around_again (before yield) around_again (after yield) around (after yield) after',controller.template.assigns['ran_filter'].join(' ')
+ test_process(ControllerWithAllTypesOfFilters,'no_raise')
+ assert_equal 'before around (before yield) around_again (before yield) around_again (after yield) around (after yield) after', @controller.template.assigns['ran_filter'].join(' ')
end
def test_filter_order_with_skip_filter_method
- controller = test_process(ControllerWithTwoLessFilters,'no_raise')
- assert_equal 'before around (before yield) around (after yield)',controller.template.assigns['ran_filter'].join(' ')
+ test_process(ControllerWithTwoLessFilters,'no_raise')
+ assert_equal 'before around (before yield) around (after yield)', @controller.template.assigns['ran_filter'].join(' ')
end
def test_first_filter_in_multiple_before_filter_chain_halts
@@ -880,6 +916,7 @@ class YieldingAroundFiltersTest < Test::Unit::TestCase
request = ActionController::TestRequest.new
request.action = action
controller = controller.new if controller.is_a?(Class)
- controller.process_with_test(request, ActionController::TestResponse.new)
+ @controller = controller
+ @controller.process_with_test(request, ActionController::TestResponse.new)
end
end
diff --git a/actionpack/test/controller/flash_test.rb b/actionpack/test/controller/flash_test.rb
index d8a892811e..ef60cae0ff 100644
--- a/actionpack/test/controller/flash_test.rb
+++ b/actionpack/test/controller/flash_test.rb
@@ -79,64 +79,64 @@ class FlashTest < ActionController::TestCase
get :set_flash
get :use_flash
- assert_equal "hello", @response.template.assigns["flash_copy"]["that"]
- assert_equal "hello", @response.template.assigns["flashy"]
+ assert_equal "hello", @controller.template.assigns["flash_copy"]["that"]
+ assert_equal "hello", @controller.template.assigns["flashy"]
get :use_flash
- assert_nil @response.template.assigns["flash_copy"]["that"], "On second flash"
+ assert_nil @controller.template.assigns["flash_copy"]["that"], "On second flash"
end
def test_keep_flash
get :set_flash
get :use_flash_and_keep_it
- assert_equal "hello", @response.template.assigns["flash_copy"]["that"]
- assert_equal "hello", @response.template.assigns["flashy"]
+ assert_equal "hello", @controller.template.assigns["flash_copy"]["that"]
+ assert_equal "hello", @controller.template.assigns["flashy"]
get :use_flash
- assert_equal "hello", @response.template.assigns["flash_copy"]["that"], "On second flash"
+ assert_equal "hello", @controller.template.assigns["flash_copy"]["that"], "On second flash"
get :use_flash
- assert_nil @response.template.assigns["flash_copy"]["that"], "On third flash"
+ assert_nil @controller.template.assigns["flash_copy"]["that"], "On third flash"
end
def test_flash_now
get :set_flash_now
- assert_equal "hello", @response.template.assigns["flash_copy"]["that"]
- assert_equal "bar" , @response.template.assigns["flash_copy"]["foo"]
- assert_equal "hello", @response.template.assigns["flashy"]
+ assert_equal "hello", @controller.template.assigns["flash_copy"]["that"]
+ assert_equal "bar" , @controller.template.assigns["flash_copy"]["foo"]
+ assert_equal "hello", @controller.template.assigns["flashy"]
get :attempt_to_use_flash_now
- assert_nil @response.template.assigns["flash_copy"]["that"]
- assert_nil @response.template.assigns["flash_copy"]["foo"]
- assert_nil @response.template.assigns["flashy"]
+ assert_nil @controller.template.assigns["flash_copy"]["that"]
+ assert_nil @controller.template.assigns["flash_copy"]["foo"]
+ assert_nil @controller.template.assigns["flashy"]
end
def test_update_flash
get :set_flash
get :use_flash_and_update_it
- assert_equal "hello", @response.template.assigns["flash_copy"]["that"]
- assert_equal "hello again", @response.template.assigns["flash_copy"]["this"]
+ assert_equal "hello", @controller.template.assigns["flash_copy"]["that"]
+ assert_equal "hello again", @controller.template.assigns["flash_copy"]["this"]
get :use_flash
- assert_nil @response.template.assigns["flash_copy"]["that"], "On second flash"
- assert_equal "hello again", @response.template.assigns["flash_copy"]["this"], "On second flash"
+ assert_nil @controller.template.assigns["flash_copy"]["that"], "On second flash"
+ assert_equal "hello again", @controller.template.assigns["flash_copy"]["this"], "On second flash"
end
def test_flash_after_reset_session
get :use_flash_after_reset_session
- assert_equal "hello", @response.template.assigns["flashy_that"]
- assert_equal "good-bye", @response.template.assigns["flashy_this"]
- assert_nil @response.template.assigns["flashy_that_reset"]
+ assert_equal "hello", @controller.template.assigns["flashy_that"]
+ assert_equal "good-bye", @controller.template.assigns["flashy_this"]
+ assert_nil @controller.template.assigns["flashy_that_reset"]
end
def test_sweep_after_halted_filter_chain
get :std_action
- assert_nil @response.template.assigns["flash_copy"]["foo"]
+ assert_nil @controller.template.assigns["flash_copy"]["foo"]
get :filter_halting_action
- assert_equal "bar", @response.template.assigns["flash_copy"]["foo"]
+ assert_equal "bar", @controller.template.assigns["flash_copy"]["foo"]
get :std_action # follow redirection
- assert_equal "bar", @response.template.assigns["flash_copy"]["foo"]
+ assert_equal "bar", @controller.template.assigns["flash_copy"]["foo"]
get :std_action
- assert_nil @response.template.assigns["flash_copy"]["foo"]
+ assert_nil @controller.template.assigns["flash_copy"]["foo"]
end
end
diff --git a/actionpack/test/controller/layout_test.rb b/actionpack/test/controller/layout_test.rb
index 11559b4071..da3f7b0cb8 100644
--- a/actionpack/test/controller/layout_test.rb
+++ b/actionpack/test/controller/layout_test.rb
@@ -57,7 +57,7 @@ class LayoutAutoDiscoveryTest < ActionController::TestCase
@controller = ThirdPartyTemplateLibraryController.new
get :hello
assert @controller.active_layout(true).identifier.include?('layouts/third_party_template_library.mab')
- assert @response.layout.include?('layouts/third_party_template_library')
+ assert @controller.template.layout.include?('layouts/third_party_template_library')
assert_response :success
assert_equal 'Mab', @response.body
end
@@ -121,49 +121,49 @@ class LayoutSetInResponseTest < ActionController::TestCase
def test_layout_set_when_using_default_layout
@controller = DefaultLayoutController.new
get :hello
- assert @response.layout.include?('layouts/layout_test')
+ assert @controller.template.layout.include?('layouts/layout_test')
end
def test_layout_set_when_set_in_controller
@controller = HasOwnLayoutController.new
get :hello
- assert @response.layout.include?('layouts/item')
+ assert @controller.template.layout.include?('layouts/item')
end
def test_layout_only_exception_when_included
@controller = OnlyLayoutController.new
get :hello
- assert @response.layout.include?('layouts/item')
+ assert @controller.template.layout.include?('layouts/item')
end
def test_layout_only_exception_when_excepted
@controller = OnlyLayoutController.new
get :goodbye
- assert_equal nil, @response.layout
+ assert_equal nil, @controller.template.layout
end
def test_layout_except_exception_when_included
@controller = ExceptLayoutController.new
get :hello
- assert @response.layout.include?('layouts/item')
+ assert @controller.template.layout.include?('layouts/item')
end
def test_layout_except_exception_when_excepted
@controller = ExceptLayoutController.new
get :goodbye
- assert_equal nil, @response.layout
+ assert_equal nil, @controller.template.layout
end
def test_layout_set_when_using_render
@controller = SetsLayoutInRenderController.new
get :hello
- assert @response.layout.include?('layouts/third_party_template_library')
+ assert @controller.template.layout.include?('layouts/third_party_template_library')
end
def test_layout_is_not_set_when_none_rendered
@controller = RendersNoLayoutController.new
get :hello
- assert_nil @response.layout
+ assert_nil @controller.template.layout
end
def test_exempt_from_layout_honored_by_render_template
@@ -181,7 +181,7 @@ class LayoutSetInResponseTest < ActionController::TestCase
pending do
@controller = PrependsViewPathController.new
get :hello
- assert_equal 'layouts/alt', @response.layout
+ assert_equal 'layouts/alt', @controller.template.layout
end
end
@@ -206,7 +206,7 @@ class LayoutExceptionRaised < ActionController::TestCase
def test_exception_raised_when_layout_file_not_found
@controller = SetsNonExistentLayoutFile.new
get :hello
- assert_kind_of ActionView::MissingTemplate, @response.template.instance_eval { @exception }
+ assert_kind_of ActionView::MissingTemplate, @controller.template.instance_eval { @exception }
end
end
@@ -234,7 +234,7 @@ unless RUBY_PLATFORM =~ /(:?mswin|mingw|bccwin)/
@controller = LayoutSymlinkedTest.new
get :hello
assert_response 200
- assert @response.layout.include?("layouts/symlinked/symlinked_layout")
+ assert @controller.template.layout.include?("layouts/symlinked/symlinked_layout")
end
end
end
diff --git a/actionpack/test/template/body_parts_test.rb b/actionpack/test/template/body_parts_test.rb
index 4c82b75cdc..5be8533293 100644
--- a/actionpack/test/template/body_parts_test.rb
+++ b/actionpack/test/template/body_parts_test.rb
@@ -6,7 +6,7 @@ class BodyPartsTest < ActionController::TestCase
class TestController < ActionController::Base
def index
RENDERINGS.each do |rendering|
- response.template.punctuate_body! rendering
+ @template.punctuate_body! rendering
end
@performed_render = true
end
diff --git a/actionpack/test/template/output_buffer_test.rb b/actionpack/test/template/output_buffer_test.rb
index 6d8eab63dc..bc17f36783 100644
--- a/actionpack/test/template/output_buffer_test.rb
+++ b/actionpack/test/template/output_buffer_test.rb
@@ -13,23 +13,23 @@ class OutputBufferTest < ActionController::TestCase
# Start with the default body parts
get :index
assert_equal ['foo'], @response.body_parts
- assert_nil @response.template.output_buffer
+ assert_nil @controller.template.output_buffer
# Nil output buffer is skipped
- @response.template.flush_output_buffer
- assert_nil @response.template.output_buffer
+ @controller.template.flush_output_buffer
+ assert_nil @controller.template.output_buffer
assert_equal ['foo'], @response.body_parts
# Empty output buffer is skipped
- @response.template.output_buffer = ''
- @response.template.flush_output_buffer
- assert_equal '', @response.template.output_buffer
+ @controller.template.output_buffer = ''
+ @controller.template.flush_output_buffer
+ assert_equal '', @controller.template.output_buffer
assert_equal ['foo'], @response.body_parts
# Flushing appends the output buffer to the body parts
- @response.template.output_buffer = 'bar'
- @response.template.flush_output_buffer
- assert_equal '', @response.template.output_buffer
+ @controller.template.output_buffer = 'bar'
+ @controller.template.flush_output_buffer
+ assert_equal '', @controller.template.output_buffer
assert_equal ['foo', 'bar'], @response.body_parts
end
end
--
cgit v1.2.3
From 7eef11eb657e6efb54dfe782ca2531df93654f83 Mon Sep 17 00:00:00 2001
From: Jeremy Kemper
Date: Wed, 29 Apr 2009 23:29:11 -0700
Subject: Convert params keys to strings
---
actionpack/lib/action_dispatch/test/mock.rb | 1 +
1 file changed, 1 insertion(+)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_dispatch/test/mock.rb b/actionpack/lib/action_dispatch/test/mock.rb
index 4042f9fbc8..68e5b108b4 100644
--- a/actionpack/lib/action_dispatch/test/mock.rb
+++ b/actionpack/lib/action_dispatch/test/mock.rb
@@ -42,6 +42,7 @@ module ActionDispatch
opts[:input] = params
end
else
+ params.stringify_keys!
params.update(::Rack::Utils.parse_query(uri.query))
uri.query = requestify(params)
end
--
cgit v1.2.3
From 988513ac7a0cbd820c9486088256b8ab4e8acf74 Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Thu, 30 Apr 2009 11:40:29 -0500
Subject: Framework backtrace cleaning is handled by ActiveSupport now
---
.../action_controller/testing/assertions/dom.rb | 20 ++--
.../action_controller/testing/assertions/model.rb | 4 +-
.../testing/assertions/response.rb | 108 ++++++++++-----------
.../testing/assertions/routing.rb | 42 ++++----
.../action_controller/testing/assertions/tag.rb | 16 ++-
.../lib/action_controller/testing/test_case.rb | 8 --
actionpack/test/controller/test_test.rb | 27 ------
7 files changed, 85 insertions(+), 140 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/testing/assertions/dom.rb b/actionpack/lib/action_controller/testing/assertions/dom.rb
index 5ffe5f1883..c0e6c68fcd 100644
--- a/actionpack/lib/action_controller/testing/assertions/dom.rb
+++ b/actionpack/lib/action_controller/testing/assertions/dom.rb
@@ -9,13 +9,11 @@ module ActionController
# assert_dom_equal 'Apples', link_to("Apples", "http://www.example.com")
#
def assert_dom_equal(expected, actual, message = "")
- clean_backtrace do
- expected_dom = HTML::Document.new(expected).root
- actual_dom = HTML::Document.new(actual).root
- full_message = build_message(message, "> expected to be == to\n>.", expected_dom.to_s, actual_dom.to_s)
+ expected_dom = HTML::Document.new(expected).root
+ actual_dom = HTML::Document.new(actual).root
+ full_message = build_message(message, "> expected to be == to\n>.", expected_dom.to_s, actual_dom.to_s)
- assert_block(full_message) { expected_dom == actual_dom }
- end
+ assert_block(full_message) { expected_dom == actual_dom }
end
# The negated form of +assert_dom_equivalent+.
@@ -26,13 +24,11 @@ module ActionController
# assert_dom_not_equal 'Apples', link_to("Oranges", "http://www.example.com")
#
def assert_dom_not_equal(expected, actual, message = "")
- clean_backtrace do
- expected_dom = HTML::Document.new(expected).root
- actual_dom = HTML::Document.new(actual).root
- full_message = build_message(message, "> expected to be != to\n>.", expected_dom.to_s, actual_dom.to_s)
+ expected_dom = HTML::Document.new(expected).root
+ actual_dom = HTML::Document.new(actual).root
+ full_message = build_message(message, "> expected to be != to\n>.", expected_dom.to_s, actual_dom.to_s)
- assert_block(full_message) { expected_dom != actual_dom }
- end
+ assert_block(full_message) { expected_dom != actual_dom }
end
end
end
diff --git a/actionpack/lib/action_controller/testing/assertions/model.rb b/actionpack/lib/action_controller/testing/assertions/model.rb
index 3a7b39b106..93e3bcf456 100644
--- a/actionpack/lib/action_controller/testing/assertions/model.rb
+++ b/actionpack/lib/action_controller/testing/assertions/model.rb
@@ -12,9 +12,7 @@ module ActionController
#
def assert_valid(record)
::ActiveSupport::Deprecation.warn("assert_valid is deprecated. Use assert record.valid? instead", caller)
- clean_backtrace do
- assert record.valid?, record.errors.full_messages.join("\n")
- end
+ assert record.valid?, record.errors.full_messages.join("\n")
end
end
end
diff --git a/actionpack/lib/action_controller/testing/assertions/response.rb b/actionpack/lib/action_controller/testing/assertions/response.rb
index 684fe1ffe0..7b2936e26c 100644
--- a/actionpack/lib/action_controller/testing/assertions/response.rb
+++ b/actionpack/lib/action_controller/testing/assertions/response.rb
@@ -24,21 +24,19 @@ module ActionController
def assert_response(type, message = nil)
validate_request!
- clean_backtrace do
- if [ :success, :missing, :redirect, :error ].include?(type) && @response.send("#{type}?")
- assert_block("") { true } # to count the assertion
- elsif type.is_a?(Fixnum) && @response.response_code == type
- assert_block("") { true } # to count the assertion
- elsif type.is_a?(Symbol) && @response.response_code == ActionDispatch::StatusCodes::SYMBOL_TO_STATUS_CODE[type]
- assert_block("") { true } # to count the assertion
+ if [ :success, :missing, :redirect, :error ].include?(type) && @response.send("#{type}?")
+ assert_block("") { true } # to count the assertion
+ elsif type.is_a?(Fixnum) && @response.response_code == type
+ assert_block("") { true } # to count the assertion
+ elsif type.is_a?(Symbol) && @response.response_code == ActionDispatch::StatusCodes::SYMBOL_TO_STATUS_CODE[type]
+ assert_block("") { true } # to count the assertion
+ else
+ if @controller && @response.error?
+ exception = @controller.template.instance_variable_get(:@exception)
+ exception_message = exception && exception.message
+ assert_block(build_message(message, "Expected response to be a >, but was >\n>", type, @response.response_code, exception_message.to_s)) { false }
else
- if @controller && @response.error?
- exception = @controller.template.instance_variable_get(:@exception)
- exception_message = exception && exception.message
- assert_block(build_message(message, "Expected response to be a >, but was >\n>", type, @response.response_code, exception_message.to_s)) { false }
- else
- assert_block(build_message(message, "Expected response to be a >, but was >", type, @response.response_code)) { false }
- end
+ assert_block(build_message(message, "Expected response to be a >, but was >", type, @response.response_code)) { false }
end
end
end
@@ -61,21 +59,19 @@ module ActionController
def assert_redirected_to(options = {}, message=nil)
validate_request!
- clean_backtrace do
- assert_response(:redirect, message)
- return true if options == @response.redirected_to
+ assert_response(:redirect, message)
+ return true if options == @response.redirected_to
- # Support partial arguments for hash redirections
- if options.is_a?(Hash) && @response.redirected_to.is_a?(Hash)
- return true if options.all? {|(key, value)| @response.redirected_to[key] == value}
- end
+ # Support partial arguments for hash redirections
+ if options.is_a?(Hash) && @response.redirected_to.is_a?(Hash)
+ return true if options.all? {|(key, value)| @response.redirected_to[key] == value}
+ end
- redirected_to_after_normalisation = normalize_argument_to_redirection(@response.redirected_to)
- options_after_normalisation = normalize_argument_to_redirection(options)
+ redirected_to_after_normalisation = normalize_argument_to_redirection(@response.redirected_to)
+ options_after_normalisation = normalize_argument_to_redirection(options)
- if redirected_to_after_normalisation != options_after_normalisation
- flunk "Expected response to be a redirect to <#{options_after_normalisation}> but was a redirect to <#{redirected_to_after_normalisation}>"
- end
+ if redirected_to_after_normalisation != options_after_normalisation
+ flunk "Expected response to be a redirect to <#{options_after_normalisation}> but was a redirect to <#{redirected_to_after_normalisation}>"
end
end
@@ -95,40 +91,38 @@ module ActionController
def assert_template(options = {}, message = nil)
validate_request!
- clean_backtrace do
- case options
- when NilClass, String
- rendered = (@controller.template.rendered[:template] || []).map { |t| t.identifier }
- msg = build_message(message,
- "expecting > but rendering with >",
- options, rendered.join(', '))
- assert_block(msg) do
- if options.nil?
- @controller.template.rendered[:template].blank?
- else
- rendered.any? { |t| t.match(options) }
- end
+ case options
+ when NilClass, String
+ rendered = (@controller.template.rendered[:template] || []).map { |t| t.identifier }
+ msg = build_message(message,
+ "expecting > but rendering with >",
+ options, rendered.join(', '))
+ assert_block(msg) do
+ if options.nil?
+ @controller.template.rendered[:template].blank?
+ else
+ rendered.any? { |t| t.match(options) }
end
- when Hash
- if expected_partial = options[:partial]
- partials = @controller.template.rendered[:partials]
- if expected_count = options[:count]
- found = partials.detect { |p, _| p.identifier.match(expected_partial) }
- actual_count = found.nil? ? 0 : found.second
- msg = build_message(message,
- "expecting ? to be rendered ? time(s) but rendered ? time(s)",
- expected_partial, expected_count, actual_count)
- assert(actual_count == expected_count.to_i, msg)
- else
- msg = build_message(message,
- "expecting partial > but action rendered >",
- options[:partial], partials.keys)
- assert(partials.keys.any? { |p| p.identifier.match(expected_partial) }, msg)
- end
+ end
+ when Hash
+ if expected_partial = options[:partial]
+ partials = @controller.template.rendered[:partials]
+ if expected_count = options[:count]
+ found = partials.detect { |p, _| p.identifier.match(expected_partial) }
+ actual_count = found.nil? ? 0 : found.second
+ msg = build_message(message,
+ "expecting ? to be rendered ? time(s) but rendered ? time(s)",
+ expected_partial, expected_count, actual_count)
+ assert(actual_count == expected_count.to_i, msg)
else
- assert @controller.template.rendered[:partials].empty?,
- "Expected no partials to be rendered"
+ msg = build_message(message,
+ "expecting partial > but action rendered >",
+ options[:partial], partials.keys)
+ assert(partials.keys.any? { |p| p.identifier.match(expected_partial) }, msg)
end
+ else
+ assert @controller.template.rendered[:partials].empty?,
+ "Expected no partials to be rendered"
end
end
end
diff --git a/actionpack/lib/action_controller/testing/assertions/routing.rb b/actionpack/lib/action_controller/testing/assertions/routing.rb
index 5101751cea..f3f4f54fe3 100644
--- a/actionpack/lib/action_controller/testing/assertions/routing.rb
+++ b/actionpack/lib/action_controller/testing/assertions/routing.rb
@@ -44,19 +44,17 @@ module ActionController
request_method = nil
end
- clean_backtrace do
- ActionController::Routing::Routes.reload if ActionController::Routing::Routes.empty?
- request = recognized_request_for(path, request_method)
+ ActionController::Routing::Routes.reload if ActionController::Routing::Routes.empty?
+ request = recognized_request_for(path, request_method)
- expected_options = expected_options.clone
- extras.each_key { |key| expected_options.delete key } unless extras.nil?
+ expected_options = expected_options.clone
+ extras.each_key { |key| expected_options.delete key } unless extras.nil?
- expected_options.stringify_keys!
- routing_diff = expected_options.diff(request.path_parameters)
- msg = build_message(message, "The recognized options > did not match >, difference: >",
- request.path_parameters, expected_options, expected_options.diff(request.path_parameters))
- assert_block(msg) { request.path_parameters == expected_options }
- end
+ expected_options.stringify_keys!
+ routing_diff = expected_options.diff(request.path_parameters)
+ msg = build_message(message, "The recognized options > did not match >, difference: >",
+ request.path_parameters, expected_options, expected_options.diff(request.path_parameters))
+ assert_block(msg) { request.path_parameters == expected_options }
end
# Asserts that the provided options can be used to generate the provided path. This is the inverse of +assert_recognizes+.
@@ -78,21 +76,19 @@ module ActionController
# # Asserts that the generated route gives us our custom route
# assert_generates "changesets/12", { :controller => 'scm', :action => 'show_diff', :revision => "12" }
def assert_generates(expected_path, options, defaults={}, extras = {}, message=nil)
- clean_backtrace do
- expected_path = "/#{expected_path}" unless expected_path[0] == ?/
- # Load routes.rb if it hasn't been loaded.
- ActionController::Routing::Routes.reload if ActionController::Routing::Routes.empty?
+ expected_path = "/#{expected_path}" unless expected_path[0] == ?/
+ # Load routes.rb if it hasn't been loaded.
+ ActionController::Routing::Routes.reload if ActionController::Routing::Routes.empty?
- generated_path, extra_keys = ActionController::Routing::Routes.generate_extras(options, defaults)
- found_extras = options.reject {|k, v| ! extra_keys.include? k}
+ generated_path, extra_keys = ActionController::Routing::Routes.generate_extras(options, defaults)
+ found_extras = options.reject {|k, v| ! extra_keys.include? k}
- msg = build_message(message, "found extras >, not >", found_extras, extras)
- assert_block(msg) { found_extras == extras }
+ msg = build_message(message, "found extras >, not >", found_extras, extras)
+ assert_block(msg) { found_extras == extras }
- msg = build_message(message, "The generated path > did not match >", generated_path,
- expected_path)
- assert_block(msg) { expected_path == generated_path }
- end
+ msg = build_message(message, "The generated path > did not match >", generated_path,
+ expected_path)
+ assert_block(msg) { expected_path == generated_path }
end
# Asserts that path and options match both ways; in other words, it verifies that path generates
diff --git a/actionpack/lib/action_controller/testing/assertions/tag.rb b/actionpack/lib/action_controller/testing/assertions/tag.rb
index 80249e0e83..d9197b7855 100644
--- a/actionpack/lib/action_controller/testing/assertions/tag.rb
+++ b/actionpack/lib/action_controller/testing/assertions/tag.rb
@@ -94,11 +94,9 @@ module ActionController
# that allow optional closing tags (p, li, td). You must explicitly
# close all of your tags to use these assertions.
def assert_tag(*opts)
- clean_backtrace do
- opts = opts.size > 1 ? opts.last.merge({ :tag => opts.first.to_s }) : opts.first
- tag = find_tag(opts)
- assert tag, "expected tag, but no tag found matching #{opts.inspect} in:\n#{@response.body.inspect}"
- end
+ opts = opts.size > 1 ? opts.last.merge({ :tag => opts.first.to_s }) : opts.first
+ tag = find_tag(opts)
+ assert tag, "expected tag, but no tag found matching #{opts.inspect} in:\n#{@response.body.inspect}"
end
# Identical to +assert_tag+, but asserts that a matching tag does _not_
@@ -116,11 +114,9 @@ module ActionController
# assert_no_tag :tag => "p",
# :children => { :count => 1..3, :only => { :tag => "img" } }
def assert_no_tag(*opts)
- clean_backtrace do
- opts = opts.size > 1 ? opts.last.merge({ :tag => opts.first.to_s }) : opts.first
- tag = find_tag(opts)
- assert !tag, "expected no tag, but found tag matching #{opts.inspect} in:\n#{@response.body.inspect}"
- end
+ opts = opts.size > 1 ? opts.last.merge({ :tag => opts.first.to_s }) : opts.first
+ tag = find_tag(opts)
+ assert !tag, "expected no tag, but found tag matching #{opts.inspect} in:\n#{@response.body.inspect}"
end
end
end
diff --git a/actionpack/lib/action_controller/testing/test_case.rb b/actionpack/lib/action_controller/testing/test_case.rb
index b020b755a0..a80488e13e 100644
--- a/actionpack/lib/action_controller/testing/test_case.rb
+++ b/actionpack/lib/action_controller/testing/test_case.rb
@@ -109,14 +109,6 @@ module ActionController
%w(response selector tag dom routing model).each do |kind|
include ActionController::Assertions.const_get("#{kind.camelize}Assertions")
end
-
- def clean_backtrace(&block)
- yield
- rescue ActiveSupport::TestCase::Assertion => error
- framework_path = Regexp.new(File.expand_path("#{File.dirname(__FILE__)}/assertions"))
- error.backtrace.reject! { |line| File.expand_path(line) =~ framework_path }
- raise
- end
end
include Assertions
diff --git a/actionpack/test/controller/test_test.rb b/actionpack/test/controller/test_test.rb
index f68ffc7a2a..b372980242 100644
--- a/actionpack/test/controller/test_test.rb
+++ b/actionpack/test/controller/test_test.rb
@@ -629,33 +629,6 @@ XML
end
end
-class CleanBacktraceTest < ActionController::TestCase
- def test_should_reraise_the_same_object
- exception = ActiveSupport::TestCase::Assertion.new('message')
- clean_backtrace { raise exception }
- rescue Exception => caught
- assert_equal exception.object_id, caught.object_id
- assert_equal exception.message, caught.message
- end
-
- def test_should_clean_assertion_lines_from_backtrace
- path = File.expand_path("#{File.dirname(__FILE__)}/../../lib/action_controller/testing")
- exception = ActiveSupport::TestCase::Assertion.new('message')
- exception.set_backtrace ["#{path}/abc", "#{path}/assertions/def"]
- clean_backtrace { raise exception }
- rescue Exception => caught
- assert_equal ["#{path}/abc"], caught.backtrace
- end
-
- def test_should_only_clean_assertion_failure_errors
- clean_backtrace do
- raise "can't touch this", [File.expand_path("#{File.dirname(__FILE__)}/../../lib/action_controller/assertions/abc")]
- end
- rescue => caught
- assert !caught.backtrace.empty?
- end
-end
-
class InferringClassNameTest < ActionController::TestCase
def test_determine_controller_class
assert_equal ContentController, determine_class("ContentControllerTest")
--
cgit v1.2.3
From 98dd726687259b96fad15cc073c610fda7fc1023 Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Thu, 30 Apr 2009 11:41:43 -0500
Subject: Test::Unit work arounds are handled by ActiveSupport
---
.../lib/action_controller/testing/integration.rb | 49 ----------------------
1 file changed, 49 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/testing/integration.rb b/actionpack/lib/action_controller/testing/integration.rb
index 037463e489..f960698566 100644
--- a/actionpack/lib/action_controller/testing/integration.rb
+++ b/actionpack/lib/action_controller/testing/integration.rb
@@ -508,54 +508,5 @@ module ActionController
# end
class IntegrationTest < ActiveSupport::TestCase
include Integration::Runner
-
- # Work around a bug in test/unit caused by the default test being named
- # as a symbol (:default_test), which causes regex test filters
- # (like "ruby test.rb -n /foo/") to fail because =~ doesn't work on
- # symbols.
- def initialize(name) #:nodoc:
- super(name.to_s)
- end
-
- # Work around test/unit's requirement that every subclass of TestCase have
- # at least one test method. Note that this implementation extends to all
- # subclasses, as well, so subclasses of IntegrationTest may also exist
- # without any test methods.
- def run(*args) #:nodoc:
- return if @method_name == "default_test"
- super
- end
-
- # Because of how use_instantiated_fixtures and use_transactional_fixtures
- # are defined, we need to treat them as special cases. Otherwise, users
- # would potentially have to set their values for both Test::Unit::TestCase
- # ActionController::IntegrationTest, since by the time the value is set on
- # TestCase, IntegrationTest has already been defined and cannot inherit
- # changes to those variables. So, we make those two attributes
- # copy-on-write.
-
- class << self
- def use_transactional_fixtures=(flag) #:nodoc:
- @_use_transactional_fixtures = true
- @use_transactional_fixtures = flag
- end
-
- def use_instantiated_fixtures=(flag) #:nodoc:
- @_use_instantiated_fixtures = true
- @use_instantiated_fixtures = flag
- end
-
- def use_transactional_fixtures #:nodoc:
- @_use_transactional_fixtures ?
- @use_transactional_fixtures :
- superclass.use_transactional_fixtures
- end
-
- def use_instantiated_fixtures #:nodoc:
- @_use_instantiated_fixtures ?
- @use_instantiated_fixtures :
- superclass.use_instantiated_fixtures
- end
- end
end
end
--
cgit v1.2.3
From 7b3b7cb2ab1ccf96d4c8a1bafd87dbfbd2ac8c84 Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Thu, 30 Apr 2009 11:55:53 -0500
Subject: Move generic assertions into ActionDispatch
---
.../action_controller/testing/assertions/dom.rb | 35 --
.../action_controller/testing/assertions/model.rb | 19 -
.../testing/assertions/response.rb | 156 -----
.../testing/assertions/routing.rb | 142 -----
.../testing/assertions/selector.rb | 632 ---------------------
.../action_controller/testing/assertions/tag.rb | 123 ----
.../lib/action_controller/testing/integration.rb | 2 +-
.../lib/action_controller/testing/test_case.rb | 7 +-
actionpack/lib/action_dispatch.rb | 2 +
.../lib/action_dispatch/testing/assertions.rb | 8 +
.../lib/action_dispatch/testing/assertions/dom.rb | 35 ++
.../action_dispatch/testing/assertions/model.rb | 19 +
.../action_dispatch/testing/assertions/response.rb | 156 +++++
.../action_dispatch/testing/assertions/routing.rb | 142 +++++
.../action_dispatch/testing/assertions/selector.rb | 632 +++++++++++++++++++++
.../lib/action_dispatch/testing/assertions/tag.rb | 123 ++++
actionpack/lib/action_view/test_case.rb | 2 +-
17 files changed, 1120 insertions(+), 1115 deletions(-)
delete mode 100644 actionpack/lib/action_controller/testing/assertions/dom.rb
delete mode 100644 actionpack/lib/action_controller/testing/assertions/model.rb
delete mode 100644 actionpack/lib/action_controller/testing/assertions/response.rb
delete mode 100644 actionpack/lib/action_controller/testing/assertions/routing.rb
delete mode 100644 actionpack/lib/action_controller/testing/assertions/selector.rb
delete mode 100644 actionpack/lib/action_controller/testing/assertions/tag.rb
create mode 100644 actionpack/lib/action_dispatch/testing/assertions.rb
create mode 100644 actionpack/lib/action_dispatch/testing/assertions/dom.rb
create mode 100644 actionpack/lib/action_dispatch/testing/assertions/model.rb
create mode 100644 actionpack/lib/action_dispatch/testing/assertions/response.rb
create mode 100644 actionpack/lib/action_dispatch/testing/assertions/routing.rb
create mode 100644 actionpack/lib/action_dispatch/testing/assertions/selector.rb
create mode 100644 actionpack/lib/action_dispatch/testing/assertions/tag.rb
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/testing/assertions/dom.rb b/actionpack/lib/action_controller/testing/assertions/dom.rb
deleted file mode 100644
index c0e6c68fcd..0000000000
--- a/actionpack/lib/action_controller/testing/assertions/dom.rb
+++ /dev/null
@@ -1,35 +0,0 @@
-module ActionController
- module Assertions
- module DomAssertions
- # Test two HTML strings for equivalency (e.g., identical up to reordering of attributes)
- #
- # ==== Examples
- #
- # # assert that the referenced method generates the appropriate HTML string
- # assert_dom_equal 'Apples', link_to("Apples", "http://www.example.com")
- #
- def assert_dom_equal(expected, actual, message = "")
- expected_dom = HTML::Document.new(expected).root
- actual_dom = HTML::Document.new(actual).root
- full_message = build_message(message, "> expected to be == to\n>.", expected_dom.to_s, actual_dom.to_s)
-
- assert_block(full_message) { expected_dom == actual_dom }
- end
-
- # The negated form of +assert_dom_equivalent+.
- #
- # ==== Examples
- #
- # # assert that the referenced method does not generate the specified HTML string
- # assert_dom_not_equal 'Apples', link_to("Oranges", "http://www.example.com")
- #
- def assert_dom_not_equal(expected, actual, message = "")
- expected_dom = HTML::Document.new(expected).root
- actual_dom = HTML::Document.new(actual).root
- full_message = build_message(message, "> expected to be != to\n>.", expected_dom.to_s, actual_dom.to_s)
-
- assert_block(full_message) { expected_dom != actual_dom }
- end
- end
- end
-end
diff --git a/actionpack/lib/action_controller/testing/assertions/model.rb b/actionpack/lib/action_controller/testing/assertions/model.rb
deleted file mode 100644
index 93e3bcf456..0000000000
--- a/actionpack/lib/action_controller/testing/assertions/model.rb
+++ /dev/null
@@ -1,19 +0,0 @@
-module ActionController
- module Assertions
- module ModelAssertions
- # Ensures that the passed record is valid by Active Record standards and
- # returns any error messages if it is not.
- #
- # ==== Examples
- #
- # # assert that a newly created record is valid
- # model = Model.new
- # assert_valid(model)
- #
- def assert_valid(record)
- ::ActiveSupport::Deprecation.warn("assert_valid is deprecated. Use assert record.valid? instead", caller)
- assert record.valid?, record.errors.full_messages.join("\n")
- end
- end
- end
-end
diff --git a/actionpack/lib/action_controller/testing/assertions/response.rb b/actionpack/lib/action_controller/testing/assertions/response.rb
deleted file mode 100644
index 7b2936e26c..0000000000
--- a/actionpack/lib/action_controller/testing/assertions/response.rb
+++ /dev/null
@@ -1,156 +0,0 @@
-module ActionController
- module Assertions
- # A small suite of assertions that test responses from Rails applications.
- module ResponseAssertions
- # Asserts that the response is one of the following types:
- #
- # * :success - Status code was 200
- # * :redirect - Status code was in the 300-399 range
- # * :missing - Status code was 404
- # * :error - Status code was in the 500-599 range
- #
- # You can also pass an explicit status number like assert_response(501)
- # or its symbolic equivalent assert_response(:not_implemented).
- # See ActionDispatch::StatusCodes for a full list.
- #
- # ==== Examples
- #
- # # assert that the response was a redirection
- # assert_response :redirect
- #
- # # assert that the response code was status code 401 (unauthorized)
- # assert_response 401
- #
- def assert_response(type, message = nil)
- validate_request!
-
- if [ :success, :missing, :redirect, :error ].include?(type) && @response.send("#{type}?")
- assert_block("") { true } # to count the assertion
- elsif type.is_a?(Fixnum) && @response.response_code == type
- assert_block("") { true } # to count the assertion
- elsif type.is_a?(Symbol) && @response.response_code == ActionDispatch::StatusCodes::SYMBOL_TO_STATUS_CODE[type]
- assert_block("") { true } # to count the assertion
- else
- if @controller && @response.error?
- exception = @controller.template.instance_variable_get(:@exception)
- exception_message = exception && exception.message
- assert_block(build_message(message, "Expected response to be a >, but was >\n>", type, @response.response_code, exception_message.to_s)) { false }
- else
- assert_block(build_message(message, "Expected response to be a >, but was >", type, @response.response_code)) { false }
- end
- end
- end
-
- # Assert that the redirection options passed in match those of the redirect called in the latest action.
- # This match can be partial, such that assert_redirected_to(:controller => "weblog") will also
- # match the redirection of redirect_to(:controller => "weblog", :action => "show") and so on.
- #
- # ==== Examples
- #
- # # assert that the redirection was to the "index" action on the WeblogController
- # assert_redirected_to :controller => "weblog", :action => "index"
- #
- # # assert that the redirection was to the named route login_url
- # assert_redirected_to login_url
- #
- # # assert that the redirection was to the url for @customer
- # assert_redirected_to @customer
- #
- def assert_redirected_to(options = {}, message=nil)
- validate_request!
-
- assert_response(:redirect, message)
- return true if options == @response.redirected_to
-
- # Support partial arguments for hash redirections
- if options.is_a?(Hash) && @response.redirected_to.is_a?(Hash)
- return true if options.all? {|(key, value)| @response.redirected_to[key] == value}
- end
-
- redirected_to_after_normalisation = normalize_argument_to_redirection(@response.redirected_to)
- options_after_normalisation = normalize_argument_to_redirection(options)
-
- if redirected_to_after_normalisation != options_after_normalisation
- flunk "Expected response to be a redirect to <#{options_after_normalisation}> but was a redirect to <#{redirected_to_after_normalisation}>"
- end
- end
-
- # Asserts that the request was rendered with the appropriate template file or partials
- #
- # ==== Examples
- #
- # # assert that the "new" view template was rendered
- # assert_template "new"
- #
- # # assert that the "_customer" partial was rendered twice
- # assert_template :partial => '_customer', :count => 2
- #
- # # assert that no partials were rendered
- # assert_template :partial => false
- #
- def assert_template(options = {}, message = nil)
- validate_request!
-
- case options
- when NilClass, String
- rendered = (@controller.template.rendered[:template] || []).map { |t| t.identifier }
- msg = build_message(message,
- "expecting > but rendering with >",
- options, rendered.join(', '))
- assert_block(msg) do
- if options.nil?
- @controller.template.rendered[:template].blank?
- else
- rendered.any? { |t| t.match(options) }
- end
- end
- when Hash
- if expected_partial = options[:partial]
- partials = @controller.template.rendered[:partials]
- if expected_count = options[:count]
- found = partials.detect { |p, _| p.identifier.match(expected_partial) }
- actual_count = found.nil? ? 0 : found.second
- msg = build_message(message,
- "expecting ? to be rendered ? time(s) but rendered ? time(s)",
- expected_partial, expected_count, actual_count)
- assert(actual_count == expected_count.to_i, msg)
- else
- msg = build_message(message,
- "expecting partial > but action rendered >",
- options[:partial], partials.keys)
- assert(partials.keys.any? { |p| p.identifier.match(expected_partial) }, msg)
- end
- else
- assert @controller.template.rendered[:partials].empty?,
- "Expected no partials to be rendered"
- end
- end
- end
-
- private
- # Proxy to to_param if the object will respond to it.
- def parameterize(value)
- value.respond_to?(:to_param) ? value.to_param : value
- end
-
- def normalize_argument_to_redirection(fragment)
- after_routing = @controller.url_for(fragment)
- if after_routing =~ %r{^\w+://.*}
- after_routing
- else
- # FIXME - this should probably get removed.
- if after_routing.first != '/'
- after_routing = '/' + after_routing
- end
- @request.protocol + @request.host_with_port + after_routing
- end
- end
-
- def validate_request!
- unless @request.is_a?(ActionDispatch::Request)
- raise ArgumentError, "@request must be an ActionDispatch::Request"
- end
- end
- end
- end
-end
diff --git a/actionpack/lib/action_controller/testing/assertions/routing.rb b/actionpack/lib/action_controller/testing/assertions/routing.rb
deleted file mode 100644
index f3f4f54fe3..0000000000
--- a/actionpack/lib/action_controller/testing/assertions/routing.rb
+++ /dev/null
@@ -1,142 +0,0 @@
-module ActionController
- module Assertions
- # Suite of assertions to test routes generated by Rails and the handling of requests made to them.
- module RoutingAssertions
- # Asserts that the routing of the given +path+ was handled correctly and that the parsed options (given in the +expected_options+ hash)
- # match +path+. Basically, it asserts that Rails recognizes the route given by +expected_options+.
- #
- # Pass a hash in the second argument (+path+) to specify the request method. This is useful for routes
- # requiring a specific HTTP method. The hash should contain a :path with the incoming request path
- # and a :method containing the required HTTP verb.
- #
- # # assert that POSTing to /items will call the create action on ItemsController
- # assert_recognizes {:controller => 'items', :action => 'create'}, {:path => 'items', :method => :post}
- #
- # You can also pass in +extras+ with a hash containing URL parameters that would normally be in the query string. This can be used
- # to assert that values in the query string string will end up in the params hash correctly. To test query strings you must use the
- # extras argument, appending the query string on the path directly will not work. For example:
- #
- # # assert that a path of '/items/list/1?view=print' returns the correct options
- # assert_recognizes {:controller => 'items', :action => 'list', :id => '1', :view => 'print'}, 'items/list/1', { :view => "print" }
- #
- # The +message+ parameter allows you to pass in an error message that is displayed upon failure.
- #
- # ==== Examples
- # # Check the default route (i.e., the index action)
- # assert_recognizes {:controller => 'items', :action => 'index'}, 'items'
- #
- # # Test a specific action
- # assert_recognizes {:controller => 'items', :action => 'list'}, 'items/list'
- #
- # # Test an action with a parameter
- # assert_recognizes {:controller => 'items', :action => 'destroy', :id => '1'}, 'items/destroy/1'
- #
- # # Test a custom route
- # assert_recognizes {:controller => 'items', :action => 'show', :id => '1'}, 'view/item1'
- #
- # # Check a Simply RESTful generated route
- # assert_recognizes list_items_url, 'items/list'
- def assert_recognizes(expected_options, path, extras={}, message=nil)
- if path.is_a? Hash
- request_method = path[:method]
- path = path[:path]
- else
- request_method = nil
- end
-
- ActionController::Routing::Routes.reload if ActionController::Routing::Routes.empty?
- request = recognized_request_for(path, request_method)
-
- expected_options = expected_options.clone
- extras.each_key { |key| expected_options.delete key } unless extras.nil?
-
- expected_options.stringify_keys!
- routing_diff = expected_options.diff(request.path_parameters)
- msg = build_message(message, "The recognized options > did not match >, difference: >",
- request.path_parameters, expected_options, expected_options.diff(request.path_parameters))
- assert_block(msg) { request.path_parameters == expected_options }
- end
-
- # Asserts that the provided options can be used to generate the provided path. This is the inverse of +assert_recognizes+.
- # The +extras+ parameter is used to tell the request the names and values of additional request parameters that would be in
- # a query string. The +message+ parameter allows you to specify a custom error message for assertion failures.
- #
- # The +defaults+ parameter is unused.
- #
- # ==== Examples
- # # Asserts that the default action is generated for a route with no action
- # assert_generates "/items", :controller => "items", :action => "index"
- #
- # # Tests that the list action is properly routed
- # assert_generates "/items/list", :controller => "items", :action => "list"
- #
- # # Tests the generation of a route with a parameter
- # assert_generates "/items/list/1", { :controller => "items", :action => "list", :id => "1" }
- #
- # # Asserts that the generated route gives us our custom route
- # assert_generates "changesets/12", { :controller => 'scm', :action => 'show_diff', :revision => "12" }
- def assert_generates(expected_path, options, defaults={}, extras = {}, message=nil)
- expected_path = "/#{expected_path}" unless expected_path[0] == ?/
- # Load routes.rb if it hasn't been loaded.
- ActionController::Routing::Routes.reload if ActionController::Routing::Routes.empty?
-
- generated_path, extra_keys = ActionController::Routing::Routes.generate_extras(options, defaults)
- found_extras = options.reject {|k, v| ! extra_keys.include? k}
-
- msg = build_message(message, "found extras >, not >", found_extras, extras)
- assert_block(msg) { found_extras == extras }
-
- msg = build_message(message, "The generated path > did not match >", generated_path,
- expected_path)
- assert_block(msg) { expected_path == generated_path }
- end
-
- # Asserts that path and options match both ways; in other words, it verifies that path generates
- # options and then that options generates path. This essentially combines +assert_recognizes+
- # and +assert_generates+ into one step.
- #
- # The +extras+ hash allows you to specify options that would normally be provided as a query string to the action. The
- # +message+ parameter allows you to specify a custom error message to display upon failure.
- #
- # ==== Examples
- # # Assert a basic route: a controller with the default action (index)
- # assert_routing '/home', :controller => 'home', :action => 'index'
- #
- # # Test a route generated with a specific controller, action, and parameter (id)
- # assert_routing '/entries/show/23', :controller => 'entries', :action => 'show', id => 23
- #
- # # Assert a basic route (controller + default action), with an error message if it fails
- # assert_routing '/store', { :controller => 'store', :action => 'index' }, {}, {}, 'Route for store index not generated properly'
- #
- # # Tests a route, providing a defaults hash
- # assert_routing 'controller/action/9', {:id => "9", :item => "square"}, {:controller => "controller", :action => "action"}, {}, {:item => "square"}
- #
- # # Tests a route with a HTTP method
- # assert_routing { :method => 'put', :path => '/product/321' }, { :controller => "product", :action => "update", :id => "321" }
- def assert_routing(path, options, defaults={}, extras={}, message=nil)
- assert_recognizes(options, path, extras, message)
-
- controller, default_controller = options[:controller], defaults[:controller]
- if controller && controller.include?(?/) && default_controller && default_controller.include?(?/)
- options[:controller] = "/#{controller}"
- end
-
- assert_generates(path.is_a?(Hash) ? path[:path] : path, options, defaults, extras, message)
- end
-
- private
- # Recognizes the route for a given path.
- def recognized_request_for(path, request_method = nil)
- path = "/#{path}" unless path.first == '/'
-
- # Assume given controller
- request = ActionController::TestRequest.new
- request.env["REQUEST_METHOD"] = request_method.to_s.upcase if request_method
- request.path = path
-
- ActionController::Routing::Routes.recognize(request)
- request
- end
- end
- end
-end
diff --git a/actionpack/lib/action_controller/testing/assertions/selector.rb b/actionpack/lib/action_controller/testing/assertions/selector.rb
deleted file mode 100644
index 0d56ea5ef7..0000000000
--- a/actionpack/lib/action_controller/testing/assertions/selector.rb
+++ /dev/null
@@ -1,632 +0,0 @@
-#--
-# Copyright (c) 2006 Assaf Arkin (http://labnotes.org)
-# Under MIT and/or CC By license.
-#++
-
-module ActionController
- module Assertions
- unless const_defined?(:NO_STRIP)
- NO_STRIP = %w{pre script style textarea}
- end
-
- # Adds the +assert_select+ method for use in Rails functional
- # test cases, which can be used to make assertions on the response HTML of a controller
- # action. You can also call +assert_select+ within another +assert_select+ to
- # make assertions on elements selected by the enclosing assertion.
- #
- # Use +css_select+ to select elements without making an assertions, either
- # from the response HTML or elements selected by the enclosing assertion.
- #
- # In addition to HTML responses, you can make the following assertions:
- # * +assert_select_rjs+ - Assertions on HTML content of RJS update and insertion operations.
- # * +assert_select_encoded+ - Assertions on HTML encoded inside XML, for example for dealing with feed item descriptions.
- # * +assert_select_email+ - Assertions on the HTML body of an e-mail.
- #
- # Also see HTML::Selector to learn how to use selectors.
- module SelectorAssertions
- # :call-seq:
- # css_select(selector) => array
- # css_select(element, selector) => array
- #
- # Select and return all matching elements.
- #
- # If called with a single argument, uses that argument as a selector
- # to match all elements of the current page. Returns an empty array
- # if no match is found.
- #
- # If called with two arguments, uses the first argument as the base
- # element and the second argument as the selector. Attempts to match the
- # base element and any of its children. Returns an empty array if no
- # match is found.
- #
- # The selector may be a CSS selector expression (String), an expression
- # with substitution values (Array) or an HTML::Selector object.
- #
- # ==== Examples
- # # Selects all div tags
- # divs = css_select("div")
- #
- # # Selects all paragraph tags and does something interesting
- # pars = css_select("p")
- # pars.each do |par|
- # # Do something fun with paragraphs here...
- # end
- #
- # # Selects all list items in unordered lists
- # items = css_select("ul>li")
- #
- # # Selects all form tags and then all inputs inside the form
- # forms = css_select("form")
- # forms.each do |form|
- # inputs = css_select(form, "input")
- # ...
- # end
- #
- def css_select(*args)
- # See assert_select to understand what's going on here.
- arg = args.shift
-
- if arg.is_a?(HTML::Node)
- root = arg
- arg = args.shift
- elsif arg == nil
- raise ArgumentError, "First argument is either selector or element to select, but nil found. Perhaps you called assert_select with an element that does not exist?"
- elsif @selected
- matches = []
-
- @selected.each do |selected|
- subset = css_select(selected, HTML::Selector.new(arg.dup, args.dup))
- subset.each do |match|
- matches << match unless matches.any? { |m| m.equal?(match) }
- end
- end
-
- return matches
- else
- root = response_from_page_or_rjs
- end
-
- case arg
- when String
- selector = HTML::Selector.new(arg, args)
- when Array
- selector = HTML::Selector.new(*arg)
- when HTML::Selector
- selector = arg
- else raise ArgumentError, "Expecting a selector as the first argument"
- end
-
- selector.select(root)
- end
-
- # :call-seq:
- # assert_select(selector, equality?, message?)
- # assert_select(element, selector, equality?, message?)
- #
- # An assertion that selects elements and makes one or more equality tests.
- #
- # If the first argument is an element, selects all matching elements
- # starting from (and including) that element and all its children in
- # depth-first order.
- #
- # If no element if specified, calling +assert_select+ selects from the
- # response HTML unless +assert_select+ is called from within an +assert_select+ block.
- #
- # When called with a block +assert_select+ passes an array of selected elements
- # to the block. Calling +assert_select+ from the block, with no element specified,
- # runs the assertion on the complete set of elements selected by the enclosing assertion.
- # Alternatively the array may be iterated through so that +assert_select+ can be called
- # separately for each element.
- #
- #
- # ==== Example
- # If the response contains two ordered lists, each with four list elements then:
- # assert_select "ol" do |elements|
- # elements.each do |element|
- # assert_select element, "li", 4
- # end
- # end
- #
- # will pass, as will:
- # assert_select "ol" do
- # assert_select "li", 8
- # end
- #
- # The selector may be a CSS selector expression (String), an expression
- # with substitution values, or an HTML::Selector object.
- #
- # === Equality Tests
- #
- # The equality test may be one of the following:
- # * true - Assertion is true if at least one element selected.
- # * false - Assertion is true if no element selected.
- # * String/Regexp - Assertion is true if the text value of at least
- # one element matches the string or regular expression.
- # * Integer - Assertion is true if exactly that number of
- # elements are selected.
- # * Range - Assertion is true if the number of selected
- # elements fit the range.
- # If no equality test specified, the assertion is true if at least one
- # element selected.
- #
- # To perform more than one equality tests, use a hash with the following keys:
- # * :text - Narrow the selection to elements that have this text
- # value (string or regexp).
- # * :html - Narrow the selection to elements that have this HTML
- # content (string or regexp).
- # * :count - Assertion is true if the number of selected elements
- # is equal to this value.
- # * :minimum - Assertion is true if the number of selected
- # elements is at least this value.
- # * :maximum - Assertion is true if the number of selected
- # elements is at most this value.
- #
- # If the method is called with a block, once all equality tests are
- # evaluated the block is called with an array of all matched elements.
- #
- # ==== Examples
- #
- # # At least one form element
- # assert_select "form"
- #
- # # Form element includes four input fields
- # assert_select "form input", 4
- #
- # # Page title is "Welcome"
- # assert_select "title", "Welcome"
- #
- # # Page title is "Welcome" and there is only one title element
- # assert_select "title", {:count=>1, :text=>"Welcome"},
- # "Wrong title or more than one title element"
- #
- # # Page contains no forms
- # assert_select "form", false, "This page must contain no forms"
- #
- # # Test the content and style
- # assert_select "body div.header ul.menu"
- #
- # # Use substitution values
- # assert_select "ol>li#?", /item-\d+/
- #
- # # All input fields in the form have a name
- # assert_select "form input" do
- # assert_select "[name=?]", /.+/ # Not empty
- # end
- def assert_select(*args, &block)
- # Start with optional element followed by mandatory selector.
- arg = args.shift
-
- if arg.is_a?(HTML::Node)
- # First argument is a node (tag or text, but also HTML root),
- # so we know what we're selecting from.
- root = arg
- arg = args.shift
- elsif arg == nil
- # This usually happens when passing a node/element that
- # happens to be nil.
- raise ArgumentError, "First argument is either selector or element to select, but nil found. Perhaps you called assert_select with an element that does not exist?"
- elsif @selected
- root = HTML::Node.new(nil)
- root.children.concat @selected
- else
- # Otherwise just operate on the response document.
- root = response_from_page_or_rjs
- end
-
- # First or second argument is the selector: string and we pass
- # all remaining arguments. Array and we pass the argument. Also
- # accepts selector itself.
- case arg
- when String
- selector = HTML::Selector.new(arg, args)
- when Array
- selector = HTML::Selector.new(*arg)
- when HTML::Selector
- selector = arg
- else raise ArgumentError, "Expecting a selector as the first argument"
- end
-
- # Next argument is used for equality tests.
- equals = {}
- case arg = args.shift
- when Hash
- equals = arg
- when String, Regexp
- equals[:text] = arg
- when Integer
- equals[:count] = arg
- when Range
- equals[:minimum] = arg.begin
- equals[:maximum] = arg.end
- when FalseClass
- equals[:count] = 0
- when NilClass, TrueClass
- equals[:minimum] = 1
- else raise ArgumentError, "I don't understand what you're trying to match"
- end
-
- # By default we're looking for at least one match.
- if equals[:count]
- equals[:minimum] = equals[:maximum] = equals[:count]
- else
- equals[:minimum] = 1 unless equals[:minimum]
- end
-
- # Last argument is the message we use if the assertion fails.
- message = args.shift
- #- message = "No match made with selector #{selector.inspect}" unless message
- if args.shift
- raise ArgumentError, "Not expecting that last argument, you either have too many arguments, or they're the wrong type"
- end
-
- matches = selector.select(root)
- # If text/html, narrow down to those elements that match it.
- content_mismatch = nil
- if match_with = equals[:text]
- matches.delete_if do |match|
- text = ""
- text.force_encoding(match_with.encoding) if text.respond_to?(:force_encoding)
- stack = match.children.reverse
- while node = stack.pop
- if node.tag?
- stack.concat node.children.reverse
- else
- content = node.content
- content.force_encoding(match_with.encoding) if content.respond_to?(:force_encoding)
- text << content
- end
- end
- text.strip! unless NO_STRIP.include?(match.name)
- unless match_with.is_a?(Regexp) ? (text =~ match_with) : (text == match_with.to_s)
- content_mismatch ||= build_message(message, "> expected but was\n>.", match_with, text)
- true
- end
- end
- elsif match_with = equals[:html]
- matches.delete_if do |match|
- html = match.children.map(&:to_s).join
- html.strip! unless NO_STRIP.include?(match.name)
- unless match_with.is_a?(Regexp) ? (html =~ match_with) : (html == match_with.to_s)
- content_mismatch ||= build_message(message, "> expected but was\n>.", match_with, html)
- true
- end
- end
- end
- # Expecting foo found bar element only if found zero, not if
- # found one but expecting two.
- message ||= content_mismatch if matches.empty?
- # Test minimum/maximum occurrence.
- min, max = equals[:minimum], equals[:maximum]
- message = message || %(Expected #{count_description(min, max)} matching "#{selector.to_s}", found #{matches.size}.)
- assert matches.size >= min, message if min
- assert matches.size <= max, message if max
-
- # If a block is given call that block. Set @selected to allow
- # nested assert_select, which can be nested several levels deep.
- if block_given? && !matches.empty?
- begin
- in_scope, @selected = @selected, matches
- yield matches
- ensure
- @selected = in_scope
- end
- end
-
- # Returns all matches elements.
- matches
- end
-
- def count_description(min, max) #:nodoc:
- pluralize = lambda {|word, quantity| word << (quantity == 1 ? '' : 's')}
-
- if min && max && (max != min)
- "between #{min} and #{max} elements"
- elsif min && !(min == 1 && max == 1)
- "at least #{min} #{pluralize['element', min]}"
- elsif max
- "at most #{max} #{pluralize['element', max]}"
- end
- end
-
- # :call-seq:
- # assert_select_rjs(id?) { |elements| ... }
- # assert_select_rjs(statement, id?) { |elements| ... }
- # assert_select_rjs(:insert, position, id?) { |elements| ... }
- #
- # Selects content from the RJS response.
- #
- # === Narrowing down
- #
- # With no arguments, asserts that one or more elements are updated or
- # inserted by RJS statements.
- #
- # Use the +id+ argument to narrow down the assertion to only statements
- # that update or insert an element with that identifier.
- #
- # Use the first argument to narrow down assertions to only statements
- # of that type. Possible values are :replace, :replace_html,
- # :show, :hide, :toggle, :remove and
- # :insert_html.
- #
- # Use the argument :insert followed by an insertion position to narrow
- # down the assertion to only statements that insert elements in that
- # position. Possible values are :top, :bottom, :before
- # and :after.
- #
- # Using the :remove statement, you will be able to pass a block, but it will
- # be ignored as there is no HTML passed for this statement.
- #
- # === Using blocks
- #
- # Without a block, +assert_select_rjs+ merely asserts that the response
- # contains one or more RJS statements that replace or update content.
- #
- # With a block, +assert_select_rjs+ also selects all elements used in
- # these statements and passes them to the block. Nested assertions are
- # supported.
- #
- # Calling +assert_select_rjs+ with no arguments and using nested asserts
- # asserts that the HTML content is returned by one or more RJS statements.
- # Using +assert_select+ directly makes the same assertion on the content,
- # but without distinguishing whether the content is returned in an HTML
- # or JavaScript.
- #
- # ==== Examples
- #
- # # Replacing the element foo.
- # # page.replace 'foo', ...
- # assert_select_rjs :replace, "foo"
- #
- # # Replacing with the chained RJS proxy.
- # # page[:foo].replace ...
- # assert_select_rjs :chained_replace, 'foo'
- #
- # # Inserting into the element bar, top position.
- # assert_select_rjs :insert, :top, "bar"
- #
- # # Remove the element bar
- # assert_select_rjs :remove, "bar"
- #
- # # Changing the element foo, with an image.
- # assert_select_rjs "foo" do
- # assert_select "img[src=/images/logo.gif""
- # end
- #
- # # RJS inserts or updates a list with four items.
- # assert_select_rjs do
- # assert_select "ol>li", 4
- # end
- #
- # # The same, but shorter.
- # assert_select "ol>li", 4
- def assert_select_rjs(*args, &block)
- rjs_type = args.first.is_a?(Symbol) ? args.shift : nil
- id = args.first.is_a?(String) ? args.shift : nil
-
- # If the first argument is a symbol, it's the type of RJS statement we're looking
- # for (update, replace, insertion, etc). Otherwise, we're looking for just about
- # any RJS statement.
- if rjs_type
- if rjs_type == :insert
- position = args.shift
- id = args.shift
- insertion = "insert_#{position}".to_sym
- raise ArgumentError, "Unknown RJS insertion type #{position}" unless RJS_STATEMENTS[insertion]
- statement = "(#{RJS_STATEMENTS[insertion]})"
- else
- raise ArgumentError, "Unknown RJS statement type #{rjs_type}" unless RJS_STATEMENTS[rjs_type]
- statement = "(#{RJS_STATEMENTS[rjs_type]})"
- end
- else
- statement = "#{RJS_STATEMENTS[:any]}"
- end
-
- # Next argument we're looking for is the element identifier. If missing, we pick
- # any element, otherwise we replace it in the statement.
- pattern = Regexp.new(
- id ? statement.gsub(RJS_ANY_ID, "\"#{id}\"") : statement
- )
-
- # Duplicate the body since the next step involves destroying it.
- matches = nil
- case rjs_type
- when :remove, :show, :hide, :toggle
- matches = @response.body.match(pattern)
- else
- @response.body.gsub(pattern) do |match|
- html = unescape_rjs(match)
- matches ||= []
- matches.concat HTML::Document.new(html).root.children.select { |n| n.tag? }
- ""
- end
- end
-
- if matches
- assert_block("") { true } # to count the assertion
- if block_given? && !([:remove, :show, :hide, :toggle].include? rjs_type)
- begin
- in_scope, @selected = @selected, matches
- yield matches
- ensure
- @selected = in_scope
- end
- end
- matches
- else
- # RJS statement not found.
- case rjs_type
- when :remove, :show, :hide, :toggle
- flunk_message = "No RJS statement that #{rjs_type.to_s}s '#{id}' was rendered."
- else
- flunk_message = "No RJS statement that replaces or inserts HTML content."
- end
- flunk args.shift || flunk_message
- end
- end
-
- # :call-seq:
- # assert_select_encoded(element?) { |elements| ... }
- #
- # Extracts the content of an element, treats it as encoded HTML and runs
- # nested assertion on it.
- #
- # You typically call this method within another assertion to operate on
- # all currently selected elements. You can also pass an element or array
- # of elements.
- #
- # The content of each element is un-encoded, and wrapped in the root
- # element +encoded+. It then calls the block with all un-encoded elements.
- #
- # ==== Examples
- # # Selects all bold tags from within the title of an ATOM feed's entries (perhaps to nab a section name prefix)
- # assert_select_feed :atom, 1.0 do
- # # Select each entry item and then the title item
- # assert_select "entry>title" do
- # # Run assertions on the encoded title elements
- # assert_select_encoded do
- # assert_select "b"
- # end
- # end
- # end
- #
- #
- # # Selects all paragraph tags from within the description of an RSS feed
- # assert_select_feed :rss, 2.0 do
- # # Select description element of each feed item.
- # assert_select "channel>item>description" do
- # # Run assertions on the encoded elements.
- # assert_select_encoded do
- # assert_select "p"
- # end
- # end
- # end
- def assert_select_encoded(element = nil, &block)
- case element
- when Array
- elements = element
- when HTML::Node
- elements = [element]
- when nil
- unless elements = @selected
- raise ArgumentError, "First argument is optional, but must be called from a nested assert_select"
- end
- else
- raise ArgumentError, "Argument is optional, and may be node or array of nodes"
- end
-
- fix_content = lambda do |node|
- # Gets around a bug in the Rails 1.1 HTML parser.
- node.content.gsub(/)?/m) { CGI.escapeHTML($1) }
- end
-
- selected = elements.map do |element|
- text = element.children.select{ |c| not c.tag? }.map{ |c| fix_content[c] }.join
- root = HTML::Document.new(CGI.unescapeHTML("#{text}")).root
- css_select(root, "encoded:root", &block)[0]
- end
-
- begin
- old_selected, @selected = @selected, selected
- assert_select ":root", &block
- ensure
- @selected = old_selected
- end
- end
-
- # :call-seq:
- # assert_select_email { }
- #
- # Extracts the body of an email and runs nested assertions on it.
- #
- # You must enable deliveries for this assertion to work, use:
- # ActionMailer::Base.perform_deliveries = true
- #
- # ==== Examples
- #
- # assert_select_email do
- # assert_select "h1", "Email alert"
- # end
- #
- # assert_select_email do
- # items = assert_select "ol>li"
- # items.each do
- # # Work with items here...
- # end
- # end
- #
- def assert_select_email(&block)
- deliveries = ActionMailer::Base.deliveries
- assert !deliveries.empty?, "No e-mail in delivery list"
-
- for delivery in deliveries
- for part in delivery.parts
- if part["Content-Type"].to_s =~ /^text\/html\W/
- root = HTML::Document.new(part.body).root
- assert_select root, ":root", &block
- end
- end
- end
- end
-
- protected
- unless const_defined?(:RJS_STATEMENTS)
- RJS_PATTERN_HTML = "\"((\\\\\"|[^\"])*)\""
- RJS_ANY_ID = "\"([^\"])*\""
- RJS_STATEMENTS = {
- :chained_replace => "\\$\\(#{RJS_ANY_ID}\\)\\.replace\\(#{RJS_PATTERN_HTML}\\)",
- :chained_replace_html => "\\$\\(#{RJS_ANY_ID}\\)\\.update\\(#{RJS_PATTERN_HTML}\\)",
- :replace_html => "Element\\.update\\(#{RJS_ANY_ID}, #{RJS_PATTERN_HTML}\\)",
- :replace => "Element\\.replace\\(#{RJS_ANY_ID}, #{RJS_PATTERN_HTML}\\)"
- }
- [:remove, :show, :hide, :toggle].each do |action|
- RJS_STATEMENTS[action] = "Element\\.#{action}\\(#{RJS_ANY_ID}\\)"
- end
- RJS_INSERTIONS = ["top", "bottom", "before", "after"]
- RJS_INSERTIONS.each do |insertion|
- RJS_STATEMENTS["insert_#{insertion}".to_sym] = "Element.insert\\(#{RJS_ANY_ID}, \\{ #{insertion}: #{RJS_PATTERN_HTML} \\}\\)"
- end
- RJS_STATEMENTS[:insert_html] = "Element.insert\\(#{RJS_ANY_ID}, \\{ (#{RJS_INSERTIONS.join('|')}): #{RJS_PATTERN_HTML} \\}\\)"
- RJS_STATEMENTS[:any] = Regexp.new("(#{RJS_STATEMENTS.values.join('|')})")
- RJS_PATTERN_UNICODE_ESCAPED_CHAR = /\\u([0-9a-zA-Z]{4})/
- end
-
- # +assert_select+ and +css_select+ call this to obtain the content in the HTML
- # page, or from all the RJS statements, depending on the type of response.
- def response_from_page_or_rjs()
- content_type = @response.content_type
-
- if content_type && Mime::JS =~ content_type
- body = @response.body.dup
- root = HTML::Node.new(nil)
-
- while true
- next if body.sub!(RJS_STATEMENTS[:any]) do |match|
- html = unescape_rjs(match)
- matches = HTML::Document.new(html).root.children.select { |n| n.tag? }
- root.children.concat matches
- ""
- end
- break
- end
-
- root
- else
- html_document.root
- end
- end
-
- # Unescapes a RJS string.
- def unescape_rjs(rjs_string)
- # RJS encodes double quotes and line breaks.
- unescaped= rjs_string.gsub('\"', '"')
- unescaped.gsub!(/\\\//, '/')
- unescaped.gsub!('\n', "\n")
- unescaped.gsub!('\076', '>')
- unescaped.gsub!('\074', '<')
- # RJS encodes non-ascii characters.
- unescaped.gsub!(RJS_PATTERN_UNICODE_ESCAPED_CHAR) {|u| [$1.hex].pack('U*')}
- unescaped
- end
- end
- end
-end
diff --git a/actionpack/lib/action_controller/testing/assertions/tag.rb b/actionpack/lib/action_controller/testing/assertions/tag.rb
deleted file mode 100644
index d9197b7855..0000000000
--- a/actionpack/lib/action_controller/testing/assertions/tag.rb
+++ /dev/null
@@ -1,123 +0,0 @@
-module ActionController
- module Assertions
- # Pair of assertions to testing elements in the HTML output of the response.
- module TagAssertions
- # Asserts that there is a tag/node/element in the body of the response
- # that meets all of the given conditions. The +conditions+ parameter must
- # be a hash of any of the following keys (all are optional):
- #
- # * :tag: the node type must match the corresponding value
- # * :attributes: a hash. The node's attributes must match the
- # corresponding values in the hash.
- # * :parent: a hash. The node's parent must match the
- # corresponding hash.
- # * :child: a hash. At least one of the node's immediate children
- # must meet the criteria described by the hash.
- # * :ancestor: a hash. At least one of the node's ancestors must
- # meet the criteria described by the hash.
- # * :descendant: a hash. At least one of the node's descendants
- # must meet the criteria described by the hash.
- # * :sibling: a hash. At least one of the node's siblings must
- # meet the criteria described by the hash.
- # * :after: a hash. The node must be after any sibling meeting
- # the criteria described by the hash, and at least one sibling must match.
- # * :before: a hash. The node must be before any sibling meeting
- # the criteria described by the hash, and at least one sibling must match.
- # * :children: a hash, for counting children of a node. Accepts
- # the keys:
- # * :count: either a number or a range which must equal (or
- # include) the number of children that match.
- # * :less_than: the number of matching children must be less
- # than this number.
- # * :greater_than: the number of matching children must be
- # greater than this number.
- # * :only: another hash consisting of the keys to use
- # to match on the children, and only matching children will be
- # counted.
- # * :content: the textual content of the node must match the
- # given value. This will not match HTML tags in the body of a
- # tag--only text.
- #
- # Conditions are matched using the following algorithm:
- #
- # * if the condition is a string, it must be a substring of the value.
- # * if the condition is a regexp, it must match the value.
- # * if the condition is a number, the value must match number.to_s.
- # * if the condition is +true+, the value must not be +nil+.
- # * if the condition is +false+ or +nil+, the value must be +nil+.
- #
- # === Examples
- #
- # # Assert that there is a "span" tag
- # assert_tag :tag => "span"
- #
- # # Assert that there is a "span" tag with id="x"
- # assert_tag :tag => "span", :attributes => { :id => "x" }
- #
- # # Assert that there is a "span" tag using the short-hand
- # assert_tag :span
- #
- # # Assert that there is a "span" tag with id="x" using the short-hand
- # assert_tag :span, :attributes => { :id => "x" }
- #
- # # Assert that there is a "span" inside of a "div"
- # assert_tag :tag => "span", :parent => { :tag => "div" }
- #
- # # Assert that there is a "span" somewhere inside a table
- # assert_tag :tag => "span", :ancestor => { :tag => "table" }
- #
- # # Assert that there is a "span" with at least one "em" child
- # assert_tag :tag => "span", :child => { :tag => "em" }
- #
- # # Assert that there is a "span" containing a (possibly nested)
- # # "strong" tag.
- # assert_tag :tag => "span", :descendant => { :tag => "strong" }
- #
- # # Assert that there is a "span" containing between 2 and 4 "em" tags
- # # as immediate children
- # assert_tag :tag => "span",
- # :children => { :count => 2..4, :only => { :tag => "em" } }
- #
- # # Get funky: assert that there is a "div", with an "ul" ancestor
- # # and an "li" parent (with "class" = "enum"), and containing a
- # # "span" descendant that contains text matching /hello world/
- # assert_tag :tag => "div",
- # :ancestor => { :tag => "ul" },
- # :parent => { :tag => "li",
- # :attributes => { :class => "enum" } },
- # :descendant => { :tag => "span",
- # :child => /hello world/ }
- #
- # Please note: +assert_tag+ and +assert_no_tag+ only work
- # with well-formed XHTML. They recognize a few tags as implicitly self-closing
- # (like br and hr and such) but will not work correctly with tags
- # that allow optional closing tags (p, li, td). You must explicitly
- # close all of your tags to use these assertions.
- def assert_tag(*opts)
- opts = opts.size > 1 ? opts.last.merge({ :tag => opts.first.to_s }) : opts.first
- tag = find_tag(opts)
- assert tag, "expected tag, but no tag found matching #{opts.inspect} in:\n#{@response.body.inspect}"
- end
-
- # Identical to +assert_tag+, but asserts that a matching tag does _not_
- # exist. (See +assert_tag+ for a full discussion of the syntax.)
- #
- # === Examples
- # # Assert that there is not a "div" containing a "p"
- # assert_no_tag :tag => "div", :descendant => { :tag => "p" }
- #
- # # Assert that an unordered list is empty
- # assert_no_tag :tag => "ul", :descendant => { :tag => "li" }
- #
- # # Assert that there is not a "p" tag with between 1 to 3 "img" tags
- # # as immediate children
- # assert_no_tag :tag => "p",
- # :children => { :count => 1..3, :only => { :tag => "img" } }
- def assert_no_tag(*opts)
- opts = opts.size > 1 ? opts.last.merge({ :tag => opts.first.to_s }) : opts.first
- tag = find_tag(opts)
- assert !tag, "expected no tag, but found tag matching #{opts.inspect} in:\n#{@response.body.inspect}"
- end
- end
- end
-end
diff --git a/actionpack/lib/action_controller/testing/integration.rb b/actionpack/lib/action_controller/testing/integration.rb
index f960698566..7fa1fd93bf 100644
--- a/actionpack/lib/action_controller/testing/integration.rb
+++ b/actionpack/lib/action_controller/testing/integration.rb
@@ -14,7 +14,7 @@ module ActionController
# Integration::Session directly.
class Session
include Test::Unit::Assertions
- include ActionController::TestCase::Assertions
+ include ActionDispatch::Assertions
include ActionController::TestProcess
# The integer HTTP status code of the last request.
diff --git a/actionpack/lib/action_controller/testing/test_case.rb b/actionpack/lib/action_controller/testing/test_case.rb
index a80488e13e..7b4eda58e5 100644
--- a/actionpack/lib/action_controller/testing/test_case.rb
+++ b/actionpack/lib/action_controller/testing/test_case.rb
@@ -105,12 +105,7 @@ module ActionController
class TestCase < ActiveSupport::TestCase
include TestProcess
- module Assertions
- %w(response selector tag dom routing model).each do |kind|
- include ActionController::Assertions.const_get("#{kind.camelize}Assertions")
- end
- end
- include Assertions
+ include ActionDispatch::Assertions
# When the request.remote_addr remains the default for testing, which is 0.0.0.0, the exception is simply raised inline
# (bystepping the regular exception handling from rescue_action). If the request.remote_addr is anything else, the regular
diff --git a/actionpack/lib/action_dispatch.rb b/actionpack/lib/action_dispatch.rb
index 4f65dcadee..8b8a1774e4 100644
--- a/actionpack/lib/action_dispatch.rb
+++ b/actionpack/lib/action_dispatch.rb
@@ -45,6 +45,8 @@ module ActionDispatch
autoload :Reloader, 'action_dispatch/middleware/reloader'
autoload :MiddlewareStack, 'action_dispatch/middleware/stack'
+ autoload :Assertions, 'action_dispatch/testing/assertions'
+
module Http
autoload :Headers, 'action_dispatch/http/headers'
end
diff --git a/actionpack/lib/action_dispatch/testing/assertions.rb b/actionpack/lib/action_dispatch/testing/assertions.rb
new file mode 100644
index 0000000000..96f08f2355
--- /dev/null
+++ b/actionpack/lib/action_dispatch/testing/assertions.rb
@@ -0,0 +1,8 @@
+module ActionDispatch
+ module Assertions
+ %w(response selector tag dom routing model).each do |kind|
+ require "action_dispatch/testing/assertions/#{kind}"
+ include const_get("#{kind.camelize}Assertions")
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/testing/assertions/dom.rb b/actionpack/lib/action_dispatch/testing/assertions/dom.rb
new file mode 100644
index 0000000000..9a917f704a
--- /dev/null
+++ b/actionpack/lib/action_dispatch/testing/assertions/dom.rb
@@ -0,0 +1,35 @@
+module ActionDispatch
+ module Assertions
+ module DomAssertions
+ # Test two HTML strings for equivalency (e.g., identical up to reordering of attributes)
+ #
+ # ==== Examples
+ #
+ # # assert that the referenced method generates the appropriate HTML string
+ # assert_dom_equal 'Apples', link_to("Apples", "http://www.example.com")
+ #
+ def assert_dom_equal(expected, actual, message = "")
+ expected_dom = HTML::Document.new(expected).root
+ actual_dom = HTML::Document.new(actual).root
+ full_message = build_message(message, "> expected to be == to\n>.", expected_dom.to_s, actual_dom.to_s)
+
+ assert_block(full_message) { expected_dom == actual_dom }
+ end
+
+ # The negated form of +assert_dom_equivalent+.
+ #
+ # ==== Examples
+ #
+ # # assert that the referenced method does not generate the specified HTML string
+ # assert_dom_not_equal 'Apples', link_to("Oranges", "http://www.example.com")
+ #
+ def assert_dom_not_equal(expected, actual, message = "")
+ expected_dom = HTML::Document.new(expected).root
+ actual_dom = HTML::Document.new(actual).root
+ full_message = build_message(message, "> expected to be != to\n>.", expected_dom.to_s, actual_dom.to_s)
+
+ assert_block(full_message) { expected_dom != actual_dom }
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/testing/assertions/model.rb b/actionpack/lib/action_dispatch/testing/assertions/model.rb
new file mode 100644
index 0000000000..46714418c6
--- /dev/null
+++ b/actionpack/lib/action_dispatch/testing/assertions/model.rb
@@ -0,0 +1,19 @@
+module ActionDispatch
+ module Assertions
+ module ModelAssertions
+ # Ensures that the passed record is valid by Active Record standards and
+ # returns any error messages if it is not.
+ #
+ # ==== Examples
+ #
+ # # assert that a newly created record is valid
+ # model = Model.new
+ # assert_valid(model)
+ #
+ def assert_valid(record)
+ ::ActiveSupport::Deprecation.warn("assert_valid is deprecated. Use assert record.valid? instead", caller)
+ assert record.valid?, record.errors.full_messages.join("\n")
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/testing/assertions/response.rb b/actionpack/lib/action_dispatch/testing/assertions/response.rb
new file mode 100644
index 0000000000..a72ce9084f
--- /dev/null
+++ b/actionpack/lib/action_dispatch/testing/assertions/response.rb
@@ -0,0 +1,156 @@
+module ActionDispatch
+ module Assertions
+ # A small suite of assertions that test responses from Rails applications.
+ module ResponseAssertions
+ # Asserts that the response is one of the following types:
+ #
+ # * :success - Status code was 200
+ # * :redirect - Status code was in the 300-399 range
+ # * :missing - Status code was 404
+ # * :error - Status code was in the 500-599 range
+ #
+ # You can also pass an explicit status number like assert_response(501)
+ # or its symbolic equivalent assert_response(:not_implemented).
+ # See ActionDispatch::StatusCodes for a full list.
+ #
+ # ==== Examples
+ #
+ # # assert that the response was a redirection
+ # assert_response :redirect
+ #
+ # # assert that the response code was status code 401 (unauthorized)
+ # assert_response 401
+ #
+ def assert_response(type, message = nil)
+ validate_request!
+
+ if [ :success, :missing, :redirect, :error ].include?(type) && @response.send("#{type}?")
+ assert_block("") { true } # to count the assertion
+ elsif type.is_a?(Fixnum) && @response.response_code == type
+ assert_block("") { true } # to count the assertion
+ elsif type.is_a?(Symbol) && @response.response_code == ActionDispatch::StatusCodes::SYMBOL_TO_STATUS_CODE[type]
+ assert_block("") { true } # to count the assertion
+ else
+ if @controller && @response.error?
+ exception = @controller.template.instance_variable_get(:@exception)
+ exception_message = exception && exception.message
+ assert_block(build_message(message, "Expected response to be a >, but was >\n>", type, @response.response_code, exception_message.to_s)) { false }
+ else
+ assert_block(build_message(message, "Expected response to be a >, but was >", type, @response.response_code)) { false }
+ end
+ end
+ end
+
+ # Assert that the redirection options passed in match those of the redirect called in the latest action.
+ # This match can be partial, such that assert_redirected_to(:controller => "weblog") will also
+ # match the redirection of redirect_to(:controller => "weblog", :action => "show") and so on.
+ #
+ # ==== Examples
+ #
+ # # assert that the redirection was to the "index" action on the WeblogController
+ # assert_redirected_to :controller => "weblog", :action => "index"
+ #
+ # # assert that the redirection was to the named route login_url
+ # assert_redirected_to login_url
+ #
+ # # assert that the redirection was to the url for @customer
+ # assert_redirected_to @customer
+ #
+ def assert_redirected_to(options = {}, message=nil)
+ validate_request!
+
+ assert_response(:redirect, message)
+ return true if options == @response.redirected_to
+
+ # Support partial arguments for hash redirections
+ if options.is_a?(Hash) && @response.redirected_to.is_a?(Hash)
+ return true if options.all? {|(key, value)| @response.redirected_to[key] == value}
+ end
+
+ redirected_to_after_normalisation = normalize_argument_to_redirection(@response.redirected_to)
+ options_after_normalisation = normalize_argument_to_redirection(options)
+
+ if redirected_to_after_normalisation != options_after_normalisation
+ flunk "Expected response to be a redirect to <#{options_after_normalisation}> but was a redirect to <#{redirected_to_after_normalisation}>"
+ end
+ end
+
+ # Asserts that the request was rendered with the appropriate template file or partials
+ #
+ # ==== Examples
+ #
+ # # assert that the "new" view template was rendered
+ # assert_template "new"
+ #
+ # # assert that the "_customer" partial was rendered twice
+ # assert_template :partial => '_customer', :count => 2
+ #
+ # # assert that no partials were rendered
+ # assert_template :partial => false
+ #
+ def assert_template(options = {}, message = nil)
+ validate_request!
+
+ case options
+ when NilClass, String
+ rendered = (@controller.template.rendered[:template] || []).map { |t| t.identifier }
+ msg = build_message(message,
+ "expecting > but rendering with >",
+ options, rendered.join(', '))
+ assert_block(msg) do
+ if options.nil?
+ @controller.template.rendered[:template].blank?
+ else
+ rendered.any? { |t| t.match(options) }
+ end
+ end
+ when Hash
+ if expected_partial = options[:partial]
+ partials = @controller.template.rendered[:partials]
+ if expected_count = options[:count]
+ found = partials.detect { |p, _| p.identifier.match(expected_partial) }
+ actual_count = found.nil? ? 0 : found.second
+ msg = build_message(message,
+ "expecting ? to be rendered ? time(s) but rendered ? time(s)",
+ expected_partial, expected_count, actual_count)
+ assert(actual_count == expected_count.to_i, msg)
+ else
+ msg = build_message(message,
+ "expecting partial > but action rendered >",
+ options[:partial], partials.keys)
+ assert(partials.keys.any? { |p| p.identifier.match(expected_partial) }, msg)
+ end
+ else
+ assert @controller.template.rendered[:partials].empty?,
+ "Expected no partials to be rendered"
+ end
+ end
+ end
+
+ private
+ # Proxy to to_param if the object will respond to it.
+ def parameterize(value)
+ value.respond_to?(:to_param) ? value.to_param : value
+ end
+
+ def normalize_argument_to_redirection(fragment)
+ after_routing = @controller.url_for(fragment)
+ if after_routing =~ %r{^\w+://.*}
+ after_routing
+ else
+ # FIXME - this should probably get removed.
+ if after_routing.first != '/'
+ after_routing = '/' + after_routing
+ end
+ @request.protocol + @request.host_with_port + after_routing
+ end
+ end
+
+ def validate_request!
+ unless @request.is_a?(ActionDispatch::Request)
+ raise ArgumentError, "@request must be an ActionDispatch::Request"
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb
new file mode 100644
index 0000000000..89d1a49403
--- /dev/null
+++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb
@@ -0,0 +1,142 @@
+module ActionDispatch
+ module Assertions
+ # Suite of assertions to test routes generated by Rails and the handling of requests made to them.
+ module RoutingAssertions
+ # Asserts that the routing of the given +path+ was handled correctly and that the parsed options (given in the +expected_options+ hash)
+ # match +path+. Basically, it asserts that Rails recognizes the route given by +expected_options+.
+ #
+ # Pass a hash in the second argument (+path+) to specify the request method. This is useful for routes
+ # requiring a specific HTTP method. The hash should contain a :path with the incoming request path
+ # and a :method containing the required HTTP verb.
+ #
+ # # assert that POSTing to /items will call the create action on ItemsController
+ # assert_recognizes {:controller => 'items', :action => 'create'}, {:path => 'items', :method => :post}
+ #
+ # You can also pass in +extras+ with a hash containing URL parameters that would normally be in the query string. This can be used
+ # to assert that values in the query string string will end up in the params hash correctly. To test query strings you must use the
+ # extras argument, appending the query string on the path directly will not work. For example:
+ #
+ # # assert that a path of '/items/list/1?view=print' returns the correct options
+ # assert_recognizes {:controller => 'items', :action => 'list', :id => '1', :view => 'print'}, 'items/list/1', { :view => "print" }
+ #
+ # The +message+ parameter allows you to pass in an error message that is displayed upon failure.
+ #
+ # ==== Examples
+ # # Check the default route (i.e., the index action)
+ # assert_recognizes {:controller => 'items', :action => 'index'}, 'items'
+ #
+ # # Test a specific action
+ # assert_recognizes {:controller => 'items', :action => 'list'}, 'items/list'
+ #
+ # # Test an action with a parameter
+ # assert_recognizes {:controller => 'items', :action => 'destroy', :id => '1'}, 'items/destroy/1'
+ #
+ # # Test a custom route
+ # assert_recognizes {:controller => 'items', :action => 'show', :id => '1'}, 'view/item1'
+ #
+ # # Check a Simply RESTful generated route
+ # assert_recognizes list_items_url, 'items/list'
+ def assert_recognizes(expected_options, path, extras={}, message=nil)
+ if path.is_a? Hash
+ request_method = path[:method]
+ path = path[:path]
+ else
+ request_method = nil
+ end
+
+ ActionController::Routing::Routes.reload if ActionController::Routing::Routes.empty?
+ request = recognized_request_for(path, request_method)
+
+ expected_options = expected_options.clone
+ extras.each_key { |key| expected_options.delete key } unless extras.nil?
+
+ expected_options.stringify_keys!
+ routing_diff = expected_options.diff(request.path_parameters)
+ msg = build_message(message, "The recognized options > did not match >, difference: >",
+ request.path_parameters, expected_options, expected_options.diff(request.path_parameters))
+ assert_block(msg) { request.path_parameters == expected_options }
+ end
+
+ # Asserts that the provided options can be used to generate the provided path. This is the inverse of +assert_recognizes+.
+ # The +extras+ parameter is used to tell the request the names and values of additional request parameters that would be in
+ # a query string. The +message+ parameter allows you to specify a custom error message for assertion failures.
+ #
+ # The +defaults+ parameter is unused.
+ #
+ # ==== Examples
+ # # Asserts that the default action is generated for a route with no action
+ # assert_generates "/items", :controller => "items", :action => "index"
+ #
+ # # Tests that the list action is properly routed
+ # assert_generates "/items/list", :controller => "items", :action => "list"
+ #
+ # # Tests the generation of a route with a parameter
+ # assert_generates "/items/list/1", { :controller => "items", :action => "list", :id => "1" }
+ #
+ # # Asserts that the generated route gives us our custom route
+ # assert_generates "changesets/12", { :controller => 'scm', :action => 'show_diff', :revision => "12" }
+ def assert_generates(expected_path, options, defaults={}, extras = {}, message=nil)
+ expected_path = "/#{expected_path}" unless expected_path[0] == ?/
+ # Load routes.rb if it hasn't been loaded.
+ ActionController::Routing::Routes.reload if ActionController::Routing::Routes.empty?
+
+ generated_path, extra_keys = ActionController::Routing::Routes.generate_extras(options, defaults)
+ found_extras = options.reject {|k, v| ! extra_keys.include? k}
+
+ msg = build_message(message, "found extras >, not >", found_extras, extras)
+ assert_block(msg) { found_extras == extras }
+
+ msg = build_message(message, "The generated path > did not match >", generated_path,
+ expected_path)
+ assert_block(msg) { expected_path == generated_path }
+ end
+
+ # Asserts that path and options match both ways; in other words, it verifies that path generates
+ # options and then that options generates path. This essentially combines +assert_recognizes+
+ # and +assert_generates+ into one step.
+ #
+ # The +extras+ hash allows you to specify options that would normally be provided as a query string to the action. The
+ # +message+ parameter allows you to specify a custom error message to display upon failure.
+ #
+ # ==== Examples
+ # # Assert a basic route: a controller with the default action (index)
+ # assert_routing '/home', :controller => 'home', :action => 'index'
+ #
+ # # Test a route generated with a specific controller, action, and parameter (id)
+ # assert_routing '/entries/show/23', :controller => 'entries', :action => 'show', id => 23
+ #
+ # # Assert a basic route (controller + default action), with an error message if it fails
+ # assert_routing '/store', { :controller => 'store', :action => 'index' }, {}, {}, 'Route for store index not generated properly'
+ #
+ # # Tests a route, providing a defaults hash
+ # assert_routing 'controller/action/9', {:id => "9", :item => "square"}, {:controller => "controller", :action => "action"}, {}, {:item => "square"}
+ #
+ # # Tests a route with a HTTP method
+ # assert_routing { :method => 'put', :path => '/product/321' }, { :controller => "product", :action => "update", :id => "321" }
+ def assert_routing(path, options, defaults={}, extras={}, message=nil)
+ assert_recognizes(options, path, extras, message)
+
+ controller, default_controller = options[:controller], defaults[:controller]
+ if controller && controller.include?(?/) && default_controller && default_controller.include?(?/)
+ options[:controller] = "/#{controller}"
+ end
+
+ assert_generates(path.is_a?(Hash) ? path[:path] : path, options, defaults, extras, message)
+ end
+
+ private
+ # Recognizes the route for a given path.
+ def recognized_request_for(path, request_method = nil)
+ path = "/#{path}" unless path.first == '/'
+
+ # Assume given controller
+ request = ActionController::TestRequest.new
+ request.env["REQUEST_METHOD"] = request_method.to_s.upcase if request_method
+ request.path = path
+
+ ActionController::Routing::Routes.recognize(request)
+ request
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/testing/assertions/selector.rb b/actionpack/lib/action_dispatch/testing/assertions/selector.rb
new file mode 100644
index 0000000000..dd75cda6b9
--- /dev/null
+++ b/actionpack/lib/action_dispatch/testing/assertions/selector.rb
@@ -0,0 +1,632 @@
+#--
+# Copyright (c) 2006 Assaf Arkin (http://labnotes.org)
+# Under MIT and/or CC By license.
+#++
+
+module ActionDispatch
+ module Assertions
+ unless const_defined?(:NO_STRIP)
+ NO_STRIP = %w{pre script style textarea}
+ end
+
+ # Adds the +assert_select+ method for use in Rails functional
+ # test cases, which can be used to make assertions on the response HTML of a controller
+ # action. You can also call +assert_select+ within another +assert_select+ to
+ # make assertions on elements selected by the enclosing assertion.
+ #
+ # Use +css_select+ to select elements without making an assertions, either
+ # from the response HTML or elements selected by the enclosing assertion.
+ #
+ # In addition to HTML responses, you can make the following assertions:
+ # * +assert_select_rjs+ - Assertions on HTML content of RJS update and insertion operations.
+ # * +assert_select_encoded+ - Assertions on HTML encoded inside XML, for example for dealing with feed item descriptions.
+ # * +assert_select_email+ - Assertions on the HTML body of an e-mail.
+ #
+ # Also see HTML::Selector to learn how to use selectors.
+ module SelectorAssertions
+ # :call-seq:
+ # css_select(selector) => array
+ # css_select(element, selector) => array
+ #
+ # Select and return all matching elements.
+ #
+ # If called with a single argument, uses that argument as a selector
+ # to match all elements of the current page. Returns an empty array
+ # if no match is found.
+ #
+ # If called with two arguments, uses the first argument as the base
+ # element and the second argument as the selector. Attempts to match the
+ # base element and any of its children. Returns an empty array if no
+ # match is found.
+ #
+ # The selector may be a CSS selector expression (String), an expression
+ # with substitution values (Array) or an HTML::Selector object.
+ #
+ # ==== Examples
+ # # Selects all div tags
+ # divs = css_select("div")
+ #
+ # # Selects all paragraph tags and does something interesting
+ # pars = css_select("p")
+ # pars.each do |par|
+ # # Do something fun with paragraphs here...
+ # end
+ #
+ # # Selects all list items in unordered lists
+ # items = css_select("ul>li")
+ #
+ # # Selects all form tags and then all inputs inside the form
+ # forms = css_select("form")
+ # forms.each do |form|
+ # inputs = css_select(form, "input")
+ # ...
+ # end
+ #
+ def css_select(*args)
+ # See assert_select to understand what's going on here.
+ arg = args.shift
+
+ if arg.is_a?(HTML::Node)
+ root = arg
+ arg = args.shift
+ elsif arg == nil
+ raise ArgumentError, "First argument is either selector or element to select, but nil found. Perhaps you called assert_select with an element that does not exist?"
+ elsif @selected
+ matches = []
+
+ @selected.each do |selected|
+ subset = css_select(selected, HTML::Selector.new(arg.dup, args.dup))
+ subset.each do |match|
+ matches << match unless matches.any? { |m| m.equal?(match) }
+ end
+ end
+
+ return matches
+ else
+ root = response_from_page_or_rjs
+ end
+
+ case arg
+ when String
+ selector = HTML::Selector.new(arg, args)
+ when Array
+ selector = HTML::Selector.new(*arg)
+ when HTML::Selector
+ selector = arg
+ else raise ArgumentError, "Expecting a selector as the first argument"
+ end
+
+ selector.select(root)
+ end
+
+ # :call-seq:
+ # assert_select(selector, equality?, message?)
+ # assert_select(element, selector, equality?, message?)
+ #
+ # An assertion that selects elements and makes one or more equality tests.
+ #
+ # If the first argument is an element, selects all matching elements
+ # starting from (and including) that element and all its children in
+ # depth-first order.
+ #
+ # If no element if specified, calling +assert_select+ selects from the
+ # response HTML unless +assert_select+ is called from within an +assert_select+ block.
+ #
+ # When called with a block +assert_select+ passes an array of selected elements
+ # to the block. Calling +assert_select+ from the block, with no element specified,
+ # runs the assertion on the complete set of elements selected by the enclosing assertion.
+ # Alternatively the array may be iterated through so that +assert_select+ can be called
+ # separately for each element.
+ #
+ #
+ # ==== Example
+ # If the response contains two ordered lists, each with four list elements then:
+ # assert_select "ol" do |elements|
+ # elements.each do |element|
+ # assert_select element, "li", 4
+ # end
+ # end
+ #
+ # will pass, as will:
+ # assert_select "ol" do
+ # assert_select "li", 8
+ # end
+ #
+ # The selector may be a CSS selector expression (String), an expression
+ # with substitution values, or an HTML::Selector object.
+ #
+ # === Equality Tests
+ #
+ # The equality test may be one of the following:
+ # * true - Assertion is true if at least one element selected.
+ # * false - Assertion is true if no element selected.
+ # * String/Regexp - Assertion is true if the text value of at least
+ # one element matches the string or regular expression.
+ # * Integer - Assertion is true if exactly that number of
+ # elements are selected.
+ # * Range - Assertion is true if the number of selected
+ # elements fit the range.
+ # If no equality test specified, the assertion is true if at least one
+ # element selected.
+ #
+ # To perform more than one equality tests, use a hash with the following keys:
+ # * :text - Narrow the selection to elements that have this text
+ # value (string or regexp).
+ # * :html - Narrow the selection to elements that have this HTML
+ # content (string or regexp).
+ # * :count - Assertion is true if the number of selected elements
+ # is equal to this value.
+ # * :minimum - Assertion is true if the number of selected
+ # elements is at least this value.
+ # * :maximum - Assertion is true if the number of selected
+ # elements is at most this value.
+ #
+ # If the method is called with a block, once all equality tests are
+ # evaluated the block is called with an array of all matched elements.
+ #
+ # ==== Examples
+ #
+ # # At least one form element
+ # assert_select "form"
+ #
+ # # Form element includes four input fields
+ # assert_select "form input", 4
+ #
+ # # Page title is "Welcome"
+ # assert_select "title", "Welcome"
+ #
+ # # Page title is "Welcome" and there is only one title element
+ # assert_select "title", {:count=>1, :text=>"Welcome"},
+ # "Wrong title or more than one title element"
+ #
+ # # Page contains no forms
+ # assert_select "form", false, "This page must contain no forms"
+ #
+ # # Test the content and style
+ # assert_select "body div.header ul.menu"
+ #
+ # # Use substitution values
+ # assert_select "ol>li#?", /item-\d+/
+ #
+ # # All input fields in the form have a name
+ # assert_select "form input" do
+ # assert_select "[name=?]", /.+/ # Not empty
+ # end
+ def assert_select(*args, &block)
+ # Start with optional element followed by mandatory selector.
+ arg = args.shift
+
+ if arg.is_a?(HTML::Node)
+ # First argument is a node (tag or text, but also HTML root),
+ # so we know what we're selecting from.
+ root = arg
+ arg = args.shift
+ elsif arg == nil
+ # This usually happens when passing a node/element that
+ # happens to be nil.
+ raise ArgumentError, "First argument is either selector or element to select, but nil found. Perhaps you called assert_select with an element that does not exist?"
+ elsif @selected
+ root = HTML::Node.new(nil)
+ root.children.concat @selected
+ else
+ # Otherwise just operate on the response document.
+ root = response_from_page_or_rjs
+ end
+
+ # First or second argument is the selector: string and we pass
+ # all remaining arguments. Array and we pass the argument. Also
+ # accepts selector itself.
+ case arg
+ when String
+ selector = HTML::Selector.new(arg, args)
+ when Array
+ selector = HTML::Selector.new(*arg)
+ when HTML::Selector
+ selector = arg
+ else raise ArgumentError, "Expecting a selector as the first argument"
+ end
+
+ # Next argument is used for equality tests.
+ equals = {}
+ case arg = args.shift
+ when Hash
+ equals = arg
+ when String, Regexp
+ equals[:text] = arg
+ when Integer
+ equals[:count] = arg
+ when Range
+ equals[:minimum] = arg.begin
+ equals[:maximum] = arg.end
+ when FalseClass
+ equals[:count] = 0
+ when NilClass, TrueClass
+ equals[:minimum] = 1
+ else raise ArgumentError, "I don't understand what you're trying to match"
+ end
+
+ # By default we're looking for at least one match.
+ if equals[:count]
+ equals[:minimum] = equals[:maximum] = equals[:count]
+ else
+ equals[:minimum] = 1 unless equals[:minimum]
+ end
+
+ # Last argument is the message we use if the assertion fails.
+ message = args.shift
+ #- message = "No match made with selector #{selector.inspect}" unless message
+ if args.shift
+ raise ArgumentError, "Not expecting that last argument, you either have too many arguments, or they're the wrong type"
+ end
+
+ matches = selector.select(root)
+ # If text/html, narrow down to those elements that match it.
+ content_mismatch = nil
+ if match_with = equals[:text]
+ matches.delete_if do |match|
+ text = ""
+ text.force_encoding(match_with.encoding) if text.respond_to?(:force_encoding)
+ stack = match.children.reverse
+ while node = stack.pop
+ if node.tag?
+ stack.concat node.children.reverse
+ else
+ content = node.content
+ content.force_encoding(match_with.encoding) if content.respond_to?(:force_encoding)
+ text << content
+ end
+ end
+ text.strip! unless NO_STRIP.include?(match.name)
+ unless match_with.is_a?(Regexp) ? (text =~ match_with) : (text == match_with.to_s)
+ content_mismatch ||= build_message(message, "> expected but was\n>.", match_with, text)
+ true
+ end
+ end
+ elsif match_with = equals[:html]
+ matches.delete_if do |match|
+ html = match.children.map(&:to_s).join
+ html.strip! unless NO_STRIP.include?(match.name)
+ unless match_with.is_a?(Regexp) ? (html =~ match_with) : (html == match_with.to_s)
+ content_mismatch ||= build_message(message, "> expected but was\n>.", match_with, html)
+ true
+ end
+ end
+ end
+ # Expecting foo found bar element only if found zero, not if
+ # found one but expecting two.
+ message ||= content_mismatch if matches.empty?
+ # Test minimum/maximum occurrence.
+ min, max = equals[:minimum], equals[:maximum]
+ message = message || %(Expected #{count_description(min, max)} matching "#{selector.to_s}", found #{matches.size}.)
+ assert matches.size >= min, message if min
+ assert matches.size <= max, message if max
+
+ # If a block is given call that block. Set @selected to allow
+ # nested assert_select, which can be nested several levels deep.
+ if block_given? && !matches.empty?
+ begin
+ in_scope, @selected = @selected, matches
+ yield matches
+ ensure
+ @selected = in_scope
+ end
+ end
+
+ # Returns all matches elements.
+ matches
+ end
+
+ def count_description(min, max) #:nodoc:
+ pluralize = lambda {|word, quantity| word << (quantity == 1 ? '' : 's')}
+
+ if min && max && (max != min)
+ "between #{min} and #{max} elements"
+ elsif min && !(min == 1 && max == 1)
+ "at least #{min} #{pluralize['element', min]}"
+ elsif max
+ "at most #{max} #{pluralize['element', max]}"
+ end
+ end
+
+ # :call-seq:
+ # assert_select_rjs(id?) { |elements| ... }
+ # assert_select_rjs(statement, id?) { |elements| ... }
+ # assert_select_rjs(:insert, position, id?) { |elements| ... }
+ #
+ # Selects content from the RJS response.
+ #
+ # === Narrowing down
+ #
+ # With no arguments, asserts that one or more elements are updated or
+ # inserted by RJS statements.
+ #
+ # Use the +id+ argument to narrow down the assertion to only statements
+ # that update or insert an element with that identifier.
+ #
+ # Use the first argument to narrow down assertions to only statements
+ # of that type. Possible values are :replace, :replace_html,
+ # :show, :hide, :toggle, :remove and
+ # :insert_html.
+ #
+ # Use the argument :insert followed by an insertion position to narrow
+ # down the assertion to only statements that insert elements in that
+ # position. Possible values are :top, :bottom, :before
+ # and :after.
+ #
+ # Using the :remove statement, you will be able to pass a block, but it will
+ # be ignored as there is no HTML passed for this statement.
+ #
+ # === Using blocks
+ #
+ # Without a block, +assert_select_rjs+ merely asserts that the response
+ # contains one or more RJS statements that replace or update content.
+ #
+ # With a block, +assert_select_rjs+ also selects all elements used in
+ # these statements and passes them to the block. Nested assertions are
+ # supported.
+ #
+ # Calling +assert_select_rjs+ with no arguments and using nested asserts
+ # asserts that the HTML content is returned by one or more RJS statements.
+ # Using +assert_select+ directly makes the same assertion on the content,
+ # but without distinguishing whether the content is returned in an HTML
+ # or JavaScript.
+ #
+ # ==== Examples
+ #
+ # # Replacing the element foo.
+ # # page.replace 'foo', ...
+ # assert_select_rjs :replace, "foo"
+ #
+ # # Replacing with the chained RJS proxy.
+ # # page[:foo].replace ...
+ # assert_select_rjs :chained_replace, 'foo'
+ #
+ # # Inserting into the element bar, top position.
+ # assert_select_rjs :insert, :top, "bar"
+ #
+ # # Remove the element bar
+ # assert_select_rjs :remove, "bar"
+ #
+ # # Changing the element foo, with an image.
+ # assert_select_rjs "foo" do
+ # assert_select "img[src=/images/logo.gif""
+ # end
+ #
+ # # RJS inserts or updates a list with four items.
+ # assert_select_rjs do
+ # assert_select "ol>li", 4
+ # end
+ #
+ # # The same, but shorter.
+ # assert_select "ol>li", 4
+ def assert_select_rjs(*args, &block)
+ rjs_type = args.first.is_a?(Symbol) ? args.shift : nil
+ id = args.first.is_a?(String) ? args.shift : nil
+
+ # If the first argument is a symbol, it's the type of RJS statement we're looking
+ # for (update, replace, insertion, etc). Otherwise, we're looking for just about
+ # any RJS statement.
+ if rjs_type
+ if rjs_type == :insert
+ position = args.shift
+ id = args.shift
+ insertion = "insert_#{position}".to_sym
+ raise ArgumentError, "Unknown RJS insertion type #{position}" unless RJS_STATEMENTS[insertion]
+ statement = "(#{RJS_STATEMENTS[insertion]})"
+ else
+ raise ArgumentError, "Unknown RJS statement type #{rjs_type}" unless RJS_STATEMENTS[rjs_type]
+ statement = "(#{RJS_STATEMENTS[rjs_type]})"
+ end
+ else
+ statement = "#{RJS_STATEMENTS[:any]}"
+ end
+
+ # Next argument we're looking for is the element identifier. If missing, we pick
+ # any element, otherwise we replace it in the statement.
+ pattern = Regexp.new(
+ id ? statement.gsub(RJS_ANY_ID, "\"#{id}\"") : statement
+ )
+
+ # Duplicate the body since the next step involves destroying it.
+ matches = nil
+ case rjs_type
+ when :remove, :show, :hide, :toggle
+ matches = @response.body.match(pattern)
+ else
+ @response.body.gsub(pattern) do |match|
+ html = unescape_rjs(match)
+ matches ||= []
+ matches.concat HTML::Document.new(html).root.children.select { |n| n.tag? }
+ ""
+ end
+ end
+
+ if matches
+ assert_block("") { true } # to count the assertion
+ if block_given? && !([:remove, :show, :hide, :toggle].include? rjs_type)
+ begin
+ in_scope, @selected = @selected, matches
+ yield matches
+ ensure
+ @selected = in_scope
+ end
+ end
+ matches
+ else
+ # RJS statement not found.
+ case rjs_type
+ when :remove, :show, :hide, :toggle
+ flunk_message = "No RJS statement that #{rjs_type.to_s}s '#{id}' was rendered."
+ else
+ flunk_message = "No RJS statement that replaces or inserts HTML content."
+ end
+ flunk args.shift || flunk_message
+ end
+ end
+
+ # :call-seq:
+ # assert_select_encoded(element?) { |elements| ... }
+ #
+ # Extracts the content of an element, treats it as encoded HTML and runs
+ # nested assertion on it.
+ #
+ # You typically call this method within another assertion to operate on
+ # all currently selected elements. You can also pass an element or array
+ # of elements.
+ #
+ # The content of each element is un-encoded, and wrapped in the root
+ # element +encoded+. It then calls the block with all un-encoded elements.
+ #
+ # ==== Examples
+ # # Selects all bold tags from within the title of an ATOM feed's entries (perhaps to nab a section name prefix)
+ # assert_select_feed :atom, 1.0 do
+ # # Select each entry item and then the title item
+ # assert_select "entry>title" do
+ # # Run assertions on the encoded title elements
+ # assert_select_encoded do
+ # assert_select "b"
+ # end
+ # end
+ # end
+ #
+ #
+ # # Selects all paragraph tags from within the description of an RSS feed
+ # assert_select_feed :rss, 2.0 do
+ # # Select description element of each feed item.
+ # assert_select "channel>item>description" do
+ # # Run assertions on the encoded elements.
+ # assert_select_encoded do
+ # assert_select "p"
+ # end
+ # end
+ # end
+ def assert_select_encoded(element = nil, &block)
+ case element
+ when Array
+ elements = element
+ when HTML::Node
+ elements = [element]
+ when nil
+ unless elements = @selected
+ raise ArgumentError, "First argument is optional, but must be called from a nested assert_select"
+ end
+ else
+ raise ArgumentError, "Argument is optional, and may be node or array of nodes"
+ end
+
+ fix_content = lambda do |node|
+ # Gets around a bug in the Rails 1.1 HTML parser.
+ node.content.gsub(/)?/m) { CGI.escapeHTML($1) }
+ end
+
+ selected = elements.map do |element|
+ text = element.children.select{ |c| not c.tag? }.map{ |c| fix_content[c] }.join
+ root = HTML::Document.new(CGI.unescapeHTML("#{text}")).root
+ css_select(root, "encoded:root", &block)[0]
+ end
+
+ begin
+ old_selected, @selected = @selected, selected
+ assert_select ":root", &block
+ ensure
+ @selected = old_selected
+ end
+ end
+
+ # :call-seq:
+ # assert_select_email { }
+ #
+ # Extracts the body of an email and runs nested assertions on it.
+ #
+ # You must enable deliveries for this assertion to work, use:
+ # ActionMailer::Base.perform_deliveries = true
+ #
+ # ==== Examples
+ #
+ # assert_select_email do
+ # assert_select "h1", "Email alert"
+ # end
+ #
+ # assert_select_email do
+ # items = assert_select "ol>li"
+ # items.each do
+ # # Work with items here...
+ # end
+ # end
+ #
+ def assert_select_email(&block)
+ deliveries = ActionMailer::Base.deliveries
+ assert !deliveries.empty?, "No e-mail in delivery list"
+
+ for delivery in deliveries
+ for part in delivery.parts
+ if part["Content-Type"].to_s =~ /^text\/html\W/
+ root = HTML::Document.new(part.body).root
+ assert_select root, ":root", &block
+ end
+ end
+ end
+ end
+
+ protected
+ unless const_defined?(:RJS_STATEMENTS)
+ RJS_PATTERN_HTML = "\"((\\\\\"|[^\"])*)\""
+ RJS_ANY_ID = "\"([^\"])*\""
+ RJS_STATEMENTS = {
+ :chained_replace => "\\$\\(#{RJS_ANY_ID}\\)\\.replace\\(#{RJS_PATTERN_HTML}\\)",
+ :chained_replace_html => "\\$\\(#{RJS_ANY_ID}\\)\\.update\\(#{RJS_PATTERN_HTML}\\)",
+ :replace_html => "Element\\.update\\(#{RJS_ANY_ID}, #{RJS_PATTERN_HTML}\\)",
+ :replace => "Element\\.replace\\(#{RJS_ANY_ID}, #{RJS_PATTERN_HTML}\\)"
+ }
+ [:remove, :show, :hide, :toggle].each do |action|
+ RJS_STATEMENTS[action] = "Element\\.#{action}\\(#{RJS_ANY_ID}\\)"
+ end
+ RJS_INSERTIONS = ["top", "bottom", "before", "after"]
+ RJS_INSERTIONS.each do |insertion|
+ RJS_STATEMENTS["insert_#{insertion}".to_sym] = "Element.insert\\(#{RJS_ANY_ID}, \\{ #{insertion}: #{RJS_PATTERN_HTML} \\}\\)"
+ end
+ RJS_STATEMENTS[:insert_html] = "Element.insert\\(#{RJS_ANY_ID}, \\{ (#{RJS_INSERTIONS.join('|')}): #{RJS_PATTERN_HTML} \\}\\)"
+ RJS_STATEMENTS[:any] = Regexp.new("(#{RJS_STATEMENTS.values.join('|')})")
+ RJS_PATTERN_UNICODE_ESCAPED_CHAR = /\\u([0-9a-zA-Z]{4})/
+ end
+
+ # +assert_select+ and +css_select+ call this to obtain the content in the HTML
+ # page, or from all the RJS statements, depending on the type of response.
+ def response_from_page_or_rjs()
+ content_type = @response.content_type
+
+ if content_type && Mime::JS =~ content_type
+ body = @response.body.dup
+ root = HTML::Node.new(nil)
+
+ while true
+ next if body.sub!(RJS_STATEMENTS[:any]) do |match|
+ html = unescape_rjs(match)
+ matches = HTML::Document.new(html).root.children.select { |n| n.tag? }
+ root.children.concat matches
+ ""
+ end
+ break
+ end
+
+ root
+ else
+ html_document.root
+ end
+ end
+
+ # Unescapes a RJS string.
+ def unescape_rjs(rjs_string)
+ # RJS encodes double quotes and line breaks.
+ unescaped= rjs_string.gsub('\"', '"')
+ unescaped.gsub!(/\\\//, '/')
+ unescaped.gsub!('\n', "\n")
+ unescaped.gsub!('\076', '>')
+ unescaped.gsub!('\074', '<')
+ # RJS encodes non-ascii characters.
+ unescaped.gsub!(RJS_PATTERN_UNICODE_ESCAPED_CHAR) {|u| [$1.hex].pack('U*')}
+ unescaped
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/testing/assertions/tag.rb b/actionpack/lib/action_dispatch/testing/assertions/tag.rb
new file mode 100644
index 0000000000..ef6867576e
--- /dev/null
+++ b/actionpack/lib/action_dispatch/testing/assertions/tag.rb
@@ -0,0 +1,123 @@
+module ActionDispatch
+ module Assertions
+ # Pair of assertions to testing elements in the HTML output of the response.
+ module TagAssertions
+ # Asserts that there is a tag/node/element in the body of the response
+ # that meets all of the given conditions. The +conditions+ parameter must
+ # be a hash of any of the following keys (all are optional):
+ #
+ # * :tag: the node type must match the corresponding value
+ # * :attributes: a hash. The node's attributes must match the
+ # corresponding values in the hash.
+ # * :parent: a hash. The node's parent must match the
+ # corresponding hash.
+ # * :child: a hash. At least one of the node's immediate children
+ # must meet the criteria described by the hash.
+ # * :ancestor: a hash. At least one of the node's ancestors must
+ # meet the criteria described by the hash.
+ # * :descendant: a hash. At least one of the node's descendants
+ # must meet the criteria described by the hash.
+ # * :sibling: a hash. At least one of the node's siblings must
+ # meet the criteria described by the hash.
+ # * :after: a hash. The node must be after any sibling meeting
+ # the criteria described by the hash, and at least one sibling must match.
+ # * :before: a hash. The node must be before any sibling meeting
+ # the criteria described by the hash, and at least one sibling must match.
+ # * :children: a hash, for counting children of a node. Accepts
+ # the keys:
+ # * :count: either a number or a range which must equal (or
+ # include) the number of children that match.
+ # * :less_than: the number of matching children must be less
+ # than this number.
+ # * :greater_than: the number of matching children must be
+ # greater than this number.
+ # * :only: another hash consisting of the keys to use
+ # to match on the children, and only matching children will be
+ # counted.
+ # * :content: the textual content of the node must match the
+ # given value. This will not match HTML tags in the body of a
+ # tag--only text.
+ #
+ # Conditions are matched using the following algorithm:
+ #
+ # * if the condition is a string, it must be a substring of the value.
+ # * if the condition is a regexp, it must match the value.
+ # * if the condition is a number, the value must match number.to_s.
+ # * if the condition is +true+, the value must not be +nil+.
+ # * if the condition is +false+ or +nil+, the value must be +nil+.
+ #
+ # === Examples
+ #
+ # # Assert that there is a "span" tag
+ # assert_tag :tag => "span"
+ #
+ # # Assert that there is a "span" tag with id="x"
+ # assert_tag :tag => "span", :attributes => { :id => "x" }
+ #
+ # # Assert that there is a "span" tag using the short-hand
+ # assert_tag :span
+ #
+ # # Assert that there is a "span" tag with id="x" using the short-hand
+ # assert_tag :span, :attributes => { :id => "x" }
+ #
+ # # Assert that there is a "span" inside of a "div"
+ # assert_tag :tag => "span", :parent => { :tag => "div" }
+ #
+ # # Assert that there is a "span" somewhere inside a table
+ # assert_tag :tag => "span", :ancestor => { :tag => "table" }
+ #
+ # # Assert that there is a "span" with at least one "em" child
+ # assert_tag :tag => "span", :child => { :tag => "em" }
+ #
+ # # Assert that there is a "span" containing a (possibly nested)
+ # # "strong" tag.
+ # assert_tag :tag => "span", :descendant => { :tag => "strong" }
+ #
+ # # Assert that there is a "span" containing between 2 and 4 "em" tags
+ # # as immediate children
+ # assert_tag :tag => "span",
+ # :children => { :count => 2..4, :only => { :tag => "em" } }
+ #
+ # # Get funky: assert that there is a "div", with an "ul" ancestor
+ # # and an "li" parent (with "class" = "enum"), and containing a
+ # # "span" descendant that contains text matching /hello world/
+ # assert_tag :tag => "div",
+ # :ancestor => { :tag => "ul" },
+ # :parent => { :tag => "li",
+ # :attributes => { :class => "enum" } },
+ # :descendant => { :tag => "span",
+ # :child => /hello world/ }
+ #
+ # Please note: +assert_tag+ and +assert_no_tag+ only work
+ # with well-formed XHTML. They recognize a few tags as implicitly self-closing
+ # (like br and hr and such) but will not work correctly with tags
+ # that allow optional closing tags (p, li, td). You must explicitly
+ # close all of your tags to use these assertions.
+ def assert_tag(*opts)
+ opts = opts.size > 1 ? opts.last.merge({ :tag => opts.first.to_s }) : opts.first
+ tag = find_tag(opts)
+ assert tag, "expected tag, but no tag found matching #{opts.inspect} in:\n#{@response.body.inspect}"
+ end
+
+ # Identical to +assert_tag+, but asserts that a matching tag does _not_
+ # exist. (See +assert_tag+ for a full discussion of the syntax.)
+ #
+ # === Examples
+ # # Assert that there is not a "div" containing a "p"
+ # assert_no_tag :tag => "div", :descendant => { :tag => "p" }
+ #
+ # # Assert that an unordered list is empty
+ # assert_no_tag :tag => "ul", :descendant => { :tag => "li" }
+ #
+ # # Assert that there is not a "p" tag with between 1 to 3 "img" tags
+ # # as immediate children
+ # assert_no_tag :tag => "p",
+ # :children => { :count => 1..3, :only => { :tag => "img" } }
+ def assert_no_tag(*opts)
+ opts = opts.size > 1 ? opts.last.merge({ :tag => opts.first.to_s }) : opts.first
+ tag = find_tag(opts)
+ assert !tag, "expected no tag, but found tag matching #{opts.inspect} in:\n#{@response.body.inspect}"
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/test_case.rb b/actionpack/lib/action_view/test_case.rb
index 50bed67f7d..22adf97304 100644
--- a/actionpack/lib/action_view/test_case.rb
+++ b/actionpack/lib/action_view/test_case.rb
@@ -21,7 +21,7 @@ module ActionView
end
class TestCase < ActiveSupport::TestCase
- include ActionController::TestCase::Assertions
+ include ActionDispatch::Assertions
include ActionController::TestProcess
class_inheritable_accessor :helper_class
--
cgit v1.2.3
From ba9887c9c02a3671c3d1d893cbee9f360ea2df2d Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Thu, 30 Apr 2009 13:45:12 -0500
Subject: Switch to action_dispatch rack namespace
---
actionpack/lib/action_controller/testing/process.rb | 2 +-
actionpack/lib/action_dispatch/http/request.rb | 4 ++--
actionpack/lib/action_dispatch/middleware/params_parser.rb | 2 +-
actionpack/test/dispatch/request_test.rb | 2 +-
4 files changed, 5 insertions(+), 5 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/testing/process.rb b/actionpack/lib/action_controller/testing/process.rb
index 16a8f66bc4..a2bb9afaa5 100644
--- a/actionpack/lib/action_controller/testing/process.rb
+++ b/actionpack/lib/action_controller/testing/process.rb
@@ -109,7 +109,7 @@ module ActionController #:nodoc:
end
def recycle!
- @env["action_controller.request.request_parameters"] = {}
+ @env["action_dispatch.request.request_parameters"] = {}
self.query_parameters = {}
self.path_parameters = {}
@headers, @request_method, @accepts, @content_type = nil, nil, nil, nil
diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb
index 2602b344ca..9f0361a874 100755
--- a/actionpack/lib/action_dispatch/http/request.rb
+++ b/actionpack/lib/action_dispatch/http/request.rb
@@ -437,13 +437,13 @@ EOM
# Override Rack's GET method to support indifferent access
def GET
- @env["action_controller.request.query_parameters"] ||= normalize_parameters(super)
+ @env["action_dispatch.request.query_parameters"] ||= normalize_parameters(super)
end
alias_method :query_parameters, :GET
# Override Rack's POST method to support indifferent access
def POST
- @env["action_controller.request.request_parameters"] ||= normalize_parameters(super)
+ @env["action_dispatch.request.request_parameters"] ||= normalize_parameters(super)
end
alias_method :request_parameters, :POST
diff --git a/actionpack/lib/action_dispatch/middleware/params_parser.rb b/actionpack/lib/action_dispatch/middleware/params_parser.rb
index abaee2829e..58d527a6e7 100644
--- a/actionpack/lib/action_dispatch/middleware/params_parser.rb
+++ b/actionpack/lib/action_dispatch/middleware/params_parser.rb
@@ -11,7 +11,7 @@ module ActionDispatch
def call(env)
if params = parse_formatted_parameters(env)
- env["action_controller.request.request_parameters"] = params
+ env["action_dispatch.request.request_parameters"] = params
end
@app.call(env)
diff --git a/actionpack/test/dispatch/request_test.rb b/actionpack/test/dispatch/request_test.rb
index d57a2a611f..3a85db8aa5 100644
--- a/actionpack/test/dispatch/request_test.rb
+++ b/actionpack/test/dispatch/request_test.rb
@@ -307,7 +307,7 @@ class RequestTest < ActiveSupport::TestCase
test "restrict method hacking" do
[:get, :put, :delete].each do |method|
request = stub_request 'REQUEST_METHOD' => method.to_s.upcase,
- 'action_controller.request.request_parameters' => { :_method => 'put' }
+ 'action_dispatch.request.request_parameters' => { :_method => 'put' }
assert_equal method, request.method
end
end
--
cgit v1.2.3
From 9bac470c7ac7bc15830a66f416358d8efc74a39d Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Thu, 30 Apr 2009 14:28:42 -0500
Subject: Group integration test helpers and delegate other helpers to request
and response objects
---
.../lib/action_controller/testing/integration.rb | 273 ++++++++++-----------
actionpack/lib/action_dispatch/http/response.rb | 9 +
actionpack/test/controller/integration_test.rb | 12 +-
3 files changed, 136 insertions(+), 158 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/testing/integration.rb b/actionpack/lib/action_controller/testing/integration.rb
index 7fa1fd93bf..f088e91de4 100644
--- a/actionpack/lib/action_controller/testing/integration.rb
+++ b/actionpack/lib/action_controller/testing/integration.rb
@@ -4,6 +4,114 @@ require 'active_support/test_case'
module ActionController
module Integration #:nodoc:
+ module RequestHelpers
+ # Performs a GET request with the given parameters.
+ #
+ # - +path+: The URI (as a String) on which you want to perform a GET
+ # request.
+ # - +parameters+: The HTTP parameters that you want to pass. This may
+ # be +nil+,
+ # a Hash, or a String that is appropriately encoded
+ # (application/x-www-form-urlencoded or
+ # multipart/form-data).
+ # - +headers+: Additional HTTP headers to pass, as a Hash. The keys will
+ # automatically be upcased, with the prefix 'HTTP_' added if needed.
+ #
+ # This method returns an Response object, which one can use to
+ # inspect the details of the response. Furthermore, if this method was
+ # called from an ActionController::IntegrationTest object, then that
+ # object's @response instance variable will point to the same
+ # response object.
+ #
+ # You can also perform POST, PUT, DELETE, and HEAD requests with +post+,
+ # +put+, +delete+, and +head+.
+ def get(path, parameters = nil, headers = nil)
+ process :get, path, parameters, headers
+ end
+
+ # Performs a POST request with the given parameters. See get() for more
+ # details.
+ def post(path, parameters = nil, headers = nil)
+ process :post, path, parameters, headers
+ end
+
+ # Performs a PUT request with the given parameters. See get() for more
+ # details.
+ def put(path, parameters = nil, headers = nil)
+ process :put, path, parameters, headers
+ end
+
+ # Performs a DELETE request with the given parameters. See get() for
+ # more details.
+ def delete(path, parameters = nil, headers = nil)
+ process :delete, path, parameters, headers
+ end
+
+ # Performs a HEAD request with the given parameters. See get() for more
+ # details.
+ def head(path, parameters = nil, headers = nil)
+ process :head, path, parameters, headers
+ end
+
+ # Performs an XMLHttpRequest request with the given parameters, mirroring
+ # a request from the Prototype library.
+ #
+ # The request_method is :get, :post, :put, :delete or :head; the
+ # parameters are +nil+, a hash, or a url-encoded or multipart string;
+ # the headers are a hash. Keys are automatically upcased and prefixed
+ # with 'HTTP_' if not already.
+ def xml_http_request(request_method, path, parameters = nil, headers = nil)
+ headers ||= {}
+ headers['X-Requested-With'] = 'XMLHttpRequest'
+ headers['Accept'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
+ process(request_method, path, parameters, headers)
+ end
+ alias xhr :xml_http_request
+
+ # Follow a single redirect response. If the last response was not a
+ # redirect, an exception will be raised. Otherwise, the redirect is
+ # performed on the location header.
+ def follow_redirect!
+ raise "not a redirect! #{status} #{status_message}" unless redirect?
+ get(response.location)
+ status
+ end
+
+ # Performs a request using the specified method, following any subsequent
+ # redirect. Note that the redirects are followed until the response is
+ # not a redirect--this means you may run into an infinite loop if your
+ # redirect loops back to itself.
+ def request_via_redirect(http_method, path, parameters = nil, headers = nil)
+ process(http_method, path, parameters, headers)
+ follow_redirect! while redirect?
+ status
+ end
+
+ # Performs a GET request, following any subsequent redirect.
+ # See +request_via_redirect+ for more information.
+ def get_via_redirect(path, parameters = nil, headers = nil)
+ request_via_redirect(:get, path, parameters, headers)
+ end
+
+ # Performs a POST request, following any subsequent redirect.
+ # See +request_via_redirect+ for more information.
+ def post_via_redirect(path, parameters = nil, headers = nil)
+ request_via_redirect(:post, path, parameters, headers)
+ end
+
+ # Performs a PUT request, following any subsequent redirect.
+ # See +request_via_redirect+ for more information.
+ def put_via_redirect(path, parameters = nil, headers = nil)
+ request_via_redirect(:put, path, parameters, headers)
+ end
+
+ # Performs a DELETE request, following any subsequent redirect.
+ # See +request_via_redirect+ for more information.
+ def delete_via_redirect(path, parameters = nil, headers = nil)
+ request_via_redirect(:delete, path, parameters, headers)
+ end
+ end
+
# An integration Session instance represents a set of requests and responses
# performed sequentially by some virtual user. Because you can instantiate
# multiple sessions and run them side-by-side, you can also mimic (to some
@@ -16,18 +124,15 @@ module ActionController
include Test::Unit::Assertions
include ActionDispatch::Assertions
include ActionController::TestProcess
+ include RequestHelpers
- # The integer HTTP status code of the last request.
- attr_reader :status
-
- # The status message that accompanied the status code of the last request.
- attr_reader :status_message
-
- # The body of the last request.
- attr_reader :body
+ %w( status status_message headers body redirect? ).each do |method|
+ delegate method, :to => :response, :allow_nil => true
+ end
- # The URI of the last request.
- attr_reader :path
+ %w( path ).each do |method|
+ delegate method, :to => :request, :allow_nil => true
+ end
# The hostname used in the last request.
attr_accessor :host
@@ -42,9 +147,6 @@ module ActionController
# sent with the next request.
attr_reader :cookies
- # A map of the headers returned by the last response.
- attr_reader :headers
-
# A reference to the controller instance used by the last request.
attr_reader :controller
@@ -69,8 +171,6 @@ module ActionController
#
# session.reset!
def reset!
- @status = @path = @headers = nil
- @result = @status_message = nil
@https = false
@cookies = {}
@controller = @request = @response = nil
@@ -118,117 +218,6 @@ module ActionController
@host = name
end
- # Follow a single redirect response. If the last response was not a
- # redirect, an exception will be raised. Otherwise, the redirect is
- # performed on the location header.
- def follow_redirect!
- raise "not a redirect! #{@status} #{@status_message}" unless redirect?
- get(interpret_uri(headers['location']))
- status
- end
-
- # Performs a request using the specified method, following any subsequent
- # redirect. Note that the redirects are followed until the response is
- # not a redirect--this means you may run into an infinite loop if your
- # redirect loops back to itself.
- def request_via_redirect(http_method, path, parameters = nil, headers = nil)
- send(http_method, path, parameters, headers)
- follow_redirect! while redirect?
- status
- end
-
- # Performs a GET request, following any subsequent redirect.
- # See +request_via_redirect+ for more information.
- def get_via_redirect(path, parameters = nil, headers = nil)
- request_via_redirect(:get, path, parameters, headers)
- end
-
- # Performs a POST request, following any subsequent redirect.
- # See +request_via_redirect+ for more information.
- def post_via_redirect(path, parameters = nil, headers = nil)
- request_via_redirect(:post, path, parameters, headers)
- end
-
- # Performs a PUT request, following any subsequent redirect.
- # See +request_via_redirect+ for more information.
- def put_via_redirect(path, parameters = nil, headers = nil)
- request_via_redirect(:put, path, parameters, headers)
- end
-
- # Performs a DELETE request, following any subsequent redirect.
- # See +request_via_redirect+ for more information.
- def delete_via_redirect(path, parameters = nil, headers = nil)
- request_via_redirect(:delete, path, parameters, headers)
- end
-
- # Returns +true+ if the last response was a redirect.
- def redirect?
- status/100 == 3
- end
-
- # Performs a GET request with the given parameters.
- #
- # - +path+: The URI (as a String) on which you want to perform a GET
- # request.
- # - +parameters+: The HTTP parameters that you want to pass. This may
- # be +nil+,
- # a Hash, or a String that is appropriately encoded
- # (application/x-www-form-urlencoded or
- # multipart/form-data).
- # - +headers+: Additional HTTP headers to pass, as a Hash. The keys will
- # automatically be upcased, with the prefix 'HTTP_' added if needed.
- #
- # This method returns an Response object, which one can use to
- # inspect the details of the response. Furthermore, if this method was
- # called from an ActionController::IntegrationTest object, then that
- # object's @response instance variable will point to the same
- # response object.
- #
- # You can also perform POST, PUT, DELETE, and HEAD requests with +post+,
- # +put+, +delete+, and +head+.
- def get(path, parameters = nil, headers = nil)
- process :get, path, parameters, headers
- end
-
- # Performs a POST request with the given parameters. See get() for more
- # details.
- def post(path, parameters = nil, headers = nil)
- process :post, path, parameters, headers
- end
-
- # Performs a PUT request with the given parameters. See get() for more
- # details.
- def put(path, parameters = nil, headers = nil)
- process :put, path, parameters, headers
- end
-
- # Performs a DELETE request with the given parameters. See get() for
- # more details.
- def delete(path, parameters = nil, headers = nil)
- process :delete, path, parameters, headers
- end
-
- # Performs a HEAD request with the given parameters. See get() for more
- # details.
- def head(path, parameters = nil, headers = nil)
- process :head, path, parameters, headers
- end
-
- # Performs an XMLHttpRequest request with the given parameters, mirroring
- # a request from the Prototype library.
- #
- # The request_method is :get, :post, :put, :delete or :head; the
- # parameters are +nil+, a hash, or a url-encoded or multipart string;
- # the headers are a hash. Keys are automatically upcased and prefixed
- # with 'HTTP_' if not already.
- def xml_http_request(request_method, path, parameters = nil, headers = nil)
- headers ||= {}
- headers['X-Requested-With'] = 'XMLHttpRequest'
- headers['Accept'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
- process(request_method, path, parameters, headers)
- end
- alias xhr :xml_http_request
-
# Returns the URL for the given options, according to the rules specified
# in the application's routes.
def url_for(options)
@@ -238,19 +227,14 @@ module ActionController
end
private
- # Tailors the session based on the given URI, setting the HTTPS value
- # and the hostname.
- def interpret_uri(path)
- location = URI.parse(path)
- https! URI::HTTPS === location if location.scheme
- host! location.host if location.host
- location.query ? "#{location.path}?#{location.query}" : location.path
- end
-
# Performs the actual request.
def process(method, path, parameters = nil, headers = nil)
- path = interpret_uri(path) if path =~ %r{://}
- @path = path
+ if path =~ %r{://}
+ location = URI.parse(path)
+ https! URI::HTTPS === location if location.scheme
+ host! location.host if location.host
+ path = location.query ? "#{location.path}?#{location.query}" : location.path
+ end
[ControllerCapture, ActionController::ProcessWithTest].each do |mod|
unless ActionController::Base < mod
@@ -279,7 +263,7 @@ module ActionController
string << "#{name}=#{value}; "
}
}
- env = ActionDispatch::Test::MockRequest.env_for(@path, opts)
+ env = ActionDispatch::Test::MockRequest.env_for(path, opts)
(headers || {}).each do |key, value|
key = key.to_s.upcase.gsub(/-/, "_")
@@ -289,17 +273,12 @@ module ActionController
app = Rack::Lint.new(@app)
status, headers, body = app.call(env)
- response = ::Rack::MockResponse.new(status, headers, body)
+ mock_response = ::Rack::MockResponse.new(status, headers, body)
@request_count += 1
- @request = Request.new(env)
-
- @response = Response.new
- @response.status = @status = response.status
- @response.headers = @headers = response.headers
- @response.body = @body = response.body
+ @request = Request.new(env)
+ @response = Response.from_response(mock_response)
- @status_message = ActionDispatch::StatusCodes::STATUS_CODES[@status]
@cookies.merge!(@response.cookies)
@html_document = nil
@@ -312,7 +291,7 @@ module ActionController
@controller.send(:set_test_assigns)
end
- return @status
+ return response.status
end
# Get a temporary URL writer object
diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb
index d104dcb8a0..1b12308cc9 100644
--- a/actionpack/lib/action_dispatch/http/response.rb
+++ b/actionpack/lib/action_dispatch/http/response.rb
@@ -31,6 +31,14 @@ module ActionDispatch # :nodoc:
# end
# end
class Response < Rack::Response
+ def self.from_response(response)
+ new.tap do |resp|
+ resp.status = response.status
+ resp.headers = response.headers
+ resp.body = response.body
+ end
+ end
+
DEFAULT_HEADERS = { "Cache-Control" => "no-cache" }
attr_accessor :request
@@ -80,6 +88,7 @@ module ActionDispatch # :nodoc:
def message
status.to_s.split(' ',2)[1] || StatusCodes::STATUS_CODES[response_code]
end
+ alias_method :status_message, :message
# Was the response successful?
def success?
diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb
index 70fa41aded..c616107324 100644
--- a/actionpack/test/controller/integration_test.rb
+++ b/actionpack/test/controller/integration_test.rb
@@ -30,7 +30,7 @@ class SessionTest < Test::Unit::TestCase
def test_request_via_redirect_uses_given_method
path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue"}
- @session.expects(:put).with(path, args, headers)
+ @session.expects(:process).with(:put, path, args, headers)
@session.stubs(:redirect?).returns(false)
@session.request_via_redirect(:put, path, args, headers)
end
@@ -90,16 +90,6 @@ class SessionTest < Test::Unit::TestCase
assert_equal '/show', @session.url_for(options)
end
- def test_redirect_bool_with_status_in_300s
- @session.stubs(:status).returns 301
- assert @session.redirect?
- end
-
- def test_redirect_bool_with_status_in_200s
- @session.stubs(:status).returns 200
- assert !@session.redirect?
- end
-
def test_get
path = "/index"; params = "blah"; headers = {:location => 'blah'}
@session.expects(:process).with(:get,path,params,headers)
--
cgit v1.2.3
From 64e66cf161ee8db0bdbccb1be18fb760f5a9d24e Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Thu, 30 Apr 2009 14:40:46 -0500
Subject: Vendor new Rack::Mock changes
---
.../lib/action_controller/testing/integration.rb | 2 +-
.../lib/action_controller/testing/process.rb | 2 +-
actionpack/lib/action_dispatch.rb | 6 +-
actionpack/lib/action_dispatch/extensions/rack.rb | 5 +
.../lib/action_dispatch/extensions/rack/mock.rb | 65 +++++
.../lib/action_dispatch/extensions/rack/utils.rb | 262 +++++++++++++++++++++
actionpack/lib/action_dispatch/test/mock.rb | 115 ---------
.../lib/action_dispatch/test/uploaded_file.rb | 33 ---
8 files changed, 335 insertions(+), 155 deletions(-)
create mode 100644 actionpack/lib/action_dispatch/extensions/rack.rb
create mode 100644 actionpack/lib/action_dispatch/extensions/rack/mock.rb
create mode 100644 actionpack/lib/action_dispatch/extensions/rack/utils.rb
delete mode 100644 actionpack/lib/action_dispatch/test/mock.rb
delete mode 100644 actionpack/lib/action_dispatch/test/uploaded_file.rb
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/testing/integration.rb b/actionpack/lib/action_controller/testing/integration.rb
index f088e91de4..ce161ef846 100644
--- a/actionpack/lib/action_controller/testing/integration.rb
+++ b/actionpack/lib/action_controller/testing/integration.rb
@@ -263,7 +263,7 @@ module ActionController
string << "#{name}=#{value}; "
}
}
- env = ActionDispatch::Test::MockRequest.env_for(path, opts)
+ env = Rack::MockRequest.env_for(path, opts)
(headers || {}).each do |key, value|
key = key.to_s.upcase.gsub(/-/, "_")
diff --git a/actionpack/lib/action_controller/testing/process.rb b/actionpack/lib/action_controller/testing/process.rb
index a2bb9afaa5..3a7445f890 100644
--- a/actionpack/lib/action_controller/testing/process.rb
+++ b/actionpack/lib/action_controller/testing/process.rb
@@ -250,7 +250,7 @@ module ActionController #:nodoc:
#
# Pass a true third parameter to ensure the uploaded file is opened in binary mode (only required for Windows):
# post :change_avatar, :avatar => ActionController::TestUploadedFile.new(ActionController::TestCase.fixture_path + '/files/spongebob.png', 'image/png', :binary)
- TestUploadedFile = ActionDispatch::Test::UploadedFile
+ TestUploadedFile = Rack::Utils::Multipart::UploadedFile
module TestProcess
def self.included(base)
diff --git a/actionpack/lib/action_dispatch.rb b/actionpack/lib/action_dispatch.rb
index 8b8a1774e4..078e631be4 100644
--- a/actionpack/lib/action_dispatch.rb
+++ b/actionpack/lib/action_dispatch.rb
@@ -34,6 +34,7 @@ require 'active_support/core/all'
gem 'rack', '~> 1.0.0'
require 'rack'
+require 'action_dispatch/extensions/rack'
module ActionDispatch
autoload :Request, 'action_dispatch/http/request'
@@ -56,11 +57,6 @@ module ActionDispatch
autoload :CookieStore, 'action_dispatch/middleware/session/cookie_store'
autoload :MemCacheStore, 'action_dispatch/middleware/session/mem_cache_store'
end
-
- module Test
- autoload :UploadedFile, 'action_dispatch/test/uploaded_file'
- autoload :MockRequest, 'action_dispatch/test/mock'
- end
end
autoload :Mime, 'action_dispatch/http/mime_type'
diff --git a/actionpack/lib/action_dispatch/extensions/rack.rb b/actionpack/lib/action_dispatch/extensions/rack.rb
new file mode 100644
index 0000000000..8a543e2110
--- /dev/null
+++ b/actionpack/lib/action_dispatch/extensions/rack.rb
@@ -0,0 +1,5 @@
+# Monkey patch in new test helper methods
+unless Rack::Utils.respond_to?(:build_nested_query)
+ require 'action_dispatch/extensions/rack/mock'
+ require 'action_dispatch/extensions/rack/utils'
+end
diff --git a/actionpack/lib/action_dispatch/extensions/rack/mock.rb b/actionpack/lib/action_dispatch/extensions/rack/mock.rb
new file mode 100644
index 0000000000..d773a74244
--- /dev/null
+++ b/actionpack/lib/action_dispatch/extensions/rack/mock.rb
@@ -0,0 +1,65 @@
+require 'rack/mock'
+
+module Rack
+ class MockRequest
+ # Return the Rack environment used for a request to +uri+.
+ def self.env_for(uri="", opts={})
+ uri = URI(uri)
+ uri.path = "/#{uri.path}" unless uri.path[0] == ?/
+
+ env = DEFAULT_ENV.dup
+
+ env["REQUEST_METHOD"] = opts[:method] ? opts[:method].to_s.upcase : "GET"
+ env["SERVER_NAME"] = uri.host || "example.org"
+ env["SERVER_PORT"] = uri.port ? uri.port.to_s : "80"
+ env["QUERY_STRING"] = uri.query.to_s
+ env["PATH_INFO"] = (!uri.path || uri.path.empty?) ? "/" : uri.path
+ env["rack.url_scheme"] = uri.scheme || "http"
+ env["HTTPS"] = env["rack.url_scheme"] == "https" ? "on" : "off"
+
+ env["SCRIPT_NAME"] = opts[:script_name] || ""
+
+ if opts[:fatal]
+ env["rack.errors"] = FatalWarner.new
+ else
+ env["rack.errors"] = StringIO.new
+ end
+
+ if params = opts[:params]
+ if env["REQUEST_METHOD"] == "GET"
+ params = Utils.parse_nested_query(params) if params.is_a?(String)
+ params.update(Utils.parse_nested_query(env["QUERY_STRING"]))
+ env["QUERY_STRING"] = Utils.build_nested_query(params)
+ elsif !opts.has_key?(:input)
+ opts["CONTENT_TYPE"] = "application/x-www-form-urlencoded"
+ if params.is_a?(Hash)
+ if data = Utils::Multipart.build_multipart(params)
+ opts[:input] = data
+ opts["CONTENT_LENGTH"] ||= data.length.to_s
+ opts["CONTENT_TYPE"] = "multipart/form-data; boundary=#{Utils::Multipart::MULTIPART_BOUNDARY}"
+ else
+ opts[:input] = Utils.build_nested_query(params)
+ end
+ else
+ opts[:input] = params
+ end
+ end
+ end
+
+ opts[:input] ||= ""
+ if String === opts[:input]
+ env["rack.input"] = StringIO.new(opts[:input])
+ else
+ env["rack.input"] = opts[:input]
+ end
+
+ env["CONTENT_LENGTH"] ||= env["rack.input"].length.to_s
+
+ opts.each { |field, value|
+ env[field] = value if String === field
+ }
+
+ env
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/extensions/rack/utils.rb b/actionpack/lib/action_dispatch/extensions/rack/utils.rb
new file mode 100644
index 0000000000..1a46f8a4db
--- /dev/null
+++ b/actionpack/lib/action_dispatch/extensions/rack/utils.rb
@@ -0,0 +1,262 @@
+# -*- encoding: binary -*-
+
+require 'rack/utils'
+
+module Rack
+ module Utils
+ def normalize_params(params, name, v = nil)
+ name =~ %r(\A[\[\]]*([^\[\]]+)\]*)
+ k = $1 || ''
+ after = $' || ''
+
+ return if k.empty?
+
+ if after == ""
+ params[k] = v
+ elsif after == "[]"
+ params[k] ||= []
+ raise TypeError, "expected Array (got #{params[k].class.name}) for param `#{k}'" unless params[k].is_a?(Array)
+ params[k] << v
+ elsif after =~ %r(^\[\]\[([^\[\]]+)\]$) || after =~ %r(^\[\](.+)$)
+ child_key = $1
+ params[k] ||= []
+ raise TypeError, "expected Array (got #{params[k].class.name}) for param `#{k}'" unless params[k].is_a?(Array)
+ if params[k].last.is_a?(Hash) && !params[k].last.key?(child_key)
+ normalize_params(params[k].last, child_key, v)
+ else
+ params[k] << normalize_params({}, child_key, v)
+ end
+ else
+ params[k] ||= {}
+ raise TypeError, "expected Hash (got #{params[k].class.name}) for param `#{k}'" unless params[k].is_a?(Hash)
+ params[k] = normalize_params(params[k], after, v)
+ end
+
+ return params
+ end
+ module_function :normalize_params
+
+ def build_nested_query(value, prefix = nil)
+ case value
+ when Array
+ value.map { |v|
+ build_nested_query(v, "#{prefix}[]")
+ }.join("&")
+ when Hash
+ value.map { |k, v|
+ build_nested_query(v, prefix ? "#{prefix}[#{escape(k)}]" : escape(k))
+ }.join("&")
+ when String
+ raise ArgumentError, "value must be a Hash" if prefix.nil?
+ "#{prefix}=#{escape(value)}"
+ else
+ prefix
+ end
+ end
+ module_function :build_nested_query
+
+ module Multipart
+ class UploadedFile
+ # The filename, *not* including the path, of the "uploaded" file
+ attr_reader :original_filename
+
+ # The content type of the "uploaded" file
+ attr_accessor :content_type
+
+ def initialize(path, content_type = "text/plain", binary = false)
+ raise "#{path} file does not exist" unless ::File.exist?(path)
+ @content_type = content_type
+ @original_filename = ::File.basename(path)
+ @tempfile = Tempfile.new(@original_filename)
+ @tempfile.set_encoding(Encoding::BINARY) if @tempfile.respond_to?(:set_encoding)
+ @tempfile.binmode if binary
+ FileUtils.copy_file(path, @tempfile.path)
+ end
+
+ def path
+ @tempfile.path
+ end
+ alias_method :local_path, :path
+
+ def method_missing(method_name, *args, &block) #:nodoc:
+ @tempfile.__send__(method_name, *args, &block)
+ end
+ end
+
+ EOL = "\r\n"
+ MULTIPART_BOUNDARY = "AaB03x"
+
+ def self.parse_multipart(env)
+ unless env['CONTENT_TYPE'] =~
+ %r|\Amultipart/.*boundary=\"?([^\";,]+)\"?|n
+ nil
+ else
+ boundary = "--#{$1}"
+
+ params = {}
+ buf = ""
+ content_length = env['CONTENT_LENGTH'].to_i
+ input = env['rack.input']
+ input.rewind
+
+ boundary_size = Utils.bytesize(boundary) + EOL.size
+ bufsize = 16384
+
+ content_length -= boundary_size
+
+ read_buffer = ''
+
+ status = input.read(boundary_size, read_buffer)
+ raise EOFError, "bad content body" unless status == boundary + EOL
+
+ rx = /(?:#{EOL})?#{Regexp.quote boundary}(#{EOL}|--)/n
+
+ loop {
+ head = nil
+ body = ''
+ filename = content_type = name = nil
+
+ until head && buf =~ rx
+ if !head && i = buf.index(EOL+EOL)
+ head = buf.slice!(0, i+2) # First \r\n
+ buf.slice!(0, 2) # Second \r\n
+
+ filename = head[/Content-Disposition:.* filename="?([^\";]*)"?/ni, 1]
+ content_type = head[/Content-Type: (.*)#{EOL}/ni, 1]
+ name = head[/Content-Disposition:.*\s+name="?([^\";]*)"?/ni, 1] || head[/Content-ID:\s*([^#{EOL}]*)/ni, 1]
+
+ if content_type || filename
+ body = Tempfile.new("RackMultipart")
+ body.binmode if body.respond_to?(:binmode)
+ end
+
+ next
+ end
+
+ # Save the read body part.
+ if head && (boundary_size+4 < buf.size)
+ body << buf.slice!(0, buf.size - (boundary_size+4))
+ end
+
+ c = input.read(bufsize < content_length ? bufsize : content_length, read_buffer)
+ raise EOFError, "bad content body" if c.nil? || c.empty?
+ buf << c
+ content_length -= c.size
+ end
+
+ # Save the rest.
+ if i = buf.index(rx)
+ body << buf.slice!(0, i)
+ buf.slice!(0, boundary_size+2)
+
+ content_length = -1 if $1 == "--"
+ end
+
+ if filename == ""
+ # filename is blank which means no file has been selected
+ data = nil
+ elsif filename
+ body.rewind
+
+ # Take the basename of the upload's original filename.
+ # This handles the full Windows paths given by Internet Explorer
+ # (and perhaps other broken user agents) without affecting
+ # those which give the lone filename.
+ filename =~ /^(?:.*[:\\\/])?(.*)/m
+ filename = $1
+
+ data = {:filename => filename, :type => content_type,
+ :name => name, :tempfile => body, :head => head}
+ elsif !filename && content_type
+ body.rewind
+
+ # Generic multipart cases, not coming from a form
+ data = {:type => content_type,
+ :name => name, :tempfile => body, :head => head}
+ else
+ data = body
+ end
+
+ Utils.normalize_params(params, name, data) unless data.nil?
+
+ break if buf.empty? || content_length == -1
+ }
+
+ input.rewind
+
+ params
+ end
+ end
+
+ def self.build_multipart(params, first = true)
+ if first
+ unless params.is_a?(Hash)
+ raise ArgumentError, "value must be a Hash"
+ end
+
+ multipart = false
+ query = lambda { |value|
+ case value
+ when Array
+ value.each(&query)
+ when Hash
+ value.values.each(&query)
+ when UploadedFile
+ multipart = true
+ end
+ }
+ params.values.each(&query)
+ return nil unless multipart
+ end
+
+ flattened_params = Hash.new
+
+ params.each do |key, value|
+ k = first ? key.to_s : "[#{key}]"
+
+ case value
+ when Array
+ value.map { |v|
+ build_multipart(v, false).each { |subkey, subvalue|
+ flattened_params["#{k}[]#{subkey}"] = subvalue
+ }
+ }
+ when Hash
+ build_multipart(value, false).each { |subkey, subvalue|
+ flattened_params[k + subkey] = subvalue
+ }
+ else
+ flattened_params[k] = value
+ end
+ end
+
+ if first
+ flattened_params.map { |name, file|
+ if file.respond_to?(:original_filename)
+ ::File.open(file.path, "rb") do |f|
+ f.set_encoding(Encoding::BINARY) if f.respond_to?(:set_encoding)
+<<-EOF
+--#{MULTIPART_BOUNDARY}\r
+Content-Disposition: form-data; name="#{name}"; filename="#{Utils.escape(file.original_filename)}"\r
+Content-Type: #{file.content_type}\r
+Content-Length: #{::File.stat(file.path).size}\r
+\r
+#{f.read}\r
+EOF
+ end
+ else
+<<-EOF
+--#{MULTIPART_BOUNDARY}\r
+Content-Disposition: form-data; name="#{name}"\r
+\r
+#{file}\r
+EOF
+ end
+ }.join + "--#{MULTIPART_BOUNDARY}--\r"
+ else
+ flattened_params
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/test/mock.rb b/actionpack/lib/action_dispatch/test/mock.rb
deleted file mode 100644
index 68e5b108b4..0000000000
--- a/actionpack/lib/action_dispatch/test/mock.rb
+++ /dev/null
@@ -1,115 +0,0 @@
-module ActionDispatch
- module Test
- class MockRequest < Rack::MockRequest
- MULTIPART_BOUNDARY = "----------XnJLe9ZIbbGUYtzPQJ16u1"
-
- class << self
- def env_for(path, opts)
- method = (opts[:method] || opts["REQUEST_METHOD"]).to_s.upcase
- opts[:method] = opts["REQUEST_METHOD"] = method
-
- path = "/#{path}" unless path[0] == ?/
- uri = URI.parse(path)
- uri.host ||= "example.org"
-
- if URI::HTTPS === uri
- opts.update("SERVER_PORT" => "443", "HTTPS" => "on")
- end
-
- if method == "POST" && !opts.has_key?(:input)
- opts["CONTENT_TYPE"] = "application/x-www-form-urlencoded"
-
- multipart = opts[:params].respond_to?(:any?) && opts[:params].any? { |k, v| UploadedFile === v }
- if multipart
- opts[:input] = multipart_body(opts.delete(:params))
- opts["CONTENT_LENGTH"] ||= opts[:input].length.to_s
- opts["CONTENT_TYPE"] = "multipart/form-data; boundary=#{MULTIPART_BOUNDARY}"
- else
- params = opts.delete(:params)
- opts[:input] = case params
- when Hash then requestify(params)
- when nil then ""
- else params
- end
- end
- end
-
- params = opts[:params] || {}
- if params.is_a?(String)
- if method == "GET"
- uri.query = params
- else
- opts[:input] = params
- end
- else
- params.stringify_keys!
- params.update(::Rack::Utils.parse_query(uri.query))
- uri.query = requestify(params)
- end
-
- ::Rack::MockRequest.env_for(uri.to_s, opts)
- end
-
- private
- def requestify(value, prefix = nil)
- case value
- when Array
- value.map do |v|
- requestify(v, "#{prefix}[]")
- end.join("&")
- when Hash
- value.map do |k, v|
- requestify(v, prefix ? "#{prefix}[#{::Rack::Utils.escape(k)}]" : ::Rack::Utils.escape(k))
- end.join("&")
- else
- "#{prefix}=#{::Rack::Utils.escape(value)}"
- end
- end
-
- def multipart_requestify(params, first=true)
- p = Hash.new
-
- params.each do |key, value|
- k = first ? key.to_s : "[#{key}]"
-
- if Hash === value
- multipart_requestify(value, false).each do |subkey, subvalue|
- p[k + subkey] = subvalue
- end
- else
- p[k] = value
- end
- end
-
- return p
- end
-
- def multipart_body(params)
- multipart_requestify(params).map do |key, value|
- if value.respond_to?(:original_filename)
- ::File.open(value.path, "rb") do |f|
- f.set_encoding(Encoding::BINARY) if f.respond_to?(:set_encoding)
-
- <<-EOF
---#{MULTIPART_BOUNDARY}\r
-Content-Disposition: form-data; name="#{key}"; filename="#{::Rack::Utils.escape(value.original_filename)}"\r
-Content-Type: #{value.content_type}\r
-Content-Length: #{::File.stat(value.path).size}\r
-\r
-#{f.read}\r
-EOF
- end
- else
-<<-EOF
---#{MULTIPART_BOUNDARY}\r
-Content-Disposition: form-data; name="#{key}"\r
-\r
-#{value}\r
-EOF
- end
- end.join("")+"--#{MULTIPART_BOUNDARY}--\r"
- end
- end
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/test/uploaded_file.rb b/actionpack/lib/action_dispatch/test/uploaded_file.rb
deleted file mode 100644
index 0ac7db4863..0000000000
--- a/actionpack/lib/action_dispatch/test/uploaded_file.rb
+++ /dev/null
@@ -1,33 +0,0 @@
-require "tempfile"
-
-module ActionDispatch
- module Test
- class UploadedFile
- # The filename, *not* including the path, of the "uploaded" file
- attr_reader :original_filename
-
- # The content type of the "uploaded" file
- attr_accessor :content_type
-
- def initialize(path, content_type = "text/plain", binary = false)
- raise "#{path} file does not exist" unless ::File.exist?(path)
- @content_type = content_type
- @original_filename = ::File.basename(path)
- @tempfile = Tempfile.new(@original_filename)
- @tempfile.set_encoding(Encoding::BINARY) if @tempfile.respond_to?(:set_encoding)
- @tempfile.binmode if binary
- FileUtils.copy_file(path, @tempfile.path)
- end
-
- def path
- @tempfile.path
- end
-
- alias_method :local_path, :path
-
- def method_missing(method_name, *args, &block) #:nodoc:
- @tempfile.__send__(method_name, *args, &block)
- end
- end
- end
-end
--
cgit v1.2.3
From 00d1a57e9f99a1b2439281cb741fd82ef47a5c55 Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Thu, 30 Apr 2009 17:26:03 -0500
Subject: Start moving TestRequest and TestResponse into ActionDispatch
---
actionpack/lib/action_controller/base/base.rb | 3 +-
.../lib/action_controller/testing/integration.rb | 11 +-
.../lib/action_controller/testing/process.rb | 170 ++-------------------
actionpack/lib/action_dispatch.rb | 2 +
.../lib/action_dispatch/extensions/rack/utils.rb | 1 -
actionpack/lib/action_dispatch/http/request.rb | 36 +++--
actionpack/lib/action_dispatch/http/response.rb | 56 -------
.../lib/action_dispatch/testing/test_request.rb | 56 +++++++
.../lib/action_dispatch/testing/test_response.rb | 131 ++++++++++++++++
.../test/controller/action_pack_assertions_test.rb | 22 ++-
actionpack/test/controller/caching_test.rb | 2 +-
actionpack/test/controller/routing_test.rb | 8 +-
actionpack/test/controller/test_test.rb | 4 +-
actionpack/test/dispatch/test_request_test.rb | 30 ++++
14 files changed, 279 insertions(+), 253 deletions(-)
create mode 100644 actionpack/lib/action_dispatch/testing/test_request.rb
create mode 100644 actionpack/lib/action_dispatch/testing/test_response.rb
create mode 100644 actionpack/test/dispatch/test_request_test.rb
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/base/base.rb b/actionpack/lib/action_controller/base/base.rb
index 14c4339c94..99b5963891 100644
--- a/actionpack/lib/action_controller/base/base.rb
+++ b/actionpack/lib/action_controller/base/base.rb
@@ -817,7 +817,8 @@ module ActionController #:nodoc:
end
def initialize_template_class(response)
- @template = response.template = ActionView::Base.new(self.class.view_paths, {}, self, formats)
+ @template = ActionView::Base.new(self.class.view_paths, {}, self, formats)
+ response.template = @template if response.respond_to?(:template=)
@template.helpers.send :include, self.class.master_helper_module
response.redirected_to = nil
@performed_render = @performed_redirect = false
diff --git a/actionpack/lib/action_controller/testing/integration.rb b/actionpack/lib/action_controller/testing/integration.rb
index ce161ef846..4f39ee6a01 100644
--- a/actionpack/lib/action_controller/testing/integration.rb
+++ b/actionpack/lib/action_controller/testing/integration.rb
@@ -245,7 +245,7 @@ module ActionController
ActionController::Base.clear_last_instantiation!
opts = {
- :method => method.to_s.upcase,
+ :method => method,
:params => parameters,
"SERVER_NAME" => host,
@@ -276,17 +276,12 @@ module ActionController
mock_response = ::Rack::MockResponse.new(status, headers, body)
@request_count += 1
- @request = Request.new(env)
- @response = Response.from_response(mock_response)
+ @request = ActionDispatch::Request.new(env)
+ @response = ActionDispatch::TestResponse.from_response(mock_response)
@cookies.merge!(@response.cookies)
@html_document = nil
- # Decorate the response with the standard behavior of the
- # TestResponse so that things like assert_response can be
- # used in integration tests.
- @response.extend(TestResponseBehavior)
-
if @controller = ActionController::Base.last_instantiation
@controller.send(:set_test_assigns)
end
diff --git a/actionpack/lib/action_controller/testing/process.rb b/actionpack/lib/action_controller/testing/process.rb
index 3a7445f890..e0f8f026fd 100644
--- a/actionpack/lib/action_controller/testing/process.rb
+++ b/actionpack/lib/action_controller/testing/process.rb
@@ -1,24 +1,19 @@
require 'rack/session/abstract/id'
module ActionController #:nodoc:
- class TestRequest < ActionDispatch::Request #:nodoc:
+ class TestRequest < ActionDispatch::TestRequest #:nodoc:
attr_accessor :cookies
- attr_accessor :query_parameters, :path
- attr_accessor :host
-
- def self.new(env = {})
- super
- end
+ attr_accessor :query_parameters
def initialize(env = {})
- super(Rack::MockRequest.env_for("/").merge(env))
+ super
- @query_parameters = {}
+ @query_parameters = {}
self.session = TestSession.new
self.session_options = TestSession::DEFAULT_OPTIONS.merge(:id => ActiveSupport::SecureRandom.hex(16))
- initialize_default_values
- initialize_containers
+ @request_uri = "/"
+ @cookies = {}
end
# Wraps raw_post in a StringIO.
@@ -36,55 +31,8 @@ module ActionController #:nodoc:
end
end
- def port=(number)
- @env["SERVER_PORT"] = number.to_i
- end
-
def action=(action_name)
- @query_parameters.update({ "action" => action_name })
- @parameters = nil
- end
-
- # Used to check AbstractRequest's request_uri functionality.
- # Disables the use of @path and @request_uri so superclass can handle those.
- def set_REQUEST_URI(value)
- @env["REQUEST_URI"] = value
- @request_uri = nil
- @path = nil
- end
-
- def request_uri=(uri)
- @request_uri = uri
- @path = uri.split("?").first
- end
-
- def request_method=(method)
- @request_method = method
- end
-
- def accept=(mime_types)
- @env["HTTP_ACCEPT"] = Array(mime_types).collect { |mime_types| mime_types.to_s }.join(",")
- @accepts = nil
- end
-
- def if_modified_since=(last_modified)
- @env["HTTP_IF_MODIFIED_SINCE"] = last_modified
- end
-
- def if_none_match=(etag)
- @env["HTTP_IF_NONE_MATCH"] = etag
- end
-
- def remote_addr=(addr)
- @env['REMOTE_ADDR'] = addr
- end
-
- def request_uri(*args)
- @request_uri || super()
- end
-
- def path(*args)
- @path || super()
+ query_parameters.update({ "action" => action_name })
end
def assign_parameters(controller_path, action, parameters)
@@ -105,34 +53,15 @@ module ActionController #:nodoc:
end
end
raw_post # populate env['RAW_POST_DATA']
- @parameters = nil # reset TestRequest#parameters to use the new path_parameters
end
def recycle!
- @env["action_dispatch.request.request_parameters"] = {}
- self.query_parameters = {}
- self.path_parameters = {}
- @headers, @request_method, @accepts, @content_type = nil, nil, nil, nil
- end
-
- def user_agent=(user_agent)
- @env['HTTP_USER_AGENT'] = user_agent
+ @env.delete_if { |k, v| k =~ /^action_dispatch\.request/ }
+ self.query_parameters = {}
+ @headers = nil
end
private
- def initialize_containers
- @cookies = {}
- end
-
- def initialize_default_values
- @host = "test.host"
- @request_uri = "/"
- @env['HTTP_USER_AGENT'] = "Rails Testing"
- @env['REMOTE_ADDR'] = "0.0.0.0"
- @env["SERVER_PORT"] = 80
- @env['REQUEST_METHOD'] = "GET"
- end
-
def url_encoded_request_parameters
params = self.request_parameters.dup
@@ -145,84 +74,13 @@ module ActionController #:nodoc:
end
end
- # A refactoring of TestResponse to allow the same behavior to be applied
- # to the "real" CgiResponse class in integration tests.
- module TestResponseBehavior #:nodoc:
- def redirect_url_match?(pattern)
- ::ActiveSupport::Deprecation.warn("response.redirect_url_match? is deprecated. Use assert_match(/foo/, response.redirect_url) instead", caller)
- return false if redirect_url.nil?
- p = Regexp.new(pattern) if pattern.class == String
- p = pattern if pattern.class == Regexp
- return false if p.nil?
- p.match(redirect_url) != nil
- end
-
- # Returns the template of the file which was used to
- # render this response (or nil)
- def rendered
- ActiveSupport::Deprecation.warn("response.rendered has been deprecated. Use tempate.rendered instead", caller)
- @template.instance_variable_get(:@_rendered)
- end
-
- # A shortcut to the flash. Returns an empty hash if no session flash exists.
- def flash
- request.session['flash'] || {}
- end
-
- # Do we have a flash?
- def has_flash?
- !flash.empty?
- end
-
- # Do we have a flash that has contents?
- def has_flash_with_contents?
- !flash.empty?
- end
-
- # Does the specified flash object exist?
- def has_flash_object?(name=nil)
- !flash[name].nil?
- end
-
- # Does the specified object exist in the session?
- def has_session_object?(name=nil)
- !session[name].nil?
- end
-
- # A shortcut to the template.assigns
- def template_objects
- ActiveSupport::Deprecation.warn("response.template_objects has been deprecated. Use tempate.assigns instead", caller)
- @template.assigns || {}
- end
-
- # Does the specified template object exist?
- def has_template_object?(name=nil)
- ActiveSupport::Deprecation.warn("response.has_template_object? has been deprecated. Use tempate.assigns[name].nil? instead", caller)
- !template_objects[name].nil?
- end
-
- # Returns binary content (downloadable file), converted to a String
- def binary_content
- raise "Response body is not a Proc: #{body_parts.inspect}" unless body_parts.kind_of?(Proc)
- require 'stringio'
-
- sio = StringIO.new
- body_parts.call(self, sio)
-
- sio.rewind
- sio.read
- end
- end
-
# Integration test methods such as ActionController::Integration::Session#get
# and ActionController::Integration::Session#post return objects of class
# TestResponse, which represent the HTTP response results of the requested
# controller actions.
#
# See Response for more information on controller response objects.
- class TestResponse < ActionDispatch::Response
- include TestResponseBehavior
-
+ class TestResponse < ActionDispatch::TestResponse
def recycle!
body_parts.clear
headers.delete('ETag')
@@ -293,7 +151,7 @@ module ActionController #:nodoc:
@response.recycle!
@html_document = nil
- @request.env['REQUEST_METHOD'] = http_method
+ @request.request_method = http_method
@request.action = action.to_s
@@ -331,7 +189,7 @@ module ActionController #:nodoc:
end
def flash
- @response.flash
+ @request.flash
end
def cookies
@@ -348,7 +206,7 @@ module ActionController #:nodoc:
options.update(:only_path => true, :action => action)
url = ActionController::UrlRewriter.new(@request, parameters)
- @request.set_REQUEST_URI(url.rewrite(options))
+ @request.request_uri = url.rewrite(options)
end
end
diff --git a/actionpack/lib/action_dispatch.rb b/actionpack/lib/action_dispatch.rb
index 078e631be4..53368b3d1d 100644
--- a/actionpack/lib/action_dispatch.rb
+++ b/actionpack/lib/action_dispatch.rb
@@ -47,6 +47,8 @@ module ActionDispatch
autoload :MiddlewareStack, 'action_dispatch/middleware/stack'
autoload :Assertions, 'action_dispatch/testing/assertions'
+ autoload :TestRequest, 'action_dispatch/testing/test_request'
+ autoload :TestResponse, 'action_dispatch/testing/test_response'
module Http
autoload :Headers, 'action_dispatch/http/headers'
diff --git a/actionpack/lib/action_dispatch/extensions/rack/utils.rb b/actionpack/lib/action_dispatch/extensions/rack/utils.rb
index 1a46f8a4db..8e4b94eda0 100644
--- a/actionpack/lib/action_dispatch/extensions/rack/utils.rb
+++ b/actionpack/lib/action_dispatch/extensions/rack/utils.rb
@@ -83,7 +83,6 @@ module Rack
end
end
- EOL = "\r\n"
MULTIPART_BOUNDARY = "AaB03x"
def self.parse_multipart(env)
diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb
index 9f0361a874..c28f59dbd6 100755
--- a/actionpack/lib/action_dispatch/http/request.rb
+++ b/actionpack/lib/action_dispatch/http/request.rb
@@ -31,7 +31,7 @@ module ActionDispatch
# :get. If the request \method is not listed in the HTTP_METHODS
# constant above, an UnknownHttpMethod exception is raised.
def request_method
- @request_method ||= HTTP_METHOD_LOOKUP[super] || raise(ActionController::UnknownHttpMethod, "#{super}, accepted HTTP methods are #{HTTP_METHODS.to_sentence(:locale => :en)}")
+ HTTP_METHOD_LOOKUP[super] || raise(ActionController::UnknownHttpMethod, "#{super}, accepted HTTP methods are #{HTTP_METHODS.to_sentence(:locale => :en)}")
end
# Returns the HTTP request \method used for action processing as a
@@ -85,7 +85,7 @@ module ActionDispatch
# For backward compatibility, the post \format is extracted from the
# X-Post-Data-Format HTTP header if present.
def content_type
- @content_type ||= begin
+ @env["action_dispatch.request.content_type"] ||= begin
if @env['CONTENT_TYPE'] =~ /^([^,\;]*)/
Mime::Type.lookup($1.strip.downcase)
else
@@ -100,7 +100,7 @@ module ActionDispatch
# Returns the accepted MIME type for the request.
def accepts
- @accepts ||= begin
+ @env["action_dispatch.request.accepts"] ||= begin
header = @env['HTTP_ACCEPT'].to_s.strip
fallback = xhr? ? Mime::JS : Mime::HTML
@@ -160,7 +160,7 @@ module ActionDispatch
# GET /posts/5 | request.format => Mime::HTML or MIME::JS, or request.accepts.first depending on the value of ActionController::Base.use_accept_header
def format(view_path = [])
- @format ||=
+ @env["action_dispatch.request.format"] ||=
if parameters[:format]
Mime[parameters[:format]]
elsif ActionController::Base.use_accept_header && !(accepts == ONLY_ALL)
@@ -171,12 +171,11 @@ module ActionDispatch
end
def formats
- @formats =
- if ActionController::Base.use_accept_header
- Array(Mime[parameters[:format]] || accepts)
- else
- [format]
- end
+ if ActionController::Base.use_accept_header
+ Array(Mime[parameters[:format]] || accepts)
+ else
+ [format]
+ end
end
# Sets the \format by string extension, which can be used to force custom formats
@@ -192,7 +191,7 @@ module ActionDispatch
# end
def format=(extension)
parameters[:format] = extension.to_s
- @format = Mime::Type.lookup_by_extension(parameters[:format])
+ @env["action_dispatch.request.format"] = Mime::Type.lookup_by_extension(parameters[:format])
end
# Returns a symbolized version of the :format parameter of the request.
@@ -328,6 +327,10 @@ EOM
port == standard_port ? '' : ":#{port}"
end
+ def server_port
+ @env['SERVER_PORT'].to_i
+ end
+
# Returns the \domain part of a \host, such as "rubyonrails.org" in "www.rubyonrails.org". You can specify
# a different tld_length, such as 2 to catch rubyonrails.co.uk in "www.rubyonrails.co.uk".
def domain(tld_length = 1)
@@ -396,18 +399,19 @@ EOM
# Returns both GET and POST \parameters in a single hash.
def parameters
- @parameters ||= request_parameters.merge(query_parameters).update(path_parameters).with_indifferent_access
+ @env["action_dispatch.request.parameters"] ||= request_parameters.merge(query_parameters).update(path_parameters).with_indifferent_access
end
alias_method :params, :parameters
def path_parameters=(parameters) #:nodoc:
+ @env.delete("action_dispatch.request.symbolized_path_parameters")
+ @env.delete("action_dispatch.request.parameters")
@env["action_dispatch.request.path_parameters"] = parameters
- @symbolized_path_parameters = @parameters = nil
end
# The same as path_parameters with explicitly symbolized keys.
def symbolized_path_parameters
- @symbolized_path_parameters ||= path_parameters.symbolize_keys
+ @env["action_dispatch.request.symbolized_path_parameters"] ||= path_parameters.symbolize_keys
end
# Returns a hash with the \parameters used to form the \path of the request.
@@ -464,8 +468,8 @@ EOM
@env['rack.session.options'] = options
end
- def server_port
- @env['SERVER_PORT'].to_i
+ def flash
+ session['flash'] || {}
end
private
diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb
index 1b12308cc9..2b969323ca 100644
--- a/actionpack/lib/action_dispatch/http/response.rb
+++ b/actionpack/lib/action_dispatch/http/response.rb
@@ -31,14 +31,6 @@ module ActionDispatch # :nodoc:
# end
# end
class Response < Rack::Response
- def self.from_response(response)
- new.tap do |resp|
- resp.status = response.status
- resp.headers = response.headers
- resp.body = response.body
- end
- end
-
DEFAULT_HEADERS = { "Cache-Control" => "no-cache" }
attr_accessor :request
@@ -47,27 +39,6 @@ module ActionDispatch # :nodoc:
attr_writer :header
alias_method :headers=, :header=
- def template
- ActiveSupport::Deprecation.warn("response.template has been deprecated. Use controller.template instead", caller)
- @template
- end
- attr_writer :template
-
- def session
- ActiveSupport::Deprecation.warn("response.session has been deprecated. Use request.session instead", caller)
- @request.session
- end
-
- def assigns
- ActiveSupport::Deprecation.warn("response.assigns has been deprecated. Use controller.assigns instead", caller)
- @template.controller.assigns
- end
-
- def layout
- ActiveSupport::Deprecation.warn("response.layout has been deprecated. Use template.layout instead", caller)
- @template.layout
- end
-
delegate :default_charset, :to => 'ActionController::Base'
def initialize
@@ -90,33 +61,6 @@ module ActionDispatch # :nodoc:
end
alias_method :status_message, :message
- # Was the response successful?
- def success?
- (200..299).include?(response_code)
- end
-
- # Was the URL not found?
- def missing?
- response_code == 404
- end
-
- # Were we redirected?
- def redirect?
- (300..399).include?(response_code)
- end
-
- # Was there a server-side error?
- def error?
- (500..599).include?(response_code)
- end
-
- alias_method :server_error?, :error?
-
- # Was there a client client?
- def client_error?
- (400..499).include?(response_code)
- end
-
def body
str = ''
each { |part| str << part.to_s }
diff --git a/actionpack/lib/action_dispatch/testing/test_request.rb b/actionpack/lib/action_dispatch/testing/test_request.rb
new file mode 100644
index 0000000000..3d20b466d3
--- /dev/null
+++ b/actionpack/lib/action_dispatch/testing/test_request.rb
@@ -0,0 +1,56 @@
+module ActionDispatch
+ class TestRequest < Request
+ def self.new(env = {})
+ super
+ end
+
+ def initialize(env = {})
+ super(Rack::MockRequest.env_for('/').merge(env))
+
+ self.host = 'test.host'
+ self.remote_addr = '0.0.0.0'
+ self.user_agent = 'Rails Testing'
+ end
+
+ def request_method=(method)
+ @env['REQUEST_METHOD'] = method.to_s.upcase
+ end
+
+ def host=(host)
+ @env['HTTP_HOST'] = host
+ end
+
+ def port=(number)
+ @env['SERVER_PORT'] = number.to_i
+ end
+
+ def request_uri=(uri)
+ @env['REQUEST_URI'] = uri
+ end
+
+ def path=(path)
+ @env['PATH_INFO'] = path
+ end
+
+ def if_modified_since=(last_modified)
+ @env['HTTP_IF_MODIFIED_SINCE'] = last_modified
+ end
+
+ def if_none_match=(etag)
+ @env['HTTP_IF_NONE_MATCH'] = etag
+ end
+
+ def remote_addr=(addr)
+ @env['REMOTE_ADDR'] = addr
+ end
+
+ def user_agent=(user_agent)
+ @env['HTTP_USER_AGENT'] = user_agent
+ end
+
+ def accept=(mime_types)
+ @env.delete("action_dispatch.request.accepts")
+ @env["HTTP_ACCEPT"] = Array(mime_types).collect { |mime_types| mime_types.to_s }.join(",")
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/testing/test_response.rb b/actionpack/lib/action_dispatch/testing/test_response.rb
new file mode 100644
index 0000000000..50c6d85828
--- /dev/null
+++ b/actionpack/lib/action_dispatch/testing/test_response.rb
@@ -0,0 +1,131 @@
+module ActionDispatch
+ class TestResponse < Response
+ def self.from_response(response)
+ new.tap do |resp|
+ resp.status = response.status
+ resp.headers = response.headers
+ resp.body = response.body
+ end
+ end
+
+ module DeprecatedHelpers
+ def template
+ ActiveSupport::Deprecation.warn("response.template has been deprecated. Use controller.template instead", caller)
+ @template
+ end
+ attr_writer :template
+
+ def session
+ ActiveSupport::Deprecation.warn("response.session has been deprecated. Use request.session instead", caller)
+ @request.session
+ end
+
+ def assigns
+ ActiveSupport::Deprecation.warn("response.assigns has been deprecated. Use controller.assigns instead", caller)
+ @template.controller.assigns
+ end
+
+ def layout
+ ActiveSupport::Deprecation.warn("response.layout has been deprecated. Use template.layout instead", caller)
+ @template.layout
+ end
+
+ def redirect_url_match?(pattern)
+ ::ActiveSupport::Deprecation.warn("response.redirect_url_match? is deprecated. Use assert_match(/foo/, response.redirect_url) instead", caller)
+ return false if redirect_url.nil?
+ p = Regexp.new(pattern) if pattern.class == String
+ p = pattern if pattern.class == Regexp
+ return false if p.nil?
+ p.match(redirect_url) != nil
+ end
+
+ # Returns the template of the file which was used to
+ # render this response (or nil)
+ def rendered
+ ActiveSupport::Deprecation.warn("response.rendered has been deprecated. Use tempate.rendered instead", caller)
+ @template.instance_variable_get(:@_rendered)
+ end
+
+ # A shortcut to the flash. Returns an empty hash if no session flash exists.
+ def flash
+ ActiveSupport::Deprecation.warn("response.flash has been deprecated. Use request.flash instead", caller)
+ request.session['flash'] || {}
+ end
+
+ # Do we have a flash?
+ def has_flash?
+ ActiveSupport::Deprecation.warn("response.has_flash? has been deprecated. Use flash.any? instead", caller)
+ !flash.empty?
+ end
+
+ # Do we have a flash that has contents?
+ def has_flash_with_contents?
+ ActiveSupport::Deprecation.warn("response.has_flash_with_contents? has been deprecated. Use flash.any? instead", caller)
+ !flash.empty?
+ end
+
+ # Does the specified flash object exist?
+ def has_flash_object?(name=nil)
+ ActiveSupport::Deprecation.warn("response.has_flash_object? has been deprecated. Use flash[name] instead", caller)
+ !flash[name].nil?
+ end
+
+ # Does the specified object exist in the session?
+ def has_session_object?(name=nil)
+ ActiveSupport::Deprecation.warn("response.has_session_object? has been deprecated. Use session[name] instead", caller)
+ !session[name].nil?
+ end
+
+ # A shortcut to the template.assigns
+ def template_objects
+ ActiveSupport::Deprecation.warn("response.template_objects has been deprecated. Use tempate.assigns instead", caller)
+ @template.assigns || {}
+ end
+
+ # Does the specified template object exist?
+ def has_template_object?(name=nil)
+ ActiveSupport::Deprecation.warn("response.has_template_object? has been deprecated. Use tempate.assigns[name].nil? instead", caller)
+ !template_objects[name].nil?
+ end
+ end
+ include DeprecatedHelpers
+
+ # Was the response successful?
+ def success?
+ (200..299).include?(response_code)
+ end
+
+ # Was the URL not found?
+ def missing?
+ response_code == 404
+ end
+
+ # Were we redirected?
+ def redirect?
+ (300..399).include?(response_code)
+ end
+
+ # Was there a server-side error?
+ def error?
+ (500..599).include?(response_code)
+ end
+ alias_method :server_error?, :error?
+
+ # Was there a client client?
+ def client_error?
+ (400..499).include?(response_code)
+ end
+
+ # Returns binary content (downloadable file), converted to a String
+ def binary_content
+ raise "Response body is not a Proc: #{body_parts.inspect}" unless body_parts.kind_of?(Proc)
+ require 'stringio'
+
+ sio = StringIO.new
+ body_parts.call(self, sio)
+
+ sio.rewind
+ sio.read
+ end
+ end
+end
diff --git a/actionpack/test/controller/action_pack_assertions_test.rb b/actionpack/test/controller/action_pack_assertions_test.rb
index dd59999a0c..711640f9a9 100644
--- a/actionpack/test/controller/action_pack_assertions_test.rb
+++ b/actionpack/test/controller/action_pack_assertions_test.rb
@@ -305,24 +305,30 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
# check the empty flashing
def test_flash_me_naked
process :flash_me_naked
- assert !@response.has_flash?
- assert !@response.has_flash_with_contents?
+ assert_deprecated do
+ assert !@response.has_flash?
+ assert !@response.has_flash_with_contents?
+ end
end
# check if we have flash objects
def test_flash_haves
process :flash_me
- assert @response.has_flash?
- assert @response.has_flash_with_contents?
- assert @response.has_flash_object?('hello')
+ assert_deprecated do
+ assert @response.has_flash?
+ assert @response.has_flash_with_contents?
+ assert @response.has_flash_object?('hello')
+ end
end
# ensure we don't have flash objects
def test_flash_have_nots
process :nothing
- assert !@response.has_flash?
- assert !@response.has_flash_with_contents?
- assert_nil @response.flash['hello']
+ assert_deprecated do
+ assert !@response.has_flash?
+ assert !@response.has_flash_with_contents?
+ assert_nil @response.flash['hello']
+ end
end
# check if we were rendered by a file-based template?
diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb
index b61a58dd09..df1a1b7683 100644
--- a/actionpack/test/controller/caching_test.rb
+++ b/actionpack/test/controller/caching_test.rb
@@ -345,7 +345,7 @@ class ActionCacheTest < ActionController::TestCase
cached_time = content_to_cache
reset!
- @request.set_REQUEST_URI "/action_caching_test/expire.xml"
+ @request.request_uri = "/action_caching_test/expire.xml"
get :expire, :format => :xml
reset!
diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb
index ef56119751..77abb68f32 100644
--- a/actionpack/test/controller/routing_test.rb
+++ b/actionpack/test/controller/routing_test.rb
@@ -1923,7 +1923,7 @@ class RouteSetTest < Test::Unit::TestCase
end
end
- request.path = "/people"
+ request.request_uri = "/people"
request.env["REQUEST_METHOD"] = "GET"
assert_nothing_raised { set.recognize(request) }
assert_equal("index", request.path_parameters[:action])
@@ -1945,7 +1945,7 @@ class RouteSetTest < Test::Unit::TestCase
}
request.recycle!
- request.path = "/people/5"
+ request.request_uri = "/people/5"
request.env["REQUEST_METHOD"] = "GET"
assert_nothing_raised { set.recognize(request) }
assert_equal("show", request.path_parameters[:action])
@@ -2047,7 +2047,7 @@ class RouteSetTest < Test::Unit::TestCase
end
end
- request.path = "/people/5"
+ request.request_uri = "/people/5"
request.env["REQUEST_METHOD"] = "GET"
assert_nothing_raised { set.recognize(request) }
assert_equal("show", request.path_parameters[:action])
@@ -2059,7 +2059,7 @@ class RouteSetTest < Test::Unit::TestCase
assert_equal("update", request.path_parameters[:action])
request.recycle!
- request.path = "/people/5.png"
+ request.request_uri = "/people/5.png"
request.env["REQUEST_METHOD"] = "GET"
assert_nothing_raised { set.recognize(request) }
assert_equal("show", request.path_parameters[:action])
diff --git a/actionpack/test/controller/test_test.rb b/actionpack/test/controller/test_test.rb
index b372980242..919f9815ec 100644
--- a/actionpack/test/controller/test_test.rb
+++ b/actionpack/test/controller/test_test.rb
@@ -201,7 +201,7 @@ XML
end
def test_process_with_request_uri_with_params_with_explicit_uri
- @request.set_REQUEST_URI "/explicit/uri"
+ @request.request_uri = "/explicit/uri"
process :test_uri, :id => 7
assert_equal "/explicit/uri", @response.body
end
@@ -212,7 +212,7 @@ XML
end
def test_process_with_query_string_with_explicit_uri
- @request.set_REQUEST_URI "/explicit/uri?q=test?extra=question"
+ @request.request_uri = "/explicit/uri?q=test?extra=question"
process :test_query_string
assert_equal "q=test?extra=question", @response.body
end
diff --git a/actionpack/test/dispatch/test_request_test.rb b/actionpack/test/dispatch/test_request_test.rb
new file mode 100644
index 0000000000..40a7f04079
--- /dev/null
+++ b/actionpack/test/dispatch/test_request_test.rb
@@ -0,0 +1,30 @@
+require 'abstract_unit'
+
+class TestRequestTest < ActiveSupport::TestCase
+ test "sane defaults" do
+ env = ActionDispatch::TestRequest.new.env
+
+ assert_equal "GET", env.delete("REQUEST_METHOD")
+ assert_equal "off", env.delete("HTTPS")
+ assert_equal "http", env.delete("rack.url_scheme")
+ assert_equal "example.org", env.delete("SERVER_NAME")
+ assert_equal "80", env.delete("SERVER_PORT")
+ assert_equal "/", env.delete("PATH_INFO")
+ assert_equal "", env.delete("SCRIPT_NAME")
+ assert_equal "", env.delete("QUERY_STRING")
+ assert_equal "0", env.delete("CONTENT_LENGTH")
+
+ assert_equal "test.host", env.delete("HTTP_HOST")
+ assert_equal "0.0.0.0", env.delete("REMOTE_ADDR")
+ assert_equal "Rails Testing", env.delete("HTTP_USER_AGENT")
+
+ assert_equal [0, 1], env.delete("rack.version")
+ assert_equal "", env.delete("rack.input").string
+ assert_kind_of StringIO, env.delete("rack.errors")
+ assert_equal true, env.delete("rack.multithread")
+ assert_equal true, env.delete("rack.multiprocess")
+ assert_equal false, env.delete("rack.run_once")
+
+ assert env.empty?, env.inspect
+ end
+end
--
cgit v1.2.3
From f0b9e2861943d32ca73a53ab5fb6f86d10c89b04 Mon Sep 17 00:00:00 2001
From: Jeremy Kemper
Date: Thu, 30 Apr 2009 16:34:00 -0700
Subject: Fix render :json => nil [#2589 state:resolved]
---
actionpack/lib/action_controller/base/render.rb | 3 ++-
actionpack/test/controller/render_test.rb | 10 ++++++++++
2 files changed, 12 insertions(+), 1 deletion(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/base/render.rb b/actionpack/lib/action_controller/base/render.rb
index 4286577ec5..cc0d878e01 100644
--- a/actionpack/lib/action_controller/base/render.rb
+++ b/actionpack/lib/action_controller/base/render.rb
@@ -253,7 +253,8 @@ module ActionController
response.content_type ||= Mime::JS
render_for_text(js)
- elsif json = options[:json]
+ elsif options.include?(:json)
+ json = options[:json]
json = ActiveSupport::JSON.encode(json) unless json.respond_to?(:to_str)
json = "#{options[:callback]}(#{json})" unless options[:callback].blank?
response.content_type ||= Mime::JSON
diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb
index da063710a9..023bf0eeaa 100644
--- a/actionpack/test/controller/render_test.rb
+++ b/actionpack/test/controller/render_test.rb
@@ -194,6 +194,10 @@ class TestController < ActionController::Base
render :inline => "<%= controller_name %>"
end
+ def render_json_nil
+ render :json => nil
+ end
+
def render_json_hello_world
render :json => ActiveSupport::JSON.encode(:hello => 'world')
end
@@ -874,6 +878,12 @@ class RenderTest < ActionController::TestCase
assert_equal "The secret is in the sauce\n", @response.body
end
+ def test_render_json_nil
+ get :render_json_nil
+ assert_equal 'null', @response.body
+ assert_equal 'application/json', @response.content_type
+ end
+
def test_render_json
get :render_json_hello_world
assert_equal '{"hello":"world"}', @response.body
--
cgit v1.2.3
From e59835bd0934a7458b71b13bf65786c8484905bd Mon Sep 17 00:00:00 2001
From: "John F. Douthat"
Date: Tue, 21 Apr 2009 13:35:54 -0500
Subject: Fix action-cached exception responses.
Methods raising ActiveRecord::RecordNotFound were returning 404 on first request and 200 OK with blank body on subsequent requests.
[#2533 state:committed]
Signed-off-by: Jeremy Kemper
---
.../lib/action_controller/caching/actions.rb | 10 ++++++-
actionpack/test/controller/caching_test.rb | 35 ++++++++++++++++++++++
2 files changed, 44 insertions(+), 1 deletion(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/caching/actions.rb b/actionpack/lib/action_controller/caching/actions.rb
index d95a346862..2b822b52c8 100644
--- a/actionpack/lib/action_controller/caching/actions.rb
+++ b/actionpack/lib/action_controller/caching/actions.rb
@@ -61,7 +61,9 @@ module ActionController #:nodoc:
filter_options = { :only => actions, :if => options.delete(:if), :unless => options.delete(:unless) }
cache_filter = ActionCacheFilter.new(:layout => options.delete(:layout), :cache_path => options.delete(:cache_path), :store_options => options)
- around_filter(cache_filter, filter_options)
+ around_filter(filter_options) do |controller, action|
+ cache_filter.filter(controller, action)
+ end
end
end
@@ -83,6 +85,12 @@ module ActionController #:nodoc:
@options = options
end
+ def filter(controller, action)
+ should_continue = before(controller)
+ action.call if should_continue
+ after(controller)
+ end
+
def before(controller)
cache_path = ActionCachePath.new(controller, path_options_for(controller, @options.slice(:cache_path)))
if cache = controller.read_fragment(cache_path.path, @options[:store_options])
diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb
index df1a1b7683..10b904481d 100644
--- a/actionpack/test/controller/caching_test.rb
+++ b/actionpack/test/controller/caching_test.rb
@@ -1,5 +1,6 @@
require 'fileutils'
require 'abstract_unit'
+require 'active_record_unit'
CACHE_DIR = 'test_cache'
# Don't change '/../temp/' cavalierly or you might hose something you don't want hosed
@@ -153,6 +154,7 @@ class ActionCachingTestController < ActionController::Base
caches_action :edit, :cache_path => Proc.new { |c| c.params[:id] ? "http://test.host/#{c.params[:id]};edit" : "http://test.host/edit" }
caches_action :with_layout
caches_action :layout_false, :layout => false
+ caches_action :record_not_found, :four_oh_four, :simple_runtime_error
layout 'talk_from_action.erb'
@@ -175,6 +177,18 @@ class ActionCachingTestController < ActionController::Base
render :text => @cache_this, :layout => true
end
+ def record_not_found
+ raise ActiveRecord::RecordNotFound, "oops!"
+ end
+
+ def four_oh_four
+ render :text => "404'd!", :status => 404
+ end
+
+ def simple_runtime_error
+ raise "oops!"
+ end
+
alias_method :show, :index
alias_method :edit, :index
alias_method :destroy, :index
@@ -458,6 +472,27 @@ class ActionCacheTest < ActionController::TestCase
assert_response :success
end
+ def test_record_not_found_returns_404_for_multiple_requests
+ get :record_not_found
+ assert_response 404
+ get :record_not_found
+ assert_response 404
+ end
+
+ def test_four_oh_four_returns_404_for_multiple_requests
+ get :four_oh_four
+ assert_response 404
+ get :four_oh_four
+ assert_response 404
+ end
+
+ def test_simple_runtime_error_returns_500_for_multiple_requests
+ get :simple_runtime_error
+ assert_response 500
+ get :simple_runtime_error
+ assert_response 500
+ end
+
private
def content_to_cache
assigns(:cache_this)
--
cgit v1.2.3
From d54604c352ca444c49e54f4dbbfcaff58f8c7d06 Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Thu, 30 Apr 2009 19:09:47 -0500
Subject: Depend on unreleased rack 1.1
---
actionpack/lib/action_dispatch.rb | 3 +-
actionpack/lib/action_dispatch/extensions/rack.rb | 5 -
.../lib/action_dispatch/extensions/rack/mock.rb | 65 -----
.../lib/action_dispatch/extensions/rack/utils.rb | 261 ---------------------
actionpack/test/dispatch/test_request_test.rb | 2 +-
5 files changed, 2 insertions(+), 334 deletions(-)
delete mode 100644 actionpack/lib/action_dispatch/extensions/rack.rb
delete mode 100644 actionpack/lib/action_dispatch/extensions/rack/mock.rb
delete mode 100644 actionpack/lib/action_dispatch/extensions/rack/utils.rb
(limited to 'actionpack')
diff --git a/actionpack/lib/action_dispatch.rb b/actionpack/lib/action_dispatch.rb
index 53368b3d1d..01e894cde6 100644
--- a/actionpack/lib/action_dispatch.rb
+++ b/actionpack/lib/action_dispatch.rb
@@ -32,9 +32,8 @@ rescue LoadError
end
require 'active_support/core/all'
-gem 'rack', '~> 1.0.0'
+gem 'rack', '~> 1.1.0'
require 'rack'
-require 'action_dispatch/extensions/rack'
module ActionDispatch
autoload :Request, 'action_dispatch/http/request'
diff --git a/actionpack/lib/action_dispatch/extensions/rack.rb b/actionpack/lib/action_dispatch/extensions/rack.rb
deleted file mode 100644
index 8a543e2110..0000000000
--- a/actionpack/lib/action_dispatch/extensions/rack.rb
+++ /dev/null
@@ -1,5 +0,0 @@
-# Monkey patch in new test helper methods
-unless Rack::Utils.respond_to?(:build_nested_query)
- require 'action_dispatch/extensions/rack/mock'
- require 'action_dispatch/extensions/rack/utils'
-end
diff --git a/actionpack/lib/action_dispatch/extensions/rack/mock.rb b/actionpack/lib/action_dispatch/extensions/rack/mock.rb
deleted file mode 100644
index d773a74244..0000000000
--- a/actionpack/lib/action_dispatch/extensions/rack/mock.rb
+++ /dev/null
@@ -1,65 +0,0 @@
-require 'rack/mock'
-
-module Rack
- class MockRequest
- # Return the Rack environment used for a request to +uri+.
- def self.env_for(uri="", opts={})
- uri = URI(uri)
- uri.path = "/#{uri.path}" unless uri.path[0] == ?/
-
- env = DEFAULT_ENV.dup
-
- env["REQUEST_METHOD"] = opts[:method] ? opts[:method].to_s.upcase : "GET"
- env["SERVER_NAME"] = uri.host || "example.org"
- env["SERVER_PORT"] = uri.port ? uri.port.to_s : "80"
- env["QUERY_STRING"] = uri.query.to_s
- env["PATH_INFO"] = (!uri.path || uri.path.empty?) ? "/" : uri.path
- env["rack.url_scheme"] = uri.scheme || "http"
- env["HTTPS"] = env["rack.url_scheme"] == "https" ? "on" : "off"
-
- env["SCRIPT_NAME"] = opts[:script_name] || ""
-
- if opts[:fatal]
- env["rack.errors"] = FatalWarner.new
- else
- env["rack.errors"] = StringIO.new
- end
-
- if params = opts[:params]
- if env["REQUEST_METHOD"] == "GET"
- params = Utils.parse_nested_query(params) if params.is_a?(String)
- params.update(Utils.parse_nested_query(env["QUERY_STRING"]))
- env["QUERY_STRING"] = Utils.build_nested_query(params)
- elsif !opts.has_key?(:input)
- opts["CONTENT_TYPE"] = "application/x-www-form-urlencoded"
- if params.is_a?(Hash)
- if data = Utils::Multipart.build_multipart(params)
- opts[:input] = data
- opts["CONTENT_LENGTH"] ||= data.length.to_s
- opts["CONTENT_TYPE"] = "multipart/form-data; boundary=#{Utils::Multipart::MULTIPART_BOUNDARY}"
- else
- opts[:input] = Utils.build_nested_query(params)
- end
- else
- opts[:input] = params
- end
- end
- end
-
- opts[:input] ||= ""
- if String === opts[:input]
- env["rack.input"] = StringIO.new(opts[:input])
- else
- env["rack.input"] = opts[:input]
- end
-
- env["CONTENT_LENGTH"] ||= env["rack.input"].length.to_s
-
- opts.each { |field, value|
- env[field] = value if String === field
- }
-
- env
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/extensions/rack/utils.rb b/actionpack/lib/action_dispatch/extensions/rack/utils.rb
deleted file mode 100644
index 8e4b94eda0..0000000000
--- a/actionpack/lib/action_dispatch/extensions/rack/utils.rb
+++ /dev/null
@@ -1,261 +0,0 @@
-# -*- encoding: binary -*-
-
-require 'rack/utils'
-
-module Rack
- module Utils
- def normalize_params(params, name, v = nil)
- name =~ %r(\A[\[\]]*([^\[\]]+)\]*)
- k = $1 || ''
- after = $' || ''
-
- return if k.empty?
-
- if after == ""
- params[k] = v
- elsif after == "[]"
- params[k] ||= []
- raise TypeError, "expected Array (got #{params[k].class.name}) for param `#{k}'" unless params[k].is_a?(Array)
- params[k] << v
- elsif after =~ %r(^\[\]\[([^\[\]]+)\]$) || after =~ %r(^\[\](.+)$)
- child_key = $1
- params[k] ||= []
- raise TypeError, "expected Array (got #{params[k].class.name}) for param `#{k}'" unless params[k].is_a?(Array)
- if params[k].last.is_a?(Hash) && !params[k].last.key?(child_key)
- normalize_params(params[k].last, child_key, v)
- else
- params[k] << normalize_params({}, child_key, v)
- end
- else
- params[k] ||= {}
- raise TypeError, "expected Hash (got #{params[k].class.name}) for param `#{k}'" unless params[k].is_a?(Hash)
- params[k] = normalize_params(params[k], after, v)
- end
-
- return params
- end
- module_function :normalize_params
-
- def build_nested_query(value, prefix = nil)
- case value
- when Array
- value.map { |v|
- build_nested_query(v, "#{prefix}[]")
- }.join("&")
- when Hash
- value.map { |k, v|
- build_nested_query(v, prefix ? "#{prefix}[#{escape(k)}]" : escape(k))
- }.join("&")
- when String
- raise ArgumentError, "value must be a Hash" if prefix.nil?
- "#{prefix}=#{escape(value)}"
- else
- prefix
- end
- end
- module_function :build_nested_query
-
- module Multipart
- class UploadedFile
- # The filename, *not* including the path, of the "uploaded" file
- attr_reader :original_filename
-
- # The content type of the "uploaded" file
- attr_accessor :content_type
-
- def initialize(path, content_type = "text/plain", binary = false)
- raise "#{path} file does not exist" unless ::File.exist?(path)
- @content_type = content_type
- @original_filename = ::File.basename(path)
- @tempfile = Tempfile.new(@original_filename)
- @tempfile.set_encoding(Encoding::BINARY) if @tempfile.respond_to?(:set_encoding)
- @tempfile.binmode if binary
- FileUtils.copy_file(path, @tempfile.path)
- end
-
- def path
- @tempfile.path
- end
- alias_method :local_path, :path
-
- def method_missing(method_name, *args, &block) #:nodoc:
- @tempfile.__send__(method_name, *args, &block)
- end
- end
-
- MULTIPART_BOUNDARY = "AaB03x"
-
- def self.parse_multipart(env)
- unless env['CONTENT_TYPE'] =~
- %r|\Amultipart/.*boundary=\"?([^\";,]+)\"?|n
- nil
- else
- boundary = "--#{$1}"
-
- params = {}
- buf = ""
- content_length = env['CONTENT_LENGTH'].to_i
- input = env['rack.input']
- input.rewind
-
- boundary_size = Utils.bytesize(boundary) + EOL.size
- bufsize = 16384
-
- content_length -= boundary_size
-
- read_buffer = ''
-
- status = input.read(boundary_size, read_buffer)
- raise EOFError, "bad content body" unless status == boundary + EOL
-
- rx = /(?:#{EOL})?#{Regexp.quote boundary}(#{EOL}|--)/n
-
- loop {
- head = nil
- body = ''
- filename = content_type = name = nil
-
- until head && buf =~ rx
- if !head && i = buf.index(EOL+EOL)
- head = buf.slice!(0, i+2) # First \r\n
- buf.slice!(0, 2) # Second \r\n
-
- filename = head[/Content-Disposition:.* filename="?([^\";]*)"?/ni, 1]
- content_type = head[/Content-Type: (.*)#{EOL}/ni, 1]
- name = head[/Content-Disposition:.*\s+name="?([^\";]*)"?/ni, 1] || head[/Content-ID:\s*([^#{EOL}]*)/ni, 1]
-
- if content_type || filename
- body = Tempfile.new("RackMultipart")
- body.binmode if body.respond_to?(:binmode)
- end
-
- next
- end
-
- # Save the read body part.
- if head && (boundary_size+4 < buf.size)
- body << buf.slice!(0, buf.size - (boundary_size+4))
- end
-
- c = input.read(bufsize < content_length ? bufsize : content_length, read_buffer)
- raise EOFError, "bad content body" if c.nil? || c.empty?
- buf << c
- content_length -= c.size
- end
-
- # Save the rest.
- if i = buf.index(rx)
- body << buf.slice!(0, i)
- buf.slice!(0, boundary_size+2)
-
- content_length = -1 if $1 == "--"
- end
-
- if filename == ""
- # filename is blank which means no file has been selected
- data = nil
- elsif filename
- body.rewind
-
- # Take the basename of the upload's original filename.
- # This handles the full Windows paths given by Internet Explorer
- # (and perhaps other broken user agents) without affecting
- # those which give the lone filename.
- filename =~ /^(?:.*[:\\\/])?(.*)/m
- filename = $1
-
- data = {:filename => filename, :type => content_type,
- :name => name, :tempfile => body, :head => head}
- elsif !filename && content_type
- body.rewind
-
- # Generic multipart cases, not coming from a form
- data = {:type => content_type,
- :name => name, :tempfile => body, :head => head}
- else
- data = body
- end
-
- Utils.normalize_params(params, name, data) unless data.nil?
-
- break if buf.empty? || content_length == -1
- }
-
- input.rewind
-
- params
- end
- end
-
- def self.build_multipart(params, first = true)
- if first
- unless params.is_a?(Hash)
- raise ArgumentError, "value must be a Hash"
- end
-
- multipart = false
- query = lambda { |value|
- case value
- when Array
- value.each(&query)
- when Hash
- value.values.each(&query)
- when UploadedFile
- multipart = true
- end
- }
- params.values.each(&query)
- return nil unless multipart
- end
-
- flattened_params = Hash.new
-
- params.each do |key, value|
- k = first ? key.to_s : "[#{key}]"
-
- case value
- when Array
- value.map { |v|
- build_multipart(v, false).each { |subkey, subvalue|
- flattened_params["#{k}[]#{subkey}"] = subvalue
- }
- }
- when Hash
- build_multipart(value, false).each { |subkey, subvalue|
- flattened_params[k + subkey] = subvalue
- }
- else
- flattened_params[k] = value
- end
- end
-
- if first
- flattened_params.map { |name, file|
- if file.respond_to?(:original_filename)
- ::File.open(file.path, "rb") do |f|
- f.set_encoding(Encoding::BINARY) if f.respond_to?(:set_encoding)
-<<-EOF
---#{MULTIPART_BOUNDARY}\r
-Content-Disposition: form-data; name="#{name}"; filename="#{Utils.escape(file.original_filename)}"\r
-Content-Type: #{file.content_type}\r
-Content-Length: #{::File.stat(file.path).size}\r
-\r
-#{f.read}\r
-EOF
- end
- else
-<<-EOF
---#{MULTIPART_BOUNDARY}\r
-Content-Disposition: form-data; name="#{name}"\r
-\r
-#{file}\r
-EOF
- end
- }.join + "--#{MULTIPART_BOUNDARY}--\r"
- else
- flattened_params
- end
- end
- end
- end
-end
diff --git a/actionpack/test/dispatch/test_request_test.rb b/actionpack/test/dispatch/test_request_test.rb
index 40a7f04079..f13f67f0ae 100644
--- a/actionpack/test/dispatch/test_request_test.rb
+++ b/actionpack/test/dispatch/test_request_test.rb
@@ -18,7 +18,7 @@ class TestRequestTest < ActiveSupport::TestCase
assert_equal "0.0.0.0", env.delete("REMOTE_ADDR")
assert_equal "Rails Testing", env.delete("HTTP_USER_AGENT")
- assert_equal [0, 1], env.delete("rack.version")
+ assert_equal [1, 0], env.delete("rack.version")
assert_equal "", env.delete("rack.input").string
assert_kind_of StringIO, env.delete("rack.errors")
assert_equal true, env.delete("rack.multithread")
--
cgit v1.2.3
From a6fff94baf0ca5d436cbc5c0fa81f690c8024ff5 Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Thu, 30 Apr 2009 19:23:50 -0500
Subject: Move TestRequest cookies accessor into AD TestRequest
---
.../lib/action_controller/testing/process.rb | 2 --
.../lib/action_dispatch/testing/test_request.rb | 24 +++++++++++++++++++---
actionpack/test/dispatch/test_request_test.rb | 15 ++++++++++++++
3 files changed, 36 insertions(+), 5 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/testing/process.rb b/actionpack/lib/action_controller/testing/process.rb
index e0f8f026fd..2fbd89ae1c 100644
--- a/actionpack/lib/action_controller/testing/process.rb
+++ b/actionpack/lib/action_controller/testing/process.rb
@@ -2,7 +2,6 @@ require 'rack/session/abstract/id'
module ActionController #:nodoc:
class TestRequest < ActionDispatch::TestRequest #:nodoc:
- attr_accessor :cookies
attr_accessor :query_parameters
def initialize(env = {})
@@ -13,7 +12,6 @@ module ActionController #:nodoc:
self.session_options = TestSession::DEFAULT_OPTIONS.merge(:id => ActiveSupport::SecureRandom.hex(16))
@request_uri = "/"
- @cookies = {}
end
# Wraps raw_post in a StringIO.
diff --git a/actionpack/lib/action_dispatch/testing/test_request.rb b/actionpack/lib/action_dispatch/testing/test_request.rb
index 3d20b466d3..bd6c26b69b 100644
--- a/actionpack/lib/action_dispatch/testing/test_request.rb
+++ b/actionpack/lib/action_dispatch/testing/test_request.rb
@@ -1,17 +1,24 @@
module ActionDispatch
class TestRequest < Request
+ DEFAULT_ENV = Rack::MockRequest.env_for('/')
+
def self.new(env = {})
super
end
def initialize(env = {})
- super(Rack::MockRequest.env_for('/').merge(env))
+ super(DEFAULT_ENV.merge(env))
self.host = 'test.host'
self.remote_addr = '0.0.0.0'
self.user_agent = 'Rails Testing'
end
+ def env
+ write_cookies!
+ super
+ end
+
def request_method=(method)
@env['REQUEST_METHOD'] = method.to_s.upcase
end
@@ -49,8 +56,19 @@ module ActionDispatch
end
def accept=(mime_types)
- @env.delete("action_dispatch.request.accepts")
- @env["HTTP_ACCEPT"] = Array(mime_types).collect { |mime_types| mime_types.to_s }.join(",")
+ @env.delete('action_dispatch.request.accepts')
+ @env['HTTP_ACCEPT'] = Array(mime_types).collect { |mime_types| mime_types.to_s }.join(",")
end
+
+ def cookies
+ @cookies ||= super
+ end
+
+ private
+ def write_cookies!
+ unless @cookies.blank?
+ @env['HTTP_COOKIE'] = @cookies.map { |name, value| "#{name}=#{value};" }.join(' ')
+ end
+ end
end
end
diff --git a/actionpack/test/dispatch/test_request_test.rb b/actionpack/test/dispatch/test_request_test.rb
index f13f67f0ae..19b5e2988b 100644
--- a/actionpack/test/dispatch/test_request_test.rb
+++ b/actionpack/test/dispatch/test_request_test.rb
@@ -27,4 +27,19 @@ class TestRequestTest < ActiveSupport::TestCase
assert env.empty?, env.inspect
end
+
+ test "cookie jar" do
+ req = ActionDispatch::TestRequest.new
+
+ assert_equal({}, req.cookies)
+ assert_equal nil, req.env["HTTP_COOKIE"]
+
+ req.cookies["user_name"] = "david"
+ assert_equal({"user_name" => "david"}, req.cookies)
+ assert_equal "user_name=david;", req.env["HTTP_COOKIE"]
+
+ req.cookies["login"] = "XJ-122"
+ assert_equal({"user_name" => "david", "login" => "XJ-122"}, req.cookies)
+ assert_equal "login=XJ-122; user_name=david;", req.env["HTTP_COOKIE"]
+ end
end
--
cgit v1.2.3
From 261ec996de6279a58d5b10f6f36ee1cc1fb96fc6 Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Thu, 30 Apr 2009 19:36:18 -0500
Subject: Missed stray @request_uri
---
actionpack/lib/action_controller/testing/process.rb | 2 --
1 file changed, 2 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/testing/process.rb b/actionpack/lib/action_controller/testing/process.rb
index 2fbd89ae1c..d059b37f6d 100644
--- a/actionpack/lib/action_controller/testing/process.rb
+++ b/actionpack/lib/action_controller/testing/process.rb
@@ -10,8 +10,6 @@ module ActionController #:nodoc:
@query_parameters = {}
self.session = TestSession.new
self.session_options = TestSession::DEFAULT_OPTIONS.merge(:id => ActiveSupport::SecureRandom.hex(16))
-
- @request_uri = "/"
end
# Wraps raw_post in a StringIO.
--
cgit v1.2.3
From 0fa1e75d416f529c61ef1cbfce230a91417d436c Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Thu, 30 Apr 2009 20:04:55 -0500
Subject: Set rack.input instead of RAW_POST_DATA in TestRequest
---
.../lib/action_controller/testing/process.rb | 39 ++++++----------------
1 file changed, 11 insertions(+), 28 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/testing/process.rb b/actionpack/lib/action_controller/testing/process.rb
index d059b37f6d..d397bc0283 100644
--- a/actionpack/lib/action_controller/testing/process.rb
+++ b/actionpack/lib/action_controller/testing/process.rb
@@ -12,21 +12,6 @@ module ActionController #:nodoc:
self.session_options = TestSession::DEFAULT_OPTIONS.merge(:id => ActiveSupport::SecureRandom.hex(16))
end
- # Wraps raw_post in a StringIO.
- def body_stream #:nodoc:
- StringIO.new(raw_post)
- end
-
- # Either the RAW_POST_DATA environment variable or the URL-encoded request
- # parameters.
- def raw_post
- @env['RAW_POST_DATA'] ||= begin
- data = url_encoded_request_parameters
- data.force_encoding(Encoding::BINARY) if data.respond_to?(:force_encoding)
- data
- end
- end
-
def action=(action_name)
query_parameters.update({ "action" => action_name })
end
@@ -48,7 +33,17 @@ module ActionController #:nodoc:
path_parameters[key.to_s] = value
end
end
- raw_post # populate env['RAW_POST_DATA']
+
+ params = self.request_parameters.dup
+
+ %w(controller action only_path).each do |k|
+ params.delete(k)
+ params.delete(k.to_sym)
+ end
+
+ data = params.to_query
+ @env['CONTENT_LENGTH'] = data.length
+ @env['rack.input'] = StringIO.new(data)
end
def recycle!
@@ -56,18 +51,6 @@ module ActionController #:nodoc:
self.query_parameters = {}
@headers = nil
end
-
- private
- def url_encoded_request_parameters
- params = self.request_parameters.dup
-
- %w(controller action only_path).each do |k|
- params.delete(k)
- params.delete(k.to_sym)
- end
-
- params.to_query
- end
end
# Integration test methods such as ActionController::Integration::Session#get
--
cgit v1.2.3
From 1fcc7dbcc8dcf7f1d42ca8486ad313f0c805033a Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Thu, 30 Apr 2009 23:31:20 -0500
Subject: Move TestRequest#query_parameters into AD TestRequest
---
actionpack/lib/action_controller/testing/process.rb | 14 ++------------
actionpack/lib/action_dispatch/http/request.rb | 2 +-
actionpack/lib/action_dispatch/testing/test_request.rb | 4 ++++
3 files changed, 7 insertions(+), 13 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/testing/process.rb b/actionpack/lib/action_controller/testing/process.rb
index d397bc0283..786dc67e2e 100644
--- a/actionpack/lib/action_controller/testing/process.rb
+++ b/actionpack/lib/action_controller/testing/process.rb
@@ -2,20 +2,13 @@ require 'rack/session/abstract/id'
module ActionController #:nodoc:
class TestRequest < ActionDispatch::TestRequest #:nodoc:
- attr_accessor :query_parameters
-
def initialize(env = {})
super
- @query_parameters = {}
self.session = TestSession.new
self.session_options = TestSession::DEFAULT_OPTIONS.merge(:id => ActiveSupport::SecureRandom.hex(16))
end
- def action=(action_name)
- query_parameters.update({ "action" => action_name })
- end
-
def assign_parameters(controller_path, action, parameters)
parameters = parameters.symbolize_keys.merge(:controller => controller_path, :action => action)
extra_keys = ActionController::Routing::Routes.extra_keys(parameters)
@@ -47,9 +40,8 @@ module ActionController #:nodoc:
end
def recycle!
- @env.delete_if { |k, v| k =~ /^action_dispatch\.request/ }
- self.query_parameters = {}
- @headers = nil
+ @env.delete_if { |k, v| k =~ /^(action_dispatch|rack)\.request/ }
+ @env['action_dispatch.request.query_parameters'] = {}
end
end
@@ -132,8 +124,6 @@ module ActionController #:nodoc:
@html_document = nil
@request.request_method = http_method
- @request.action = action.to_s
-
parameters ||= {}
@request.assign_parameters(@controller.class.controller_path, action.to_s, parameters)
diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb
index c28f59dbd6..e4f3a8f125 100755
--- a/actionpack/lib/action_dispatch/http/request.rb
+++ b/actionpack/lib/action_dispatch/http/request.rb
@@ -351,7 +351,7 @@ EOM
# Returns the query string, accounting for server idiosyncrasies.
def query_string
- @env['QUERY_STRING'].present? ? @env['QUERY_STRING'] : (@env['REQUEST_URI'].split('?', 2)[1] || '')
+ @env['QUERY_STRING'].present? ? @env['QUERY_STRING'] : (@env['REQUEST_URI'].to_s.split('?', 2)[1] || '')
end
# Returns the request URI, accounting for server idiosyncrasies.
diff --git a/actionpack/lib/action_dispatch/testing/test_request.rb b/actionpack/lib/action_dispatch/testing/test_request.rb
index bd6c26b69b..5d8cd7e619 100644
--- a/actionpack/lib/action_dispatch/testing/test_request.rb
+++ b/actionpack/lib/action_dispatch/testing/test_request.rb
@@ -39,6 +39,10 @@ module ActionDispatch
@env['PATH_INFO'] = path
end
+ def action=(action_name)
+ path_parameters["action"] = action_name.to_s
+ end
+
def if_modified_since=(last_modified)
@env['HTTP_IF_MODIFIED_SINCE'] = last_modified
end
--
cgit v1.2.3
From 05bd863c022601bb0bbd17c51adbcb420f349323 Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Thu, 30 Apr 2009 23:36:47 -0500
Subject: alias method chain process with test
---
actionpack/lib/action_controller/testing/process.rb | 9 ++++++---
actionpack/test/controller/filters_test.rb | 4 ++--
2 files changed, 8 insertions(+), 5 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/testing/process.rb b/actionpack/lib/action_controller/testing/process.rb
index 786dc67e2e..8315a160ad 100644
--- a/actionpack/lib/action_controller/testing/process.rb
+++ b/actionpack/lib/action_controller/testing/process.rb
@@ -132,7 +132,7 @@ module ActionController #:nodoc:
build_request_uri(action, parameters)
Base.class_eval { include ProcessWithTest } unless Base < ProcessWithTest
- @controller.process_with_test(@request, @response)
+ @controller.process(@request, @response)
end
def xml_http_request(request_method, action, parameters = nil, session = nil, flash = nil)
@@ -248,11 +248,14 @@ module ActionController #:nodoc:
module ProcessWithTest #:nodoc:
def self.included(base)
- base.class_eval { attr_reader :assigns }
+ base.class_eval {
+ attr_reader :assigns
+ alias_method_chain :process, :test
+ }
end
def process_with_test(*args)
- process(*args).tap { set_test_assigns }
+ process_without_test(*args).tap { set_test_assigns }
end
private
diff --git a/actionpack/test/controller/filters_test.rb b/actionpack/test/controller/filters_test.rb
index aca7a821c8..bdec5d2d4c 100644
--- a/actionpack/test/controller/filters_test.rb
+++ b/actionpack/test/controller/filters_test.rb
@@ -674,7 +674,7 @@ class FilterTest < Test::Unit::TestCase
request.action = action
controller = controller.new if controller.is_a?(Class)
@controller = controller
- @controller.process_with_test(request, ActionController::TestResponse.new)
+ @controller.process(request, ActionController::TestResponse.new)
end
end
@@ -917,6 +917,6 @@ class YieldingAroundFiltersTest < Test::Unit::TestCase
request.action = action
controller = controller.new if controller.is_a?(Class)
@controller = controller
- @controller.process_with_test(request, ActionController::TestResponse.new)
+ @controller.process(request, ActionController::TestResponse.new)
end
end
--
cgit v1.2.3
From 664ae187a927ba54c8c7ec6eaf9ad89be291fc95 Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Thu, 30 Apr 2009 23:43:35 -0500
Subject: Update some old tests to use AC TestProcess
---
actionpack/test/controller/filters_test.rb | 25 +++++++++++++------------
1 file changed, 13 insertions(+), 12 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/test/controller/filters_test.rb b/actionpack/test/controller/filters_test.rb
index bdec5d2d4c..9e74538310 100644
--- a/actionpack/test/controller/filters_test.rb
+++ b/actionpack/test/controller/filters_test.rb
@@ -2,6 +2,8 @@ require 'abstract_unit'
# FIXME: crashes Ruby 1.9
class FilterTest < Test::Unit::TestCase
+ include ActionController::TestProcess
+
class TestController < ActionController::Base
before_filter :ensure_login
after_filter :clean_up
@@ -669,12 +671,11 @@ class FilterTest < Test::Unit::TestCase
private
def test_process(controller, action = "show")
- ActionController::Base.class_eval { include ActionController::ProcessWithTest } unless ActionController::Base < ActionController::ProcessWithTest
- request = ActionController::TestRequest.new
- request.action = action
- controller = controller.new if controller.is_a?(Class)
- @controller = controller
- @controller.process(request, ActionController::TestResponse.new)
+ @controller = controller.is_a?(Class) ? controller.new : controller
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+
+ process(action)
end
end
@@ -810,6 +811,7 @@ end
class YieldingAroundFiltersTest < Test::Unit::TestCase
include PostsController::AroundExceptions
+ include ActionController::TestProcess
def test_filters_registering
assert_equal 1, ControllerWithFilterMethod.filter_chain.size
@@ -912,11 +914,10 @@ class YieldingAroundFiltersTest < Test::Unit::TestCase
protected
def test_process(controller, action = "show")
- ActionController::Base.class_eval { include ActionController::ProcessWithTest } unless ActionController::Base < ActionController::ProcessWithTest
- request = ActionController::TestRequest.new
- request.action = action
- controller = controller.new if controller.is_a?(Class)
- @controller = controller
- @controller.process(request, ActionController::TestResponse.new)
+ @controller = controller.is_a?(Class) ? controller.new : controller
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+
+ process(action)
end
end
--
cgit v1.2.3
From 432e631d5c9cc59db3e5c515c348352a4268eb7f Mon Sep 17 00:00:00 2001
From: Pratik Naik
Date: Fri, 1 May 2009 20:12:49 +0100
Subject: Vendor Rack edge ( commit : 815342a8e15db564b766f209ffb1e340233f064f
)
---
actionpack/lib/action_dispatch.rb | 7 +-
actionpack/lib/action_dispatch/vendor/rack/rack.rb | 90 ++++
.../vendor/rack/rack/adapter/camping.rb | 22 +
.../vendor/rack/rack/auth/abstract/handler.rb | 37 ++
.../vendor/rack/rack/auth/abstract/request.rb | 37 ++
.../action_dispatch/vendor/rack/rack/auth/basic.rb | 58 +++
.../vendor/rack/rack/auth/digest/md5.rb | 124 +++++
.../vendor/rack/rack/auth/digest/nonce.rb | 51 ++
.../vendor/rack/rack/auth/digest/params.rb | 55 +++
.../vendor/rack/rack/auth/digest/request.rb | 40 ++
.../vendor/rack/rack/auth/openid.rb | 480 ++++++++++++++++++
.../action_dispatch/vendor/rack/rack/builder.rb | 63 +++
.../action_dispatch/vendor/rack/rack/cascade.rb | 36 ++
.../action_dispatch/vendor/rack/rack/chunked.rb | 49 ++
.../vendor/rack/rack/commonlogger.rb | 61 +++
.../vendor/rack/rack/conditionalget.rb | 47 ++
.../vendor/rack/rack/content_length.rb | 29 ++
.../vendor/rack/rack/content_type.rb | 23 +
.../action_dispatch/vendor/rack/rack/deflater.rb | 96 ++++
.../action_dispatch/vendor/rack/rack/directory.rb | 153 ++++++
.../lib/action_dispatch/vendor/rack/rack/file.rb | 88 ++++
.../action_dispatch/vendor/rack/rack/handler.rb | 69 +++
.../vendor/rack/rack/handler/cgi.rb | 61 +++
.../vendor/rack/rack/handler/evented_mongrel.rb | 8 +
.../vendor/rack/rack/handler/fastcgi.rb | 88 ++++
.../vendor/rack/rack/handler/lsws.rb | 55 +++
.../vendor/rack/rack/handler/mongrel.rb | 84 ++++
.../vendor/rack/rack/handler/scgi.rb | 59 +++
.../rack/rack/handler/swiftiplied_mongrel.rb | 8 +
.../vendor/rack/rack/handler/thin.rb | 18 +
.../vendor/rack/rack/handler/webrick.rb | 67 +++
.../lib/action_dispatch/vendor/rack/rack/head.rb | 19 +
.../lib/action_dispatch/vendor/rack/rack/lint.rb | 537 +++++++++++++++++++++
.../action_dispatch/vendor/rack/rack/lobster.rb | 65 +++
.../lib/action_dispatch/vendor/rack/rack/lock.rb | 16 +
.../vendor/rack/rack/methodoverride.rb | 27 ++
.../lib/action_dispatch/vendor/rack/rack/mime.rb | 204 ++++++++
.../lib/action_dispatch/vendor/rack/rack/mock.rb | 184 +++++++
.../action_dispatch/vendor/rack/rack/recursive.rb | 57 +++
.../action_dispatch/vendor/rack/rack/reloader.rb | 106 ++++
.../action_dispatch/vendor/rack/rack/request.rb | 254 ++++++++++
.../action_dispatch/vendor/rack/rack/response.rb | 183 +++++++
.../vendor/rack/rack/rewindable_input.rb | 98 ++++
.../vendor/rack/rack/session/abstract/id.rb | 142 ++++++
.../vendor/rack/rack/session/cookie.rb | 91 ++++
.../vendor/rack/rack/session/memcache.rb | 109 +++++
.../vendor/rack/rack/session/pool.rb | 100 ++++
.../vendor/rack/rack/showexceptions.rb | 349 +++++++++++++
.../action_dispatch/vendor/rack/rack/showstatus.rb | 106 ++++
.../lib/action_dispatch/vendor/rack/rack/static.rb | 38 ++
.../lib/action_dispatch/vendor/rack/rack/urlmap.rb | 55 +++
.../lib/action_dispatch/vendor/rack/rack/utils.rb | 516 ++++++++++++++++++++
52 files changed, 5418 insertions(+), 1 deletion(-)
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/adapter/camping.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/auth/abstract/handler.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/auth/abstract/request.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/auth/basic.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/auth/digest/md5.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/auth/digest/nonce.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/auth/digest/params.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/auth/digest/request.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/auth/openid.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/builder.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/cascade.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/chunked.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/commonlogger.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/conditionalget.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/content_length.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/content_type.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/deflater.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/directory.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/file.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/handler.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/handler/cgi.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/handler/evented_mongrel.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/handler/fastcgi.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/handler/lsws.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/handler/mongrel.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/handler/scgi.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/handler/swiftiplied_mongrel.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/handler/thin.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/handler/webrick.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/head.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/lint.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/lobster.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/lock.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/methodoverride.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/mime.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/mock.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/recursive.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/reloader.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/request.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/response.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/rewindable_input.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/session/abstract/id.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/session/cookie.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/session/memcache.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/session/pool.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/showexceptions.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/showstatus.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/static.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/urlmap.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack/rack/utils.rb
(limited to 'actionpack')
diff --git a/actionpack/lib/action_dispatch.rb b/actionpack/lib/action_dispatch.rb
index 01e894cde6..a57fc5abdd 100644
--- a/actionpack/lib/action_dispatch.rb
+++ b/actionpack/lib/action_dispatch.rb
@@ -32,7 +32,12 @@ rescue LoadError
end
require 'active_support/core/all'
-gem 'rack', '~> 1.1.0'
+begin
+ gem 'rack', '~> 1.1.0'
+rescue Gem::LoadError
+ $:.unshift "#{File.dirname(__FILE__)}/action_dispatch/vendor/rack"
+end
+
require 'rack'
module ActionDispatch
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack.rb b/actionpack/lib/action_dispatch/vendor/rack/rack.rb
new file mode 100644
index 0000000000..371d015690
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack.rb
@@ -0,0 +1,90 @@
+# Copyright (C) 2007, 2008, 2009 Christian Neukirchen
+#
+# Rack is freely distributable under the terms of an MIT-style license.
+# See COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+path = File.expand_path(File.dirname(__FILE__))
+$:.unshift(path) unless $:.include?(path)
+
+
+# The Rack main module, serving as a namespace for all core Rack
+# modules and classes.
+#
+# All modules meant for use in your application are autoloaded here,
+# so it should be enough just to require rack.rb in your code.
+
+module Rack
+ # The Rack protocol version number implemented.
+ VERSION = [1,0]
+
+ # Return the Rack protocol version as a dotted string.
+ def self.version
+ VERSION.join(".")
+ end
+
+ # Return the Rack release as a dotted string.
+ def self.release
+ "1.0"
+ end
+
+ autoload :Builder, "rack/builder"
+ autoload :Cascade, "rack/cascade"
+ autoload :Chunked, "rack/chunked"
+ autoload :CommonLogger, "rack/commonlogger"
+ autoload :ConditionalGet, "rack/conditionalget"
+ autoload :ContentLength, "rack/content_length"
+ autoload :ContentType, "rack/content_type"
+ autoload :File, "rack/file"
+ autoload :Deflater, "rack/deflater"
+ autoload :Directory, "rack/directory"
+ autoload :ForwardRequest, "rack/recursive"
+ autoload :Handler, "rack/handler"
+ autoload :Head, "rack/head"
+ autoload :Lint, "rack/lint"
+ autoload :Lock, "rack/lock"
+ autoload :MethodOverride, "rack/methodoverride"
+ autoload :Mime, "rack/mime"
+ autoload :Recursive, "rack/recursive"
+ autoload :Reloader, "rack/reloader"
+ autoload :ShowExceptions, "rack/showexceptions"
+ autoload :ShowStatus, "rack/showstatus"
+ autoload :Static, "rack/static"
+ autoload :URLMap, "rack/urlmap"
+ autoload :Utils, "rack/utils"
+
+ autoload :MockRequest, "rack/mock"
+ autoload :MockResponse, "rack/mock"
+
+ autoload :Request, "rack/request"
+ autoload :Response, "rack/response"
+
+ module Auth
+ autoload :Basic, "rack/auth/basic"
+ autoload :AbstractRequest, "rack/auth/abstract/request"
+ autoload :AbstractHandler, "rack/auth/abstract/handler"
+ autoload :OpenID, "rack/auth/openid"
+ module Digest
+ autoload :MD5, "rack/auth/digest/md5"
+ autoload :Nonce, "rack/auth/digest/nonce"
+ autoload :Params, "rack/auth/digest/params"
+ autoload :Request, "rack/auth/digest/request"
+ end
+ end
+
+ module Session
+ autoload :Cookie, "rack/session/cookie"
+ autoload :Pool, "rack/session/pool"
+ autoload :Memcache, "rack/session/memcache"
+ end
+
+ # *Adapters* connect Rack with third party web frameworks.
+ #
+ # Rack includes an adapter for Camping, see README for other
+ # frameworks supporting Rack in their code bases.
+ #
+ # Refer to the submodules for framework-specific calling details.
+
+ module Adapter
+ autoload :Camping, "rack/adapter/camping"
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/adapter/camping.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/adapter/camping.rb
new file mode 100644
index 0000000000..63bc787f54
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/adapter/camping.rb
@@ -0,0 +1,22 @@
+module Rack
+ module Adapter
+ class Camping
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ env["PATH_INFO"] ||= ""
+ env["SCRIPT_NAME"] ||= ""
+ controller = @app.run(env['rack.input'], env)
+ h = controller.headers
+ h.each_pair do |k,v|
+ if v.kind_of? URI
+ h[k] = v.to_s
+ end
+ end
+ [controller.status, controller.headers, [controller.body.to_s]]
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/auth/abstract/handler.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/auth/abstract/handler.rb
new file mode 100644
index 0000000000..214df6299e
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/auth/abstract/handler.rb
@@ -0,0 +1,37 @@
+module Rack
+ module Auth
+ # Rack::Auth::AbstractHandler implements common authentication functionality.
+ #
+ # +realm+ should be set for all handlers.
+
+ class AbstractHandler
+
+ attr_accessor :realm
+
+ def initialize(app, realm=nil, &authenticator)
+ @app, @realm, @authenticator = app, realm, authenticator
+ end
+
+
+ private
+
+ def unauthorized(www_authenticate = challenge)
+ return [ 401,
+ { 'Content-Type' => 'text/plain',
+ 'Content-Length' => '0',
+ 'WWW-Authenticate' => www_authenticate.to_s },
+ []
+ ]
+ end
+
+ def bad_request
+ return [ 400,
+ { 'Content-Type' => 'text/plain',
+ 'Content-Length' => '0' },
+ []
+ ]
+ end
+
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/auth/abstract/request.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/auth/abstract/request.rb
new file mode 100644
index 0000000000..1d9ccec685
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/auth/abstract/request.rb
@@ -0,0 +1,37 @@
+module Rack
+ module Auth
+ class AbstractRequest
+
+ def initialize(env)
+ @env = env
+ end
+
+ def provided?
+ !authorization_key.nil?
+ end
+
+ def parts
+ @parts ||= @env[authorization_key].split(' ', 2)
+ end
+
+ def scheme
+ @scheme ||= parts.first.downcase.to_sym
+ end
+
+ def params
+ @params ||= parts.last
+ end
+
+
+ private
+
+ AUTHORIZATION_KEYS = ['HTTP_AUTHORIZATION', 'X-HTTP_AUTHORIZATION', 'X_HTTP_AUTHORIZATION']
+
+ def authorization_key
+ @authorization_key ||= AUTHORIZATION_KEYS.detect { |key| @env.has_key?(key) }
+ end
+
+ end
+
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/auth/basic.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/auth/basic.rb
new file mode 100644
index 0000000000..9557224648
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/auth/basic.rb
@@ -0,0 +1,58 @@
+require 'rack/auth/abstract/handler'
+require 'rack/auth/abstract/request'
+
+module Rack
+ module Auth
+ # Rack::Auth::Basic implements HTTP Basic Authentication, as per RFC 2617.
+ #
+ # Initialize with the Rack application that you want protecting,
+ # and a block that checks if a username and password pair are valid.
+ #
+ # See also: example/protectedlobster.rb
+
+ class Basic < AbstractHandler
+
+ def call(env)
+ auth = Basic::Request.new(env)
+
+ return unauthorized unless auth.provided?
+
+ return bad_request unless auth.basic?
+
+ if valid?(auth)
+ env['REMOTE_USER'] = auth.username
+
+ return @app.call(env)
+ end
+
+ unauthorized
+ end
+
+
+ private
+
+ def challenge
+ 'Basic realm="%s"' % realm
+ end
+
+ def valid?(auth)
+ @authenticator.call(*auth.credentials)
+ end
+
+ class Request < Auth::AbstractRequest
+ def basic?
+ :basic == scheme
+ end
+
+ def credentials
+ @credentials ||= params.unpack("m*").first.split(/:/, 2)
+ end
+
+ def username
+ credentials.first
+ end
+ end
+
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/auth/digest/md5.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/auth/digest/md5.rb
new file mode 100644
index 0000000000..e579dc9632
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/auth/digest/md5.rb
@@ -0,0 +1,124 @@
+require 'rack/auth/abstract/handler'
+require 'rack/auth/digest/request'
+require 'rack/auth/digest/params'
+require 'rack/auth/digest/nonce'
+require 'digest/md5'
+
+module Rack
+ module Auth
+ module Digest
+ # Rack::Auth::Digest::MD5 implements the MD5 algorithm version of
+ # HTTP Digest Authentication, as per RFC 2617.
+ #
+ # Initialize with the [Rack] application that you want protecting,
+ # and a block that looks up a plaintext password for a given username.
+ #
+ # +opaque+ needs to be set to a constant base64/hexadecimal string.
+ #
+ class MD5 < AbstractHandler
+
+ attr_accessor :opaque
+
+ attr_writer :passwords_hashed
+
+ def initialize(*args)
+ super
+ @passwords_hashed = nil
+ end
+
+ def passwords_hashed?
+ !!@passwords_hashed
+ end
+
+ def call(env)
+ auth = Request.new(env)
+
+ unless auth.provided?
+ return unauthorized
+ end
+
+ if !auth.digest? || !auth.correct_uri? || !valid_qop?(auth)
+ return bad_request
+ end
+
+ if valid?(auth)
+ if auth.nonce.stale?
+ return unauthorized(challenge(:stale => true))
+ else
+ env['REMOTE_USER'] = auth.username
+
+ return @app.call(env)
+ end
+ end
+
+ unauthorized
+ end
+
+
+ private
+
+ QOP = 'auth'.freeze
+
+ def params(hash = {})
+ Params.new do |params|
+ params['realm'] = realm
+ params['nonce'] = Nonce.new.to_s
+ params['opaque'] = H(opaque)
+ params['qop'] = QOP
+
+ hash.each { |k, v| params[k] = v }
+ end
+ end
+
+ def challenge(hash = {})
+ "Digest #{params(hash)}"
+ end
+
+ def valid?(auth)
+ valid_opaque?(auth) && valid_nonce?(auth) && valid_digest?(auth)
+ end
+
+ def valid_qop?(auth)
+ QOP == auth.qop
+ end
+
+ def valid_opaque?(auth)
+ H(opaque) == auth.opaque
+ end
+
+ def valid_nonce?(auth)
+ auth.nonce.valid?
+ end
+
+ def valid_digest?(auth)
+ digest(auth, @authenticator.call(auth.username)) == auth.response
+ end
+
+ def md5(data)
+ ::Digest::MD5.hexdigest(data)
+ end
+
+ alias :H :md5
+
+ def KD(secret, data)
+ H([secret, data] * ':')
+ end
+
+ def A1(auth, password)
+ [ auth.username, auth.realm, password ] * ':'
+ end
+
+ def A2(auth)
+ [ auth.method, auth.uri ] * ':'
+ end
+
+ def digest(auth, password)
+ password_hash = passwords_hashed? ? password : H(A1(auth, password))
+
+ KD(password_hash, [ auth.nonce, auth.nc, auth.cnonce, QOP, H(A2(auth)) ] * ':')
+ end
+
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/auth/digest/nonce.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/auth/digest/nonce.rb
new file mode 100644
index 0000000000..dbe109f29a
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/auth/digest/nonce.rb
@@ -0,0 +1,51 @@
+require 'digest/md5'
+
+module Rack
+ module Auth
+ module Digest
+ # Rack::Auth::Digest::Nonce is the default nonce generator for the
+ # Rack::Auth::Digest::MD5 authentication handler.
+ #
+ # +private_key+ needs to set to a constant string.
+ #
+ # +time_limit+ can be optionally set to an integer (number of seconds),
+ # to limit the validity of the generated nonces.
+
+ class Nonce
+
+ class << self
+ attr_accessor :private_key, :time_limit
+ end
+
+ def self.parse(string)
+ new(*string.unpack("m*").first.split(' ', 2))
+ end
+
+ def initialize(timestamp = Time.now, given_digest = nil)
+ @timestamp, @given_digest = timestamp.to_i, given_digest
+ end
+
+ def to_s
+ [([ @timestamp, digest ] * ' ')].pack("m*").strip
+ end
+
+ def digest
+ ::Digest::MD5.hexdigest([ @timestamp, self.class.private_key ] * ':')
+ end
+
+ def valid?
+ digest == @given_digest
+ end
+
+ def stale?
+ !self.class.time_limit.nil? && (@timestamp - Time.now.to_i) < self.class.time_limit
+ end
+
+ def fresh?
+ !stale?
+ end
+
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/auth/digest/params.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/auth/digest/params.rb
new file mode 100644
index 0000000000..730e2efdc8
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/auth/digest/params.rb
@@ -0,0 +1,55 @@
+module Rack
+ module Auth
+ module Digest
+ class Params < Hash
+
+ def self.parse(str)
+ split_header_value(str).inject(new) do |header, param|
+ k, v = param.split('=', 2)
+ header[k] = dequote(v)
+ header
+ end
+ end
+
+ def self.dequote(str) # From WEBrick::HTTPUtils
+ ret = (/\A"(.*)"\Z/ =~ str) ? $1 : str.dup
+ ret.gsub!(/\\(.)/, "\\1")
+ ret
+ end
+
+ def self.split_header_value(str)
+ str.scan( /(\w+\=(?:"[^\"]+"|[^,]+))/n ).collect{ |v| v[0] }
+ end
+
+ def initialize
+ super
+
+ yield self if block_given?
+ end
+
+ def [](k)
+ super k.to_s
+ end
+
+ def []=(k, v)
+ super k.to_s, v.to_s
+ end
+
+ UNQUOTED = ['qop', 'nc', 'stale']
+
+ def to_s
+ inject([]) do |parts, (k, v)|
+ parts << "#{k}=" + (UNQUOTED.include?(k) ? v.to_s : quote(v))
+ parts
+ end.join(', ')
+ end
+
+ def quote(str) # From WEBrick::HTTPUtils
+ '"' << str.gsub(/[\\\"]/o, "\\\1") << '"'
+ end
+
+ end
+ end
+ end
+end
+
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/auth/digest/request.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/auth/digest/request.rb
new file mode 100644
index 0000000000..a8aa3bf996
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/auth/digest/request.rb
@@ -0,0 +1,40 @@
+require 'rack/auth/abstract/request'
+require 'rack/auth/digest/params'
+require 'rack/auth/digest/nonce'
+
+module Rack
+ module Auth
+ module Digest
+ class Request < Auth::AbstractRequest
+
+ def method
+ @env['rack.methodoverride.original_method'] || @env['REQUEST_METHOD']
+ end
+
+ def digest?
+ :digest == scheme
+ end
+
+ def correct_uri?
+ (@env['SCRIPT_NAME'].to_s + @env['PATH_INFO'].to_s) == uri
+ end
+
+ def nonce
+ @nonce ||= Nonce.parse(params['nonce'])
+ end
+
+ def params
+ @params ||= Params.parse(parts.last)
+ end
+
+ def method_missing(sym)
+ if params.has_key? key = sym.to_s
+ return params[key]
+ end
+ super
+ end
+
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/auth/openid.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/auth/openid.rb
new file mode 100644
index 0000000000..c5f6a5143e
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/auth/openid.rb
@@ -0,0 +1,480 @@
+# AUTHOR: blink ; blink#ruby-lang@irc.freenode.net
+
+gem 'ruby-openid', '~> 2' if defined? Gem
+require 'rack/request'
+require 'rack/utils'
+require 'rack/auth/abstract/handler'
+require 'uri'
+require 'openid' #gem
+require 'openid/extension' #gem
+require 'openid/store/memory' #gem
+
+module Rack
+ class Request
+ def openid_request
+ @env['rack.auth.openid.request']
+ end
+
+ def openid_response
+ @env['rack.auth.openid.response']
+ end
+ end
+
+ module Auth
+
+ # Rack::Auth::OpenID provides a simple method for setting up an OpenID
+ # Consumer. It requires the ruby-openid library from janrain to operate,
+ # as well as a rack method of session management.
+ #
+ # The ruby-openid home page is at http://openidenabled.com/ruby-openid/.
+ #
+ # The OpenID specifications can be found at
+ # http://openid.net/specs/openid-authentication-1_1.html
+ # and
+ # http://openid.net/specs/openid-authentication-2_0.html. Documentation
+ # for published OpenID extensions and related topics can be found at
+ # http://openid.net/developers/specs/.
+ #
+ # It is recommended to read through the OpenID spec, as well as
+ # ruby-openid's documentation, to understand what exactly goes on. However
+ # a setup as simple as the presented examples is enough to provide
+ # Consumer functionality.
+ #
+ # This library strongly intends to utilize the OpenID 2.0 features of the
+ # ruby-openid library, which provides OpenID 1.0 compatiblity.
+ #
+ # NOTE: Due to the amount of data that this library stores in the
+ # session, Rack::Session::Cookie may fault.
+
+ class OpenID
+
+ class NoSession < RuntimeError; end
+ class BadExtension < RuntimeError; end
+ # Required for ruby-openid
+ ValidStatus = [:success, :setup_needed, :cancel, :failure]
+
+ # = Arguments
+ #
+ # The first argument is the realm, identifying the site they are trusting
+ # with their identity. This is required, also treated as the trust_root
+ # in OpenID 1.x exchanges.
+ #
+ # The optional second argument is a hash of options.
+ #
+ # == Options
+ #
+ # :return_to defines the url to return to after the client
+ # authenticates with the openid service provider. This url should point
+ # to where Rack::Auth::OpenID is mounted. If :return_to is not
+ # provided, return_to will be the current url which allows flexibility
+ # with caveats.
+ #
+ # :session_key defines the key to the session hash in the env.
+ # It defaults to 'rack.session'.
+ #
+ # :openid_param defines at what key in the request parameters to
+ # find the identifier to resolve. As per the 2.0 spec, the default is
+ # 'openid_identifier'.
+ #
+ # :store defined what OpenID Store to use for persistant
+ # information. By default a Store::Memory will be used.
+ #
+ # :immediate as true will make initial requests to be of an
+ # immediate type. This is false by default. See OpenID specification
+ # documentation.
+ #
+ # :extensions should be a hash of openid extension
+ # implementations. The key should be the extension main module, the value
+ # should be an array of arguments for extension::Request.new.
+ # The hash is iterated over and passed to #add_extension for processing.
+ # Please see #add_extension for further documentation.
+ #
+ # == Examples
+ #
+ # simple_oid = OpenID.new('http://mysite.com/')
+ #
+ # return_oid = OpenID.new('http://mysite.com/', {
+ # :return_to => 'http://mysite.com/openid'
+ # })
+ #
+ # complex_oid = OpenID.new('http://mysite.com/',
+ # :immediate => true,
+ # :extensions => {
+ # ::OpenID::SReg => [['email'],['nickname']]
+ # }
+ # )
+ #
+ # = Advanced
+ #
+ # Most of the functionality of this library is encapsulated such that
+ # expansion and overriding functions isn't difficult nor tricky.
+ # Alternately, to avoid opening up singleton objects or subclassing, a
+ # wrapper rack middleware can be composed to act upon Auth::OpenID's
+ # responses. See #check and #finish for locations of pertinent data.
+ #
+ # == Responses
+ #
+ # To change the responses that Auth::OpenID returns, override the methods
+ # #redirect, #bad_request, #unauthorized, #access_denied, and
+ # #foreign_server_failure.
+ #
+ # Additionally #confirm_post_params is used when the URI would exceed
+ # length limits on a GET request when doing the initial verification
+ # request.
+ #
+ # == Processing
+ #
+ # To change methods of processing completed transactions, override the
+ # methods #success, #setup_needed, #cancel, and #failure. Please ensure
+ # the returned object is a rack compatible response.
+ #
+ # The first argument is an OpenID::Response, the second is a
+ # Rack::Request of the current request, the last is the hash used in
+ # ruby-openid handling, which can be found manually at
+ # env['rack.session'][:openid].
+ #
+ # This is useful if you wanted to expand the processing done, such as
+ # setting up user accounts.
+ #
+ # oid_app = Rack::Auth::OpenID.new realm, :return_to => return_to
+ # def oid_app.success oid, request, session
+ # user = Models::User[oid.identity_url]
+ # user ||= Models::User.create_from_openid oid
+ # request['rack.session'][:user] = user.id
+ # redirect MyApp.site_home
+ # end
+ #
+ # site_map['/openid'] = oid_app
+ # map = Rack::URLMap.new site_map
+ # ...
+
+ def initialize(realm, options={})
+ realm = URI(realm)
+ raise ArgumentError, "Invalid realm: #{realm}" \
+ unless realm.absolute? \
+ and realm.fragment.nil? \
+ and realm.scheme =~ /^https?$/ \
+ and realm.host =~ /^(\*\.)?#{URI::REGEXP::PATTERN::URIC_NO_SLASH}+/
+ realm.path = '/' if realm.path.empty?
+ @realm = realm.to_s
+
+ if ruri = options[:return_to]
+ ruri = URI(ruri)
+ raise ArgumentError, "Invalid return_to: #{ruri}" \
+ unless ruri.absolute? \
+ and ruri.scheme =~ /^https?$/ \
+ and ruri.fragment.nil?
+ raise ArgumentError, "return_to #{ruri} not within realm #{realm}" \
+ unless self.within_realm?(ruri)
+ @return_to = ruri.to_s
+ end
+
+ @session_key = options[:session_key] || 'rack.session'
+ @openid_param = options[:openid_param] || 'openid_identifier'
+ @store = options[:store] || ::OpenID::Store::Memory.new
+ @immediate = !!options[:immediate]
+
+ @extensions = {}
+ if extensions = options.delete(:extensions)
+ extensions.each do |ext, args|
+ add_extension ext, *args
+ end
+ end
+
+ # Undocumented, semi-experimental
+ @anonymous = !!options[:anonymous]
+ end
+
+ attr_reader :realm, :return_to, :session_key, :openid_param, :store,
+ :immediate, :extensions
+
+ # Sets up and uses session data at :openid within the session.
+ # Errors in this setup will raise a NoSession exception.
+ #
+ # If the parameter 'openid.mode' is set, which implies a followup from
+ # the openid server, processing is passed to #finish and the result is
+ # returned. However, if there is no appropriate openid information in the
+ # session, a 400 error is returned.
+ #
+ # If the parameter specified by options[:openid_param] is
+ # present, processing is passed to #check and the result is returned.
+ #
+ # If neither of these conditions are met, #unauthorized is called.
+
+ def call(env)
+ env['rack.auth.openid'] = self
+ env_session = env[@session_key]
+ unless env_session and env_session.is_a?(Hash)
+ raise NoSession, 'No compatible session'
+ end
+ # let us work in our own namespace...
+ session = (env_session[:openid] ||= {})
+ unless session and session.is_a?(Hash)
+ raise NoSession, 'Incompatible openid session'
+ end
+
+ request = Rack::Request.new(env)
+ consumer = ::OpenID::Consumer.new(session, @store)
+
+ if mode = request.GET['openid.mode']
+ if session.key?(:openid_param)
+ finish(consumer, session, request)
+ else
+ bad_request
+ end
+ elsif request.GET[@openid_param]
+ check(consumer, session, request)
+ else
+ unauthorized
+ end
+ end
+
+ # As the first part of OpenID consumer action, #check retrieves the data
+ # required for completion.
+ #
+ # If all parameters fit within the max length of a URI, a 303 redirect
+ # will be returned. Otherwise #confirm_post_params will be called.
+ #
+ # Any messages from OpenID's request are logged to env['rack.errors']
+ #
+ # env['rack.auth.openid.request'] is the openid checkid request
+ # instance.
+ #
+ # session[:openid_param] is set to the openid identifier
+ # provided by the user.
+ #
+ # session[:return_to] is set to the return_to uri given to the
+ # identity provider.
+
+ def check(consumer, session, req)
+ oid = consumer.begin(req.GET[@openid_param], @anonymous)
+ req.env['rack.auth.openid.request'] = oid
+ req.env['rack.errors'].puts(oid.message)
+ p oid if $DEBUG
+
+ ## Extension support
+ extensions.each do |ext,args|
+ oid.add_extension(ext::Request.new(*args))
+ end
+
+ session[:openid_param] = req.GET[openid_param]
+ return_to_uri = return_to ? return_to : req.url
+ session[:return_to] = return_to_uri
+ immediate = session.key?(:setup_needed) ? false : immediate
+
+ if oid.send_redirect?(realm, return_to_uri, immediate)
+ uri = oid.redirect_url(realm, return_to_uri, immediate)
+ redirect(uri)
+ else
+ confirm_post_params(oid, realm, return_to_uri, immediate)
+ end
+ rescue ::OpenID::DiscoveryFailure => e
+ # thrown from inside OpenID::Consumer#begin by yadis stuff
+ req.env['rack.errors'].puts([e.message, *e.backtrace]*"\n")
+ return foreign_server_failure
+ end
+
+ # This is the final portion of authentication.
+ # If successful, a redirect to the realm is be returned.
+ # Data gathered from extensions are stored in session[:openid] with the
+ # extension's namespace uri as the key.
+ #
+ # Any messages from OpenID's response are logged to env['rack.errors']
+ #
+ # env['rack.auth.openid.response'] will contain the openid
+ # response.
+
+ def finish(consumer, session, req)
+ oid = consumer.complete(req.GET, req.url)
+ req.env['rack.auth.openid.response'] = oid
+ req.env['rack.errors'].puts(oid.message)
+ p oid if $DEBUG
+
+ raise unless ValidStatus.include?(oid.status)
+ __send__(oid.status, oid, req, session)
+ end
+
+ # The first argument should be the main extension module.
+ # The extension module should contain the constants:
+ # * class Request, should have OpenID::Extension as an ancestor
+ # * class Response, should have OpenID::Extension as an ancestor
+ # * string NS_URI, which defining the namespace of the extension
+ #
+ # All trailing arguments will be passed to extension::Request.new in
+ # #check.
+ # The openid response will be passed to
+ # extension::Response#from_success_response, #get_extension_args will be
+ # called on the result to attain the gathered data.
+ #
+ # This method returns the key at which the response data will be found in
+ # the session, which is the namespace uri by default.
+
+ def add_extension(ext, *args)
+ raise BadExtension unless valid_extension?(ext)
+ extensions[ext] = args
+ return ext::NS_URI
+ end
+
+ # Checks the validitity, in the context of usage, of a submitted
+ # extension.
+
+ def valid_extension?(ext)
+ if not %w[NS_URI Request Response].all?{|c| ext.const_defined?(c) }
+ raise ArgumentError, 'Extension is missing constants.'
+ elsif not ext::Response.respond_to?(:from_success_response)
+ raise ArgumentError, 'Response is missing required method.'
+ end
+ return true
+ rescue
+ return false
+ end
+
+ # Checks the provided uri to ensure it'd be considered within the realm.
+ # is currently not compatible with wildcard realms.
+
+ def within_realm? uri
+ uri = URI.parse(uri.to_s)
+ realm = URI.parse(self.realm)
+ return false unless uri.absolute?
+ return false unless uri.path[0, realm.path.size] == realm.path
+ return false unless uri.host == realm.host or realm.host[/^\*\./]
+ # for wildcard support, is awkward with URI limitations
+ realm_match = Regexp.escape(realm.host).
+ sub(/^\*\./,"^#{URI::REGEXP::PATTERN::URIC_NO_SLASH}+.")+'$'
+ return false unless uri.host.match(realm_match)
+ return true
+ end
+ alias_method :include?, :within_realm?
+
+ protected
+
+ ### These methods define some of the boilerplate responses.
+
+ # Returns an html form page for posting to an Identity Provider if the
+ # GET request would exceed the upper URI length limit.
+
+ def confirm_post_params(oid, realm, return_to, immediate)
+ Rack::Response.new.finish do |r|
+ r.write 'Confirm...'
+ r.write oid.form_markup(realm, return_to, immediate)
+ r.write ''
+ end
+ end
+
+ # Returns a 303 redirect with the destination of that provided by the
+ # argument.
+
+ def redirect(uri)
+ [ 303, {'Content-Length'=>'0', 'Content-Type'=>'text/plain',
+ 'Location' => uri},
+ [] ]
+ end
+
+ # Returns an empty 400 response.
+
+ def bad_request
+ [ 400, {'Content-Type'=>'text/plain', 'Content-Length'=>'0'},
+ [''] ]
+ end
+
+ # Returns a basic unauthorized 401 response.
+
+ def unauthorized
+ [ 401, {'Content-Type' => 'text/plain', 'Content-Length' => '13'},
+ ['Unauthorized.'] ]
+ end
+
+ # Returns a basic access denied 403 response.
+
+ def access_denied
+ [ 403, {'Content-Type' => 'text/plain', 'Content-Length' => '14'},
+ ['Access denied.'] ]
+ end
+
+ # Returns a 503 response to be used if communication with the remote
+ # OpenID server fails.
+
+ def foreign_server_failure
+ [ 503, {'Content-Type'=>'text/plain', 'Content-Length' => '23'},
+ ['Foreign server failure.'] ]
+ end
+
+ private
+
+ ### These methods are called after a transaction is completed, depending
+ # on its outcome. These should all return a rack compatible response.
+ # You'd want to override these to provide additional functionality.
+
+ # Called to complete processing on a successful transaction.
+ # Within the openid session, :openid_identity and :openid_identifier are
+ # set to the user friendly and the standard representation of the
+ # validated identity. All other data in the openid session is cleared.
+
+ def success(oid, request, session)
+ session.clear
+ session[:openid_identity] = oid.display_identifier
+ session[:openid_identifier] = oid.identity_url
+ extensions.keys.each do |ext|
+ label = ext.name[/[^:]+$/].downcase
+ response = ext::Response.from_success_response(oid)
+ session[label] = response.data
+ end
+ redirect(realm)
+ end
+
+ # Called if the Identity Provider indicates further setup by the user is
+ # required.
+ # The identifier is retrived from the openid session at :openid_param.
+ # And :setup_needed is set to true to prevent looping.
+
+ def setup_needed(oid, request, session)
+ identifier = session[:openid_param]
+ session[:setup_needed] = true
+ redirect req.script_name + '?' + openid_param + '=' + identifier
+ end
+
+ # Called if the user indicates they wish to cancel identification.
+ # Data within openid session is cleared.
+
+ def cancel(oid, request, session)
+ session.clear
+ access_denied
+ end
+
+ # Called if the Identity Provider indicates the user is unable to confirm
+ # their identity. Data within the openid session is left alone, in case
+ # of swarm auth attacks.
+
+ def failure(oid, request, session)
+ unauthorized
+ end
+ end
+
+ # A class developed out of the request to use OpenID as an authentication
+ # middleware. The request will be sent to the OpenID instance unless the
+ # block evaluates to true. For example in rackup, you can use it as such:
+ #
+ # use Rack::Session::Pool
+ # use Rack::Auth::OpenIDAuth, realm, openid_options do |env|
+ # env['rack.session'][:authkey] == a_string
+ # end
+ # run RackApp
+ #
+ # Or simply:
+ #
+ # app = Rack::Auth::OpenIDAuth.new app, realm, openid_options, &auth
+
+ class OpenIDAuth < Rack::Auth::AbstractHandler
+ attr_reader :oid
+ def initialize(app, realm, options={}, &auth)
+ @oid = OpenID.new(realm, options)
+ super(app, &auth)
+ end
+
+ def call(env)
+ to = auth.call(env) ? @app : @oid
+ to.call env
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/builder.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/builder.rb
new file mode 100644
index 0000000000..295235e56a
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/builder.rb
@@ -0,0 +1,63 @@
+module Rack
+ # Rack::Builder implements a small DSL to iteratively construct Rack
+ # applications.
+ #
+ # Example:
+ #
+ # app = Rack::Builder.new {
+ # use Rack::CommonLogger
+ # use Rack::ShowExceptions
+ # map "/lobster" do
+ # use Rack::Lint
+ # run Rack::Lobster.new
+ # end
+ # }
+ #
+ # Or
+ #
+ # app = Rack::Builder.app do
+ # use Rack::CommonLogger
+ # lambda { |env| [200, {'Content-Type' => 'text/plain'}, 'OK'] }
+ # end
+ #
+ # +use+ adds a middleware to the stack, +run+ dispatches to an application.
+ # You can use +map+ to construct a Rack::URLMap in a convenient way.
+
+ class Builder
+ def initialize(&block)
+ @ins = []
+ instance_eval(&block) if block_given?
+ end
+
+ def self.app(&block)
+ self.new(&block).to_app
+ end
+
+ def use(middleware, *args, &block)
+ @ins << lambda { |app| middleware.new(app, *args, &block) }
+ end
+
+ def run(app)
+ @ins << app #lambda { |nothing| app }
+ end
+
+ def map(path, &block)
+ if @ins.last.kind_of? Hash
+ @ins.last[path] = self.class.new(&block).to_app
+ else
+ @ins << {}
+ map(path, &block)
+ end
+ end
+
+ def to_app
+ @ins[-1] = Rack::URLMap.new(@ins.last) if Hash === @ins.last
+ inner_app = @ins.last
+ @ins[0...-1].reverse.inject(inner_app) { |a, e| e.call(a) }
+ end
+
+ def call(env)
+ to_app.call(env)
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/cascade.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/cascade.rb
new file mode 100644
index 0000000000..a038aa1105
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/cascade.rb
@@ -0,0 +1,36 @@
+module Rack
+ # Rack::Cascade tries an request on several apps, and returns the
+ # first response that is not 404 (or in a list of configurable
+ # status codes).
+
+ class Cascade
+ attr_reader :apps
+
+ def initialize(apps, catch=404)
+ @apps = apps
+ @catch = [*catch]
+ end
+
+ def call(env)
+ status = headers = body = nil
+ raise ArgumentError, "empty cascade" if @apps.empty?
+ @apps.each { |app|
+ begin
+ status, headers, body = app.call(env)
+ break unless @catch.include?(status.to_i)
+ end
+ }
+ [status, headers, body]
+ end
+
+ def add app
+ @apps << app
+ end
+
+ def include? app
+ @apps.include? app
+ end
+
+ alias_method :<<, :add
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/chunked.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/chunked.rb
new file mode 100644
index 0000000000..280d89dd65
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/chunked.rb
@@ -0,0 +1,49 @@
+require 'rack/utils'
+
+module Rack
+
+ # Middleware that applies chunked transfer encoding to response bodies
+ # when the response does not include a Content-Length header.
+ class Chunked
+ include Rack::Utils
+
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ status, headers, body = @app.call(env)
+ headers = HeaderHash.new(headers)
+
+ if env['HTTP_VERSION'] == 'HTTP/1.0' ||
+ STATUS_WITH_NO_ENTITY_BODY.include?(status) ||
+ headers['Content-Length'] ||
+ headers['Transfer-Encoding']
+ [status, headers.to_hash, body]
+ else
+ dup.chunk(status, headers, body)
+ end
+ end
+
+ def chunk(status, headers, body)
+ @body = body
+ headers.delete('Content-Length')
+ headers['Transfer-Encoding'] = 'chunked'
+ [status, headers.to_hash, self]
+ end
+
+ def each
+ term = "\r\n"
+ @body.each do |chunk|
+ size = bytesize(chunk)
+ next if size == 0
+ yield [size.to_s(16), term, chunk, term].join
+ end
+ yield ["0", term, "", term].join
+ end
+
+ def close
+ @body.close if @body.respond_to?(:close)
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/commonlogger.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/commonlogger.rb
new file mode 100644
index 0000000000..5e68ac626d
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/commonlogger.rb
@@ -0,0 +1,61 @@
+module Rack
+ # Rack::CommonLogger forwards every request to an +app+ given, and
+ # logs a line in the Apache common log format to the +logger+, or
+ # rack.errors by default.
+
+ class CommonLogger
+ def initialize(app, logger=nil)
+ @app = app
+ @logger = logger
+ end
+
+ def call(env)
+ dup._call(env)
+ end
+
+ def _call(env)
+ @env = env
+ @logger ||= self
+ @time = Time.now
+ @status, @header, @body = @app.call(env)
+ [@status, @header, self]
+ end
+
+ def close
+ @body.close if @body.respond_to? :close
+ end
+
+ # By default, log to rack.errors.
+ def <<(str)
+ @env["rack.errors"].write(str)
+ @env["rack.errors"].flush
+ end
+
+ def each
+ length = 0
+ @body.each { |part|
+ length += part.size
+ yield part
+ }
+
+ @now = Time.now
+
+ # Common Log Format: http://httpd.apache.org/docs/1.3/logs.html#common
+ # lilith.local - - [07/Aug/2006 23:58:02] "GET / HTTP/1.1" 500 -
+ # %{%s - %s [%s] "%s %s%s %s" %d %s\n} %
+ @logger << %{%s - %s [%s] "%s %s%s %s" %d %s %0.4f\n} %
+ [
+ @env['HTTP_X_FORWARDED_FOR'] || @env["REMOTE_ADDR"] || "-",
+ @env["REMOTE_USER"] || "-",
+ @now.strftime("%d/%b/%Y %H:%M:%S"),
+ @env["REQUEST_METHOD"],
+ @env["PATH_INFO"],
+ @env["QUERY_STRING"].empty? ? "" : "?"+@env["QUERY_STRING"],
+ @env["HTTP_VERSION"],
+ @status.to_s[0..3],
+ (length.zero? ? "-" : length.to_s),
+ @now - @time
+ ]
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/conditionalget.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/conditionalget.rb
new file mode 100644
index 0000000000..046ebdb00a
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/conditionalget.rb
@@ -0,0 +1,47 @@
+require 'rack/utils'
+
+module Rack
+
+ # Middleware that enables conditional GET using If-None-Match and
+ # If-Modified-Since. The application should set either or both of the
+ # Last-Modified or Etag response headers according to RFC 2616. When
+ # either of the conditions is met, the response body is set to be zero
+ # length and the response status is set to 304 Not Modified.
+ #
+ # Applications that defer response body generation until the body's each
+ # message is received will avoid response body generation completely when
+ # a conditional GET matches.
+ #
+ # Adapted from Michael Klishin's Merb implementation:
+ # http://github.com/wycats/merb-core/tree/master/lib/merb-core/rack/middleware/conditional_get.rb
+ class ConditionalGet
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ return @app.call(env) unless %w[GET HEAD].include?(env['REQUEST_METHOD'])
+
+ status, headers, body = @app.call(env)
+ headers = Utils::HeaderHash.new(headers)
+ if etag_matches?(env, headers) || modified_since?(env, headers)
+ status = 304
+ headers.delete('Content-Type')
+ headers.delete('Content-Length')
+ body = []
+ end
+ [status, headers, body]
+ end
+
+ private
+ def etag_matches?(env, headers)
+ etag = headers['Etag'] and etag == env['HTTP_IF_NONE_MATCH']
+ end
+
+ def modified_since?(env, headers)
+ last_modified = headers['Last-Modified'] and
+ last_modified == env['HTTP_IF_MODIFIED_SINCE']
+ end
+ end
+
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/content_length.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/content_length.rb
new file mode 100644
index 0000000000..1e56d43853
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/content_length.rb
@@ -0,0 +1,29 @@
+require 'rack/utils'
+
+module Rack
+ # Sets the Content-Length header on responses with fixed-length bodies.
+ class ContentLength
+ include Rack::Utils
+
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ status, headers, body = @app.call(env)
+ headers = HeaderHash.new(headers)
+
+ if !STATUS_WITH_NO_ENTITY_BODY.include?(status) &&
+ !headers['Content-Length'] &&
+ !headers['Transfer-Encoding'] &&
+ (body.respond_to?(:to_ary) || body.respond_to?(:to_str))
+
+ body = [body] if body.respond_to?(:to_str) # rack 0.4 compat
+ length = body.to_ary.inject(0) { |len, part| len + bytesize(part) }
+ headers['Content-Length'] = length.to_s
+ end
+
+ [status, headers, body]
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/content_type.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/content_type.rb
new file mode 100644
index 0000000000..0c1e1ca3e1
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/content_type.rb
@@ -0,0 +1,23 @@
+require 'rack/utils'
+
+module Rack
+
+ # Sets the Content-Type header on responses which don't have one.
+ #
+ # Builder Usage:
+ # use Rack::ContentType, "text/plain"
+ #
+ # When no content type argument is provided, "text/html" is assumed.
+ class ContentType
+ def initialize(app, content_type = "text/html")
+ @app, @content_type = app, content_type
+ end
+
+ def call(env)
+ status, headers, body = @app.call(env)
+ headers = Utils::HeaderHash.new(headers)
+ headers['Content-Type'] ||= @content_type
+ [status, headers.to_hash, body]
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/deflater.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/deflater.rb
new file mode 100644
index 0000000000..14137a944d
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/deflater.rb
@@ -0,0 +1,96 @@
+require "zlib"
+require "stringio"
+require "time" # for Time.httpdate
+require 'rack/utils'
+
+module Rack
+ class Deflater
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ status, headers, body = @app.call(env)
+ headers = Utils::HeaderHash.new(headers)
+
+ # Skip compressing empty entity body responses and responses with
+ # no-transform set.
+ if Utils::STATUS_WITH_NO_ENTITY_BODY.include?(status) ||
+ headers['Cache-Control'].to_s =~ /\bno-transform\b/
+ return [status, headers, body]
+ end
+
+ request = Request.new(env)
+
+ encoding = Utils.select_best_encoding(%w(gzip deflate identity),
+ request.accept_encoding)
+
+ # Set the Vary HTTP header.
+ vary = headers["Vary"].to_s.split(",").map { |v| v.strip }
+ unless vary.include?("*") || vary.include?("Accept-Encoding")
+ headers["Vary"] = vary.push("Accept-Encoding").join(",")
+ end
+
+ case encoding
+ when "gzip"
+ headers['Content-Encoding'] = "gzip"
+ headers.delete('Content-Length')
+ mtime = headers.key?("Last-Modified") ?
+ Time.httpdate(headers["Last-Modified"]) : Time.now
+ [status, headers, GzipStream.new(body, mtime)]
+ when "deflate"
+ headers['Content-Encoding'] = "deflate"
+ headers.delete('Content-Length')
+ [status, headers, DeflateStream.new(body)]
+ when "identity"
+ [status, headers, body]
+ when nil
+ message = "An acceptable encoding for the requested resource #{request.fullpath} could not be found."
+ [406, {"Content-Type" => "text/plain", "Content-Length" => message.length.to_s}, [message]]
+ end
+ end
+
+ class GzipStream
+ def initialize(body, mtime)
+ @body = body
+ @mtime = mtime
+ end
+
+ def each(&block)
+ @writer = block
+ gzip =::Zlib::GzipWriter.new(self)
+ gzip.mtime = @mtime
+ @body.each { |part| gzip << part }
+ @body.close if @body.respond_to?(:close)
+ gzip.close
+ @writer = nil
+ end
+
+ def write(data)
+ @writer.call(data)
+ end
+ end
+
+ class DeflateStream
+ DEFLATE_ARGS = [
+ Zlib::DEFAULT_COMPRESSION,
+ # drop the zlib header which causes both Safari and IE to choke
+ -Zlib::MAX_WBITS,
+ Zlib::DEF_MEM_LEVEL,
+ Zlib::DEFAULT_STRATEGY
+ ]
+
+ def initialize(body)
+ @body = body
+ end
+
+ def each
+ deflater = ::Zlib::Deflate.new(*DEFLATE_ARGS)
+ @body.each { |part| yield deflater.deflate(part) }
+ @body.close if @body.respond_to?(:close)
+ yield deflater.finish
+ nil
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/directory.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/directory.rb
new file mode 100644
index 0000000000..acdd3029d3
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/directory.rb
@@ -0,0 +1,153 @@
+require 'time'
+require 'rack/utils'
+require 'rack/mime'
+
+module Rack
+ # Rack::Directory serves entries below the +root+ given, according to the
+ # path info of the Rack request. If a directory is found, the file's contents
+ # will be presented in an html based index. If a file is found, the env will
+ # be passed to the specified +app+.
+ #
+ # If +app+ is not specified, a Rack::File of the same +root+ will be used.
+
+ class Directory
+ DIR_FILE = "
+
+
+ PAGE
+
+ attr_reader :files
+ attr_accessor :root, :path
+
+ def initialize(root, app=nil)
+ @root = F.expand_path(root)
+ @app = app || Rack::File.new(@root)
+ end
+
+ def call(env)
+ dup._call(env)
+ end
+
+ F = ::File
+
+ def _call(env)
+ @env = env
+ @script_name = env['SCRIPT_NAME']
+ @path_info = Utils.unescape(env['PATH_INFO'])
+
+ if forbidden = check_forbidden
+ forbidden
+ else
+ @path = F.join(@root, @path_info)
+ list_path
+ end
+ end
+
+ def check_forbidden
+ return unless @path_info.include? ".."
+
+ body = "Forbidden\n"
+ size = Rack::Utils.bytesize(body)
+ return [403, {"Content-Type" => "text/plain","Content-Length" => size.to_s}, [body]]
+ end
+
+ def list_directory
+ @files = [['../','Parent Directory','','','']]
+ glob = F.join(@path, '*')
+
+ Dir[glob].sort.each do |node|
+ stat = stat(node)
+ next unless stat
+ basename = F.basename(node)
+ ext = F.extname(node)
+
+ url = F.join(@script_name, @path_info, basename)
+ size = stat.size
+ type = stat.directory? ? 'directory' : Mime.mime_type(ext)
+ size = stat.directory? ? '-' : filesize_format(size)
+ mtime = stat.mtime.httpdate
+ url << '/' if stat.directory?
+ basename << '/' if stat.directory?
+
+ @files << [ url, basename, size, type, mtime ]
+ end
+
+ return [ 200, {'Content-Type'=>'text/html; charset=utf-8'}, self ]
+ end
+
+ def stat(node, max = 10)
+ F.stat(node)
+ rescue Errno::ENOENT, Errno::ELOOP
+ return nil
+ end
+
+ # TODO: add correct response if not readable, not sure if 404 is the best
+ # option
+ def list_path
+ @stat = F.stat(@path)
+
+ if @stat.readable?
+ return @app.call(@env) if @stat.file?
+ return list_directory if @stat.directory?
+ else
+ raise Errno::ENOENT, 'No such file or directory'
+ end
+
+ rescue Errno::ENOENT, Errno::ELOOP
+ return entity_not_found
+ end
+
+ def entity_not_found
+ body = "Entity not found: #{@path_info}\n"
+ size = Rack::Utils.bytesize(body)
+ return [404, {"Content-Type" => "text/plain", "Content-Length" => size.to_s}, [body]]
+ end
+
+ def each
+ show_path = @path.sub(/^#{@root}/,'')
+ files = @files.map{|f| DIR_FILE % f }*"\n"
+ page = DIR_PAGE % [ show_path, show_path , files ]
+ page.each_line{|l| yield l }
+ end
+
+ # Stolen from Ramaze
+
+ FILESIZE_FORMAT = [
+ ['%.1fT', 1 << 40],
+ ['%.1fG', 1 << 30],
+ ['%.1fM', 1 << 20],
+ ['%.1fK', 1 << 10],
+ ]
+
+ def filesize_format(int)
+ FILESIZE_FORMAT.each do |format, size|
+ return format % (int.to_f / size) if int >= size
+ end
+
+ int.to_s + 'B'
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/file.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/file.rb
new file mode 100644
index 0000000000..fe62bd6b86
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/file.rb
@@ -0,0 +1,88 @@
+require 'time'
+require 'rack/utils'
+require 'rack/mime'
+
+module Rack
+ # Rack::File serves files below the +root+ given, according to the
+ # path info of the Rack request.
+ #
+ # Handlers can detect if bodies are a Rack::File, and use mechanisms
+ # like sendfile on the +path+.
+
+ class File
+ attr_accessor :root
+ attr_accessor :path
+
+ alias :to_path :path
+
+ def initialize(root)
+ @root = root
+ end
+
+ def call(env)
+ dup._call(env)
+ end
+
+ F = ::File
+
+ def _call(env)
+ @path_info = Utils.unescape(env["PATH_INFO"])
+ return forbidden if @path_info.include? ".."
+
+ @path = F.join(@root, @path_info)
+
+ begin
+ if F.file?(@path) && F.readable?(@path)
+ serving
+ else
+ raise Errno::EPERM
+ end
+ rescue SystemCallError
+ not_found
+ end
+ end
+
+ def forbidden
+ body = "Forbidden\n"
+ [403, {"Content-Type" => "text/plain",
+ "Content-Length" => body.size.to_s},
+ [body]]
+ end
+
+ # NOTE:
+ # We check via File::size? whether this file provides size info
+ # via stat (e.g. /proc files often don't), otherwise we have to
+ # figure it out by reading the whole file into memory. And while
+ # we're at it we also use this as body then.
+
+ def serving
+ if size = F.size?(@path)
+ body = self
+ else
+ body = [F.read(@path)]
+ size = Utils.bytesize(body.first)
+ end
+
+ [200, {
+ "Last-Modified" => F.mtime(@path).httpdate,
+ "Content-Type" => Mime.mime_type(F.extname(@path), 'text/plain'),
+ "Content-Length" => size.to_s
+ }, body]
+ end
+
+ def not_found
+ body = "File not found: #{@path_info}\n"
+ [404, {"Content-Type" => "text/plain",
+ "Content-Length" => body.size.to_s},
+ [body]]
+ end
+
+ def each
+ F.open(@path, "rb") { |file|
+ while part = file.read(8192)
+ yield part
+ end
+ }
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/handler.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/handler.rb
new file mode 100644
index 0000000000..5624a1e79d
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/handler.rb
@@ -0,0 +1,69 @@
+module Rack
+ # *Handlers* connect web servers with Rack.
+ #
+ # Rack includes Handlers for Mongrel, WEBrick, FastCGI, CGI, SCGI
+ # and LiteSpeed.
+ #
+ # Handlers usually are activated by calling MyHandler.run(myapp).
+ # A second optional hash can be passed to include server-specific
+ # configuration.
+ module Handler
+ def self.get(server)
+ return unless server
+ server = server.to_s
+
+ if klass = @handlers[server]
+ obj = Object
+ klass.split("::").each { |x| obj = obj.const_get(x) }
+ obj
+ else
+ try_require('rack/handler', server)
+ const_get(server)
+ end
+ end
+
+ # Transforms server-name constants to their canonical form as filenames,
+ # then tries to require them but silences the LoadError if not found
+ #
+ # Naming convention:
+ #
+ # Foo # => 'foo'
+ # FooBar # => 'foo_bar.rb'
+ # FooBAR # => 'foobar.rb'
+ # FOObar # => 'foobar.rb'
+ # FOOBAR # => 'foobar.rb'
+ # FooBarBaz # => 'foo_bar_baz.rb'
+ def self.try_require(prefix, const_name)
+ file = const_name.gsub(/^[A-Z]+/) { |pre| pre.downcase }.
+ gsub(/[A-Z]+[^A-Z]/, '_\&').downcase
+
+ require(::File.join(prefix, file))
+ rescue LoadError
+ end
+
+ def self.register(server, klass)
+ @handlers ||= {}
+ @handlers[server] = klass
+ end
+
+ autoload :CGI, "rack/handler/cgi"
+ autoload :FastCGI, "rack/handler/fastcgi"
+ autoload :Mongrel, "rack/handler/mongrel"
+ autoload :EventedMongrel, "rack/handler/evented_mongrel"
+ autoload :SwiftipliedMongrel, "rack/handler/swiftiplied_mongrel"
+ autoload :WEBrick, "rack/handler/webrick"
+ autoload :LSWS, "rack/handler/lsws"
+ autoload :SCGI, "rack/handler/scgi"
+ autoload :Thin, "rack/handler/thin"
+
+ register 'cgi', 'Rack::Handler::CGI'
+ register 'fastcgi', 'Rack::Handler::FastCGI'
+ register 'mongrel', 'Rack::Handler::Mongrel'
+ register 'emongrel', 'Rack::Handler::EventedMongrel'
+ register 'smongrel', 'Rack::Handler::SwiftipliedMongrel'
+ register 'webrick', 'Rack::Handler::WEBrick'
+ register 'lsws', 'Rack::Handler::LSWS'
+ register 'scgi', 'Rack::Handler::SCGI'
+ register 'thin', 'Rack::Handler::Thin'
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/handler/cgi.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/handler/cgi.rb
new file mode 100644
index 0000000000..f45f3d735a
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/handler/cgi.rb
@@ -0,0 +1,61 @@
+require 'rack/content_length'
+
+module Rack
+ module Handler
+ class CGI
+ def self.run(app, options=nil)
+ serve app
+ end
+
+ def self.serve(app)
+ app = ContentLength.new(app)
+
+ env = ENV.to_hash
+ env.delete "HTTP_CONTENT_LENGTH"
+
+ env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/"
+
+ env.update({"rack.version" => [1,0],
+ "rack.input" => $stdin,
+ "rack.errors" => $stderr,
+
+ "rack.multithread" => false,
+ "rack.multiprocess" => true,
+ "rack.run_once" => true,
+
+ "rack.url_scheme" => ["yes", "on", "1"].include?(ENV["HTTPS"]) ? "https" : "http"
+ })
+
+ env["QUERY_STRING"] ||= ""
+ env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"]
+ env["REQUEST_PATH"] ||= "/"
+
+ status, headers, body = app.call(env)
+ begin
+ send_headers status, headers
+ send_body body
+ ensure
+ body.close if body.respond_to? :close
+ end
+ end
+
+ def self.send_headers(status, headers)
+ STDOUT.print "Status: #{status}\r\n"
+ headers.each { |k, vs|
+ vs.split("\n").each { |v|
+ STDOUT.print "#{k}: #{v}\r\n"
+ }
+ }
+ STDOUT.print "\r\n"
+ STDOUT.flush
+ end
+
+ def self.send_body(body)
+ body.each { |part|
+ STDOUT.print part
+ STDOUT.flush
+ }
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/handler/evented_mongrel.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/handler/evented_mongrel.rb
new file mode 100644
index 0000000000..0f5cbf7293
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/handler/evented_mongrel.rb
@@ -0,0 +1,8 @@
+require 'swiftcore/evented_mongrel'
+
+module Rack
+ module Handler
+ class EventedMongrel < Handler::Mongrel
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/handler/fastcgi.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/handler/fastcgi.rb
new file mode 100644
index 0000000000..11e1fcaa74
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/handler/fastcgi.rb
@@ -0,0 +1,88 @@
+require 'fcgi'
+require 'socket'
+require 'rack/content_length'
+require 'rack/rewindable_input'
+
+class FCGI::Stream
+ alias _rack_read_without_buffer read
+
+ def read(n, buffer=nil)
+ buf = _rack_read_without_buffer n
+ buffer.replace(buf.to_s) if buffer
+ buf
+ end
+end
+
+module Rack
+ module Handler
+ class FastCGI
+ def self.run(app, options={})
+ file = options[:File] and STDIN.reopen(UNIXServer.new(file))
+ port = options[:Port] and STDIN.reopen(TCPServer.new(port))
+ FCGI.each { |request|
+ serve request, app
+ }
+ end
+
+ def self.serve(request, app)
+ app = Rack::ContentLength.new(app)
+
+ env = request.env
+ env.delete "HTTP_CONTENT_LENGTH"
+
+ env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/"
+
+ rack_input = RewindableInput.new(request.in)
+
+ env.update({"rack.version" => [1,0],
+ "rack.input" => rack_input,
+ "rack.errors" => request.err,
+
+ "rack.multithread" => false,
+ "rack.multiprocess" => true,
+ "rack.run_once" => false,
+
+ "rack.url_scheme" => ["yes", "on", "1"].include?(env["HTTPS"]) ? "https" : "http"
+ })
+
+ env["QUERY_STRING"] ||= ""
+ env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"]
+ env["REQUEST_PATH"] ||= "/"
+ env.delete "PATH_INFO" if env["PATH_INFO"] == ""
+ env.delete "CONTENT_TYPE" if env["CONTENT_TYPE"] == ""
+ env.delete "CONTENT_LENGTH" if env["CONTENT_LENGTH"] == ""
+
+ begin
+ status, headers, body = app.call(env)
+ begin
+ send_headers request.out, status, headers
+ send_body request.out, body
+ ensure
+ body.close if body.respond_to? :close
+ end
+ ensure
+ rack_input.close
+ request.finish
+ end
+ end
+
+ def self.send_headers(out, status, headers)
+ out.print "Status: #{status}\r\n"
+ headers.each { |k, vs|
+ vs.split("\n").each { |v|
+ out.print "#{k}: #{v}\r\n"
+ }
+ }
+ out.print "\r\n"
+ out.flush
+ end
+
+ def self.send_body(out, body)
+ body.each { |part|
+ out.print part
+ out.flush
+ }
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/handler/lsws.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/handler/lsws.rb
new file mode 100644
index 0000000000..7231336d7b
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/handler/lsws.rb
@@ -0,0 +1,55 @@
+require 'lsapi'
+require 'rack/content_length'
+
+module Rack
+ module Handler
+ class LSWS
+ def self.run(app, options=nil)
+ while LSAPI.accept != nil
+ serve app
+ end
+ end
+ def self.serve(app)
+ app = Rack::ContentLength.new(app)
+
+ env = ENV.to_hash
+ env.delete "HTTP_CONTENT_LENGTH"
+ env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/"
+ env.update({"rack.version" => [1,0],
+ "rack.input" => StringIO.new($stdin.read.to_s),
+ "rack.errors" => $stderr,
+ "rack.multithread" => false,
+ "rack.multiprocess" => true,
+ "rack.run_once" => false,
+ "rack.url_scheme" => ["yes", "on", "1"].include?(ENV["HTTPS"]) ? "https" : "http"
+ })
+ env["QUERY_STRING"] ||= ""
+ env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"]
+ env["REQUEST_PATH"] ||= "/"
+ status, headers, body = app.call(env)
+ begin
+ send_headers status, headers
+ send_body body
+ ensure
+ body.close if body.respond_to? :close
+ end
+ end
+ def self.send_headers(status, headers)
+ print "Status: #{status}\r\n"
+ headers.each { |k, vs|
+ vs.split("\n").each { |v|
+ print "#{k}: #{v}\r\n"
+ }
+ }
+ print "\r\n"
+ STDOUT.flush
+ end
+ def self.send_body(body)
+ body.each { |part|
+ print part
+ STDOUT.flush
+ }
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/handler/mongrel.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/handler/mongrel.rb
new file mode 100644
index 0000000000..3a5ef32d4b
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/handler/mongrel.rb
@@ -0,0 +1,84 @@
+require 'mongrel'
+require 'stringio'
+require 'rack/content_length'
+require 'rack/chunked'
+
+module Rack
+ module Handler
+ class Mongrel < ::Mongrel::HttpHandler
+ def self.run(app, options={})
+ server = ::Mongrel::HttpServer.new(options[:Host] || '0.0.0.0',
+ options[:Port] || 8080)
+ # Acts like Rack::URLMap, utilizing Mongrel's own path finding methods.
+ # Use is similar to #run, replacing the app argument with a hash of
+ # { path=>app, ... } or an instance of Rack::URLMap.
+ if options[:map]
+ if app.is_a? Hash
+ app.each do |path, appl|
+ path = '/'+path unless path[0] == ?/
+ server.register(path, Rack::Handler::Mongrel.new(appl))
+ end
+ elsif app.is_a? URLMap
+ app.instance_variable_get(:@mapping).each do |(host, path, appl)|
+ next if !host.nil? && !options[:Host].nil? && options[:Host] != host
+ path = '/'+path unless path[0] == ?/
+ server.register(path, Rack::Handler::Mongrel.new(appl))
+ end
+ else
+ raise ArgumentError, "first argument should be a Hash or URLMap"
+ end
+ else
+ server.register('/', Rack::Handler::Mongrel.new(app))
+ end
+ yield server if block_given?
+ server.run.join
+ end
+
+ def initialize(app)
+ @app = Rack::Chunked.new(Rack::ContentLength.new(app))
+ end
+
+ def process(request, response)
+ env = {}.replace(request.params)
+ env.delete "HTTP_CONTENT_TYPE"
+ env.delete "HTTP_CONTENT_LENGTH"
+
+ env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/"
+
+ env.update({"rack.version" => [1,0],
+ "rack.input" => request.body || StringIO.new(""),
+ "rack.errors" => $stderr,
+
+ "rack.multithread" => true,
+ "rack.multiprocess" => false, # ???
+ "rack.run_once" => false,
+
+ "rack.url_scheme" => "http",
+ })
+ env["QUERY_STRING"] ||= ""
+ env.delete "PATH_INFO" if env["PATH_INFO"] == ""
+
+ status, headers, body = @app.call(env)
+
+ begin
+ response.status = status.to_i
+ response.send_status(nil)
+
+ headers.each { |k, vs|
+ vs.split("\n").each { |v|
+ response.header[k] = v
+ }
+ }
+ response.send_header
+
+ body.each { |part|
+ response.write part
+ response.socket.flush
+ }
+ ensure
+ body.close if body.respond_to? :close
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/handler/scgi.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/handler/scgi.rb
new file mode 100644
index 0000000000..6c4932df95
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/handler/scgi.rb
@@ -0,0 +1,59 @@
+require 'scgi'
+require 'stringio'
+require 'rack/content_length'
+require 'rack/chunked'
+
+module Rack
+ module Handler
+ class SCGI < ::SCGI::Processor
+ attr_accessor :app
+
+ def self.run(app, options=nil)
+ new(options.merge(:app=>app,
+ :host=>options[:Host],
+ :port=>options[:Port],
+ :socket=>options[:Socket])).listen
+ end
+
+ def initialize(settings = {})
+ @app = Rack::Chunked.new(Rack::ContentLength.new(settings[:app]))
+ @log = Object.new
+ def @log.info(*args); end
+ def @log.error(*args); end
+ super(settings)
+ end
+
+ def process_request(request, input_body, socket)
+ env = {}.replace(request)
+ env.delete "HTTP_CONTENT_TYPE"
+ env.delete "HTTP_CONTENT_LENGTH"
+ env["REQUEST_PATH"], env["QUERY_STRING"] = env["REQUEST_URI"].split('?', 2)
+ env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"]
+ env["PATH_INFO"] = env["REQUEST_PATH"]
+ env["QUERY_STRING"] ||= ""
+ env["SCRIPT_NAME"] = ""
+ env.update({"rack.version" => [1,0],
+ "rack.input" => StringIO.new(input_body),
+ "rack.errors" => $stderr,
+
+ "rack.multithread" => true,
+ "rack.multiprocess" => true,
+ "rack.run_once" => false,
+
+ "rack.url_scheme" => ["yes", "on", "1"].include?(env["HTTPS"]) ? "https" : "http"
+ })
+ status, headers, body = app.call(env)
+ begin
+ socket.write("Status: #{status}\r\n")
+ headers.each do |k, vs|
+ vs.split("\n").each { |v| socket.write("#{k}: #{v}\r\n")}
+ end
+ socket.write("\r\n")
+ body.each {|s| socket.write(s)}
+ ensure
+ body.close if body.respond_to? :close
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/handler/swiftiplied_mongrel.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/handler/swiftiplied_mongrel.rb
new file mode 100644
index 0000000000..4bafd0b953
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/handler/swiftiplied_mongrel.rb
@@ -0,0 +1,8 @@
+require 'swiftcore/swiftiplied_mongrel'
+
+module Rack
+ module Handler
+ class SwiftipliedMongrel < Handler::Mongrel
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/handler/thin.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/handler/thin.rb
new file mode 100644
index 0000000000..3d4fedff75
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/handler/thin.rb
@@ -0,0 +1,18 @@
+require "thin"
+require "rack/content_length"
+require "rack/chunked"
+
+module Rack
+ module Handler
+ class Thin
+ def self.run(app, options={})
+ app = Rack::Chunked.new(Rack::ContentLength.new(app))
+ server = ::Thin::Server.new(options[:Host] || '0.0.0.0',
+ options[:Port] || 8080,
+ app)
+ yield server if block_given?
+ server.start
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/handler/webrick.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/handler/webrick.rb
new file mode 100644
index 0000000000..2bdc83a9ff
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/handler/webrick.rb
@@ -0,0 +1,67 @@
+require 'webrick'
+require 'stringio'
+require 'rack/content_length'
+
+module Rack
+ module Handler
+ class WEBrick < ::WEBrick::HTTPServlet::AbstractServlet
+ def self.run(app, options={})
+ server = ::WEBrick::HTTPServer.new(options)
+ server.mount "/", Rack::Handler::WEBrick, app
+ trap(:INT) { server.shutdown }
+ yield server if block_given?
+ server.start
+ end
+
+ def initialize(server, app)
+ super server
+ @app = Rack::ContentLength.new(app)
+ end
+
+ def service(req, res)
+ env = req.meta_vars
+ env.delete_if { |k, v| v.nil? }
+
+ env.update({"rack.version" => [1,0],
+ "rack.input" => StringIO.new(req.body.to_s),
+ "rack.errors" => $stderr,
+
+ "rack.multithread" => true,
+ "rack.multiprocess" => false,
+ "rack.run_once" => false,
+
+ "rack.url_scheme" => ["yes", "on", "1"].include?(ENV["HTTPS"]) ? "https" : "http"
+ })
+
+ env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"]
+ env["QUERY_STRING"] ||= ""
+ env["REQUEST_PATH"] ||= "/"
+ if env["PATH_INFO"] == ""
+ env.delete "PATH_INFO"
+ else
+ path, n = req.request_uri.path, env["SCRIPT_NAME"].length
+ env["PATH_INFO"] = path[n, path.length-n]
+ end
+
+ status, headers, body = @app.call(env)
+ begin
+ res.status = status.to_i
+ headers.each { |k, vs|
+ if k.downcase == "set-cookie"
+ res.cookies.concat vs.split("\n")
+ else
+ vs.split("\n").each { |v|
+ res[k] = v
+ }
+ end
+ }
+ body.each { |part|
+ res.body << part
+ }
+ ensure
+ body.close if body.respond_to? :close
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/head.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/head.rb
new file mode 100644
index 0000000000..deab822a99
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/head.rb
@@ -0,0 +1,19 @@
+module Rack
+
+class Head
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ status, headers, body = @app.call(env)
+
+ if env["REQUEST_METHOD"] == "HEAD"
+ [status, headers, []]
+ else
+ [status, headers, body]
+ end
+ end
+end
+
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/lint.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/lint.rb
new file mode 100644
index 0000000000..bf2e9787a1
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/lint.rb
@@ -0,0 +1,537 @@
+require 'rack/utils'
+
+module Rack
+ # Rack::Lint validates your application and the requests and
+ # responses according to the Rack spec.
+
+ class Lint
+ def initialize(app)
+ @app = app
+ end
+
+ # :stopdoc:
+
+ class LintError < RuntimeError; end
+ module Assertion
+ def assert(message, &block)
+ unless block.call
+ raise LintError, message
+ end
+ end
+ end
+ include Assertion
+
+ ## This specification aims to formalize the Rack protocol. You
+ ## can (and should) use Rack::Lint to enforce it.
+ ##
+ ## When you develop middleware, be sure to add a Lint before and
+ ## after to catch all mistakes.
+
+ ## = Rack applications
+
+ ## A Rack application is an Ruby object (not a class) that
+ ## responds to +call+.
+ def call(env=nil)
+ dup._call(env)
+ end
+
+ def _call(env)
+ ## It takes exactly one argument, the *environment*
+ assert("No env given") { env }
+ check_env env
+
+ env['rack.input'] = InputWrapper.new(env['rack.input'])
+ env['rack.errors'] = ErrorWrapper.new(env['rack.errors'])
+
+ ## and returns an Array of exactly three values:
+ status, headers, @body = @app.call(env)
+ ## The *status*,
+ check_status status
+ ## the *headers*,
+ check_headers headers
+ ## and the *body*.
+ check_content_type status, headers
+ check_content_length status, headers, env
+ [status, headers, self]
+ end
+
+ ## == The Environment
+ def check_env(env)
+ ## The environment must be an true instance of Hash (no
+ ## subclassing allowed) that includes CGI-like headers.
+ ## The application is free to modify the environment.
+ assert("env #{env.inspect} is not a Hash, but #{env.class}") {
+ env.instance_of? Hash
+ }
+
+ ##
+ ## The environment is required to include these variables
+ ## (adopted from PEP333), except when they'd be empty, but see
+ ## below.
+
+ ## REQUEST_METHOD:: The HTTP request method, such as
+ ## "GET" or "POST". This cannot ever
+ ## be an empty string, and so is
+ ## always required.
+
+ ## SCRIPT_NAME:: The initial portion of the request
+ ## URL's "path" that corresponds to the
+ ## application object, so that the
+ ## application knows its virtual
+ ## "location". This may be an empty
+ ## string, if the application corresponds
+ ## to the "root" of the server.
+
+ ## PATH_INFO:: The remainder of the request URL's
+ ## "path", designating the virtual
+ ## "location" of the request's target
+ ## within the application. This may be an
+ ## empty string, if the request URL targets
+ ## the application root and does not have a
+ ## trailing slash. This value may be
+ ## percent-encoded when I originating from
+ ## a URL.
+
+ ## QUERY_STRING:: The portion of the request URL that
+ ## follows the ?, if any. May be
+ ## empty, but is always required!
+
+ ## SERVER_NAME, SERVER_PORT:: When combined with SCRIPT_NAME and PATH_INFO, these variables can be used to complete the URL. Note, however, that HTTP_HOST, if present, should be used in preference to SERVER_NAME for reconstructing the request URL. SERVER_NAME and SERVER_PORT can never be empty strings, and so are always required.
+
+ ## HTTP_ Variables:: Variables corresponding to the
+ ## client-supplied HTTP request
+ ## headers (i.e., variables whose
+ ## names begin with HTTP_). The
+ ## presence or absence of these
+ ## variables should correspond with
+ ## the presence or absence of the
+ ## appropriate HTTP header in the
+ ## request.
+
+ ## In addition to this, the Rack environment must include these
+ ## Rack-specific variables:
+
+ ## rack.version:: The Array [1,0], representing this version of Rack.
+ ## rack.url_scheme:: +http+ or +https+, depending on the request URL.
+ ## rack.input:: See below, the input stream.
+ ## rack.errors:: See below, the error stream.
+ ## rack.multithread:: true if the application object may be simultaneously invoked by another thread in the same process, false otherwise.
+ ## rack.multiprocess:: true if an equivalent application object may be simultaneously invoked by another process, false otherwise.
+ ## rack.run_once:: true if the server expects (but does not guarantee!) that the application will only be invoked this one time during the life of its containing process. Normally, this will only be true for a server based on CGI (or something similar).
+ ##
+
+ ## Additional environment specifications have approved to
+ ## standardized middleware APIs. None of these are required to
+ ## be implemented by the server.
+
+ ## rack.session:: A hash like interface for storing request session data.
+ ## The store must implement:
+ if session = env['rack.session']
+ ## store(key, value) (aliased as []=);
+ assert("session #{session.inspect} must respond to store and []=") {
+ session.respond_to?(:store) && session.respond_to?(:[]=)
+ }
+
+ ## fetch(key, default = nil) (aliased as []);
+ assert("session #{session.inspect} must respond to fetch and []") {
+ session.respond_to?(:fetch) && session.respond_to?(:[])
+ }
+
+ ## delete(key);
+ assert("session #{session.inspect} must respond to delete") {
+ session.respond_to?(:delete)
+ }
+
+ ## clear;
+ assert("session #{session.inspect} must respond to clear") {
+ session.respond_to?(:clear)
+ }
+ end
+
+ ## The server or the application can store their own data in the
+ ## environment, too. The keys must contain at least one dot,
+ ## and should be prefixed uniquely. The prefix rack.
+ ## is reserved for use with the Rack core distribution and other
+ ## accepted specifications and must not be used otherwise.
+ ##
+
+ %w[REQUEST_METHOD SERVER_NAME SERVER_PORT
+ QUERY_STRING
+ rack.version rack.input rack.errors
+ rack.multithread rack.multiprocess rack.run_once].each { |header|
+ assert("env missing required key #{header}") { env.include? header }
+ }
+
+ ## The environment must not contain the keys
+ ## HTTP_CONTENT_TYPE or HTTP_CONTENT_LENGTH
+ ## (use the versions without HTTP_).
+ %w[HTTP_CONTENT_TYPE HTTP_CONTENT_LENGTH].each { |header|
+ assert("env contains #{header}, must use #{header[5,-1]}") {
+ not env.include? header
+ }
+ }
+
+ ## The CGI keys (named without a period) must have String values.
+ env.each { |key, value|
+ next if key.include? "." # Skip extensions
+ assert("env variable #{key} has non-string value #{value.inspect}") {
+ value.instance_of? String
+ }
+ }
+
+ ##
+ ## There are the following restrictions:
+
+ ## * rack.version must be an array of Integers.
+ assert("rack.version must be an Array, was #{env["rack.version"].class}") {
+ env["rack.version"].instance_of? Array
+ }
+ ## * rack.url_scheme must either be +http+ or +https+.
+ assert("rack.url_scheme unknown: #{env["rack.url_scheme"].inspect}") {
+ %w[http https].include? env["rack.url_scheme"]
+ }
+
+ ## * There must be a valid input stream in rack.input.
+ check_input env["rack.input"]
+ ## * There must be a valid error stream in rack.errors.
+ check_error env["rack.errors"]
+
+ ## * The REQUEST_METHOD must be a valid token.
+ assert("REQUEST_METHOD unknown: #{env["REQUEST_METHOD"]}") {
+ env["REQUEST_METHOD"] =~ /\A[0-9A-Za-z!\#$%&'*+.^_`|~-]+\z/
+ }
+
+ ## * The SCRIPT_NAME, if non-empty, must start with /
+ assert("SCRIPT_NAME must start with /") {
+ !env.include?("SCRIPT_NAME") ||
+ env["SCRIPT_NAME"] == "" ||
+ env["SCRIPT_NAME"] =~ /\A\//
+ }
+ ## * The PATH_INFO, if non-empty, must start with /
+ assert("PATH_INFO must start with /") {
+ !env.include?("PATH_INFO") ||
+ env["PATH_INFO"] == "" ||
+ env["PATH_INFO"] =~ /\A\//
+ }
+ ## * The CONTENT_LENGTH, if given, must consist of digits only.
+ assert("Invalid CONTENT_LENGTH: #{env["CONTENT_LENGTH"]}") {
+ !env.include?("CONTENT_LENGTH") || env["CONTENT_LENGTH"] =~ /\A\d+\z/
+ }
+
+ ## * One of SCRIPT_NAME or PATH_INFO must be
+ ## set. PATH_INFO should be / if
+ ## SCRIPT_NAME is empty.
+ assert("One of SCRIPT_NAME or PATH_INFO must be set (make PATH_INFO '/' if SCRIPT_NAME is empty)") {
+ env["SCRIPT_NAME"] || env["PATH_INFO"]
+ }
+ ## SCRIPT_NAME never should be /, but instead be empty.
+ assert("SCRIPT_NAME cannot be '/', make it '' and PATH_INFO '/'") {
+ env["SCRIPT_NAME"] != "/"
+ }
+ end
+
+ ## === The Input Stream
+ ##
+ ## The input stream is an IO-like object which contains the raw HTTP
+ ## POST data. If it is a file then it must be opened in binary mode.
+ def check_input(input)
+ ## The input stream must respond to +gets+, +each+, +read+ and +rewind+.
+ [:gets, :each, :read, :rewind].each { |method|
+ assert("rack.input #{input} does not respond to ##{method}") {
+ input.respond_to? method
+ }
+ }
+ end
+
+ class InputWrapper
+ include Assertion
+
+ def initialize(input)
+ @input = input
+ end
+
+ def size
+ @input.size
+ end
+
+ ## * +gets+ must be called without arguments and return a string,
+ ## or +nil+ on EOF.
+ def gets(*args)
+ assert("rack.input#gets called with arguments") { args.size == 0 }
+ v = @input.gets
+ assert("rack.input#gets didn't return a String") {
+ v.nil? or v.instance_of? String
+ }
+ v
+ end
+
+ ## * +read+ behaves like IO#read. Its signature is read([length, [buffer]]).
+ ## If given, +length+ must be an non-negative Integer (>= 0) or +nil+, and +buffer+ must
+ ## be a String and may not be nil. If +length+ is given and not nil, then this method
+ ## reads at most +length+ bytes from the input stream. If +length+ is not given or nil,
+ ## then this method reads all data until EOF.
+ ## When EOF is reached, this method returns nil if +length+ is given and not nil, or ""
+ ## if +length+ is not given or is nil.
+ ## If +buffer+ is given, then the read data will be placed into +buffer+ instead of a
+ ## newly created String object.
+ def read(*args)
+ assert("rack.input#read called with too many arguments") {
+ args.size <= 2
+ }
+ if args.size >= 1
+ assert("rack.input#read called with non-integer and non-nil length") {
+ args.first.kind_of?(Integer) || args.first.nil?
+ }
+ assert("rack.input#read called with a negative length") {
+ args.first.nil? || args.first >= 0
+ }
+ end
+ if args.size >= 2
+ assert("rack.input#read called with non-String buffer") {
+ args[1].kind_of?(String)
+ }
+ end
+
+ v = @input.read(*args)
+
+ assert("rack.input#read didn't return nil or a String") {
+ v.nil? or v.instance_of? String
+ }
+ if args[0].nil?
+ assert("rack.input#read(nil) returned nil on EOF") {
+ !v.nil?
+ }
+ end
+
+ v
+ end
+
+ ## * +each+ must be called without arguments and only yield Strings.
+ def each(*args)
+ assert("rack.input#each called with arguments") { args.size == 0 }
+ @input.each { |line|
+ assert("rack.input#each didn't yield a String") {
+ line.instance_of? String
+ }
+ yield line
+ }
+ end
+
+ ## * +rewind+ must be called without arguments. It rewinds the input
+ ## stream back to the beginning. It must not raise Errno::ESPIPE:
+ ## that is, it may not be a pipe or a socket. Therefore, handler
+ ## developers must buffer the input data into some rewindable object
+ ## if the underlying input stream is not rewindable.
+ def rewind(*args)
+ assert("rack.input#rewind called with arguments") { args.size == 0 }
+ assert("rack.input#rewind raised Errno::ESPIPE") {
+ begin
+ @input.rewind
+ true
+ rescue Errno::ESPIPE
+ false
+ end
+ }
+ end
+
+ ## * +close+ must never be called on the input stream.
+ def close(*args)
+ assert("rack.input#close must not be called") { false }
+ end
+ end
+
+ ## === The Error Stream
+ def check_error(error)
+ ## The error stream must respond to +puts+, +write+ and +flush+.
+ [:puts, :write, :flush].each { |method|
+ assert("rack.error #{error} does not respond to ##{method}") {
+ error.respond_to? method
+ }
+ }
+ end
+
+ class ErrorWrapper
+ include Assertion
+
+ def initialize(error)
+ @error = error
+ end
+
+ ## * +puts+ must be called with a single argument that responds to +to_s+.
+ def puts(str)
+ @error.puts str
+ end
+
+ ## * +write+ must be called with a single argument that is a String.
+ def write(str)
+ assert("rack.errors#write not called with a String") { str.instance_of? String }
+ @error.write str
+ end
+
+ ## * +flush+ must be called without arguments and must be called
+ ## in order to make the error appear for sure.
+ def flush
+ @error.flush
+ end
+
+ ## * +close+ must never be called on the error stream.
+ def close(*args)
+ assert("rack.errors#close must not be called") { false }
+ end
+ end
+
+ ## == The Response
+
+ ## === The Status
+ def check_status(status)
+ ## This is an HTTP status. When parsed as integer (+to_i+), it must be
+ ## greater than or equal to 100.
+ assert("Status must be >=100 seen as integer") { status.to_i >= 100 }
+ end
+
+ ## === The Headers
+ def check_headers(header)
+ ## The header must respond to +each+, and yield values of key and value.
+ assert("headers object should respond to #each, but doesn't (got #{header.class} as headers)") {
+ header.respond_to? :each
+ }
+ header.each { |key, value|
+ ## The header keys must be Strings.
+ assert("header key must be a string, was #{key.class}") {
+ key.instance_of? String
+ }
+ ## The header must not contain a +Status+ key,
+ assert("header must not contain Status") { key.downcase != "status" }
+ ## contain keys with : or newlines in their name,
+ assert("header names must not contain : or \\n") { key !~ /[:\n]/ }
+ ## contain keys names that end in - or _,
+ assert("header names must not end in - or _") { key !~ /[-_]\z/ }
+ ## but only contain keys that consist of
+ ## letters, digits, _ or - and start with a letter.
+ assert("invalid header name: #{key}") { key =~ /\A[a-zA-Z][a-zA-Z0-9_-]*\z/ }
+
+ ## The values of the header must be Strings,
+ assert("a header value must be a String, but the value of " +
+ "'#{key}' is a #{value.class}") { value.kind_of? String }
+ ## consisting of lines (for multiple header values, e.g. multiple
+ ## Set-Cookie values) seperated by "\n".
+ value.split("\n").each { |item|
+ ## The lines must not contain characters below 037.
+ assert("invalid header value #{key}: #{item.inspect}") {
+ item !~ /[\000-\037]/
+ }
+ }
+ }
+ end
+
+ ## === The Content-Type
+ def check_content_type(status, headers)
+ headers.each { |key, value|
+ ## There must be a Content-Type, except when the
+ ## +Status+ is 1xx, 204 or 304, in which case there must be none
+ ## given.
+ if key.downcase == "content-type"
+ assert("Content-Type header found in #{status} response, not allowed") {
+ not Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
+ }
+ return
+ end
+ }
+ assert("No Content-Type header found") {
+ Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
+ }
+ end
+
+ ## === The Content-Length
+ def check_content_length(status, headers, env)
+ headers.each { |key, value|
+ if key.downcase == 'content-length'
+ ## There must not be a Content-Length header when the
+ ## +Status+ is 1xx, 204 or 304.
+ assert("Content-Length header found in #{status} response, not allowed") {
+ not Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
+ }
+
+ bytes = 0
+ string_body = true
+
+ if @body.respond_to?(:to_ary)
+ @body.each { |part|
+ unless part.kind_of?(String)
+ string_body = false
+ break
+ end
+
+ bytes += Rack::Utils.bytesize(part)
+ }
+
+ if env["REQUEST_METHOD"] == "HEAD"
+ assert("Response body was given for HEAD request, but should be empty") {
+ bytes == 0
+ }
+ else
+ if string_body
+ assert("Content-Length header was #{value}, but should be #{bytes}") {
+ value == bytes.to_s
+ }
+ end
+ end
+ end
+
+ return
+ end
+ }
+ end
+
+ ## === The Body
+ def each
+ @closed = false
+ ## The Body must respond to +each+
+ @body.each { |part|
+ ## and must only yield String values.
+ assert("Body yielded non-string value #{part.inspect}") {
+ part.instance_of? String
+ }
+ yield part
+ }
+ ##
+ ## The Body itself should not be an instance of String, as this will
+ ## break in Ruby 1.9.
+ ##
+ ## If the Body responds to +close+, it will be called after iteration.
+ # XXX howto: assert("Body has not been closed") { @closed }
+
+
+ ##
+ ## If the Body responds to +to_path+, it must return a String
+ ## identifying the location of a file whose contents are identical
+ ## to that produced by calling +each+; this may be used by the
+ ## server as an alternative, possibly more efficient way to
+ ## transport the response.
+
+ if @body.respond_to?(:to_path)
+ assert("The file identified by body.to_path does not exist") {
+ ::File.exist? @body.to_path
+ }
+ end
+
+ ##
+ ## The Body commonly is an Array of Strings, the application
+ ## instance itself, or a File-like object.
+ end
+
+ def close
+ @closed = true
+ @body.close if @body.respond_to?(:close)
+ end
+
+ # :startdoc:
+
+ end
+end
+
+## == Thanks
+## Some parts of this specification are adopted from PEP333: Python
+## Web Server Gateway Interface
+## v1.0 (http://www.python.org/dev/peps/pep-0333/). I'd like to thank
+## everyone involved in that effort.
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/lobster.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/lobster.rb
new file mode 100644
index 0000000000..f63f419a49
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack/rack/lobster.rb
@@ -0,0 +1,65 @@
+require 'zlib'
+
+require 'rack/request'
+require 'rack/response'
+
+module Rack
+ # Paste has a Pony, Rack has a Lobster!
+ class Lobster
+ LobsterString = Zlib::Inflate.inflate("eJx9kEEOwyAMBO99xd7MAcytUhPlJyj2
+ P6jy9i4k9EQyGAnBarEXeCBqSkntNXsi/ZCvC48zGQoZKikGrFMZvgS5ZHd+aGWVuWwhVF0
+ t1drVmiR42HcWNz5w3QanT+2gIvTVCiE1lm1Y0eU4JGmIIbaKwextKn8rvW+p5PIwFl8ZWJ
+ I8jyiTlhTcYXkekJAzTyYN6E08A+dk8voBkAVTJQ==".delete("\n ").unpack("m*")[0])
+
+ LambdaLobster = lambda { |env|
+ if env["QUERY_STRING"].include?("flip")
+ lobster = LobsterString.split("\n").
+ map { |line| line.ljust(42).reverse }.
+ join("\n")
+ href = "?"
+ else
+ lobster = LobsterString
+ href = "?flip"
+ end
+
+ content = ["Lobstericious!",
+ "
+
+
+ PAGE
+
+ attr_reader :files
+ attr_accessor :root, :path
+
+ def initialize(root, app=nil)
+ @root = F.expand_path(root)
+ @app = app || Rack::File.new(@root)
+ end
+
+ def call(env)
+ dup._call(env)
+ end
+
+ F = ::File
+
+ def _call(env)
+ @env = env
+ @script_name = env['SCRIPT_NAME']
+ @path_info = Utils.unescape(env['PATH_INFO'])
+
+ if forbidden = check_forbidden
+ forbidden
+ else
+ @path = F.join(@root, @path_info)
+ list_path
+ end
+ end
+
+ def check_forbidden
+ return unless @path_info.include? ".."
+
+ body = "Forbidden\n"
+ size = Rack::Utils.bytesize(body)
+ return [403, {"Content-Type" => "text/plain","Content-Length" => size.to_s}, [body]]
+ end
+
+ def list_directory
+ @files = [['../','Parent Directory','','','']]
+ glob = F.join(@path, '*')
+
+ Dir[glob].sort.each do |node|
+ stat = stat(node)
+ next unless stat
+ basename = F.basename(node)
+ ext = F.extname(node)
+
+ url = F.join(@script_name, @path_info, basename)
+ size = stat.size
+ type = stat.directory? ? 'directory' : Mime.mime_type(ext)
+ size = stat.directory? ? '-' : filesize_format(size)
+ mtime = stat.mtime.httpdate
+ url << '/' if stat.directory?
+ basename << '/' if stat.directory?
+
+ @files << [ url, basename, size, type, mtime ]
+ end
+
+ return [ 200, {'Content-Type'=>'text/html; charset=utf-8'}, self ]
+ end
+
+ def stat(node, max = 10)
+ F.stat(node)
+ rescue Errno::ENOENT, Errno::ELOOP
+ return nil
+ end
+
+ # TODO: add correct response if not readable, not sure if 404 is the best
+ # option
+ def list_path
+ @stat = F.stat(@path)
+
+ if @stat.readable?
+ return @app.call(@env) if @stat.file?
+ return list_directory if @stat.directory?
+ else
+ raise Errno::ENOENT, 'No such file or directory'
+ end
+
+ rescue Errno::ENOENT, Errno::ELOOP
+ return entity_not_found
+ end
+
+ def entity_not_found
+ body = "Entity not found: #{@path_info}\n"
+ size = Rack::Utils.bytesize(body)
+ return [404, {"Content-Type" => "text/plain", "Content-Length" => size.to_s}, [body]]
+ end
+
+ def each
+ show_path = @path.sub(/^#{@root}/,'')
+ files = @files.map{|f| DIR_FILE % f }*"\n"
+ page = DIR_PAGE % [ show_path, show_path , files ]
+ page.each_line{|l| yield l }
+ end
+
+ # Stolen from Ramaze
+
+ FILESIZE_FORMAT = [
+ ['%.1fT', 1 << 40],
+ ['%.1fG', 1 << 30],
+ ['%.1fM', 1 << 20],
+ ['%.1fK', 1 << 10],
+ ]
+
+ def filesize_format(int)
+ FILESIZE_FORMAT.each do |format, size|
+ return format % (int.to_f / size) if int >= size
+ end
+
+ int.to_s + 'B'
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/file.rb b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/file.rb
new file mode 100644
index 0000000000..fe62bd6b86
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/file.rb
@@ -0,0 +1,88 @@
+require 'time'
+require 'rack/utils'
+require 'rack/mime'
+
+module Rack
+ # Rack::File serves files below the +root+ given, according to the
+ # path info of the Rack request.
+ #
+ # Handlers can detect if bodies are a Rack::File, and use mechanisms
+ # like sendfile on the +path+.
+
+ class File
+ attr_accessor :root
+ attr_accessor :path
+
+ alias :to_path :path
+
+ def initialize(root)
+ @root = root
+ end
+
+ def call(env)
+ dup._call(env)
+ end
+
+ F = ::File
+
+ def _call(env)
+ @path_info = Utils.unescape(env["PATH_INFO"])
+ return forbidden if @path_info.include? ".."
+
+ @path = F.join(@root, @path_info)
+
+ begin
+ if F.file?(@path) && F.readable?(@path)
+ serving
+ else
+ raise Errno::EPERM
+ end
+ rescue SystemCallError
+ not_found
+ end
+ end
+
+ def forbidden
+ body = "Forbidden\n"
+ [403, {"Content-Type" => "text/plain",
+ "Content-Length" => body.size.to_s},
+ [body]]
+ end
+
+ # NOTE:
+ # We check via File::size? whether this file provides size info
+ # via stat (e.g. /proc files often don't), otherwise we have to
+ # figure it out by reading the whole file into memory. And while
+ # we're at it we also use this as body then.
+
+ def serving
+ if size = F.size?(@path)
+ body = self
+ else
+ body = [F.read(@path)]
+ size = Utils.bytesize(body.first)
+ end
+
+ [200, {
+ "Last-Modified" => F.mtime(@path).httpdate,
+ "Content-Type" => Mime.mime_type(F.extname(@path), 'text/plain'),
+ "Content-Length" => size.to_s
+ }, body]
+ end
+
+ def not_found
+ body = "File not found: #{@path_info}\n"
+ [404, {"Content-Type" => "text/plain",
+ "Content-Length" => body.size.to_s},
+ [body]]
+ end
+
+ def each
+ F.open(@path, "rb") { |file|
+ while part = file.read(8192)
+ yield part
+ end
+ }
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler.rb b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler.rb
new file mode 100644
index 0000000000..5624a1e79d
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler.rb
@@ -0,0 +1,69 @@
+module Rack
+ # *Handlers* connect web servers with Rack.
+ #
+ # Rack includes Handlers for Mongrel, WEBrick, FastCGI, CGI, SCGI
+ # and LiteSpeed.
+ #
+ # Handlers usually are activated by calling MyHandler.run(myapp).
+ # A second optional hash can be passed to include server-specific
+ # configuration.
+ module Handler
+ def self.get(server)
+ return unless server
+ server = server.to_s
+
+ if klass = @handlers[server]
+ obj = Object
+ klass.split("::").each { |x| obj = obj.const_get(x) }
+ obj
+ else
+ try_require('rack/handler', server)
+ const_get(server)
+ end
+ end
+
+ # Transforms server-name constants to their canonical form as filenames,
+ # then tries to require them but silences the LoadError if not found
+ #
+ # Naming convention:
+ #
+ # Foo # => 'foo'
+ # FooBar # => 'foo_bar.rb'
+ # FooBAR # => 'foobar.rb'
+ # FOObar # => 'foobar.rb'
+ # FOOBAR # => 'foobar.rb'
+ # FooBarBaz # => 'foo_bar_baz.rb'
+ def self.try_require(prefix, const_name)
+ file = const_name.gsub(/^[A-Z]+/) { |pre| pre.downcase }.
+ gsub(/[A-Z]+[^A-Z]/, '_\&').downcase
+
+ require(::File.join(prefix, file))
+ rescue LoadError
+ end
+
+ def self.register(server, klass)
+ @handlers ||= {}
+ @handlers[server] = klass
+ end
+
+ autoload :CGI, "rack/handler/cgi"
+ autoload :FastCGI, "rack/handler/fastcgi"
+ autoload :Mongrel, "rack/handler/mongrel"
+ autoload :EventedMongrel, "rack/handler/evented_mongrel"
+ autoload :SwiftipliedMongrel, "rack/handler/swiftiplied_mongrel"
+ autoload :WEBrick, "rack/handler/webrick"
+ autoload :LSWS, "rack/handler/lsws"
+ autoload :SCGI, "rack/handler/scgi"
+ autoload :Thin, "rack/handler/thin"
+
+ register 'cgi', 'Rack::Handler::CGI'
+ register 'fastcgi', 'Rack::Handler::FastCGI'
+ register 'mongrel', 'Rack::Handler::Mongrel'
+ register 'emongrel', 'Rack::Handler::EventedMongrel'
+ register 'smongrel', 'Rack::Handler::SwiftipliedMongrel'
+ register 'webrick', 'Rack::Handler::WEBrick'
+ register 'lsws', 'Rack::Handler::LSWS'
+ register 'scgi', 'Rack::Handler::SCGI'
+ register 'thin', 'Rack::Handler::Thin'
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler/cgi.rb b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler/cgi.rb
new file mode 100644
index 0000000000..f45f3d735a
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler/cgi.rb
@@ -0,0 +1,61 @@
+require 'rack/content_length'
+
+module Rack
+ module Handler
+ class CGI
+ def self.run(app, options=nil)
+ serve app
+ end
+
+ def self.serve(app)
+ app = ContentLength.new(app)
+
+ env = ENV.to_hash
+ env.delete "HTTP_CONTENT_LENGTH"
+
+ env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/"
+
+ env.update({"rack.version" => [1,0],
+ "rack.input" => $stdin,
+ "rack.errors" => $stderr,
+
+ "rack.multithread" => false,
+ "rack.multiprocess" => true,
+ "rack.run_once" => true,
+
+ "rack.url_scheme" => ["yes", "on", "1"].include?(ENV["HTTPS"]) ? "https" : "http"
+ })
+
+ env["QUERY_STRING"] ||= ""
+ env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"]
+ env["REQUEST_PATH"] ||= "/"
+
+ status, headers, body = app.call(env)
+ begin
+ send_headers status, headers
+ send_body body
+ ensure
+ body.close if body.respond_to? :close
+ end
+ end
+
+ def self.send_headers(status, headers)
+ STDOUT.print "Status: #{status}\r\n"
+ headers.each { |k, vs|
+ vs.split("\n").each { |v|
+ STDOUT.print "#{k}: #{v}\r\n"
+ }
+ }
+ STDOUT.print "\r\n"
+ STDOUT.flush
+ end
+
+ def self.send_body(body)
+ body.each { |part|
+ STDOUT.print part
+ STDOUT.flush
+ }
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler/evented_mongrel.rb b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler/evented_mongrel.rb
new file mode 100644
index 0000000000..0f5cbf7293
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler/evented_mongrel.rb
@@ -0,0 +1,8 @@
+require 'swiftcore/evented_mongrel'
+
+module Rack
+ module Handler
+ class EventedMongrel < Handler::Mongrel
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler/fastcgi.rb b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler/fastcgi.rb
new file mode 100644
index 0000000000..11e1fcaa74
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler/fastcgi.rb
@@ -0,0 +1,88 @@
+require 'fcgi'
+require 'socket'
+require 'rack/content_length'
+require 'rack/rewindable_input'
+
+class FCGI::Stream
+ alias _rack_read_without_buffer read
+
+ def read(n, buffer=nil)
+ buf = _rack_read_without_buffer n
+ buffer.replace(buf.to_s) if buffer
+ buf
+ end
+end
+
+module Rack
+ module Handler
+ class FastCGI
+ def self.run(app, options={})
+ file = options[:File] and STDIN.reopen(UNIXServer.new(file))
+ port = options[:Port] and STDIN.reopen(TCPServer.new(port))
+ FCGI.each { |request|
+ serve request, app
+ }
+ end
+
+ def self.serve(request, app)
+ app = Rack::ContentLength.new(app)
+
+ env = request.env
+ env.delete "HTTP_CONTENT_LENGTH"
+
+ env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/"
+
+ rack_input = RewindableInput.new(request.in)
+
+ env.update({"rack.version" => [1,0],
+ "rack.input" => rack_input,
+ "rack.errors" => request.err,
+
+ "rack.multithread" => false,
+ "rack.multiprocess" => true,
+ "rack.run_once" => false,
+
+ "rack.url_scheme" => ["yes", "on", "1"].include?(env["HTTPS"]) ? "https" : "http"
+ })
+
+ env["QUERY_STRING"] ||= ""
+ env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"]
+ env["REQUEST_PATH"] ||= "/"
+ env.delete "PATH_INFO" if env["PATH_INFO"] == ""
+ env.delete "CONTENT_TYPE" if env["CONTENT_TYPE"] == ""
+ env.delete "CONTENT_LENGTH" if env["CONTENT_LENGTH"] == ""
+
+ begin
+ status, headers, body = app.call(env)
+ begin
+ send_headers request.out, status, headers
+ send_body request.out, body
+ ensure
+ body.close if body.respond_to? :close
+ end
+ ensure
+ rack_input.close
+ request.finish
+ end
+ end
+
+ def self.send_headers(out, status, headers)
+ out.print "Status: #{status}\r\n"
+ headers.each { |k, vs|
+ vs.split("\n").each { |v|
+ out.print "#{k}: #{v}\r\n"
+ }
+ }
+ out.print "\r\n"
+ out.flush
+ end
+
+ def self.send_body(out, body)
+ body.each { |part|
+ out.print part
+ out.flush
+ }
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler/lsws.rb b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler/lsws.rb
new file mode 100644
index 0000000000..7231336d7b
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler/lsws.rb
@@ -0,0 +1,55 @@
+require 'lsapi'
+require 'rack/content_length'
+
+module Rack
+ module Handler
+ class LSWS
+ def self.run(app, options=nil)
+ while LSAPI.accept != nil
+ serve app
+ end
+ end
+ def self.serve(app)
+ app = Rack::ContentLength.new(app)
+
+ env = ENV.to_hash
+ env.delete "HTTP_CONTENT_LENGTH"
+ env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/"
+ env.update({"rack.version" => [1,0],
+ "rack.input" => StringIO.new($stdin.read.to_s),
+ "rack.errors" => $stderr,
+ "rack.multithread" => false,
+ "rack.multiprocess" => true,
+ "rack.run_once" => false,
+ "rack.url_scheme" => ["yes", "on", "1"].include?(ENV["HTTPS"]) ? "https" : "http"
+ })
+ env["QUERY_STRING"] ||= ""
+ env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"]
+ env["REQUEST_PATH"] ||= "/"
+ status, headers, body = app.call(env)
+ begin
+ send_headers status, headers
+ send_body body
+ ensure
+ body.close if body.respond_to? :close
+ end
+ end
+ def self.send_headers(status, headers)
+ print "Status: #{status}\r\n"
+ headers.each { |k, vs|
+ vs.split("\n").each { |v|
+ print "#{k}: #{v}\r\n"
+ }
+ }
+ print "\r\n"
+ STDOUT.flush
+ end
+ def self.send_body(body)
+ body.each { |part|
+ print part
+ STDOUT.flush
+ }
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler/mongrel.rb b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler/mongrel.rb
new file mode 100644
index 0000000000..3a5ef32d4b
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler/mongrel.rb
@@ -0,0 +1,84 @@
+require 'mongrel'
+require 'stringio'
+require 'rack/content_length'
+require 'rack/chunked'
+
+module Rack
+ module Handler
+ class Mongrel < ::Mongrel::HttpHandler
+ def self.run(app, options={})
+ server = ::Mongrel::HttpServer.new(options[:Host] || '0.0.0.0',
+ options[:Port] || 8080)
+ # Acts like Rack::URLMap, utilizing Mongrel's own path finding methods.
+ # Use is similar to #run, replacing the app argument with a hash of
+ # { path=>app, ... } or an instance of Rack::URLMap.
+ if options[:map]
+ if app.is_a? Hash
+ app.each do |path, appl|
+ path = '/'+path unless path[0] == ?/
+ server.register(path, Rack::Handler::Mongrel.new(appl))
+ end
+ elsif app.is_a? URLMap
+ app.instance_variable_get(:@mapping).each do |(host, path, appl)|
+ next if !host.nil? && !options[:Host].nil? && options[:Host] != host
+ path = '/'+path unless path[0] == ?/
+ server.register(path, Rack::Handler::Mongrel.new(appl))
+ end
+ else
+ raise ArgumentError, "first argument should be a Hash or URLMap"
+ end
+ else
+ server.register('/', Rack::Handler::Mongrel.new(app))
+ end
+ yield server if block_given?
+ server.run.join
+ end
+
+ def initialize(app)
+ @app = Rack::Chunked.new(Rack::ContentLength.new(app))
+ end
+
+ def process(request, response)
+ env = {}.replace(request.params)
+ env.delete "HTTP_CONTENT_TYPE"
+ env.delete "HTTP_CONTENT_LENGTH"
+
+ env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/"
+
+ env.update({"rack.version" => [1,0],
+ "rack.input" => request.body || StringIO.new(""),
+ "rack.errors" => $stderr,
+
+ "rack.multithread" => true,
+ "rack.multiprocess" => false, # ???
+ "rack.run_once" => false,
+
+ "rack.url_scheme" => "http",
+ })
+ env["QUERY_STRING"] ||= ""
+ env.delete "PATH_INFO" if env["PATH_INFO"] == ""
+
+ status, headers, body = @app.call(env)
+
+ begin
+ response.status = status.to_i
+ response.send_status(nil)
+
+ headers.each { |k, vs|
+ vs.split("\n").each { |v|
+ response.header[k] = v
+ }
+ }
+ response.send_header
+
+ body.each { |part|
+ response.write part
+ response.socket.flush
+ }
+ ensure
+ body.close if body.respond_to? :close
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler/scgi.rb b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler/scgi.rb
new file mode 100644
index 0000000000..6c4932df95
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler/scgi.rb
@@ -0,0 +1,59 @@
+require 'scgi'
+require 'stringio'
+require 'rack/content_length'
+require 'rack/chunked'
+
+module Rack
+ module Handler
+ class SCGI < ::SCGI::Processor
+ attr_accessor :app
+
+ def self.run(app, options=nil)
+ new(options.merge(:app=>app,
+ :host=>options[:Host],
+ :port=>options[:Port],
+ :socket=>options[:Socket])).listen
+ end
+
+ def initialize(settings = {})
+ @app = Rack::Chunked.new(Rack::ContentLength.new(settings[:app]))
+ @log = Object.new
+ def @log.info(*args); end
+ def @log.error(*args); end
+ super(settings)
+ end
+
+ def process_request(request, input_body, socket)
+ env = {}.replace(request)
+ env.delete "HTTP_CONTENT_TYPE"
+ env.delete "HTTP_CONTENT_LENGTH"
+ env["REQUEST_PATH"], env["QUERY_STRING"] = env["REQUEST_URI"].split('?', 2)
+ env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"]
+ env["PATH_INFO"] = env["REQUEST_PATH"]
+ env["QUERY_STRING"] ||= ""
+ env["SCRIPT_NAME"] = ""
+ env.update({"rack.version" => [1,0],
+ "rack.input" => StringIO.new(input_body),
+ "rack.errors" => $stderr,
+
+ "rack.multithread" => true,
+ "rack.multiprocess" => true,
+ "rack.run_once" => false,
+
+ "rack.url_scheme" => ["yes", "on", "1"].include?(env["HTTPS"]) ? "https" : "http"
+ })
+ status, headers, body = app.call(env)
+ begin
+ socket.write("Status: #{status}\r\n")
+ headers.each do |k, vs|
+ vs.split("\n").each { |v| socket.write("#{k}: #{v}\r\n")}
+ end
+ socket.write("\r\n")
+ body.each {|s| socket.write(s)}
+ ensure
+ body.close if body.respond_to? :close
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler/swiftiplied_mongrel.rb b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler/swiftiplied_mongrel.rb
new file mode 100644
index 0000000000..4bafd0b953
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler/swiftiplied_mongrel.rb
@@ -0,0 +1,8 @@
+require 'swiftcore/swiftiplied_mongrel'
+
+module Rack
+ module Handler
+ class SwiftipliedMongrel < Handler::Mongrel
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler/thin.rb b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler/thin.rb
new file mode 100644
index 0000000000..3d4fedff75
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler/thin.rb
@@ -0,0 +1,18 @@
+require "thin"
+require "rack/content_length"
+require "rack/chunked"
+
+module Rack
+ module Handler
+ class Thin
+ def self.run(app, options={})
+ app = Rack::Chunked.new(Rack::ContentLength.new(app))
+ server = ::Thin::Server.new(options[:Host] || '0.0.0.0',
+ options[:Port] || 8080,
+ app)
+ yield server if block_given?
+ server.start
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler/webrick.rb b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler/webrick.rb
new file mode 100644
index 0000000000..2bdc83a9ff
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/handler/webrick.rb
@@ -0,0 +1,67 @@
+require 'webrick'
+require 'stringio'
+require 'rack/content_length'
+
+module Rack
+ module Handler
+ class WEBrick < ::WEBrick::HTTPServlet::AbstractServlet
+ def self.run(app, options={})
+ server = ::WEBrick::HTTPServer.new(options)
+ server.mount "/", Rack::Handler::WEBrick, app
+ trap(:INT) { server.shutdown }
+ yield server if block_given?
+ server.start
+ end
+
+ def initialize(server, app)
+ super server
+ @app = Rack::ContentLength.new(app)
+ end
+
+ def service(req, res)
+ env = req.meta_vars
+ env.delete_if { |k, v| v.nil? }
+
+ env.update({"rack.version" => [1,0],
+ "rack.input" => StringIO.new(req.body.to_s),
+ "rack.errors" => $stderr,
+
+ "rack.multithread" => true,
+ "rack.multiprocess" => false,
+ "rack.run_once" => false,
+
+ "rack.url_scheme" => ["yes", "on", "1"].include?(ENV["HTTPS"]) ? "https" : "http"
+ })
+
+ env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"]
+ env["QUERY_STRING"] ||= ""
+ env["REQUEST_PATH"] ||= "/"
+ if env["PATH_INFO"] == ""
+ env.delete "PATH_INFO"
+ else
+ path, n = req.request_uri.path, env["SCRIPT_NAME"].length
+ env["PATH_INFO"] = path[n, path.length-n]
+ end
+
+ status, headers, body = @app.call(env)
+ begin
+ res.status = status.to_i
+ headers.each { |k, vs|
+ if k.downcase == "set-cookie"
+ res.cookies.concat vs.split("\n")
+ else
+ vs.split("\n").each { |v|
+ res[k] = v
+ }
+ end
+ }
+ body.each { |part|
+ res.body << part
+ }
+ ensure
+ body.close if body.respond_to? :close
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/head.rb b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/head.rb
new file mode 100644
index 0000000000..deab822a99
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/head.rb
@@ -0,0 +1,19 @@
+module Rack
+
+class Head
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ status, headers, body = @app.call(env)
+
+ if env["REQUEST_METHOD"] == "HEAD"
+ [status, headers, []]
+ else
+ [status, headers, body]
+ end
+ end
+end
+
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/lint.rb b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/lint.rb
new file mode 100644
index 0000000000..bf2e9787a1
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/lint.rb
@@ -0,0 +1,537 @@
+require 'rack/utils'
+
+module Rack
+ # Rack::Lint validates your application and the requests and
+ # responses according to the Rack spec.
+
+ class Lint
+ def initialize(app)
+ @app = app
+ end
+
+ # :stopdoc:
+
+ class LintError < RuntimeError; end
+ module Assertion
+ def assert(message, &block)
+ unless block.call
+ raise LintError, message
+ end
+ end
+ end
+ include Assertion
+
+ ## This specification aims to formalize the Rack protocol. You
+ ## can (and should) use Rack::Lint to enforce it.
+ ##
+ ## When you develop middleware, be sure to add a Lint before and
+ ## after to catch all mistakes.
+
+ ## = Rack applications
+
+ ## A Rack application is an Ruby object (not a class) that
+ ## responds to +call+.
+ def call(env=nil)
+ dup._call(env)
+ end
+
+ def _call(env)
+ ## It takes exactly one argument, the *environment*
+ assert("No env given") { env }
+ check_env env
+
+ env['rack.input'] = InputWrapper.new(env['rack.input'])
+ env['rack.errors'] = ErrorWrapper.new(env['rack.errors'])
+
+ ## and returns an Array of exactly three values:
+ status, headers, @body = @app.call(env)
+ ## The *status*,
+ check_status status
+ ## the *headers*,
+ check_headers headers
+ ## and the *body*.
+ check_content_type status, headers
+ check_content_length status, headers, env
+ [status, headers, self]
+ end
+
+ ## == The Environment
+ def check_env(env)
+ ## The environment must be an true instance of Hash (no
+ ## subclassing allowed) that includes CGI-like headers.
+ ## The application is free to modify the environment.
+ assert("env #{env.inspect} is not a Hash, but #{env.class}") {
+ env.instance_of? Hash
+ }
+
+ ##
+ ## The environment is required to include these variables
+ ## (adopted from PEP333), except when they'd be empty, but see
+ ## below.
+
+ ## REQUEST_METHOD:: The HTTP request method, such as
+ ## "GET" or "POST". This cannot ever
+ ## be an empty string, and so is
+ ## always required.
+
+ ## SCRIPT_NAME:: The initial portion of the request
+ ## URL's "path" that corresponds to the
+ ## application object, so that the
+ ## application knows its virtual
+ ## "location". This may be an empty
+ ## string, if the application corresponds
+ ## to the "root" of the server.
+
+ ## PATH_INFO:: The remainder of the request URL's
+ ## "path", designating the virtual
+ ## "location" of the request's target
+ ## within the application. This may be an
+ ## empty string, if the request URL targets
+ ## the application root and does not have a
+ ## trailing slash. This value may be
+ ## percent-encoded when I originating from
+ ## a URL.
+
+ ## QUERY_STRING:: The portion of the request URL that
+ ## follows the ?, if any. May be
+ ## empty, but is always required!
+
+ ## SERVER_NAME, SERVER_PORT:: When combined with SCRIPT_NAME and PATH_INFO, these variables can be used to complete the URL. Note, however, that HTTP_HOST, if present, should be used in preference to SERVER_NAME for reconstructing the request URL. SERVER_NAME and SERVER_PORT can never be empty strings, and so are always required.
+
+ ## HTTP_ Variables:: Variables corresponding to the
+ ## client-supplied HTTP request
+ ## headers (i.e., variables whose
+ ## names begin with HTTP_). The
+ ## presence or absence of these
+ ## variables should correspond with
+ ## the presence or absence of the
+ ## appropriate HTTP header in the
+ ## request.
+
+ ## In addition to this, the Rack environment must include these
+ ## Rack-specific variables:
+
+ ## rack.version:: The Array [1,0], representing this version of Rack.
+ ## rack.url_scheme:: +http+ or +https+, depending on the request URL.
+ ## rack.input:: See below, the input stream.
+ ## rack.errors:: See below, the error stream.
+ ## rack.multithread:: true if the application object may be simultaneously invoked by another thread in the same process, false otherwise.
+ ## rack.multiprocess:: true if an equivalent application object may be simultaneously invoked by another process, false otherwise.
+ ## rack.run_once:: true if the server expects (but does not guarantee!) that the application will only be invoked this one time during the life of its containing process. Normally, this will only be true for a server based on CGI (or something similar).
+ ##
+
+ ## Additional environment specifications have approved to
+ ## standardized middleware APIs. None of these are required to
+ ## be implemented by the server.
+
+ ## rack.session:: A hash like interface for storing request session data.
+ ## The store must implement:
+ if session = env['rack.session']
+ ## store(key, value) (aliased as []=);
+ assert("session #{session.inspect} must respond to store and []=") {
+ session.respond_to?(:store) && session.respond_to?(:[]=)
+ }
+
+ ## fetch(key, default = nil) (aliased as []);
+ assert("session #{session.inspect} must respond to fetch and []") {
+ session.respond_to?(:fetch) && session.respond_to?(:[])
+ }
+
+ ## delete(key);
+ assert("session #{session.inspect} must respond to delete") {
+ session.respond_to?(:delete)
+ }
+
+ ## clear;
+ assert("session #{session.inspect} must respond to clear") {
+ session.respond_to?(:clear)
+ }
+ end
+
+ ## The server or the application can store their own data in the
+ ## environment, too. The keys must contain at least one dot,
+ ## and should be prefixed uniquely. The prefix rack.
+ ## is reserved for use with the Rack core distribution and other
+ ## accepted specifications and must not be used otherwise.
+ ##
+
+ %w[REQUEST_METHOD SERVER_NAME SERVER_PORT
+ QUERY_STRING
+ rack.version rack.input rack.errors
+ rack.multithread rack.multiprocess rack.run_once].each { |header|
+ assert("env missing required key #{header}") { env.include? header }
+ }
+
+ ## The environment must not contain the keys
+ ## HTTP_CONTENT_TYPE or HTTP_CONTENT_LENGTH
+ ## (use the versions without HTTP_).
+ %w[HTTP_CONTENT_TYPE HTTP_CONTENT_LENGTH].each { |header|
+ assert("env contains #{header}, must use #{header[5,-1]}") {
+ not env.include? header
+ }
+ }
+
+ ## The CGI keys (named without a period) must have String values.
+ env.each { |key, value|
+ next if key.include? "." # Skip extensions
+ assert("env variable #{key} has non-string value #{value.inspect}") {
+ value.instance_of? String
+ }
+ }
+
+ ##
+ ## There are the following restrictions:
+
+ ## * rack.version must be an array of Integers.
+ assert("rack.version must be an Array, was #{env["rack.version"].class}") {
+ env["rack.version"].instance_of? Array
+ }
+ ## * rack.url_scheme must either be +http+ or +https+.
+ assert("rack.url_scheme unknown: #{env["rack.url_scheme"].inspect}") {
+ %w[http https].include? env["rack.url_scheme"]
+ }
+
+ ## * There must be a valid input stream in rack.input.
+ check_input env["rack.input"]
+ ## * There must be a valid error stream in rack.errors.
+ check_error env["rack.errors"]
+
+ ## * The REQUEST_METHOD must be a valid token.
+ assert("REQUEST_METHOD unknown: #{env["REQUEST_METHOD"]}") {
+ env["REQUEST_METHOD"] =~ /\A[0-9A-Za-z!\#$%&'*+.^_`|~-]+\z/
+ }
+
+ ## * The SCRIPT_NAME, if non-empty, must start with /
+ assert("SCRIPT_NAME must start with /") {
+ !env.include?("SCRIPT_NAME") ||
+ env["SCRIPT_NAME"] == "" ||
+ env["SCRIPT_NAME"] =~ /\A\//
+ }
+ ## * The PATH_INFO, if non-empty, must start with /
+ assert("PATH_INFO must start with /") {
+ !env.include?("PATH_INFO") ||
+ env["PATH_INFO"] == "" ||
+ env["PATH_INFO"] =~ /\A\//
+ }
+ ## * The CONTENT_LENGTH, if given, must consist of digits only.
+ assert("Invalid CONTENT_LENGTH: #{env["CONTENT_LENGTH"]}") {
+ !env.include?("CONTENT_LENGTH") || env["CONTENT_LENGTH"] =~ /\A\d+\z/
+ }
+
+ ## * One of SCRIPT_NAME or PATH_INFO must be
+ ## set. PATH_INFO should be / if
+ ## SCRIPT_NAME is empty.
+ assert("One of SCRIPT_NAME or PATH_INFO must be set (make PATH_INFO '/' if SCRIPT_NAME is empty)") {
+ env["SCRIPT_NAME"] || env["PATH_INFO"]
+ }
+ ## SCRIPT_NAME never should be /, but instead be empty.
+ assert("SCRIPT_NAME cannot be '/', make it '' and PATH_INFO '/'") {
+ env["SCRIPT_NAME"] != "/"
+ }
+ end
+
+ ## === The Input Stream
+ ##
+ ## The input stream is an IO-like object which contains the raw HTTP
+ ## POST data. If it is a file then it must be opened in binary mode.
+ def check_input(input)
+ ## The input stream must respond to +gets+, +each+, +read+ and +rewind+.
+ [:gets, :each, :read, :rewind].each { |method|
+ assert("rack.input #{input} does not respond to ##{method}") {
+ input.respond_to? method
+ }
+ }
+ end
+
+ class InputWrapper
+ include Assertion
+
+ def initialize(input)
+ @input = input
+ end
+
+ def size
+ @input.size
+ end
+
+ ## * +gets+ must be called without arguments and return a string,
+ ## or +nil+ on EOF.
+ def gets(*args)
+ assert("rack.input#gets called with arguments") { args.size == 0 }
+ v = @input.gets
+ assert("rack.input#gets didn't return a String") {
+ v.nil? or v.instance_of? String
+ }
+ v
+ end
+
+ ## * +read+ behaves like IO#read. Its signature is read([length, [buffer]]).
+ ## If given, +length+ must be an non-negative Integer (>= 0) or +nil+, and +buffer+ must
+ ## be a String and may not be nil. If +length+ is given and not nil, then this method
+ ## reads at most +length+ bytes from the input stream. If +length+ is not given or nil,
+ ## then this method reads all data until EOF.
+ ## When EOF is reached, this method returns nil if +length+ is given and not nil, or ""
+ ## if +length+ is not given or is nil.
+ ## If +buffer+ is given, then the read data will be placed into +buffer+ instead of a
+ ## newly created String object.
+ def read(*args)
+ assert("rack.input#read called with too many arguments") {
+ args.size <= 2
+ }
+ if args.size >= 1
+ assert("rack.input#read called with non-integer and non-nil length") {
+ args.first.kind_of?(Integer) || args.first.nil?
+ }
+ assert("rack.input#read called with a negative length") {
+ args.first.nil? || args.first >= 0
+ }
+ end
+ if args.size >= 2
+ assert("rack.input#read called with non-String buffer") {
+ args[1].kind_of?(String)
+ }
+ end
+
+ v = @input.read(*args)
+
+ assert("rack.input#read didn't return nil or a String") {
+ v.nil? or v.instance_of? String
+ }
+ if args[0].nil?
+ assert("rack.input#read(nil) returned nil on EOF") {
+ !v.nil?
+ }
+ end
+
+ v
+ end
+
+ ## * +each+ must be called without arguments and only yield Strings.
+ def each(*args)
+ assert("rack.input#each called with arguments") { args.size == 0 }
+ @input.each { |line|
+ assert("rack.input#each didn't yield a String") {
+ line.instance_of? String
+ }
+ yield line
+ }
+ end
+
+ ## * +rewind+ must be called without arguments. It rewinds the input
+ ## stream back to the beginning. It must not raise Errno::ESPIPE:
+ ## that is, it may not be a pipe or a socket. Therefore, handler
+ ## developers must buffer the input data into some rewindable object
+ ## if the underlying input stream is not rewindable.
+ def rewind(*args)
+ assert("rack.input#rewind called with arguments") { args.size == 0 }
+ assert("rack.input#rewind raised Errno::ESPIPE") {
+ begin
+ @input.rewind
+ true
+ rescue Errno::ESPIPE
+ false
+ end
+ }
+ end
+
+ ## * +close+ must never be called on the input stream.
+ def close(*args)
+ assert("rack.input#close must not be called") { false }
+ end
+ end
+
+ ## === The Error Stream
+ def check_error(error)
+ ## The error stream must respond to +puts+, +write+ and +flush+.
+ [:puts, :write, :flush].each { |method|
+ assert("rack.error #{error} does not respond to ##{method}") {
+ error.respond_to? method
+ }
+ }
+ end
+
+ class ErrorWrapper
+ include Assertion
+
+ def initialize(error)
+ @error = error
+ end
+
+ ## * +puts+ must be called with a single argument that responds to +to_s+.
+ def puts(str)
+ @error.puts str
+ end
+
+ ## * +write+ must be called with a single argument that is a String.
+ def write(str)
+ assert("rack.errors#write not called with a String") { str.instance_of? String }
+ @error.write str
+ end
+
+ ## * +flush+ must be called without arguments and must be called
+ ## in order to make the error appear for sure.
+ def flush
+ @error.flush
+ end
+
+ ## * +close+ must never be called on the error stream.
+ def close(*args)
+ assert("rack.errors#close must not be called") { false }
+ end
+ end
+
+ ## == The Response
+
+ ## === The Status
+ def check_status(status)
+ ## This is an HTTP status. When parsed as integer (+to_i+), it must be
+ ## greater than or equal to 100.
+ assert("Status must be >=100 seen as integer") { status.to_i >= 100 }
+ end
+
+ ## === The Headers
+ def check_headers(header)
+ ## The header must respond to +each+, and yield values of key and value.
+ assert("headers object should respond to #each, but doesn't (got #{header.class} as headers)") {
+ header.respond_to? :each
+ }
+ header.each { |key, value|
+ ## The header keys must be Strings.
+ assert("header key must be a string, was #{key.class}") {
+ key.instance_of? String
+ }
+ ## The header must not contain a +Status+ key,
+ assert("header must not contain Status") { key.downcase != "status" }
+ ## contain keys with : or newlines in their name,
+ assert("header names must not contain : or \\n") { key !~ /[:\n]/ }
+ ## contain keys names that end in - or _,
+ assert("header names must not end in - or _") { key !~ /[-_]\z/ }
+ ## but only contain keys that consist of
+ ## letters, digits, _ or - and start with a letter.
+ assert("invalid header name: #{key}") { key =~ /\A[a-zA-Z][a-zA-Z0-9_-]*\z/ }
+
+ ## The values of the header must be Strings,
+ assert("a header value must be a String, but the value of " +
+ "'#{key}' is a #{value.class}") { value.kind_of? String }
+ ## consisting of lines (for multiple header values, e.g. multiple
+ ## Set-Cookie values) seperated by "\n".
+ value.split("\n").each { |item|
+ ## The lines must not contain characters below 037.
+ assert("invalid header value #{key}: #{item.inspect}") {
+ item !~ /[\000-\037]/
+ }
+ }
+ }
+ end
+
+ ## === The Content-Type
+ def check_content_type(status, headers)
+ headers.each { |key, value|
+ ## There must be a Content-Type, except when the
+ ## +Status+ is 1xx, 204 or 304, in which case there must be none
+ ## given.
+ if key.downcase == "content-type"
+ assert("Content-Type header found in #{status} response, not allowed") {
+ not Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
+ }
+ return
+ end
+ }
+ assert("No Content-Type header found") {
+ Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
+ }
+ end
+
+ ## === The Content-Length
+ def check_content_length(status, headers, env)
+ headers.each { |key, value|
+ if key.downcase == 'content-length'
+ ## There must not be a Content-Length header when the
+ ## +Status+ is 1xx, 204 or 304.
+ assert("Content-Length header found in #{status} response, not allowed") {
+ not Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
+ }
+
+ bytes = 0
+ string_body = true
+
+ if @body.respond_to?(:to_ary)
+ @body.each { |part|
+ unless part.kind_of?(String)
+ string_body = false
+ break
+ end
+
+ bytes += Rack::Utils.bytesize(part)
+ }
+
+ if env["REQUEST_METHOD"] == "HEAD"
+ assert("Response body was given for HEAD request, but should be empty") {
+ bytes == 0
+ }
+ else
+ if string_body
+ assert("Content-Length header was #{value}, but should be #{bytes}") {
+ value == bytes.to_s
+ }
+ end
+ end
+ end
+
+ return
+ end
+ }
+ end
+
+ ## === The Body
+ def each
+ @closed = false
+ ## The Body must respond to +each+
+ @body.each { |part|
+ ## and must only yield String values.
+ assert("Body yielded non-string value #{part.inspect}") {
+ part.instance_of? String
+ }
+ yield part
+ }
+ ##
+ ## The Body itself should not be an instance of String, as this will
+ ## break in Ruby 1.9.
+ ##
+ ## If the Body responds to +close+, it will be called after iteration.
+ # XXX howto: assert("Body has not been closed") { @closed }
+
+
+ ##
+ ## If the Body responds to +to_path+, it must return a String
+ ## identifying the location of a file whose contents are identical
+ ## to that produced by calling +each+; this may be used by the
+ ## server as an alternative, possibly more efficient way to
+ ## transport the response.
+
+ if @body.respond_to?(:to_path)
+ assert("The file identified by body.to_path does not exist") {
+ ::File.exist? @body.to_path
+ }
+ end
+
+ ##
+ ## The Body commonly is an Array of Strings, the application
+ ## instance itself, or a File-like object.
+ end
+
+ def close
+ @closed = true
+ @body.close if @body.respond_to?(:close)
+ end
+
+ # :startdoc:
+
+ end
+end
+
+## == Thanks
+## Some parts of this specification are adopted from PEP333: Python
+## Web Server Gateway Interface
+## v1.0 (http://www.python.org/dev/peps/pep-0333/). I'd like to thank
+## everyone involved in that effort.
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/lobster.rb b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/lobster.rb
new file mode 100644
index 0000000000..f63f419a49
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/lobster.rb
@@ -0,0 +1,65 @@
+require 'zlib'
+
+require 'rack/request'
+require 'rack/response'
+
+module Rack
+ # Paste has a Pony, Rack has a Lobster!
+ class Lobster
+ LobsterString = Zlib::Inflate.inflate("eJx9kEEOwyAMBO99xd7MAcytUhPlJyj2
+ P6jy9i4k9EQyGAnBarEXeCBqSkntNXsi/ZCvC48zGQoZKikGrFMZvgS5ZHd+aGWVuWwhVF0
+ t1drVmiR42HcWNz5w3QanT+2gIvTVCiE1lm1Y0eU4JGmIIbaKwextKn8rvW+p5PIwFl8ZWJ
+ I8jyiTlhTcYXkekJAzTyYN6E08A+dk8voBkAVTJQ==".delete("\n ").unpack("m*")[0])
+
+ LambdaLobster = lambda { |env|
+ if env["QUERY_STRING"].include?("flip")
+ lobster = LobsterString.split("\n").
+ map { |line| line.ljust(42).reverse }.
+ join("\n")
+ href = "?"
+ else
+ lobster = LobsterString
+ href = "?flip"
+ end
+
+ content = ["Lobstericious!",
+ "
+ You're seeing this error because you use Rack::ShowExceptions.
+
+
+
+
+
+HTML
+
+ # :startdoc:
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/showstatus.rb b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/showstatus.rb
new file mode 100644
index 0000000000..28258c7c89
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/showstatus.rb
@@ -0,0 +1,106 @@
+require 'erb'
+require 'rack/request'
+require 'rack/utils'
+
+module Rack
+ # Rack::ShowStatus catches all empty responses the app it wraps and
+ # replaces them with a site explaining the error.
+ #
+ # Additional details can be put into rack.showstatus.detail
+ # and will be shown as HTML. If such details exist, the error page
+ # is always rendered, even if the reply was not empty.
+
+ class ShowStatus
+ def initialize(app)
+ @app = app
+ @template = ERB.new(TEMPLATE)
+ end
+
+ def call(env)
+ status, headers, body = @app.call(env)
+ headers = Utils::HeaderHash.new(headers)
+ empty = headers['Content-Length'].to_i <= 0
+
+ # client or server error, or explicit message
+ if (status.to_i >= 400 && empty) || env["rack.showstatus.detail"]
+ req = Rack::Request.new(env)
+ message = Rack::Utils::HTTP_STATUS_CODES[status.to_i] || status.to_s
+ detail = env["rack.showstatus.detail"] || message
+ body = @template.result(binding)
+ size = Rack::Utils.bytesize(body)
+ [status, headers.merge("Content-Type" => "text/html", "Content-Length" => size.to_s), [body]]
+ else
+ [status, headers, body]
+ end
+ end
+
+ def h(obj) # :nodoc:
+ case obj
+ when String
+ Utils.escape_html(obj)
+ else
+ Utils.escape_html(obj.inspect)
+ end
+ end
+
+ # :stopdoc:
+
+# adapted from Django
+# Copyright (c) 2005, the Lawrence Journal-World
+# Used under the modified BSD license:
+# http://www.xfree86.org/3.3.6/COPYRIGHT2.html#5
+TEMPLATE = <<'HTML'
+
+
+
+
+ <%=h message %> at <%=h req.script_name + req.path_info %>
+
+
+
+
+
+
<%=h message %> (<%= status.to_i %>)
+
+
+
Request Method:
+
<%=h req.request_method %>
+
+
+
Request URL:
+
<%=h req.url %>
+
+
+
+
+
<%= detail %>
+
+
+
+
+ You're seeing this error because you use Rack::ShowStatus.
+
+
+
+
+HTML
+
+ # :startdoc:
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/static.rb b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/static.rb
new file mode 100644
index 0000000000..168e8f83b2
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/static.rb
@@ -0,0 +1,38 @@
+module Rack
+
+ # The Rack::Static middleware intercepts requests for static files
+ # (javascript files, images, stylesheets, etc) based on the url prefixes
+ # passed in the options, and serves them using a Rack::File object. This
+ # allows a Rack stack to serve both static and dynamic content.
+ #
+ # Examples:
+ # use Rack::Static, :urls => ["/media"]
+ # will serve all requests beginning with /media from the "media" folder
+ # located in the current directory (ie media/*).
+ #
+ # use Rack::Static, :urls => ["/css", "/images"], :root => "public"
+ # will serve all requests beginning with /css or /images from the folder
+ # "public" in the current directory (ie public/css/* and public/images/*)
+
+ class Static
+
+ def initialize(app, options={})
+ @app = app
+ @urls = options[:urls] || ["/favicon.ico"]
+ root = options[:root] || Dir.pwd
+ @file_server = Rack::File.new(root)
+ end
+
+ def call(env)
+ path = env["PATH_INFO"]
+ can_serve = @urls.any? { |url| path.index(url) == 0 }
+
+ if can_serve
+ @file_server.call(env)
+ else
+ @app.call(env)
+ end
+ end
+
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/urlmap.rb b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/urlmap.rb
new file mode 100644
index 0000000000..fcf6616c58
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/urlmap.rb
@@ -0,0 +1,55 @@
+module Rack
+ # Rack::URLMap takes a hash mapping urls or paths to apps, and
+ # dispatches accordingly. Support for HTTP/1.1 host names exists if
+ # the URLs start with http:// or https://.
+ #
+ # URLMap modifies the SCRIPT_NAME and PATH_INFO such that the part
+ # relevant for dispatch is in the SCRIPT_NAME, and the rest in the
+ # PATH_INFO. This should be taken care of when you need to
+ # reconstruct the URL in order to create links.
+ #
+ # URLMap dispatches in such a way that the longest paths are tried
+ # first, since they are most specific.
+
+ class URLMap
+ def initialize(map = {})
+ remap(map)
+ end
+
+ def remap(map)
+ @mapping = map.map { |location, app|
+ if location =~ %r{\Ahttps?://(.*?)(/.*)}
+ host, location = $1, $2
+ else
+ host = nil
+ end
+
+ unless location[0] == ?/
+ raise ArgumentError, "paths need to start with /"
+ end
+ location = location.chomp('/')
+
+ [host, location, app]
+ }.sort_by { |(h, l, a)| [h ? -h.size : (-1.0 / 0.0), -l.size] } # Longest path first
+ end
+
+ def call(env)
+ path = env["PATH_INFO"].to_s.squeeze("/")
+ script_name = env['SCRIPT_NAME']
+ hHost, sName, sPort = env.values_at('HTTP_HOST','SERVER_NAME','SERVER_PORT')
+ @mapping.each { |host, location, app|
+ next unless (hHost == host || sName == host \
+ || (host.nil? && (hHost == sName || hHost == sName+':'+sPort)))
+ next unless location == path[0, location.size]
+ next unless path[location.size] == nil || path[location.size] == ?/
+
+ return app.call(
+ env.merge(
+ 'SCRIPT_NAME' => (script_name + location),
+ 'PATH_INFO' => path[location.size..-1]))
+ }
+ [404, {"Content-Type" => "text/plain"}, ["Not Found: #{path}"]]
+ end
+ end
+end
+
diff --git a/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/utils.rb b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/utils.rb
new file mode 100644
index 0000000000..42e2e698f4
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/utils.rb
@@ -0,0 +1,516 @@
+# -*- encoding: binary -*-
+
+require 'set'
+require 'tempfile'
+
+module Rack
+ # Rack::Utils contains a grab-bag of useful methods for writing web
+ # applications adopted from all kinds of Ruby libraries.
+
+ module Utils
+ # Performs URI escaping so that you can construct proper
+ # query strings faster. Use this rather than the cgi.rb
+ # version since it's faster. (Stolen from Camping).
+ def escape(s)
+ s.to_s.gsub(/([^ a-zA-Z0-9_.-]+)/n) {
+ '%'+$1.unpack('H2'*$1.size).join('%').upcase
+ }.tr(' ', '+')
+ end
+ module_function :escape
+
+ # Unescapes a URI escaped string. (Stolen from Camping).
+ def unescape(s)
+ s.tr('+', ' ').gsub(/((?:%[0-9a-fA-F]{2})+)/n){
+ [$1.delete('%')].pack('H*')
+ }
+ end
+ module_function :unescape
+
+ # Stolen from Mongrel, with some small modifications:
+ # Parses a query string by breaking it up at the '&'
+ # and ';' characters. You can also use this to parse
+ # cookies by changing the characters used in the second
+ # parameter (which defaults to '&;').
+ def parse_query(qs, d = '&;')
+ params = {}
+
+ (qs || '').split(/[#{d}] */n).each do |p|
+ k, v = unescape(p).split('=', 2)
+
+ if cur = params[k]
+ if cur.class == Array
+ params[k] << v
+ else
+ params[k] = [cur, v]
+ end
+ else
+ params[k] = v
+ end
+ end
+
+ return params
+ end
+ module_function :parse_query
+
+ def parse_nested_query(qs, d = '&;')
+ params = {}
+
+ (qs || '').split(/[#{d}] */n).each do |p|
+ k, v = unescape(p).split('=', 2)
+ normalize_params(params, k, v)
+ end
+
+ return params
+ end
+ module_function :parse_nested_query
+
+ def normalize_params(params, name, v = nil)
+ name =~ %r(\A[\[\]]*([^\[\]]+)\]*)
+ k = $1 || ''
+ after = $' || ''
+
+ return if k.empty?
+
+ if after == ""
+ params[k] = v
+ elsif after == "[]"
+ params[k] ||= []
+ raise TypeError, "expected Array (got #{params[k].class.name}) for param `#{k}'" unless params[k].is_a?(Array)
+ params[k] << v
+ elsif after =~ %r(^\[\]\[([^\[\]]+)\]$) || after =~ %r(^\[\](.+)$)
+ child_key = $1
+ params[k] ||= []
+ raise TypeError, "expected Array (got #{params[k].class.name}) for param `#{k}'" unless params[k].is_a?(Array)
+ if params[k].last.is_a?(Hash) && !params[k].last.key?(child_key)
+ normalize_params(params[k].last, child_key, v)
+ else
+ params[k] << normalize_params({}, child_key, v)
+ end
+ else
+ params[k] ||= {}
+ raise TypeError, "expected Hash (got #{params[k].class.name}) for param `#{k}'" unless params[k].is_a?(Hash)
+ params[k] = normalize_params(params[k], after, v)
+ end
+
+ return params
+ end
+ module_function :normalize_params
+
+ def build_query(params)
+ params.map { |k, v|
+ if v.class == Array
+ build_query(v.map { |x| [k, x] })
+ else
+ escape(k) + "=" + escape(v)
+ end
+ }.join("&")
+ end
+ module_function :build_query
+
+ def build_nested_query(value, prefix = nil)
+ case value
+ when Array
+ value.map { |v|
+ build_nested_query(v, "#{prefix}[]")
+ }.join("&")
+ when Hash
+ value.map { |k, v|
+ build_nested_query(v, prefix ? "#{prefix}[#{escape(k)}]" : escape(k))
+ }.join("&")
+ when String
+ raise ArgumentError, "value must be a Hash" if prefix.nil?
+ "#{prefix}=#{escape(value)}"
+ else
+ prefix
+ end
+ end
+ module_function :build_nested_query
+
+ # Escape ampersands, brackets and quotes to their HTML/XML entities.
+ def escape_html(string)
+ string.to_s.gsub("&", "&").
+ gsub("<", "<").
+ gsub(">", ">").
+ gsub("'", "'").
+ gsub('"', """)
+ end
+ module_function :escape_html
+
+ def select_best_encoding(available_encodings, accept_encoding)
+ # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
+
+ expanded_accept_encoding =
+ accept_encoding.map { |m, q|
+ if m == "*"
+ (available_encodings - accept_encoding.map { |m2, _| m2 }).map { |m2| [m2, q] }
+ else
+ [[m, q]]
+ end
+ }.inject([]) { |mem, list|
+ mem + list
+ }
+
+ encoding_candidates = expanded_accept_encoding.sort_by { |_, q| -q }.map { |m, _| m }
+
+ unless encoding_candidates.include?("identity")
+ encoding_candidates.push("identity")
+ end
+
+ expanded_accept_encoding.find_all { |m, q|
+ q == 0.0
+ }.each { |m, _|
+ encoding_candidates.delete(m)
+ }
+
+ return (encoding_candidates & available_encodings)[0]
+ end
+ module_function :select_best_encoding
+
+ # Return the bytesize of String; uses String#length under Ruby 1.8 and
+ # String#bytesize under 1.9.
+ if ''.respond_to?(:bytesize)
+ def bytesize(string)
+ string.bytesize
+ end
+ else
+ def bytesize(string)
+ string.size
+ end
+ end
+ module_function :bytesize
+
+ # Context allows the use of a compatible middleware at different points
+ # in a request handling stack. A compatible middleware must define
+ # #context which should take the arguments env and app. The first of which
+ # would be the request environment. The second of which would be the rack
+ # application that the request would be forwarded to.
+ class Context
+ attr_reader :for, :app
+
+ def initialize(app_f, app_r)
+ raise 'running context does not respond to #context' unless app_f.respond_to? :context
+ @for, @app = app_f, app_r
+ end
+
+ def call(env)
+ @for.context(env, @app)
+ end
+
+ def recontext(app)
+ self.class.new(@for, app)
+ end
+
+ def context(env, app=@app)
+ recontext(app).call(env)
+ end
+ end
+
+ # A case-insensitive Hash that preserves the original case of a
+ # header when set.
+ class HeaderHash < Hash
+ def initialize(hash={})
+ @names = {}
+ hash.each { |k, v| self[k] = v }
+ end
+
+ def to_hash
+ inject({}) do |hash, (k,v)|
+ if v.respond_to? :to_ary
+ hash[k] = v.to_ary.join("\n")
+ else
+ hash[k] = v
+ end
+ hash
+ end
+ end
+
+ def [](k)
+ super @names[k.downcase]
+ end
+
+ def []=(k, v)
+ delete k
+ @names[k.downcase] = k
+ super k, v
+ end
+
+ def delete(k)
+ super @names.delete(k.downcase)
+ end
+
+ def include?(k)
+ @names.has_key? k.downcase
+ end
+
+ alias_method :has_key?, :include?
+ alias_method :member?, :include?
+ alias_method :key?, :include?
+
+ def merge!(other)
+ other.each { |k, v| self[k] = v }
+ self
+ end
+
+ def merge(other)
+ hash = dup
+ hash.merge! other
+ end
+ end
+
+ # Every standard HTTP code mapped to the appropriate message.
+ # Stolen from Mongrel.
+ HTTP_STATUS_CODES = {
+ 100 => 'Continue',
+ 101 => 'Switching Protocols',
+ 200 => 'OK',
+ 201 => 'Created',
+ 202 => 'Accepted',
+ 203 => 'Non-Authoritative Information',
+ 204 => 'No Content',
+ 205 => 'Reset Content',
+ 206 => 'Partial Content',
+ 300 => 'Multiple Choices',
+ 301 => 'Moved Permanently',
+ 302 => 'Found',
+ 303 => 'See Other',
+ 304 => 'Not Modified',
+ 305 => 'Use Proxy',
+ 307 => 'Temporary Redirect',
+ 400 => 'Bad Request',
+ 401 => 'Unauthorized',
+ 402 => 'Payment Required',
+ 403 => 'Forbidden',
+ 404 => 'Not Found',
+ 405 => 'Method Not Allowed',
+ 406 => 'Not Acceptable',
+ 407 => 'Proxy Authentication Required',
+ 408 => 'Request Timeout',
+ 409 => 'Conflict',
+ 410 => 'Gone',
+ 411 => 'Length Required',
+ 412 => 'Precondition Failed',
+ 413 => 'Request Entity Too Large',
+ 414 => 'Request-URI Too Large',
+ 415 => 'Unsupported Media Type',
+ 416 => 'Requested Range Not Satisfiable',
+ 417 => 'Expectation Failed',
+ 500 => 'Internal Server Error',
+ 501 => 'Not Implemented',
+ 502 => 'Bad Gateway',
+ 503 => 'Service Unavailable',
+ 504 => 'Gateway Timeout',
+ 505 => 'HTTP Version Not Supported'
+ }
+
+ # Responses with HTTP status codes that should not have an entity body
+ STATUS_WITH_NO_ENTITY_BODY = Set.new((100..199).to_a << 204 << 304)
+
+ # A multipart form data parser, adapted from IOWA.
+ #
+ # Usually, Rack::Request#POST takes care of calling this.
+
+ module Multipart
+ class UploadedFile
+ # The filename, *not* including the path, of the "uploaded" file
+ attr_reader :original_filename
+
+ # The content type of the "uploaded" file
+ attr_accessor :content_type
+
+ def initialize(path, content_type = "text/plain", binary = false)
+ raise "#{path} file does not exist" unless ::File.exist?(path)
+ @content_type = content_type
+ @original_filename = ::File.basename(path)
+ @tempfile = Tempfile.new(@original_filename)
+ @tempfile.set_encoding(Encoding::BINARY) if @tempfile.respond_to?(:set_encoding)
+ @tempfile.binmode if binary
+ FileUtils.copy_file(path, @tempfile.path)
+ end
+
+ def path
+ @tempfile.path
+ end
+ alias_method :local_path, :path
+
+ def method_missing(method_name, *args, &block) #:nodoc:
+ @tempfile.__send__(method_name, *args, &block)
+ end
+ end
+
+ EOL = "\r\n"
+ MULTIPART_BOUNDARY = "AaB03x"
+
+ def self.parse_multipart(env)
+ unless env['CONTENT_TYPE'] =~
+ %r|\Amultipart/.*boundary=\"?([^\";,]+)\"?|n
+ nil
+ else
+ boundary = "--#{$1}"
+
+ params = {}
+ buf = ""
+ content_length = env['CONTENT_LENGTH'].to_i
+ input = env['rack.input']
+ input.rewind
+
+ boundary_size = Utils.bytesize(boundary) + EOL.size
+ bufsize = 16384
+
+ content_length -= boundary_size
+
+ read_buffer = ''
+
+ status = input.read(boundary_size, read_buffer)
+ raise EOFError, "bad content body" unless status == boundary + EOL
+
+ rx = /(?:#{EOL})?#{Regexp.quote boundary}(#{EOL}|--)/n
+
+ loop {
+ head = nil
+ body = ''
+ filename = content_type = name = nil
+
+ until head && buf =~ rx
+ if !head && i = buf.index(EOL+EOL)
+ head = buf.slice!(0, i+2) # First \r\n
+ buf.slice!(0, 2) # Second \r\n
+
+ filename = head[/Content-Disposition:.* filename="?([^\";]*)"?/ni, 1]
+ content_type = head[/Content-Type: (.*)#{EOL}/ni, 1]
+ name = head[/Content-Disposition:.*\s+name="?([^\";]*)"?/ni, 1] || head[/Content-ID:\s*([^#{EOL}]*)/ni, 1]
+
+ if content_type || filename
+ body = Tempfile.new("RackMultipart")
+ body.binmode if body.respond_to?(:binmode)
+ end
+
+ next
+ end
+
+ # Save the read body part.
+ if head && (boundary_size+4 < buf.size)
+ body << buf.slice!(0, buf.size - (boundary_size+4))
+ end
+
+ c = input.read(bufsize < content_length ? bufsize : content_length, read_buffer)
+ raise EOFError, "bad content body" if c.nil? || c.empty?
+ buf << c
+ content_length -= c.size
+ end
+
+ # Save the rest.
+ if i = buf.index(rx)
+ body << buf.slice!(0, i)
+ buf.slice!(0, boundary_size+2)
+
+ content_length = -1 if $1 == "--"
+ end
+
+ if filename == ""
+ # filename is blank which means no file has been selected
+ data = nil
+ elsif filename
+ body.rewind
+
+ # Take the basename of the upload's original filename.
+ # This handles the full Windows paths given by Internet Explorer
+ # (and perhaps other broken user agents) without affecting
+ # those which give the lone filename.
+ filename =~ /^(?:.*[:\\\/])?(.*)/m
+ filename = $1
+
+ data = {:filename => filename, :type => content_type,
+ :name => name, :tempfile => body, :head => head}
+ elsif !filename && content_type
+ body.rewind
+
+ # Generic multipart cases, not coming from a form
+ data = {:type => content_type,
+ :name => name, :tempfile => body, :head => head}
+ else
+ data = body
+ end
+
+ Utils.normalize_params(params, name, data) unless data.nil?
+
+ break if buf.empty? || content_length == -1
+ }
+
+ input.rewind
+
+ params
+ end
+ end
+
+ def self.build_multipart(params, first = true)
+ if first
+ unless params.is_a?(Hash)
+ raise ArgumentError, "value must be a Hash"
+ end
+
+ multipart = false
+ query = lambda { |value|
+ case value
+ when Array
+ value.each(&query)
+ when Hash
+ value.values.each(&query)
+ when UploadedFile
+ multipart = true
+ end
+ }
+ params.values.each(&query)
+ return nil unless multipart
+ end
+
+ flattened_params = Hash.new
+
+ params.each do |key, value|
+ k = first ? key.to_s : "[#{key}]"
+
+ case value
+ when Array
+ value.map { |v|
+ build_multipart(v, false).each { |subkey, subvalue|
+ flattened_params["#{k}[]#{subkey}"] = subvalue
+ }
+ }
+ when Hash
+ build_multipart(value, false).each { |subkey, subvalue|
+ flattened_params[k + subkey] = subvalue
+ }
+ else
+ flattened_params[k] = value
+ end
+ end
+
+ if first
+ flattened_params.map { |name, file|
+ if file.respond_to?(:original_filename)
+ ::File.open(file.path, "rb") do |f|
+ f.set_encoding(Encoding::BINARY) if f.respond_to?(:set_encoding)
+<<-EOF
+--#{MULTIPART_BOUNDARY}\r
+Content-Disposition: form-data; name="#{name}"; filename="#{Utils.escape(file.original_filename)}"\r
+Content-Type: #{file.content_type}\r
+Content-Length: #{::File.stat(file.path).size}\r
+\r
+#{f.read}\r
+EOF
+ end
+ else
+<<-EOF
+--#{MULTIPART_BOUNDARY}\r
+Content-Disposition: form-data; name="#{name}"\r
+\r
+#{file}\r
+EOF
+ end
+ }.join + "--#{MULTIPART_BOUNDARY}--\r"
+ else
+ flattened_params
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack.rb b/actionpack/lib/action_dispatch/vendor/rack/rack.rb
deleted file mode 100644
index 371d015690..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack.rb
+++ /dev/null
@@ -1,90 +0,0 @@
-# Copyright (C) 2007, 2008, 2009 Christian Neukirchen
-#
-# Rack is freely distributable under the terms of an MIT-style license.
-# See COPYING or http://www.opensource.org/licenses/mit-license.php.
-
-path = File.expand_path(File.dirname(__FILE__))
-$:.unshift(path) unless $:.include?(path)
-
-
-# The Rack main module, serving as a namespace for all core Rack
-# modules and classes.
-#
-# All modules meant for use in your application are autoloaded here,
-# so it should be enough just to require rack.rb in your code.
-
-module Rack
- # The Rack protocol version number implemented.
- VERSION = [1,0]
-
- # Return the Rack protocol version as a dotted string.
- def self.version
- VERSION.join(".")
- end
-
- # Return the Rack release as a dotted string.
- def self.release
- "1.0"
- end
-
- autoload :Builder, "rack/builder"
- autoload :Cascade, "rack/cascade"
- autoload :Chunked, "rack/chunked"
- autoload :CommonLogger, "rack/commonlogger"
- autoload :ConditionalGet, "rack/conditionalget"
- autoload :ContentLength, "rack/content_length"
- autoload :ContentType, "rack/content_type"
- autoload :File, "rack/file"
- autoload :Deflater, "rack/deflater"
- autoload :Directory, "rack/directory"
- autoload :ForwardRequest, "rack/recursive"
- autoload :Handler, "rack/handler"
- autoload :Head, "rack/head"
- autoload :Lint, "rack/lint"
- autoload :Lock, "rack/lock"
- autoload :MethodOverride, "rack/methodoverride"
- autoload :Mime, "rack/mime"
- autoload :Recursive, "rack/recursive"
- autoload :Reloader, "rack/reloader"
- autoload :ShowExceptions, "rack/showexceptions"
- autoload :ShowStatus, "rack/showstatus"
- autoload :Static, "rack/static"
- autoload :URLMap, "rack/urlmap"
- autoload :Utils, "rack/utils"
-
- autoload :MockRequest, "rack/mock"
- autoload :MockResponse, "rack/mock"
-
- autoload :Request, "rack/request"
- autoload :Response, "rack/response"
-
- module Auth
- autoload :Basic, "rack/auth/basic"
- autoload :AbstractRequest, "rack/auth/abstract/request"
- autoload :AbstractHandler, "rack/auth/abstract/handler"
- autoload :OpenID, "rack/auth/openid"
- module Digest
- autoload :MD5, "rack/auth/digest/md5"
- autoload :Nonce, "rack/auth/digest/nonce"
- autoload :Params, "rack/auth/digest/params"
- autoload :Request, "rack/auth/digest/request"
- end
- end
-
- module Session
- autoload :Cookie, "rack/session/cookie"
- autoload :Pool, "rack/session/pool"
- autoload :Memcache, "rack/session/memcache"
- end
-
- # *Adapters* connect Rack with third party web frameworks.
- #
- # Rack includes an adapter for Camping, see README for other
- # frameworks supporting Rack in their code bases.
- #
- # Refer to the submodules for framework-specific calling details.
-
- module Adapter
- autoload :Camping, "rack/adapter/camping"
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/adapter/camping.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/adapter/camping.rb
deleted file mode 100644
index 63bc787f54..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/adapter/camping.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-module Rack
- module Adapter
- class Camping
- def initialize(app)
- @app = app
- end
-
- def call(env)
- env["PATH_INFO"] ||= ""
- env["SCRIPT_NAME"] ||= ""
- controller = @app.run(env['rack.input'], env)
- h = controller.headers
- h.each_pair do |k,v|
- if v.kind_of? URI
- h[k] = v.to_s
- end
- end
- [controller.status, controller.headers, [controller.body.to_s]]
- end
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/auth/abstract/handler.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/auth/abstract/handler.rb
deleted file mode 100644
index 214df6299e..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/auth/abstract/handler.rb
+++ /dev/null
@@ -1,37 +0,0 @@
-module Rack
- module Auth
- # Rack::Auth::AbstractHandler implements common authentication functionality.
- #
- # +realm+ should be set for all handlers.
-
- class AbstractHandler
-
- attr_accessor :realm
-
- def initialize(app, realm=nil, &authenticator)
- @app, @realm, @authenticator = app, realm, authenticator
- end
-
-
- private
-
- def unauthorized(www_authenticate = challenge)
- return [ 401,
- { 'Content-Type' => 'text/plain',
- 'Content-Length' => '0',
- 'WWW-Authenticate' => www_authenticate.to_s },
- []
- ]
- end
-
- def bad_request
- return [ 400,
- { 'Content-Type' => 'text/plain',
- 'Content-Length' => '0' },
- []
- ]
- end
-
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/auth/abstract/request.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/auth/abstract/request.rb
deleted file mode 100644
index 1d9ccec685..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/auth/abstract/request.rb
+++ /dev/null
@@ -1,37 +0,0 @@
-module Rack
- module Auth
- class AbstractRequest
-
- def initialize(env)
- @env = env
- end
-
- def provided?
- !authorization_key.nil?
- end
-
- def parts
- @parts ||= @env[authorization_key].split(' ', 2)
- end
-
- def scheme
- @scheme ||= parts.first.downcase.to_sym
- end
-
- def params
- @params ||= parts.last
- end
-
-
- private
-
- AUTHORIZATION_KEYS = ['HTTP_AUTHORIZATION', 'X-HTTP_AUTHORIZATION', 'X_HTTP_AUTHORIZATION']
-
- def authorization_key
- @authorization_key ||= AUTHORIZATION_KEYS.detect { |key| @env.has_key?(key) }
- end
-
- end
-
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/auth/basic.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/auth/basic.rb
deleted file mode 100644
index 9557224648..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/auth/basic.rb
+++ /dev/null
@@ -1,58 +0,0 @@
-require 'rack/auth/abstract/handler'
-require 'rack/auth/abstract/request'
-
-module Rack
- module Auth
- # Rack::Auth::Basic implements HTTP Basic Authentication, as per RFC 2617.
- #
- # Initialize with the Rack application that you want protecting,
- # and a block that checks if a username and password pair are valid.
- #
- # See also: example/protectedlobster.rb
-
- class Basic < AbstractHandler
-
- def call(env)
- auth = Basic::Request.new(env)
-
- return unauthorized unless auth.provided?
-
- return bad_request unless auth.basic?
-
- if valid?(auth)
- env['REMOTE_USER'] = auth.username
-
- return @app.call(env)
- end
-
- unauthorized
- end
-
-
- private
-
- def challenge
- 'Basic realm="%s"' % realm
- end
-
- def valid?(auth)
- @authenticator.call(*auth.credentials)
- end
-
- class Request < Auth::AbstractRequest
- def basic?
- :basic == scheme
- end
-
- def credentials
- @credentials ||= params.unpack("m*").first.split(/:/, 2)
- end
-
- def username
- credentials.first
- end
- end
-
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/auth/digest/md5.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/auth/digest/md5.rb
deleted file mode 100644
index e579dc9632..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/auth/digest/md5.rb
+++ /dev/null
@@ -1,124 +0,0 @@
-require 'rack/auth/abstract/handler'
-require 'rack/auth/digest/request'
-require 'rack/auth/digest/params'
-require 'rack/auth/digest/nonce'
-require 'digest/md5'
-
-module Rack
- module Auth
- module Digest
- # Rack::Auth::Digest::MD5 implements the MD5 algorithm version of
- # HTTP Digest Authentication, as per RFC 2617.
- #
- # Initialize with the [Rack] application that you want protecting,
- # and a block that looks up a plaintext password for a given username.
- #
- # +opaque+ needs to be set to a constant base64/hexadecimal string.
- #
- class MD5 < AbstractHandler
-
- attr_accessor :opaque
-
- attr_writer :passwords_hashed
-
- def initialize(*args)
- super
- @passwords_hashed = nil
- end
-
- def passwords_hashed?
- !!@passwords_hashed
- end
-
- def call(env)
- auth = Request.new(env)
-
- unless auth.provided?
- return unauthorized
- end
-
- if !auth.digest? || !auth.correct_uri? || !valid_qop?(auth)
- return bad_request
- end
-
- if valid?(auth)
- if auth.nonce.stale?
- return unauthorized(challenge(:stale => true))
- else
- env['REMOTE_USER'] = auth.username
-
- return @app.call(env)
- end
- end
-
- unauthorized
- end
-
-
- private
-
- QOP = 'auth'.freeze
-
- def params(hash = {})
- Params.new do |params|
- params['realm'] = realm
- params['nonce'] = Nonce.new.to_s
- params['opaque'] = H(opaque)
- params['qop'] = QOP
-
- hash.each { |k, v| params[k] = v }
- end
- end
-
- def challenge(hash = {})
- "Digest #{params(hash)}"
- end
-
- def valid?(auth)
- valid_opaque?(auth) && valid_nonce?(auth) && valid_digest?(auth)
- end
-
- def valid_qop?(auth)
- QOP == auth.qop
- end
-
- def valid_opaque?(auth)
- H(opaque) == auth.opaque
- end
-
- def valid_nonce?(auth)
- auth.nonce.valid?
- end
-
- def valid_digest?(auth)
- digest(auth, @authenticator.call(auth.username)) == auth.response
- end
-
- def md5(data)
- ::Digest::MD5.hexdigest(data)
- end
-
- alias :H :md5
-
- def KD(secret, data)
- H([secret, data] * ':')
- end
-
- def A1(auth, password)
- [ auth.username, auth.realm, password ] * ':'
- end
-
- def A2(auth)
- [ auth.method, auth.uri ] * ':'
- end
-
- def digest(auth, password)
- password_hash = passwords_hashed? ? password : H(A1(auth, password))
-
- KD(password_hash, [ auth.nonce, auth.nc, auth.cnonce, QOP, H(A2(auth)) ] * ':')
- end
-
- end
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/auth/digest/nonce.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/auth/digest/nonce.rb
deleted file mode 100644
index dbe109f29a..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/auth/digest/nonce.rb
+++ /dev/null
@@ -1,51 +0,0 @@
-require 'digest/md5'
-
-module Rack
- module Auth
- module Digest
- # Rack::Auth::Digest::Nonce is the default nonce generator for the
- # Rack::Auth::Digest::MD5 authentication handler.
- #
- # +private_key+ needs to set to a constant string.
- #
- # +time_limit+ can be optionally set to an integer (number of seconds),
- # to limit the validity of the generated nonces.
-
- class Nonce
-
- class << self
- attr_accessor :private_key, :time_limit
- end
-
- def self.parse(string)
- new(*string.unpack("m*").first.split(' ', 2))
- end
-
- def initialize(timestamp = Time.now, given_digest = nil)
- @timestamp, @given_digest = timestamp.to_i, given_digest
- end
-
- def to_s
- [([ @timestamp, digest ] * ' ')].pack("m*").strip
- end
-
- def digest
- ::Digest::MD5.hexdigest([ @timestamp, self.class.private_key ] * ':')
- end
-
- def valid?
- digest == @given_digest
- end
-
- def stale?
- !self.class.time_limit.nil? && (@timestamp - Time.now.to_i) < self.class.time_limit
- end
-
- def fresh?
- !stale?
- end
-
- end
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/auth/digest/params.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/auth/digest/params.rb
deleted file mode 100644
index 730e2efdc8..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/auth/digest/params.rb
+++ /dev/null
@@ -1,55 +0,0 @@
-module Rack
- module Auth
- module Digest
- class Params < Hash
-
- def self.parse(str)
- split_header_value(str).inject(new) do |header, param|
- k, v = param.split('=', 2)
- header[k] = dequote(v)
- header
- end
- end
-
- def self.dequote(str) # From WEBrick::HTTPUtils
- ret = (/\A"(.*)"\Z/ =~ str) ? $1 : str.dup
- ret.gsub!(/\\(.)/, "\\1")
- ret
- end
-
- def self.split_header_value(str)
- str.scan( /(\w+\=(?:"[^\"]+"|[^,]+))/n ).collect{ |v| v[0] }
- end
-
- def initialize
- super
-
- yield self if block_given?
- end
-
- def [](k)
- super k.to_s
- end
-
- def []=(k, v)
- super k.to_s, v.to_s
- end
-
- UNQUOTED = ['qop', 'nc', 'stale']
-
- def to_s
- inject([]) do |parts, (k, v)|
- parts << "#{k}=" + (UNQUOTED.include?(k) ? v.to_s : quote(v))
- parts
- end.join(', ')
- end
-
- def quote(str) # From WEBrick::HTTPUtils
- '"' << str.gsub(/[\\\"]/o, "\\\1") << '"'
- end
-
- end
- end
- end
-end
-
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/auth/digest/request.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/auth/digest/request.rb
deleted file mode 100644
index a8aa3bf996..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/auth/digest/request.rb
+++ /dev/null
@@ -1,40 +0,0 @@
-require 'rack/auth/abstract/request'
-require 'rack/auth/digest/params'
-require 'rack/auth/digest/nonce'
-
-module Rack
- module Auth
- module Digest
- class Request < Auth::AbstractRequest
-
- def method
- @env['rack.methodoverride.original_method'] || @env['REQUEST_METHOD']
- end
-
- def digest?
- :digest == scheme
- end
-
- def correct_uri?
- (@env['SCRIPT_NAME'].to_s + @env['PATH_INFO'].to_s) == uri
- end
-
- def nonce
- @nonce ||= Nonce.parse(params['nonce'])
- end
-
- def params
- @params ||= Params.parse(parts.last)
- end
-
- def method_missing(sym)
- if params.has_key? key = sym.to_s
- return params[key]
- end
- super
- end
-
- end
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/auth/openid.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/auth/openid.rb
deleted file mode 100644
index c5f6a5143e..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/auth/openid.rb
+++ /dev/null
@@ -1,480 +0,0 @@
-# AUTHOR: blink ; blink#ruby-lang@irc.freenode.net
-
-gem 'ruby-openid', '~> 2' if defined? Gem
-require 'rack/request'
-require 'rack/utils'
-require 'rack/auth/abstract/handler'
-require 'uri'
-require 'openid' #gem
-require 'openid/extension' #gem
-require 'openid/store/memory' #gem
-
-module Rack
- class Request
- def openid_request
- @env['rack.auth.openid.request']
- end
-
- def openid_response
- @env['rack.auth.openid.response']
- end
- end
-
- module Auth
-
- # Rack::Auth::OpenID provides a simple method for setting up an OpenID
- # Consumer. It requires the ruby-openid library from janrain to operate,
- # as well as a rack method of session management.
- #
- # The ruby-openid home page is at http://openidenabled.com/ruby-openid/.
- #
- # The OpenID specifications can be found at
- # http://openid.net/specs/openid-authentication-1_1.html
- # and
- # http://openid.net/specs/openid-authentication-2_0.html. Documentation
- # for published OpenID extensions and related topics can be found at
- # http://openid.net/developers/specs/.
- #
- # It is recommended to read through the OpenID spec, as well as
- # ruby-openid's documentation, to understand what exactly goes on. However
- # a setup as simple as the presented examples is enough to provide
- # Consumer functionality.
- #
- # This library strongly intends to utilize the OpenID 2.0 features of the
- # ruby-openid library, which provides OpenID 1.0 compatiblity.
- #
- # NOTE: Due to the amount of data that this library stores in the
- # session, Rack::Session::Cookie may fault.
-
- class OpenID
-
- class NoSession < RuntimeError; end
- class BadExtension < RuntimeError; end
- # Required for ruby-openid
- ValidStatus = [:success, :setup_needed, :cancel, :failure]
-
- # = Arguments
- #
- # The first argument is the realm, identifying the site they are trusting
- # with their identity. This is required, also treated as the trust_root
- # in OpenID 1.x exchanges.
- #
- # The optional second argument is a hash of options.
- #
- # == Options
- #
- # :return_to defines the url to return to after the client
- # authenticates with the openid service provider. This url should point
- # to where Rack::Auth::OpenID is mounted. If :return_to is not
- # provided, return_to will be the current url which allows flexibility
- # with caveats.
- #
- # :session_key defines the key to the session hash in the env.
- # It defaults to 'rack.session'.
- #
- # :openid_param defines at what key in the request parameters to
- # find the identifier to resolve. As per the 2.0 spec, the default is
- # 'openid_identifier'.
- #
- # :store defined what OpenID Store to use for persistant
- # information. By default a Store::Memory will be used.
- #
- # :immediate as true will make initial requests to be of an
- # immediate type. This is false by default. See OpenID specification
- # documentation.
- #
- # :extensions should be a hash of openid extension
- # implementations. The key should be the extension main module, the value
- # should be an array of arguments for extension::Request.new.
- # The hash is iterated over and passed to #add_extension for processing.
- # Please see #add_extension for further documentation.
- #
- # == Examples
- #
- # simple_oid = OpenID.new('http://mysite.com/')
- #
- # return_oid = OpenID.new('http://mysite.com/', {
- # :return_to => 'http://mysite.com/openid'
- # })
- #
- # complex_oid = OpenID.new('http://mysite.com/',
- # :immediate => true,
- # :extensions => {
- # ::OpenID::SReg => [['email'],['nickname']]
- # }
- # )
- #
- # = Advanced
- #
- # Most of the functionality of this library is encapsulated such that
- # expansion and overriding functions isn't difficult nor tricky.
- # Alternately, to avoid opening up singleton objects or subclassing, a
- # wrapper rack middleware can be composed to act upon Auth::OpenID's
- # responses. See #check and #finish for locations of pertinent data.
- #
- # == Responses
- #
- # To change the responses that Auth::OpenID returns, override the methods
- # #redirect, #bad_request, #unauthorized, #access_denied, and
- # #foreign_server_failure.
- #
- # Additionally #confirm_post_params is used when the URI would exceed
- # length limits on a GET request when doing the initial verification
- # request.
- #
- # == Processing
- #
- # To change methods of processing completed transactions, override the
- # methods #success, #setup_needed, #cancel, and #failure. Please ensure
- # the returned object is a rack compatible response.
- #
- # The first argument is an OpenID::Response, the second is a
- # Rack::Request of the current request, the last is the hash used in
- # ruby-openid handling, which can be found manually at
- # env['rack.session'][:openid].
- #
- # This is useful if you wanted to expand the processing done, such as
- # setting up user accounts.
- #
- # oid_app = Rack::Auth::OpenID.new realm, :return_to => return_to
- # def oid_app.success oid, request, session
- # user = Models::User[oid.identity_url]
- # user ||= Models::User.create_from_openid oid
- # request['rack.session'][:user] = user.id
- # redirect MyApp.site_home
- # end
- #
- # site_map['/openid'] = oid_app
- # map = Rack::URLMap.new site_map
- # ...
-
- def initialize(realm, options={})
- realm = URI(realm)
- raise ArgumentError, "Invalid realm: #{realm}" \
- unless realm.absolute? \
- and realm.fragment.nil? \
- and realm.scheme =~ /^https?$/ \
- and realm.host =~ /^(\*\.)?#{URI::REGEXP::PATTERN::URIC_NO_SLASH}+/
- realm.path = '/' if realm.path.empty?
- @realm = realm.to_s
-
- if ruri = options[:return_to]
- ruri = URI(ruri)
- raise ArgumentError, "Invalid return_to: #{ruri}" \
- unless ruri.absolute? \
- and ruri.scheme =~ /^https?$/ \
- and ruri.fragment.nil?
- raise ArgumentError, "return_to #{ruri} not within realm #{realm}" \
- unless self.within_realm?(ruri)
- @return_to = ruri.to_s
- end
-
- @session_key = options[:session_key] || 'rack.session'
- @openid_param = options[:openid_param] || 'openid_identifier'
- @store = options[:store] || ::OpenID::Store::Memory.new
- @immediate = !!options[:immediate]
-
- @extensions = {}
- if extensions = options.delete(:extensions)
- extensions.each do |ext, args|
- add_extension ext, *args
- end
- end
-
- # Undocumented, semi-experimental
- @anonymous = !!options[:anonymous]
- end
-
- attr_reader :realm, :return_to, :session_key, :openid_param, :store,
- :immediate, :extensions
-
- # Sets up and uses session data at :openid within the session.
- # Errors in this setup will raise a NoSession exception.
- #
- # If the parameter 'openid.mode' is set, which implies a followup from
- # the openid server, processing is passed to #finish and the result is
- # returned. However, if there is no appropriate openid information in the
- # session, a 400 error is returned.
- #
- # If the parameter specified by options[:openid_param] is
- # present, processing is passed to #check and the result is returned.
- #
- # If neither of these conditions are met, #unauthorized is called.
-
- def call(env)
- env['rack.auth.openid'] = self
- env_session = env[@session_key]
- unless env_session and env_session.is_a?(Hash)
- raise NoSession, 'No compatible session'
- end
- # let us work in our own namespace...
- session = (env_session[:openid] ||= {})
- unless session and session.is_a?(Hash)
- raise NoSession, 'Incompatible openid session'
- end
-
- request = Rack::Request.new(env)
- consumer = ::OpenID::Consumer.new(session, @store)
-
- if mode = request.GET['openid.mode']
- if session.key?(:openid_param)
- finish(consumer, session, request)
- else
- bad_request
- end
- elsif request.GET[@openid_param]
- check(consumer, session, request)
- else
- unauthorized
- end
- end
-
- # As the first part of OpenID consumer action, #check retrieves the data
- # required for completion.
- #
- # If all parameters fit within the max length of a URI, a 303 redirect
- # will be returned. Otherwise #confirm_post_params will be called.
- #
- # Any messages from OpenID's request are logged to env['rack.errors']
- #
- # env['rack.auth.openid.request'] is the openid checkid request
- # instance.
- #
- # session[:openid_param] is set to the openid identifier
- # provided by the user.
- #
- # session[:return_to] is set to the return_to uri given to the
- # identity provider.
-
- def check(consumer, session, req)
- oid = consumer.begin(req.GET[@openid_param], @anonymous)
- req.env['rack.auth.openid.request'] = oid
- req.env['rack.errors'].puts(oid.message)
- p oid if $DEBUG
-
- ## Extension support
- extensions.each do |ext,args|
- oid.add_extension(ext::Request.new(*args))
- end
-
- session[:openid_param] = req.GET[openid_param]
- return_to_uri = return_to ? return_to : req.url
- session[:return_to] = return_to_uri
- immediate = session.key?(:setup_needed) ? false : immediate
-
- if oid.send_redirect?(realm, return_to_uri, immediate)
- uri = oid.redirect_url(realm, return_to_uri, immediate)
- redirect(uri)
- else
- confirm_post_params(oid, realm, return_to_uri, immediate)
- end
- rescue ::OpenID::DiscoveryFailure => e
- # thrown from inside OpenID::Consumer#begin by yadis stuff
- req.env['rack.errors'].puts([e.message, *e.backtrace]*"\n")
- return foreign_server_failure
- end
-
- # This is the final portion of authentication.
- # If successful, a redirect to the realm is be returned.
- # Data gathered from extensions are stored in session[:openid] with the
- # extension's namespace uri as the key.
- #
- # Any messages from OpenID's response are logged to env['rack.errors']
- #
- # env['rack.auth.openid.response'] will contain the openid
- # response.
-
- def finish(consumer, session, req)
- oid = consumer.complete(req.GET, req.url)
- req.env['rack.auth.openid.response'] = oid
- req.env['rack.errors'].puts(oid.message)
- p oid if $DEBUG
-
- raise unless ValidStatus.include?(oid.status)
- __send__(oid.status, oid, req, session)
- end
-
- # The first argument should be the main extension module.
- # The extension module should contain the constants:
- # * class Request, should have OpenID::Extension as an ancestor
- # * class Response, should have OpenID::Extension as an ancestor
- # * string NS_URI, which defining the namespace of the extension
- #
- # All trailing arguments will be passed to extension::Request.new in
- # #check.
- # The openid response will be passed to
- # extension::Response#from_success_response, #get_extension_args will be
- # called on the result to attain the gathered data.
- #
- # This method returns the key at which the response data will be found in
- # the session, which is the namespace uri by default.
-
- def add_extension(ext, *args)
- raise BadExtension unless valid_extension?(ext)
- extensions[ext] = args
- return ext::NS_URI
- end
-
- # Checks the validitity, in the context of usage, of a submitted
- # extension.
-
- def valid_extension?(ext)
- if not %w[NS_URI Request Response].all?{|c| ext.const_defined?(c) }
- raise ArgumentError, 'Extension is missing constants.'
- elsif not ext::Response.respond_to?(:from_success_response)
- raise ArgumentError, 'Response is missing required method.'
- end
- return true
- rescue
- return false
- end
-
- # Checks the provided uri to ensure it'd be considered within the realm.
- # is currently not compatible with wildcard realms.
-
- def within_realm? uri
- uri = URI.parse(uri.to_s)
- realm = URI.parse(self.realm)
- return false unless uri.absolute?
- return false unless uri.path[0, realm.path.size] == realm.path
- return false unless uri.host == realm.host or realm.host[/^\*\./]
- # for wildcard support, is awkward with URI limitations
- realm_match = Regexp.escape(realm.host).
- sub(/^\*\./,"^#{URI::REGEXP::PATTERN::URIC_NO_SLASH}+.")+'$'
- return false unless uri.host.match(realm_match)
- return true
- end
- alias_method :include?, :within_realm?
-
- protected
-
- ### These methods define some of the boilerplate responses.
-
- # Returns an html form page for posting to an Identity Provider if the
- # GET request would exceed the upper URI length limit.
-
- def confirm_post_params(oid, realm, return_to, immediate)
- Rack::Response.new.finish do |r|
- r.write 'Confirm...'
- r.write oid.form_markup(realm, return_to, immediate)
- r.write ''
- end
- end
-
- # Returns a 303 redirect with the destination of that provided by the
- # argument.
-
- def redirect(uri)
- [ 303, {'Content-Length'=>'0', 'Content-Type'=>'text/plain',
- 'Location' => uri},
- [] ]
- end
-
- # Returns an empty 400 response.
-
- def bad_request
- [ 400, {'Content-Type'=>'text/plain', 'Content-Length'=>'0'},
- [''] ]
- end
-
- # Returns a basic unauthorized 401 response.
-
- def unauthorized
- [ 401, {'Content-Type' => 'text/plain', 'Content-Length' => '13'},
- ['Unauthorized.'] ]
- end
-
- # Returns a basic access denied 403 response.
-
- def access_denied
- [ 403, {'Content-Type' => 'text/plain', 'Content-Length' => '14'},
- ['Access denied.'] ]
- end
-
- # Returns a 503 response to be used if communication with the remote
- # OpenID server fails.
-
- def foreign_server_failure
- [ 503, {'Content-Type'=>'text/plain', 'Content-Length' => '23'},
- ['Foreign server failure.'] ]
- end
-
- private
-
- ### These methods are called after a transaction is completed, depending
- # on its outcome. These should all return a rack compatible response.
- # You'd want to override these to provide additional functionality.
-
- # Called to complete processing on a successful transaction.
- # Within the openid session, :openid_identity and :openid_identifier are
- # set to the user friendly and the standard representation of the
- # validated identity. All other data in the openid session is cleared.
-
- def success(oid, request, session)
- session.clear
- session[:openid_identity] = oid.display_identifier
- session[:openid_identifier] = oid.identity_url
- extensions.keys.each do |ext|
- label = ext.name[/[^:]+$/].downcase
- response = ext::Response.from_success_response(oid)
- session[label] = response.data
- end
- redirect(realm)
- end
-
- # Called if the Identity Provider indicates further setup by the user is
- # required.
- # The identifier is retrived from the openid session at :openid_param.
- # And :setup_needed is set to true to prevent looping.
-
- def setup_needed(oid, request, session)
- identifier = session[:openid_param]
- session[:setup_needed] = true
- redirect req.script_name + '?' + openid_param + '=' + identifier
- end
-
- # Called if the user indicates they wish to cancel identification.
- # Data within openid session is cleared.
-
- def cancel(oid, request, session)
- session.clear
- access_denied
- end
-
- # Called if the Identity Provider indicates the user is unable to confirm
- # their identity. Data within the openid session is left alone, in case
- # of swarm auth attacks.
-
- def failure(oid, request, session)
- unauthorized
- end
- end
-
- # A class developed out of the request to use OpenID as an authentication
- # middleware. The request will be sent to the OpenID instance unless the
- # block evaluates to true. For example in rackup, you can use it as such:
- #
- # use Rack::Session::Pool
- # use Rack::Auth::OpenIDAuth, realm, openid_options do |env|
- # env['rack.session'][:authkey] == a_string
- # end
- # run RackApp
- #
- # Or simply:
- #
- # app = Rack::Auth::OpenIDAuth.new app, realm, openid_options, &auth
-
- class OpenIDAuth < Rack::Auth::AbstractHandler
- attr_reader :oid
- def initialize(app, realm, options={}, &auth)
- @oid = OpenID.new(realm, options)
- super(app, &auth)
- end
-
- def call(env)
- to = auth.call(env) ? @app : @oid
- to.call env
- end
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/builder.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/builder.rb
deleted file mode 100644
index 295235e56a..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/builder.rb
+++ /dev/null
@@ -1,63 +0,0 @@
-module Rack
- # Rack::Builder implements a small DSL to iteratively construct Rack
- # applications.
- #
- # Example:
- #
- # app = Rack::Builder.new {
- # use Rack::CommonLogger
- # use Rack::ShowExceptions
- # map "/lobster" do
- # use Rack::Lint
- # run Rack::Lobster.new
- # end
- # }
- #
- # Or
- #
- # app = Rack::Builder.app do
- # use Rack::CommonLogger
- # lambda { |env| [200, {'Content-Type' => 'text/plain'}, 'OK'] }
- # end
- #
- # +use+ adds a middleware to the stack, +run+ dispatches to an application.
- # You can use +map+ to construct a Rack::URLMap in a convenient way.
-
- class Builder
- def initialize(&block)
- @ins = []
- instance_eval(&block) if block_given?
- end
-
- def self.app(&block)
- self.new(&block).to_app
- end
-
- def use(middleware, *args, &block)
- @ins << lambda { |app| middleware.new(app, *args, &block) }
- end
-
- def run(app)
- @ins << app #lambda { |nothing| app }
- end
-
- def map(path, &block)
- if @ins.last.kind_of? Hash
- @ins.last[path] = self.class.new(&block).to_app
- else
- @ins << {}
- map(path, &block)
- end
- end
-
- def to_app
- @ins[-1] = Rack::URLMap.new(@ins.last) if Hash === @ins.last
- inner_app = @ins.last
- @ins[0...-1].reverse.inject(inner_app) { |a, e| e.call(a) }
- end
-
- def call(env)
- to_app.call(env)
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/cascade.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/cascade.rb
deleted file mode 100644
index a038aa1105..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/cascade.rb
+++ /dev/null
@@ -1,36 +0,0 @@
-module Rack
- # Rack::Cascade tries an request on several apps, and returns the
- # first response that is not 404 (or in a list of configurable
- # status codes).
-
- class Cascade
- attr_reader :apps
-
- def initialize(apps, catch=404)
- @apps = apps
- @catch = [*catch]
- end
-
- def call(env)
- status = headers = body = nil
- raise ArgumentError, "empty cascade" if @apps.empty?
- @apps.each { |app|
- begin
- status, headers, body = app.call(env)
- break unless @catch.include?(status.to_i)
- end
- }
- [status, headers, body]
- end
-
- def add app
- @apps << app
- end
-
- def include? app
- @apps.include? app
- end
-
- alias_method :<<, :add
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/chunked.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/chunked.rb
deleted file mode 100644
index 280d89dd65..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/chunked.rb
+++ /dev/null
@@ -1,49 +0,0 @@
-require 'rack/utils'
-
-module Rack
-
- # Middleware that applies chunked transfer encoding to response bodies
- # when the response does not include a Content-Length header.
- class Chunked
- include Rack::Utils
-
- def initialize(app)
- @app = app
- end
-
- def call(env)
- status, headers, body = @app.call(env)
- headers = HeaderHash.new(headers)
-
- if env['HTTP_VERSION'] == 'HTTP/1.0' ||
- STATUS_WITH_NO_ENTITY_BODY.include?(status) ||
- headers['Content-Length'] ||
- headers['Transfer-Encoding']
- [status, headers.to_hash, body]
- else
- dup.chunk(status, headers, body)
- end
- end
-
- def chunk(status, headers, body)
- @body = body
- headers.delete('Content-Length')
- headers['Transfer-Encoding'] = 'chunked'
- [status, headers.to_hash, self]
- end
-
- def each
- term = "\r\n"
- @body.each do |chunk|
- size = bytesize(chunk)
- next if size == 0
- yield [size.to_s(16), term, chunk, term].join
- end
- yield ["0", term, "", term].join
- end
-
- def close
- @body.close if @body.respond_to?(:close)
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/commonlogger.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/commonlogger.rb
deleted file mode 100644
index 5e68ac626d..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/commonlogger.rb
+++ /dev/null
@@ -1,61 +0,0 @@
-module Rack
- # Rack::CommonLogger forwards every request to an +app+ given, and
- # logs a line in the Apache common log format to the +logger+, or
- # rack.errors by default.
-
- class CommonLogger
- def initialize(app, logger=nil)
- @app = app
- @logger = logger
- end
-
- def call(env)
- dup._call(env)
- end
-
- def _call(env)
- @env = env
- @logger ||= self
- @time = Time.now
- @status, @header, @body = @app.call(env)
- [@status, @header, self]
- end
-
- def close
- @body.close if @body.respond_to? :close
- end
-
- # By default, log to rack.errors.
- def <<(str)
- @env["rack.errors"].write(str)
- @env["rack.errors"].flush
- end
-
- def each
- length = 0
- @body.each { |part|
- length += part.size
- yield part
- }
-
- @now = Time.now
-
- # Common Log Format: http://httpd.apache.org/docs/1.3/logs.html#common
- # lilith.local - - [07/Aug/2006 23:58:02] "GET / HTTP/1.1" 500 -
- # %{%s - %s [%s] "%s %s%s %s" %d %s\n} %
- @logger << %{%s - %s [%s] "%s %s%s %s" %d %s %0.4f\n} %
- [
- @env['HTTP_X_FORWARDED_FOR'] || @env["REMOTE_ADDR"] || "-",
- @env["REMOTE_USER"] || "-",
- @now.strftime("%d/%b/%Y %H:%M:%S"),
- @env["REQUEST_METHOD"],
- @env["PATH_INFO"],
- @env["QUERY_STRING"].empty? ? "" : "?"+@env["QUERY_STRING"],
- @env["HTTP_VERSION"],
- @status.to_s[0..3],
- (length.zero? ? "-" : length.to_s),
- @now - @time
- ]
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/conditionalget.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/conditionalget.rb
deleted file mode 100644
index 046ebdb00a..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/conditionalget.rb
+++ /dev/null
@@ -1,47 +0,0 @@
-require 'rack/utils'
-
-module Rack
-
- # Middleware that enables conditional GET using If-None-Match and
- # If-Modified-Since. The application should set either or both of the
- # Last-Modified or Etag response headers according to RFC 2616. When
- # either of the conditions is met, the response body is set to be zero
- # length and the response status is set to 304 Not Modified.
- #
- # Applications that defer response body generation until the body's each
- # message is received will avoid response body generation completely when
- # a conditional GET matches.
- #
- # Adapted from Michael Klishin's Merb implementation:
- # http://github.com/wycats/merb-core/tree/master/lib/merb-core/rack/middleware/conditional_get.rb
- class ConditionalGet
- def initialize(app)
- @app = app
- end
-
- def call(env)
- return @app.call(env) unless %w[GET HEAD].include?(env['REQUEST_METHOD'])
-
- status, headers, body = @app.call(env)
- headers = Utils::HeaderHash.new(headers)
- if etag_matches?(env, headers) || modified_since?(env, headers)
- status = 304
- headers.delete('Content-Type')
- headers.delete('Content-Length')
- body = []
- end
- [status, headers, body]
- end
-
- private
- def etag_matches?(env, headers)
- etag = headers['Etag'] and etag == env['HTTP_IF_NONE_MATCH']
- end
-
- def modified_since?(env, headers)
- last_modified = headers['Last-Modified'] and
- last_modified == env['HTTP_IF_MODIFIED_SINCE']
- end
- end
-
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/content_length.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/content_length.rb
deleted file mode 100644
index 1e56d43853..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/content_length.rb
+++ /dev/null
@@ -1,29 +0,0 @@
-require 'rack/utils'
-
-module Rack
- # Sets the Content-Length header on responses with fixed-length bodies.
- class ContentLength
- include Rack::Utils
-
- def initialize(app)
- @app = app
- end
-
- def call(env)
- status, headers, body = @app.call(env)
- headers = HeaderHash.new(headers)
-
- if !STATUS_WITH_NO_ENTITY_BODY.include?(status) &&
- !headers['Content-Length'] &&
- !headers['Transfer-Encoding'] &&
- (body.respond_to?(:to_ary) || body.respond_to?(:to_str))
-
- body = [body] if body.respond_to?(:to_str) # rack 0.4 compat
- length = body.to_ary.inject(0) { |len, part| len + bytesize(part) }
- headers['Content-Length'] = length.to_s
- end
-
- [status, headers, body]
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/content_type.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/content_type.rb
deleted file mode 100644
index 0c1e1ca3e1..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/content_type.rb
+++ /dev/null
@@ -1,23 +0,0 @@
-require 'rack/utils'
-
-module Rack
-
- # Sets the Content-Type header on responses which don't have one.
- #
- # Builder Usage:
- # use Rack::ContentType, "text/plain"
- #
- # When no content type argument is provided, "text/html" is assumed.
- class ContentType
- def initialize(app, content_type = "text/html")
- @app, @content_type = app, content_type
- end
-
- def call(env)
- status, headers, body = @app.call(env)
- headers = Utils::HeaderHash.new(headers)
- headers['Content-Type'] ||= @content_type
- [status, headers.to_hash, body]
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/deflater.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/deflater.rb
deleted file mode 100644
index 14137a944d..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/deflater.rb
+++ /dev/null
@@ -1,96 +0,0 @@
-require "zlib"
-require "stringio"
-require "time" # for Time.httpdate
-require 'rack/utils'
-
-module Rack
- class Deflater
- def initialize(app)
- @app = app
- end
-
- def call(env)
- status, headers, body = @app.call(env)
- headers = Utils::HeaderHash.new(headers)
-
- # Skip compressing empty entity body responses and responses with
- # no-transform set.
- if Utils::STATUS_WITH_NO_ENTITY_BODY.include?(status) ||
- headers['Cache-Control'].to_s =~ /\bno-transform\b/
- return [status, headers, body]
- end
-
- request = Request.new(env)
-
- encoding = Utils.select_best_encoding(%w(gzip deflate identity),
- request.accept_encoding)
-
- # Set the Vary HTTP header.
- vary = headers["Vary"].to_s.split(",").map { |v| v.strip }
- unless vary.include?("*") || vary.include?("Accept-Encoding")
- headers["Vary"] = vary.push("Accept-Encoding").join(",")
- end
-
- case encoding
- when "gzip"
- headers['Content-Encoding'] = "gzip"
- headers.delete('Content-Length')
- mtime = headers.key?("Last-Modified") ?
- Time.httpdate(headers["Last-Modified"]) : Time.now
- [status, headers, GzipStream.new(body, mtime)]
- when "deflate"
- headers['Content-Encoding'] = "deflate"
- headers.delete('Content-Length')
- [status, headers, DeflateStream.new(body)]
- when "identity"
- [status, headers, body]
- when nil
- message = "An acceptable encoding for the requested resource #{request.fullpath} could not be found."
- [406, {"Content-Type" => "text/plain", "Content-Length" => message.length.to_s}, [message]]
- end
- end
-
- class GzipStream
- def initialize(body, mtime)
- @body = body
- @mtime = mtime
- end
-
- def each(&block)
- @writer = block
- gzip =::Zlib::GzipWriter.new(self)
- gzip.mtime = @mtime
- @body.each { |part| gzip << part }
- @body.close if @body.respond_to?(:close)
- gzip.close
- @writer = nil
- end
-
- def write(data)
- @writer.call(data)
- end
- end
-
- class DeflateStream
- DEFLATE_ARGS = [
- Zlib::DEFAULT_COMPRESSION,
- # drop the zlib header which causes both Safari and IE to choke
- -Zlib::MAX_WBITS,
- Zlib::DEF_MEM_LEVEL,
- Zlib::DEFAULT_STRATEGY
- ]
-
- def initialize(body)
- @body = body
- end
-
- def each
- deflater = ::Zlib::Deflate.new(*DEFLATE_ARGS)
- @body.each { |part| yield deflater.deflate(part) }
- @body.close if @body.respond_to?(:close)
- yield deflater.finish
- nil
- end
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/directory.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/directory.rb
deleted file mode 100644
index acdd3029d3..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/directory.rb
+++ /dev/null
@@ -1,153 +0,0 @@
-require 'time'
-require 'rack/utils'
-require 'rack/mime'
-
-module Rack
- # Rack::Directory serves entries below the +root+ given, according to the
- # path info of the Rack request. If a directory is found, the file's contents
- # will be presented in an html based index. If a file is found, the env will
- # be passed to the specified +app+.
- #
- # If +app+ is not specified, a Rack::File of the same +root+ will be used.
-
- class Directory
- DIR_FILE = "
-
-
- PAGE
-
- attr_reader :files
- attr_accessor :root, :path
-
- def initialize(root, app=nil)
- @root = F.expand_path(root)
- @app = app || Rack::File.new(@root)
- end
-
- def call(env)
- dup._call(env)
- end
-
- F = ::File
-
- def _call(env)
- @env = env
- @script_name = env['SCRIPT_NAME']
- @path_info = Utils.unescape(env['PATH_INFO'])
-
- if forbidden = check_forbidden
- forbidden
- else
- @path = F.join(@root, @path_info)
- list_path
- end
- end
-
- def check_forbidden
- return unless @path_info.include? ".."
-
- body = "Forbidden\n"
- size = Rack::Utils.bytesize(body)
- return [403, {"Content-Type" => "text/plain","Content-Length" => size.to_s}, [body]]
- end
-
- def list_directory
- @files = [['../','Parent Directory','','','']]
- glob = F.join(@path, '*')
-
- Dir[glob].sort.each do |node|
- stat = stat(node)
- next unless stat
- basename = F.basename(node)
- ext = F.extname(node)
-
- url = F.join(@script_name, @path_info, basename)
- size = stat.size
- type = stat.directory? ? 'directory' : Mime.mime_type(ext)
- size = stat.directory? ? '-' : filesize_format(size)
- mtime = stat.mtime.httpdate
- url << '/' if stat.directory?
- basename << '/' if stat.directory?
-
- @files << [ url, basename, size, type, mtime ]
- end
-
- return [ 200, {'Content-Type'=>'text/html; charset=utf-8'}, self ]
- end
-
- def stat(node, max = 10)
- F.stat(node)
- rescue Errno::ENOENT, Errno::ELOOP
- return nil
- end
-
- # TODO: add correct response if not readable, not sure if 404 is the best
- # option
- def list_path
- @stat = F.stat(@path)
-
- if @stat.readable?
- return @app.call(@env) if @stat.file?
- return list_directory if @stat.directory?
- else
- raise Errno::ENOENT, 'No such file or directory'
- end
-
- rescue Errno::ENOENT, Errno::ELOOP
- return entity_not_found
- end
-
- def entity_not_found
- body = "Entity not found: #{@path_info}\n"
- size = Rack::Utils.bytesize(body)
- return [404, {"Content-Type" => "text/plain", "Content-Length" => size.to_s}, [body]]
- end
-
- def each
- show_path = @path.sub(/^#{@root}/,'')
- files = @files.map{|f| DIR_FILE % f }*"\n"
- page = DIR_PAGE % [ show_path, show_path , files ]
- page.each_line{|l| yield l }
- end
-
- # Stolen from Ramaze
-
- FILESIZE_FORMAT = [
- ['%.1fT', 1 << 40],
- ['%.1fG', 1 << 30],
- ['%.1fM', 1 << 20],
- ['%.1fK', 1 << 10],
- ]
-
- def filesize_format(int)
- FILESIZE_FORMAT.each do |format, size|
- return format % (int.to_f / size) if int >= size
- end
-
- int.to_s + 'B'
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/file.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/file.rb
deleted file mode 100644
index fe62bd6b86..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/file.rb
+++ /dev/null
@@ -1,88 +0,0 @@
-require 'time'
-require 'rack/utils'
-require 'rack/mime'
-
-module Rack
- # Rack::File serves files below the +root+ given, according to the
- # path info of the Rack request.
- #
- # Handlers can detect if bodies are a Rack::File, and use mechanisms
- # like sendfile on the +path+.
-
- class File
- attr_accessor :root
- attr_accessor :path
-
- alias :to_path :path
-
- def initialize(root)
- @root = root
- end
-
- def call(env)
- dup._call(env)
- end
-
- F = ::File
-
- def _call(env)
- @path_info = Utils.unescape(env["PATH_INFO"])
- return forbidden if @path_info.include? ".."
-
- @path = F.join(@root, @path_info)
-
- begin
- if F.file?(@path) && F.readable?(@path)
- serving
- else
- raise Errno::EPERM
- end
- rescue SystemCallError
- not_found
- end
- end
-
- def forbidden
- body = "Forbidden\n"
- [403, {"Content-Type" => "text/plain",
- "Content-Length" => body.size.to_s},
- [body]]
- end
-
- # NOTE:
- # We check via File::size? whether this file provides size info
- # via stat (e.g. /proc files often don't), otherwise we have to
- # figure it out by reading the whole file into memory. And while
- # we're at it we also use this as body then.
-
- def serving
- if size = F.size?(@path)
- body = self
- else
- body = [F.read(@path)]
- size = Utils.bytesize(body.first)
- end
-
- [200, {
- "Last-Modified" => F.mtime(@path).httpdate,
- "Content-Type" => Mime.mime_type(F.extname(@path), 'text/plain'),
- "Content-Length" => size.to_s
- }, body]
- end
-
- def not_found
- body = "File not found: #{@path_info}\n"
- [404, {"Content-Type" => "text/plain",
- "Content-Length" => body.size.to_s},
- [body]]
- end
-
- def each
- F.open(@path, "rb") { |file|
- while part = file.read(8192)
- yield part
- end
- }
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/handler.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/handler.rb
deleted file mode 100644
index 5624a1e79d..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/handler.rb
+++ /dev/null
@@ -1,69 +0,0 @@
-module Rack
- # *Handlers* connect web servers with Rack.
- #
- # Rack includes Handlers for Mongrel, WEBrick, FastCGI, CGI, SCGI
- # and LiteSpeed.
- #
- # Handlers usually are activated by calling MyHandler.run(myapp).
- # A second optional hash can be passed to include server-specific
- # configuration.
- module Handler
- def self.get(server)
- return unless server
- server = server.to_s
-
- if klass = @handlers[server]
- obj = Object
- klass.split("::").each { |x| obj = obj.const_get(x) }
- obj
- else
- try_require('rack/handler', server)
- const_get(server)
- end
- end
-
- # Transforms server-name constants to their canonical form as filenames,
- # then tries to require them but silences the LoadError if not found
- #
- # Naming convention:
- #
- # Foo # => 'foo'
- # FooBar # => 'foo_bar.rb'
- # FooBAR # => 'foobar.rb'
- # FOObar # => 'foobar.rb'
- # FOOBAR # => 'foobar.rb'
- # FooBarBaz # => 'foo_bar_baz.rb'
- def self.try_require(prefix, const_name)
- file = const_name.gsub(/^[A-Z]+/) { |pre| pre.downcase }.
- gsub(/[A-Z]+[^A-Z]/, '_\&').downcase
-
- require(::File.join(prefix, file))
- rescue LoadError
- end
-
- def self.register(server, klass)
- @handlers ||= {}
- @handlers[server] = klass
- end
-
- autoload :CGI, "rack/handler/cgi"
- autoload :FastCGI, "rack/handler/fastcgi"
- autoload :Mongrel, "rack/handler/mongrel"
- autoload :EventedMongrel, "rack/handler/evented_mongrel"
- autoload :SwiftipliedMongrel, "rack/handler/swiftiplied_mongrel"
- autoload :WEBrick, "rack/handler/webrick"
- autoload :LSWS, "rack/handler/lsws"
- autoload :SCGI, "rack/handler/scgi"
- autoload :Thin, "rack/handler/thin"
-
- register 'cgi', 'Rack::Handler::CGI'
- register 'fastcgi', 'Rack::Handler::FastCGI'
- register 'mongrel', 'Rack::Handler::Mongrel'
- register 'emongrel', 'Rack::Handler::EventedMongrel'
- register 'smongrel', 'Rack::Handler::SwiftipliedMongrel'
- register 'webrick', 'Rack::Handler::WEBrick'
- register 'lsws', 'Rack::Handler::LSWS'
- register 'scgi', 'Rack::Handler::SCGI'
- register 'thin', 'Rack::Handler::Thin'
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/handler/cgi.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/handler/cgi.rb
deleted file mode 100644
index f45f3d735a..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/handler/cgi.rb
+++ /dev/null
@@ -1,61 +0,0 @@
-require 'rack/content_length'
-
-module Rack
- module Handler
- class CGI
- def self.run(app, options=nil)
- serve app
- end
-
- def self.serve(app)
- app = ContentLength.new(app)
-
- env = ENV.to_hash
- env.delete "HTTP_CONTENT_LENGTH"
-
- env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/"
-
- env.update({"rack.version" => [1,0],
- "rack.input" => $stdin,
- "rack.errors" => $stderr,
-
- "rack.multithread" => false,
- "rack.multiprocess" => true,
- "rack.run_once" => true,
-
- "rack.url_scheme" => ["yes", "on", "1"].include?(ENV["HTTPS"]) ? "https" : "http"
- })
-
- env["QUERY_STRING"] ||= ""
- env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"]
- env["REQUEST_PATH"] ||= "/"
-
- status, headers, body = app.call(env)
- begin
- send_headers status, headers
- send_body body
- ensure
- body.close if body.respond_to? :close
- end
- end
-
- def self.send_headers(status, headers)
- STDOUT.print "Status: #{status}\r\n"
- headers.each { |k, vs|
- vs.split("\n").each { |v|
- STDOUT.print "#{k}: #{v}\r\n"
- }
- }
- STDOUT.print "\r\n"
- STDOUT.flush
- end
-
- def self.send_body(body)
- body.each { |part|
- STDOUT.print part
- STDOUT.flush
- }
- end
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/handler/evented_mongrel.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/handler/evented_mongrel.rb
deleted file mode 100644
index 0f5cbf7293..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/handler/evented_mongrel.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-require 'swiftcore/evented_mongrel'
-
-module Rack
- module Handler
- class EventedMongrel < Handler::Mongrel
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/handler/fastcgi.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/handler/fastcgi.rb
deleted file mode 100644
index 11e1fcaa74..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/handler/fastcgi.rb
+++ /dev/null
@@ -1,88 +0,0 @@
-require 'fcgi'
-require 'socket'
-require 'rack/content_length'
-require 'rack/rewindable_input'
-
-class FCGI::Stream
- alias _rack_read_without_buffer read
-
- def read(n, buffer=nil)
- buf = _rack_read_without_buffer n
- buffer.replace(buf.to_s) if buffer
- buf
- end
-end
-
-module Rack
- module Handler
- class FastCGI
- def self.run(app, options={})
- file = options[:File] and STDIN.reopen(UNIXServer.new(file))
- port = options[:Port] and STDIN.reopen(TCPServer.new(port))
- FCGI.each { |request|
- serve request, app
- }
- end
-
- def self.serve(request, app)
- app = Rack::ContentLength.new(app)
-
- env = request.env
- env.delete "HTTP_CONTENT_LENGTH"
-
- env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/"
-
- rack_input = RewindableInput.new(request.in)
-
- env.update({"rack.version" => [1,0],
- "rack.input" => rack_input,
- "rack.errors" => request.err,
-
- "rack.multithread" => false,
- "rack.multiprocess" => true,
- "rack.run_once" => false,
-
- "rack.url_scheme" => ["yes", "on", "1"].include?(env["HTTPS"]) ? "https" : "http"
- })
-
- env["QUERY_STRING"] ||= ""
- env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"]
- env["REQUEST_PATH"] ||= "/"
- env.delete "PATH_INFO" if env["PATH_INFO"] == ""
- env.delete "CONTENT_TYPE" if env["CONTENT_TYPE"] == ""
- env.delete "CONTENT_LENGTH" if env["CONTENT_LENGTH"] == ""
-
- begin
- status, headers, body = app.call(env)
- begin
- send_headers request.out, status, headers
- send_body request.out, body
- ensure
- body.close if body.respond_to? :close
- end
- ensure
- rack_input.close
- request.finish
- end
- end
-
- def self.send_headers(out, status, headers)
- out.print "Status: #{status}\r\n"
- headers.each { |k, vs|
- vs.split("\n").each { |v|
- out.print "#{k}: #{v}\r\n"
- }
- }
- out.print "\r\n"
- out.flush
- end
-
- def self.send_body(out, body)
- body.each { |part|
- out.print part
- out.flush
- }
- end
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/handler/lsws.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/handler/lsws.rb
deleted file mode 100644
index 7231336d7b..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/handler/lsws.rb
+++ /dev/null
@@ -1,55 +0,0 @@
-require 'lsapi'
-require 'rack/content_length'
-
-module Rack
- module Handler
- class LSWS
- def self.run(app, options=nil)
- while LSAPI.accept != nil
- serve app
- end
- end
- def self.serve(app)
- app = Rack::ContentLength.new(app)
-
- env = ENV.to_hash
- env.delete "HTTP_CONTENT_LENGTH"
- env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/"
- env.update({"rack.version" => [1,0],
- "rack.input" => StringIO.new($stdin.read.to_s),
- "rack.errors" => $stderr,
- "rack.multithread" => false,
- "rack.multiprocess" => true,
- "rack.run_once" => false,
- "rack.url_scheme" => ["yes", "on", "1"].include?(ENV["HTTPS"]) ? "https" : "http"
- })
- env["QUERY_STRING"] ||= ""
- env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"]
- env["REQUEST_PATH"] ||= "/"
- status, headers, body = app.call(env)
- begin
- send_headers status, headers
- send_body body
- ensure
- body.close if body.respond_to? :close
- end
- end
- def self.send_headers(status, headers)
- print "Status: #{status}\r\n"
- headers.each { |k, vs|
- vs.split("\n").each { |v|
- print "#{k}: #{v}\r\n"
- }
- }
- print "\r\n"
- STDOUT.flush
- end
- def self.send_body(body)
- body.each { |part|
- print part
- STDOUT.flush
- }
- end
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/handler/mongrel.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/handler/mongrel.rb
deleted file mode 100644
index 3a5ef32d4b..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/handler/mongrel.rb
+++ /dev/null
@@ -1,84 +0,0 @@
-require 'mongrel'
-require 'stringio'
-require 'rack/content_length'
-require 'rack/chunked'
-
-module Rack
- module Handler
- class Mongrel < ::Mongrel::HttpHandler
- def self.run(app, options={})
- server = ::Mongrel::HttpServer.new(options[:Host] || '0.0.0.0',
- options[:Port] || 8080)
- # Acts like Rack::URLMap, utilizing Mongrel's own path finding methods.
- # Use is similar to #run, replacing the app argument with a hash of
- # { path=>app, ... } or an instance of Rack::URLMap.
- if options[:map]
- if app.is_a? Hash
- app.each do |path, appl|
- path = '/'+path unless path[0] == ?/
- server.register(path, Rack::Handler::Mongrel.new(appl))
- end
- elsif app.is_a? URLMap
- app.instance_variable_get(:@mapping).each do |(host, path, appl)|
- next if !host.nil? && !options[:Host].nil? && options[:Host] != host
- path = '/'+path unless path[0] == ?/
- server.register(path, Rack::Handler::Mongrel.new(appl))
- end
- else
- raise ArgumentError, "first argument should be a Hash or URLMap"
- end
- else
- server.register('/', Rack::Handler::Mongrel.new(app))
- end
- yield server if block_given?
- server.run.join
- end
-
- def initialize(app)
- @app = Rack::Chunked.new(Rack::ContentLength.new(app))
- end
-
- def process(request, response)
- env = {}.replace(request.params)
- env.delete "HTTP_CONTENT_TYPE"
- env.delete "HTTP_CONTENT_LENGTH"
-
- env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/"
-
- env.update({"rack.version" => [1,0],
- "rack.input" => request.body || StringIO.new(""),
- "rack.errors" => $stderr,
-
- "rack.multithread" => true,
- "rack.multiprocess" => false, # ???
- "rack.run_once" => false,
-
- "rack.url_scheme" => "http",
- })
- env["QUERY_STRING"] ||= ""
- env.delete "PATH_INFO" if env["PATH_INFO"] == ""
-
- status, headers, body = @app.call(env)
-
- begin
- response.status = status.to_i
- response.send_status(nil)
-
- headers.each { |k, vs|
- vs.split("\n").each { |v|
- response.header[k] = v
- }
- }
- response.send_header
-
- body.each { |part|
- response.write part
- response.socket.flush
- }
- ensure
- body.close if body.respond_to? :close
- end
- end
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/handler/scgi.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/handler/scgi.rb
deleted file mode 100644
index 6c4932df95..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/handler/scgi.rb
+++ /dev/null
@@ -1,59 +0,0 @@
-require 'scgi'
-require 'stringio'
-require 'rack/content_length'
-require 'rack/chunked'
-
-module Rack
- module Handler
- class SCGI < ::SCGI::Processor
- attr_accessor :app
-
- def self.run(app, options=nil)
- new(options.merge(:app=>app,
- :host=>options[:Host],
- :port=>options[:Port],
- :socket=>options[:Socket])).listen
- end
-
- def initialize(settings = {})
- @app = Rack::Chunked.new(Rack::ContentLength.new(settings[:app]))
- @log = Object.new
- def @log.info(*args); end
- def @log.error(*args); end
- super(settings)
- end
-
- def process_request(request, input_body, socket)
- env = {}.replace(request)
- env.delete "HTTP_CONTENT_TYPE"
- env.delete "HTTP_CONTENT_LENGTH"
- env["REQUEST_PATH"], env["QUERY_STRING"] = env["REQUEST_URI"].split('?', 2)
- env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"]
- env["PATH_INFO"] = env["REQUEST_PATH"]
- env["QUERY_STRING"] ||= ""
- env["SCRIPT_NAME"] = ""
- env.update({"rack.version" => [1,0],
- "rack.input" => StringIO.new(input_body),
- "rack.errors" => $stderr,
-
- "rack.multithread" => true,
- "rack.multiprocess" => true,
- "rack.run_once" => false,
-
- "rack.url_scheme" => ["yes", "on", "1"].include?(env["HTTPS"]) ? "https" : "http"
- })
- status, headers, body = app.call(env)
- begin
- socket.write("Status: #{status}\r\n")
- headers.each do |k, vs|
- vs.split("\n").each { |v| socket.write("#{k}: #{v}\r\n")}
- end
- socket.write("\r\n")
- body.each {|s| socket.write(s)}
- ensure
- body.close if body.respond_to? :close
- end
- end
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/handler/swiftiplied_mongrel.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/handler/swiftiplied_mongrel.rb
deleted file mode 100644
index 4bafd0b953..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/handler/swiftiplied_mongrel.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-require 'swiftcore/swiftiplied_mongrel'
-
-module Rack
- module Handler
- class SwiftipliedMongrel < Handler::Mongrel
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/handler/thin.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/handler/thin.rb
deleted file mode 100644
index 3d4fedff75..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/handler/thin.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-require "thin"
-require "rack/content_length"
-require "rack/chunked"
-
-module Rack
- module Handler
- class Thin
- def self.run(app, options={})
- app = Rack::Chunked.new(Rack::ContentLength.new(app))
- server = ::Thin::Server.new(options[:Host] || '0.0.0.0',
- options[:Port] || 8080,
- app)
- yield server if block_given?
- server.start
- end
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/handler/webrick.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/handler/webrick.rb
deleted file mode 100644
index 2bdc83a9ff..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/handler/webrick.rb
+++ /dev/null
@@ -1,67 +0,0 @@
-require 'webrick'
-require 'stringio'
-require 'rack/content_length'
-
-module Rack
- module Handler
- class WEBrick < ::WEBrick::HTTPServlet::AbstractServlet
- def self.run(app, options={})
- server = ::WEBrick::HTTPServer.new(options)
- server.mount "/", Rack::Handler::WEBrick, app
- trap(:INT) { server.shutdown }
- yield server if block_given?
- server.start
- end
-
- def initialize(server, app)
- super server
- @app = Rack::ContentLength.new(app)
- end
-
- def service(req, res)
- env = req.meta_vars
- env.delete_if { |k, v| v.nil? }
-
- env.update({"rack.version" => [1,0],
- "rack.input" => StringIO.new(req.body.to_s),
- "rack.errors" => $stderr,
-
- "rack.multithread" => true,
- "rack.multiprocess" => false,
- "rack.run_once" => false,
-
- "rack.url_scheme" => ["yes", "on", "1"].include?(ENV["HTTPS"]) ? "https" : "http"
- })
-
- env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"]
- env["QUERY_STRING"] ||= ""
- env["REQUEST_PATH"] ||= "/"
- if env["PATH_INFO"] == ""
- env.delete "PATH_INFO"
- else
- path, n = req.request_uri.path, env["SCRIPT_NAME"].length
- env["PATH_INFO"] = path[n, path.length-n]
- end
-
- status, headers, body = @app.call(env)
- begin
- res.status = status.to_i
- headers.each { |k, vs|
- if k.downcase == "set-cookie"
- res.cookies.concat vs.split("\n")
- else
- vs.split("\n").each { |v|
- res[k] = v
- }
- end
- }
- body.each { |part|
- res.body << part
- }
- ensure
- body.close if body.respond_to? :close
- end
- end
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/head.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/head.rb
deleted file mode 100644
index deab822a99..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/head.rb
+++ /dev/null
@@ -1,19 +0,0 @@
-module Rack
-
-class Head
- def initialize(app)
- @app = app
- end
-
- def call(env)
- status, headers, body = @app.call(env)
-
- if env["REQUEST_METHOD"] == "HEAD"
- [status, headers, []]
- else
- [status, headers, body]
- end
- end
-end
-
-end
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/lint.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/lint.rb
deleted file mode 100644
index bf2e9787a1..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/lint.rb
+++ /dev/null
@@ -1,537 +0,0 @@
-require 'rack/utils'
-
-module Rack
- # Rack::Lint validates your application and the requests and
- # responses according to the Rack spec.
-
- class Lint
- def initialize(app)
- @app = app
- end
-
- # :stopdoc:
-
- class LintError < RuntimeError; end
- module Assertion
- def assert(message, &block)
- unless block.call
- raise LintError, message
- end
- end
- end
- include Assertion
-
- ## This specification aims to formalize the Rack protocol. You
- ## can (and should) use Rack::Lint to enforce it.
- ##
- ## When you develop middleware, be sure to add a Lint before and
- ## after to catch all mistakes.
-
- ## = Rack applications
-
- ## A Rack application is an Ruby object (not a class) that
- ## responds to +call+.
- def call(env=nil)
- dup._call(env)
- end
-
- def _call(env)
- ## It takes exactly one argument, the *environment*
- assert("No env given") { env }
- check_env env
-
- env['rack.input'] = InputWrapper.new(env['rack.input'])
- env['rack.errors'] = ErrorWrapper.new(env['rack.errors'])
-
- ## and returns an Array of exactly three values:
- status, headers, @body = @app.call(env)
- ## The *status*,
- check_status status
- ## the *headers*,
- check_headers headers
- ## and the *body*.
- check_content_type status, headers
- check_content_length status, headers, env
- [status, headers, self]
- end
-
- ## == The Environment
- def check_env(env)
- ## The environment must be an true instance of Hash (no
- ## subclassing allowed) that includes CGI-like headers.
- ## The application is free to modify the environment.
- assert("env #{env.inspect} is not a Hash, but #{env.class}") {
- env.instance_of? Hash
- }
-
- ##
- ## The environment is required to include these variables
- ## (adopted from PEP333), except when they'd be empty, but see
- ## below.
-
- ## REQUEST_METHOD:: The HTTP request method, such as
- ## "GET" or "POST". This cannot ever
- ## be an empty string, and so is
- ## always required.
-
- ## SCRIPT_NAME:: The initial portion of the request
- ## URL's "path" that corresponds to the
- ## application object, so that the
- ## application knows its virtual
- ## "location". This may be an empty
- ## string, if the application corresponds
- ## to the "root" of the server.
-
- ## PATH_INFO:: The remainder of the request URL's
- ## "path", designating the virtual
- ## "location" of the request's target
- ## within the application. This may be an
- ## empty string, if the request URL targets
- ## the application root and does not have a
- ## trailing slash. This value may be
- ## percent-encoded when I originating from
- ## a URL.
-
- ## QUERY_STRING:: The portion of the request URL that
- ## follows the ?, if any. May be
- ## empty, but is always required!
-
- ## SERVER_NAME, SERVER_PORT:: When combined with SCRIPT_NAME and PATH_INFO, these variables can be used to complete the URL. Note, however, that HTTP_HOST, if present, should be used in preference to SERVER_NAME for reconstructing the request URL. SERVER_NAME and SERVER_PORT can never be empty strings, and so are always required.
-
- ## HTTP_ Variables:: Variables corresponding to the
- ## client-supplied HTTP request
- ## headers (i.e., variables whose
- ## names begin with HTTP_). The
- ## presence or absence of these
- ## variables should correspond with
- ## the presence or absence of the
- ## appropriate HTTP header in the
- ## request.
-
- ## In addition to this, the Rack environment must include these
- ## Rack-specific variables:
-
- ## rack.version:: The Array [1,0], representing this version of Rack.
- ## rack.url_scheme:: +http+ or +https+, depending on the request URL.
- ## rack.input:: See below, the input stream.
- ## rack.errors:: See below, the error stream.
- ## rack.multithread:: true if the application object may be simultaneously invoked by another thread in the same process, false otherwise.
- ## rack.multiprocess:: true if an equivalent application object may be simultaneously invoked by another process, false otherwise.
- ## rack.run_once:: true if the server expects (but does not guarantee!) that the application will only be invoked this one time during the life of its containing process. Normally, this will only be true for a server based on CGI (or something similar).
- ##
-
- ## Additional environment specifications have approved to
- ## standardized middleware APIs. None of these are required to
- ## be implemented by the server.
-
- ## rack.session:: A hash like interface for storing request session data.
- ## The store must implement:
- if session = env['rack.session']
- ## store(key, value) (aliased as []=);
- assert("session #{session.inspect} must respond to store and []=") {
- session.respond_to?(:store) && session.respond_to?(:[]=)
- }
-
- ## fetch(key, default = nil) (aliased as []);
- assert("session #{session.inspect} must respond to fetch and []") {
- session.respond_to?(:fetch) && session.respond_to?(:[])
- }
-
- ## delete(key);
- assert("session #{session.inspect} must respond to delete") {
- session.respond_to?(:delete)
- }
-
- ## clear;
- assert("session #{session.inspect} must respond to clear") {
- session.respond_to?(:clear)
- }
- end
-
- ## The server or the application can store their own data in the
- ## environment, too. The keys must contain at least one dot,
- ## and should be prefixed uniquely. The prefix rack.
- ## is reserved for use with the Rack core distribution and other
- ## accepted specifications and must not be used otherwise.
- ##
-
- %w[REQUEST_METHOD SERVER_NAME SERVER_PORT
- QUERY_STRING
- rack.version rack.input rack.errors
- rack.multithread rack.multiprocess rack.run_once].each { |header|
- assert("env missing required key #{header}") { env.include? header }
- }
-
- ## The environment must not contain the keys
- ## HTTP_CONTENT_TYPE or HTTP_CONTENT_LENGTH
- ## (use the versions without HTTP_).
- %w[HTTP_CONTENT_TYPE HTTP_CONTENT_LENGTH].each { |header|
- assert("env contains #{header}, must use #{header[5,-1]}") {
- not env.include? header
- }
- }
-
- ## The CGI keys (named without a period) must have String values.
- env.each { |key, value|
- next if key.include? "." # Skip extensions
- assert("env variable #{key} has non-string value #{value.inspect}") {
- value.instance_of? String
- }
- }
-
- ##
- ## There are the following restrictions:
-
- ## * rack.version must be an array of Integers.
- assert("rack.version must be an Array, was #{env["rack.version"].class}") {
- env["rack.version"].instance_of? Array
- }
- ## * rack.url_scheme must either be +http+ or +https+.
- assert("rack.url_scheme unknown: #{env["rack.url_scheme"].inspect}") {
- %w[http https].include? env["rack.url_scheme"]
- }
-
- ## * There must be a valid input stream in rack.input.
- check_input env["rack.input"]
- ## * There must be a valid error stream in rack.errors.
- check_error env["rack.errors"]
-
- ## * The REQUEST_METHOD must be a valid token.
- assert("REQUEST_METHOD unknown: #{env["REQUEST_METHOD"]}") {
- env["REQUEST_METHOD"] =~ /\A[0-9A-Za-z!\#$%&'*+.^_`|~-]+\z/
- }
-
- ## * The SCRIPT_NAME, if non-empty, must start with /
- assert("SCRIPT_NAME must start with /") {
- !env.include?("SCRIPT_NAME") ||
- env["SCRIPT_NAME"] == "" ||
- env["SCRIPT_NAME"] =~ /\A\//
- }
- ## * The PATH_INFO, if non-empty, must start with /
- assert("PATH_INFO must start with /") {
- !env.include?("PATH_INFO") ||
- env["PATH_INFO"] == "" ||
- env["PATH_INFO"] =~ /\A\//
- }
- ## * The CONTENT_LENGTH, if given, must consist of digits only.
- assert("Invalid CONTENT_LENGTH: #{env["CONTENT_LENGTH"]}") {
- !env.include?("CONTENT_LENGTH") || env["CONTENT_LENGTH"] =~ /\A\d+\z/
- }
-
- ## * One of SCRIPT_NAME or PATH_INFO must be
- ## set. PATH_INFO should be / if
- ## SCRIPT_NAME is empty.
- assert("One of SCRIPT_NAME or PATH_INFO must be set (make PATH_INFO '/' if SCRIPT_NAME is empty)") {
- env["SCRIPT_NAME"] || env["PATH_INFO"]
- }
- ## SCRIPT_NAME never should be /, but instead be empty.
- assert("SCRIPT_NAME cannot be '/', make it '' and PATH_INFO '/'") {
- env["SCRIPT_NAME"] != "/"
- }
- end
-
- ## === The Input Stream
- ##
- ## The input stream is an IO-like object which contains the raw HTTP
- ## POST data. If it is a file then it must be opened in binary mode.
- def check_input(input)
- ## The input stream must respond to +gets+, +each+, +read+ and +rewind+.
- [:gets, :each, :read, :rewind].each { |method|
- assert("rack.input #{input} does not respond to ##{method}") {
- input.respond_to? method
- }
- }
- end
-
- class InputWrapper
- include Assertion
-
- def initialize(input)
- @input = input
- end
-
- def size
- @input.size
- end
-
- ## * +gets+ must be called without arguments and return a string,
- ## or +nil+ on EOF.
- def gets(*args)
- assert("rack.input#gets called with arguments") { args.size == 0 }
- v = @input.gets
- assert("rack.input#gets didn't return a String") {
- v.nil? or v.instance_of? String
- }
- v
- end
-
- ## * +read+ behaves like IO#read. Its signature is read([length, [buffer]]).
- ## If given, +length+ must be an non-negative Integer (>= 0) or +nil+, and +buffer+ must
- ## be a String and may not be nil. If +length+ is given and not nil, then this method
- ## reads at most +length+ bytes from the input stream. If +length+ is not given or nil,
- ## then this method reads all data until EOF.
- ## When EOF is reached, this method returns nil if +length+ is given and not nil, or ""
- ## if +length+ is not given or is nil.
- ## If +buffer+ is given, then the read data will be placed into +buffer+ instead of a
- ## newly created String object.
- def read(*args)
- assert("rack.input#read called with too many arguments") {
- args.size <= 2
- }
- if args.size >= 1
- assert("rack.input#read called with non-integer and non-nil length") {
- args.first.kind_of?(Integer) || args.first.nil?
- }
- assert("rack.input#read called with a negative length") {
- args.first.nil? || args.first >= 0
- }
- end
- if args.size >= 2
- assert("rack.input#read called with non-String buffer") {
- args[1].kind_of?(String)
- }
- end
-
- v = @input.read(*args)
-
- assert("rack.input#read didn't return nil or a String") {
- v.nil? or v.instance_of? String
- }
- if args[0].nil?
- assert("rack.input#read(nil) returned nil on EOF") {
- !v.nil?
- }
- end
-
- v
- end
-
- ## * +each+ must be called without arguments and only yield Strings.
- def each(*args)
- assert("rack.input#each called with arguments") { args.size == 0 }
- @input.each { |line|
- assert("rack.input#each didn't yield a String") {
- line.instance_of? String
- }
- yield line
- }
- end
-
- ## * +rewind+ must be called without arguments. It rewinds the input
- ## stream back to the beginning. It must not raise Errno::ESPIPE:
- ## that is, it may not be a pipe or a socket. Therefore, handler
- ## developers must buffer the input data into some rewindable object
- ## if the underlying input stream is not rewindable.
- def rewind(*args)
- assert("rack.input#rewind called with arguments") { args.size == 0 }
- assert("rack.input#rewind raised Errno::ESPIPE") {
- begin
- @input.rewind
- true
- rescue Errno::ESPIPE
- false
- end
- }
- end
-
- ## * +close+ must never be called on the input stream.
- def close(*args)
- assert("rack.input#close must not be called") { false }
- end
- end
-
- ## === The Error Stream
- def check_error(error)
- ## The error stream must respond to +puts+, +write+ and +flush+.
- [:puts, :write, :flush].each { |method|
- assert("rack.error #{error} does not respond to ##{method}") {
- error.respond_to? method
- }
- }
- end
-
- class ErrorWrapper
- include Assertion
-
- def initialize(error)
- @error = error
- end
-
- ## * +puts+ must be called with a single argument that responds to +to_s+.
- def puts(str)
- @error.puts str
- end
-
- ## * +write+ must be called with a single argument that is a String.
- def write(str)
- assert("rack.errors#write not called with a String") { str.instance_of? String }
- @error.write str
- end
-
- ## * +flush+ must be called without arguments and must be called
- ## in order to make the error appear for sure.
- def flush
- @error.flush
- end
-
- ## * +close+ must never be called on the error stream.
- def close(*args)
- assert("rack.errors#close must not be called") { false }
- end
- end
-
- ## == The Response
-
- ## === The Status
- def check_status(status)
- ## This is an HTTP status. When parsed as integer (+to_i+), it must be
- ## greater than or equal to 100.
- assert("Status must be >=100 seen as integer") { status.to_i >= 100 }
- end
-
- ## === The Headers
- def check_headers(header)
- ## The header must respond to +each+, and yield values of key and value.
- assert("headers object should respond to #each, but doesn't (got #{header.class} as headers)") {
- header.respond_to? :each
- }
- header.each { |key, value|
- ## The header keys must be Strings.
- assert("header key must be a string, was #{key.class}") {
- key.instance_of? String
- }
- ## The header must not contain a +Status+ key,
- assert("header must not contain Status") { key.downcase != "status" }
- ## contain keys with : or newlines in their name,
- assert("header names must not contain : or \\n") { key !~ /[:\n]/ }
- ## contain keys names that end in - or _,
- assert("header names must not end in - or _") { key !~ /[-_]\z/ }
- ## but only contain keys that consist of
- ## letters, digits, _ or - and start with a letter.
- assert("invalid header name: #{key}") { key =~ /\A[a-zA-Z][a-zA-Z0-9_-]*\z/ }
-
- ## The values of the header must be Strings,
- assert("a header value must be a String, but the value of " +
- "'#{key}' is a #{value.class}") { value.kind_of? String }
- ## consisting of lines (for multiple header values, e.g. multiple
- ## Set-Cookie values) seperated by "\n".
- value.split("\n").each { |item|
- ## The lines must not contain characters below 037.
- assert("invalid header value #{key}: #{item.inspect}") {
- item !~ /[\000-\037]/
- }
- }
- }
- end
-
- ## === The Content-Type
- def check_content_type(status, headers)
- headers.each { |key, value|
- ## There must be a Content-Type, except when the
- ## +Status+ is 1xx, 204 or 304, in which case there must be none
- ## given.
- if key.downcase == "content-type"
- assert("Content-Type header found in #{status} response, not allowed") {
- not Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
- }
- return
- end
- }
- assert("No Content-Type header found") {
- Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
- }
- end
-
- ## === The Content-Length
- def check_content_length(status, headers, env)
- headers.each { |key, value|
- if key.downcase == 'content-length'
- ## There must not be a Content-Length header when the
- ## +Status+ is 1xx, 204 or 304.
- assert("Content-Length header found in #{status} response, not allowed") {
- not Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
- }
-
- bytes = 0
- string_body = true
-
- if @body.respond_to?(:to_ary)
- @body.each { |part|
- unless part.kind_of?(String)
- string_body = false
- break
- end
-
- bytes += Rack::Utils.bytesize(part)
- }
-
- if env["REQUEST_METHOD"] == "HEAD"
- assert("Response body was given for HEAD request, but should be empty") {
- bytes == 0
- }
- else
- if string_body
- assert("Content-Length header was #{value}, but should be #{bytes}") {
- value == bytes.to_s
- }
- end
- end
- end
-
- return
- end
- }
- end
-
- ## === The Body
- def each
- @closed = false
- ## The Body must respond to +each+
- @body.each { |part|
- ## and must only yield String values.
- assert("Body yielded non-string value #{part.inspect}") {
- part.instance_of? String
- }
- yield part
- }
- ##
- ## The Body itself should not be an instance of String, as this will
- ## break in Ruby 1.9.
- ##
- ## If the Body responds to +close+, it will be called after iteration.
- # XXX howto: assert("Body has not been closed") { @closed }
-
-
- ##
- ## If the Body responds to +to_path+, it must return a String
- ## identifying the location of a file whose contents are identical
- ## to that produced by calling +each+; this may be used by the
- ## server as an alternative, possibly more efficient way to
- ## transport the response.
-
- if @body.respond_to?(:to_path)
- assert("The file identified by body.to_path does not exist") {
- ::File.exist? @body.to_path
- }
- end
-
- ##
- ## The Body commonly is an Array of Strings, the application
- ## instance itself, or a File-like object.
- end
-
- def close
- @closed = true
- @body.close if @body.respond_to?(:close)
- end
-
- # :startdoc:
-
- end
-end
-
-## == Thanks
-## Some parts of this specification are adopted from PEP333: Python
-## Web Server Gateway Interface
-## v1.0 (http://www.python.org/dev/peps/pep-0333/). I'd like to thank
-## everyone involved in that effort.
diff --git a/actionpack/lib/action_dispatch/vendor/rack/rack/lobster.rb b/actionpack/lib/action_dispatch/vendor/rack/rack/lobster.rb
deleted file mode 100644
index f63f419a49..0000000000
--- a/actionpack/lib/action_dispatch/vendor/rack/rack/lobster.rb
+++ /dev/null
@@ -1,65 +0,0 @@
-require 'zlib'
-
-require 'rack/request'
-require 'rack/response'
-
-module Rack
- # Paste has a Pony, Rack has a Lobster!
- class Lobster
- LobsterString = Zlib::Inflate.inflate("eJx9kEEOwyAMBO99xd7MAcytUhPlJyj2
- P6jy9i4k9EQyGAnBarEXeCBqSkntNXsi/ZCvC48zGQoZKikGrFMZvgS5ZHd+aGWVuWwhVF0
- t1drVmiR42HcWNz5w3QanT+2gIvTVCiE1lm1Y0eU4JGmIIbaKwextKn8rvW+p5PIwFl8ZWJ
- I8jyiTlhTcYXkekJAzTyYN6E08A+dk8voBkAVTJQ==".delete("\n ").unpack("m*")[0])
-
- LambdaLobster = lambda { |env|
- if env["QUERY_STRING"].include?("flip")
- lobster = LobsterString.split("\n").
- map { |line| line.ljust(42).reverse }.
- join("\n")
- href = "?"
- else
- lobster = LobsterString
- href = "?flip"
- end
-
- content = ["Lobstericious!",
- "
\n", @response.body
end
+ # :move: test in AV
def test_render_xml_with_partial
get :builder_partial_test
assert_equal "\n \n\n", @response.body
end
+ # :ported:
def test_layout_rendering
get :layout_test
assert_equal "Hello world!", @response.body
diff --git a/actionpack/test/new_base/render_action_test.rb b/actionpack/test/new_base/render_action_test.rb
index 348d70381b..f25faee433 100644
--- a/actionpack/test/new_base/render_action_test.rb
+++ b/actionpack/test/new_base/render_action_test.rb
@@ -131,8 +131,10 @@ module RenderActionWithApplicationLayout
# Set the view path to an application view structure with layouts
self.view_paths = self.view_paths = [ActionView::Template::FixturePath.new(
"render_action_with_application_layout/basic/hello_world.html.erb" => "Hello World!",
+ "render_action_with_application_layout/basic/hello.html.builder" => "xml.p 'Omg'",
"layouts/application.html.erb" => "OHAI <%= yield %> KTHXBAI",
- "layouts/greetings.html.erb" => "Greetings <%= yield %> Bai"
+ "layouts/greetings.html.erb" => "Greetings <%= yield %> Bai",
+ "layouts/builder.html.builder" => "xml.html do\n xml << yield\nend"
)]
def hello_world
@@ -154,6 +156,10 @@ module RenderActionWithApplicationLayout
def hello_world_with_custom_layout
render :action => "hello_world", :layout => "greetings"
end
+
+ def with_builder_and_layout
+ render :action => "hello", :layout => "builder"
+ end
end
class TestDefaultLayout < SimpleRouteCase
@@ -199,6 +205,15 @@ module RenderActionWithApplicationLayout
assert_status 200
end
+ class TestLayout < SimpleRouteCase
+ testing BasicController
+
+ test "builder works with layouts" do
+ get :with_builder_and_layout
+ assert_response "\n
Omg
\n\n"
+ end
+ end
+
end
module RenderActionWithControllerLayout
diff --git a/actionpack/test/new_base/render_layout_test.rb b/actionpack/test/new_base/render_layout_test.rb
index 7f627f86ec..dc858b4f5c 100644
--- a/actionpack/test/new_base/render_layout_test.rb
+++ b/actionpack/test/new_base/render_layout_test.rb
@@ -22,8 +22,6 @@ module ControllerLayouts
render :layout => false
end
-
-
def builder_override
end
diff --git a/actionpack/test/new_base/render_partial_test.rb b/actionpack/test/new_base/render_partial_test.rb
new file mode 100644
index 0000000000..3a300afe5c
--- /dev/null
+++ b/actionpack/test/new_base/render_partial_test.rb
@@ -0,0 +1,27 @@
+require File.join(File.expand_path(File.dirname(__FILE__)), "test_helper")
+
+module RenderPartial
+
+ class BasicController < ActionController::Base
+
+ self.view_paths = [ActionView::Template::FixturePath.new(
+ "render_partial/basic/_basic.html.erb" => "OMG!",
+ "render_partial/basic/basic.html.erb" => "<%= @test_unchanged = 'goodbye' %><%= render :partial => 'basic' %><%= @test_unchanged %>"
+ )]
+
+ def changing
+ @test_unchanged = 'hello'
+ render :action => "basic"
+ end
+ end
+
+ class TestPartial < SimpleRouteCase
+ testing BasicController
+
+ test "rendering a partial in ActionView doesn't pull the ivars again from the controller" do
+ get :changing
+ assert_response("goodbyeOMG!goodbye")
+ end
+ end
+
+end
\ No newline at end of file
diff --git a/actionpack/test/new_base/render_template_test.rb b/actionpack/test/new_base/render_template_test.rb
index c09eeb1926..6c50ae4203 100644
--- a/actionpack/test/new_base/render_template_test.rb
+++ b/actionpack/test/new_base/render_template_test.rb
@@ -4,14 +4,19 @@ module RenderTemplate
class WithoutLayoutController < ActionController::Base
self.view_paths = [ActionView::Template::FixturePath.new(
- "test/basic.html.erb" => "Hello from basic.html.erb",
- "shared.html.erb" => "Elastica",
- "locals.html.erb" => "The secret is <%= secret %>"
+ "test/basic.html.erb" => "Hello from basic.html.erb",
+ "shared.html.erb" => "Elastica",
+ "locals.html.erb" => "The secret is <%= secret %>",
+ "xml_template.xml.builder" => "xml.html do\n xml.p 'Hello'\nend"
)]
def index
render :template => "test/basic"
end
+
+ def index_without_key
+ render "test/basic"
+ end
def in_top_directory
render :template => 'shared'
@@ -21,41 +26,56 @@ module RenderTemplate
render :template => '/shared'
end
+ def in_top_directory_with_slash_without_key
+ render '/shared'
+ end
+
def with_locals
render :template => "locals", :locals => { :secret => 'area51' }
end
+
+ def builder_template
+ render :template => "xml_template"
+ end
end
class TestWithoutLayout < SimpleRouteCase
- describe "rendering a normal template with full path without layout"
+ testing RenderTemplate::WithoutLayoutController
- get "/render_template/without_layout"
- assert_body "Hello from basic.html.erb"
- assert_status 200
- end
-
- class TestTemplateRenderInTopDirectory < SimpleRouteCase
- describe "rendering a template not in a subdirectory"
+ test "rendering a normal template with full path without layout" do
+ get :index
+ assert_response "Hello from basic.html.erb"
+ end
- get "/render_template/without_layout/in_top_directory"
- assert_body "Elastica"
- assert_status 200
- end
-
- class TestTemplateRenderInTopDirectoryWithSlash < SimpleRouteCase
- describe "rendering a template not in a subdirectory with a leading slash"
+ test "rendering a normal template with full path without layout without key" do
+ get :index_without_key
+ assert_response "Hello from basic.html.erb"
+ end
- get "/render_template/without_layout/in_top_directory_with_slash"
- assert_body "Elastica"
- assert_status 200
- end
-
- class TestTemplateRenderWithLocals < SimpleRouteCase
- describe "rendering a template with local variables"
+ test "rendering a template not in a subdirectory" do
+ get :in_top_directory
+ assert_response "Elastica"
+ end
- get "/render_template/without_layout/with_locals"
- assert_body "The secret is area51"
- assert_status 200
+ test "rendering a template not in a subdirectory with a leading slash" do
+ get :in_top_directory_with_slash
+ assert_response "Elastica"
+ end
+
+ test "rendering a template not in a subdirectory with a leading slash without key" do
+ get :in_top_directory_with_slash_without_key
+ assert_response "Elastica"
+ end
+
+ test "rendering a template with local variables" do
+ get :with_locals
+ assert_response "The secret is area51"
+ end
+
+ test "rendering a builder template" do
+ get :builder_template
+ assert_response "\n
Hello
\n\n"
+ end
end
class WithLayoutController < ::ApplicationController
diff --git a/actionpack/test/new_base/render_xml_test.rb b/actionpack/test/new_base/render_xml_test.rb
new file mode 100644
index 0000000000..e6c40b1533
--- /dev/null
+++ b/actionpack/test/new_base/render_xml_test.rb
@@ -0,0 +1,11 @@
+require File.join(File.expand_path(File.dirname(__FILE__)), "test_helper")
+
+module RenderXml
+
+ # This has no layout and it works
+ class BasicController < ActionController::Base
+ self.view_paths = [ActionView::Template::FixturePath.new(
+ "render_xml/basic/with_render_erb" => "Hello world!"
+ )]
+ end
+end
\ No newline at end of file
diff --git a/actionpack/test/new_base/test_helper.rb b/actionpack/test/new_base/test_helper.rb
index a7302af060..ec7dbffaae 100644
--- a/actionpack/test/new_base/test_helper.rb
+++ b/actionpack/test/new_base/test_helper.rb
@@ -46,7 +46,7 @@ class Rack::TestCase < ActiveSupport::TestCase
ActionController::Routing.use_controllers!(controllers)
# Move into a bootloader
- AbstractController::Base.subclasses.each do |klass|
+ ActionController::Base.subclasses.each do |klass|
klass = klass.constantize
next unless klass < AbstractController::Layouts
klass.class_eval do
--
cgit v1.2.3
From da65320433088548bc4cff33758e5acd71fd137a Mon Sep 17 00:00:00 2001
From: Yehuda Katz + Carl Lerche
Date: Thu, 14 May 2009 17:25:10 -0700
Subject: Got new base to pass controller/base_test.rb, implemented
method_missing action semantics in compatibility mode, and fixed a few
action_missing bugs.
---
actionpack/lib/action_controller/abstract/base.rb | 10 +++++--
.../lib/action_controller/abstract/logger.rb | 33 ++++++++++++++++++++++
.../action_controller/new_base/compatibility.rb | 15 ++++++++++
.../lib/action_controller/new_base/hide_actions.rb | 4 +--
actionpack/lib/action_controller/new_base/http.rb | 5 ----
actionpack/lib/action_controller/routing.rb | 1 +
actionpack/test/abstract_unit.rb | 2 +-
actionpack/test/controller/base_test.rb | 2 +-
8 files changed, 61 insertions(+), 11 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/abstract/base.rb b/actionpack/lib/action_controller/abstract/base.rb
index 8f2bfb5711..483356a4be 100644
--- a/actionpack/lib/action_controller/abstract/base.rb
+++ b/actionpack/lib/action_controller/abstract/base.rb
@@ -67,6 +67,8 @@ module AbstractController
end
def process(action_name)
+ action_name = action_name.to_s
+
unless respond_to_action?(action_name)
raise ActionNotFound, "The action '#{action_name}' could not be found"
end
@@ -82,13 +84,17 @@ module AbstractController
self.class.action_methods
end
+ def action_method?(action)
+ action_methods.include?(action)
+ end
+
# It is possible for respond_to?(action_name) to be false and
# respond_to?(:action_missing) to be false if respond_to_action?
# is overridden in a subclass. For instance, ActionController::Base
# overrides it to include the case where a template matching the
# action_name is found.
def process_action
- if respond_to?(action_name) then send(action_name)
+ if action_method?(action_name) then send(action_name)
elsif respond_to?(:action_missing, true) then action_missing(action_name)
end
end
@@ -98,7 +104,7 @@ module AbstractController
# you must handle it by also overriding process_action and
# handling the case.
def respond_to_action?(action_name)
- action_methods.include?(action_name) || respond_to?(:action_missing, true)
+ action_method?(action_name) || respond_to?(:action_missing, true)
end
end
end
\ No newline at end of file
diff --git a/actionpack/lib/action_controller/abstract/logger.rb b/actionpack/lib/action_controller/abstract/logger.rb
index 5fb78f1755..d0603a4ad7 100644
--- a/actionpack/lib/action_controller/abstract/logger.rb
+++ b/actionpack/lib/action_controller/abstract/logger.rb
@@ -2,8 +2,41 @@ module AbstractController
module Logger
extend ActiveSupport::DependencyModule
+ class DelayedLog
+ def initialize(&blk)
+ @blk = blk
+ end
+
+ def to_s
+ @blk.call
+ end
+ alias to_str to_s
+ end
+
included do
cattr_accessor :logger
end
+
+ def process(action)
+ ret = super
+
+ if logger
+ log = DelayedLog.new do
+ "\n\nProcessing #{self.class.name}\##{action_name} " \
+ "to #{request.formats} " \
+ "(for #{request_origin}) [#{request.method.to_s.upcase}]"
+ end
+
+ logger.info(log)
+ end
+
+ ret
+ end
+
+ def request_origin
+ # this *needs* to be cached!
+ # otherwise you'd get different results if calling it more than once
+ @request_origin ||= "#{request.remote_ip} at #{Time.now.to_s(:db)}"
+ end
end
end
\ No newline at end of file
diff --git a/actionpack/lib/action_controller/new_base/compatibility.rb b/actionpack/lib/action_controller/new_base/compatibility.rb
index d17f498b60..993e571aba 100644
--- a/actionpack/lib/action_controller/new_base/compatibility.rb
+++ b/actionpack/lib/action_controller/new_base/compatibility.rb
@@ -42,6 +42,9 @@ module ActionController
# Controls the resource action separator
cattr_accessor :resource_action_separator
self.resource_action_separator = "/"
+
+ cattr_accessor :use_accept_header
+ self.use_accept_header = true
end
module ClassMethods
@@ -66,6 +69,18 @@ module ActionController
super
end
+
+ def respond_to_action?(action_name)
+ if respond_to?(:method_missing) && !respond_to?(:action_missing)
+ self.class.class_eval do
+ private
+ def action_missing(name, *args)
+ method_missing(name.to_sym, *args)
+ end
+ end
+ end
+ super
+ end
def _layout_for_name(name)
name &&= name.sub(%r{^/?layouts/}, '')
diff --git a/actionpack/lib/action_controller/new_base/hide_actions.rb b/actionpack/lib/action_controller/new_base/hide_actions.rb
index d1857a9169..a29b09a893 100644
--- a/actionpack/lib/action_controller/new_base/hide_actions.rb
+++ b/actionpack/lib/action_controller/new_base/hide_actions.rb
@@ -12,8 +12,8 @@ module ActionController
private
- def respond_to_action?(action_name)
- !hidden_actions.include?(action_name) && (super || respond_to?(:method_missing))
+ def action_method?(action_name)
+ !hidden_actions.include?(action_name) && super
end
module ClassMethods
diff --git a/actionpack/lib/action_controller/new_base/http.rb b/actionpack/lib/action_controller/new_base/http.rb
index fb6041a04e..f3a60b3bf8 100644
--- a/actionpack/lib/action_controller/new_base/http.rb
+++ b/actionpack/lib/action_controller/new_base/http.rb
@@ -21,11 +21,6 @@ module ActionController
# :api: public
def controller_path() self.class.controller_path end
- # :api: private
- def self.internal_methods
- ActionController::Http.public_instance_methods(true)
- end
-
# :api: private
def self.action_names() action_methods end
diff --git a/actionpack/lib/action_controller/routing.rb b/actionpack/lib/action_controller/routing.rb
index c0eb61340b..06a07a4d0a 100644
--- a/actionpack/lib/action_controller/routing.rb
+++ b/actionpack/lib/action_controller/routing.rb
@@ -1,5 +1,6 @@
require 'cgi'
require 'uri'
+require 'set'
require 'action_controller/routing/optimisations'
require 'action_controller/routing/routing_ext'
require 'action_controller/routing/route'
diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb
index 825ac9a46c..7982f06545 100644
--- a/actionpack/test/abstract_unit.rb
+++ b/actionpack/test/abstract_unit.rb
@@ -37,7 +37,7 @@ ActionController::Base.session_store = nil
# Register danish language for testing
I18n.backend.store_translations 'da', {}
I18n.backend.store_translations 'pt-BR', {}
-ORIGINAL_LOCALES = I18n.available_locales.map(&:to_s).sort
+ORIGINAL_LOCALES = I18n.available_locales.map {|locale| locale.to_s }.sort
FIXTURE_LOAD_PATH = File.join(File.dirname(__FILE__), 'fixtures')
ActionController::Base.view_paths = FIXTURE_LOAD_PATH
diff --git a/actionpack/test/controller/base_test.rb b/actionpack/test/controller/base_test.rb
index a09db95d7d..3a4cdb81d9 100644
--- a/actionpack/test/controller/base_test.rb
+++ b/actionpack/test/controller/base_test.rb
@@ -117,7 +117,7 @@ class PerformActionTest < ActionController::TestCase
end
def method_missing(method, *args)
- @logged << args.first
+ @logged << args.first.to_s
end
end
--
cgit v1.2.3
From 628110d7eeb446fee7f9e043f113c083d24883c1 Mon Sep 17 00:00:00 2001
From: Jeremy Kemper
Date: Thu, 14 May 2009 17:42:20 -0700
Subject: Active Support dependencies
---
actionpack/lib/action_view/helpers/active_record_helper.rb | 1 +
actionpack/test/abstract_controller/layouts_test.rb | 1 +
2 files changed, 2 insertions(+)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_view/helpers/active_record_helper.rb b/actionpack/lib/action_view/helpers/active_record_helper.rb
index 7c0dfdab10..b4b9f6e34b 100644
--- a/actionpack/lib/action_view/helpers/active_record_helper.rb
+++ b/actionpack/lib/action_view/helpers/active_record_helper.rb
@@ -1,5 +1,6 @@
require 'cgi'
require 'action_view/helpers/form_helper'
+require 'active_support/core_ext/class/attribute_accessors'
module ActionView
class Base
diff --git a/actionpack/test/abstract_controller/layouts_test.rb b/actionpack/test/abstract_controller/layouts_test.rb
index 6e1c2bf9e8..d3440c3de0 100644
--- a/actionpack/test/abstract_controller/layouts_test.rb
+++ b/actionpack/test/abstract_controller/layouts_test.rb
@@ -1,4 +1,5 @@
require File.join(File.expand_path(File.dirname(__FILE__)), "test_helper")
+require 'active_support/core_ext/class/removal'
module AbstractControllerTests
module Layouts
--
cgit v1.2.3
From eb021707f53be46140b55a48e5ef03ed0577a45c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jos=C3=A9=20Valim?=
Date: Wed, 1 Apr 2009 12:44:56 +0200
Subject: Allow strings to be sent as collection to select.
Signed-off-by: Michael Koziarski
---
.../lib/action_view/helpers/form_options_helper.rb | 2 ++
.../test/template/form_options_helper_test.rb | 22 ++++++++++++++++++++++
2 files changed, 24 insertions(+)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_view/helpers/form_options_helper.rb b/actionpack/lib/action_view/helpers/form_options_helper.rb
index 6b385ef77d..6adbab175f 100644
--- a/actionpack/lib/action_view/helpers/form_options_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_options_helper.rb
@@ -230,6 +230,8 @@ module ActionView
#
# NOTE: Only the option tags are returned, you have to wrap this call in a regular HTML select tag.
def options_for_select(container, selected = nil)
+ return container if String === container
+
container = container.to_a if Hash === container
selected, disabled = extract_selected_and_disabled(selected)
diff --git a/actionpack/test/template/form_options_helper_test.rb b/actionpack/test/template/form_options_helper_test.rb
index 78db87971b..73624406be 100644
--- a/actionpack/test/template/form_options_helper_test.rb
+++ b/actionpack/test/template/form_options_helper_test.rb
@@ -80,6 +80,14 @@ class FormOptionsHelperTest < ActionView::TestCase
)
end
+ def test_string_options_for_select
+ options = ""
+ assert_dom_equal(
+ options,
+ options_for_select(options)
+ )
+ end
+
def test_array_options_for_select
assert_dom_equal(
"\n\n",
@@ -324,6 +332,20 @@ class FormOptionsHelperTest < ActionView::TestCase
)
end
+ def test_select_under_fields_for_with_string_and_given_prompt
+ @post = Post.new
+ options = ""
+
+ fields_for :post, @post do |f|
+ concat f.select(:category, options, :prompt => 'The prompt')
+ end
+
+ assert_dom_equal(
+ "",
+ output_buffer
+ )
+ end
+
def test_select_with_blank
@post = Post.new
@post.category = ""
--
cgit v1.2.3
From 7e10504bdeab14ea70a942110a1b1ef6d8467ed3 Mon Sep 17 00:00:00 2001
From: Yehuda Katz + Carl Lerche
Date: Fri, 15 May 2009 15:57:12 -0700
Subject: Refactored AbstractController to provide better hook points for
overriding aspects of action dispatching
---
actionpack/lib/action_controller/abstract/base.rb | 27 ++++++++++++----------
.../lib/action_controller/abstract/callbacks.rb | 4 ++--
actionpack/lib/action_controller/new_base/base.rb | 16 +++++++++----
.../action_controller/new_base/compatibility.rb | 18 ++++++---------
.../abstract_controller_test.rb | 7 +++---
5 files changed, 39 insertions(+), 33 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/abstract/base.rb b/actionpack/lib/action_controller/abstract/base.rb
index f2db201063..1f2f096dae 100644
--- a/actionpack/lib/action_controller/abstract/base.rb
+++ b/actionpack/lib/action_controller/abstract/base.rb
@@ -69,14 +69,13 @@ module AbstractController
end
def process(action_name)
- action_name = action_name.to_s
+ @_action_name = action_name = action_name.to_s
- unless respond_to_action?(action_name)
+ unless action_name = method_for_action(action_name)
raise ActionNotFound, "The action '#{action_name}' could not be found"
end
-
- @_action_name = action_name
- process_action
+
+ process_action(action_name)
self
end
@@ -95,18 +94,22 @@ module AbstractController
# is overridden in a subclass. For instance, ActionController::Base
# overrides it to include the case where a template matching the
# action_name is found.
- def process_action
- if action_method?(action_name) then send(action_name)
- elsif respond_to?(:action_missing, true) then action_missing(action_name)
- end
+ def process_action(method_name)
+ send(method_name)
end
-
+
+ def _handle_action_missing
+ action_missing(@_action_name)
+ end
+
# Override this to change the conditions that will raise an
# ActionNotFound error. If you accept a difference case,
# you must handle it by also overriding process_action and
# handling the case.
- def respond_to_action?(action_name)
- action_method?(action_name) || respond_to?(:action_missing, true)
+ def method_for_action(action_name)
+ if action_method?(action_name) then action_name
+ elsif respond_to?(:action_missing, true) then "_handle_action_missing"
+ end
end
end
end
\ No newline at end of file
diff --git a/actionpack/lib/action_controller/abstract/callbacks.rb b/actionpack/lib/action_controller/abstract/callbacks.rb
index 3aff83a209..51b968c694 100644
--- a/actionpack/lib/action_controller/abstract/callbacks.rb
+++ b/actionpack/lib/action_controller/abstract/callbacks.rb
@@ -8,8 +8,8 @@ module AbstractController
define_callbacks :process_action, "response_body"
end
- def process_action
- _run_process_action_callbacks(action_name) do
+ def process_action(method_name)
+ _run_process_action_callbacks(method_name) do
super
end
end
diff --git a/actionpack/lib/action_controller/new_base/base.rb b/actionpack/lib/action_controller/new_base/base.rb
index 1adcc9c71f..3ee17769a8 100644
--- a/actionpack/lib/action_controller/new_base/base.rb
+++ b/actionpack/lib/action_controller/new_base/base.rb
@@ -114,14 +114,22 @@ module ActionController
super(url, status)
end
- def process_action
+ def process_action(method_name)
ret = super
render if response_body.nil?
ret
end
-
- def respond_to_action?(action_name)
- super || view_paths.find_by_parts?(action_name.to_s, {:formats => formats, :locales => [I18n.locale]}, controller_path)
+
+ def _implicit_render
+ render
+ end
+
+ def method_for_action(action_name)
+ super || begin
+ if view_paths.find_by_parts?(action_name.to_s, {:formats => formats, :locales => [I18n.locale]}, controller_path)
+ "_implicit_render"
+ end
+ end
end
end
end
\ No newline at end of file
diff --git a/actionpack/lib/action_controller/new_base/compatibility.rb b/actionpack/lib/action_controller/new_base/compatibility.rb
index 993e571aba..9884ed12e5 100644
--- a/actionpack/lib/action_controller/new_base/compatibility.rb
+++ b/actionpack/lib/action_controller/new_base/compatibility.rb
@@ -69,17 +69,13 @@ module ActionController
super
end
-
- def respond_to_action?(action_name)
- if respond_to?(:method_missing) && !respond_to?(:action_missing)
- self.class.class_eval do
- private
- def action_missing(name, *args)
- method_missing(name.to_sym, *args)
- end
- end
- end
- super
+
+ def _handle_method_missing
+ method_missing(@_action_name.to_sym)
+ end
+
+ def method_for_action(action_name)
+ super || (respond_to?(:method_missing) && "_handle_method_missing")
end
def _layout_for_name(name)
diff --git a/actionpack/test/abstract_controller/abstract_controller_test.rb b/actionpack/test/abstract_controller/abstract_controller_test.rb
index 689aa99fd8..9c028e7d1e 100644
--- a/actionpack/test/abstract_controller/abstract_controller_test.rb
+++ b/actionpack/test/abstract_controller/abstract_controller_test.rb
@@ -201,11 +201,10 @@ module AbstractController
def fail() self.response_body = "fail" end
private
-
- def respond_to_action?(action_name)
- action_name.to_s != "fail"
+
+ def method_for_action(action_name)
+ action_name.to_s != "fail" && action_name
end
-
end
class TestRespondToAction < ActiveSupport::TestCase
--
cgit v1.2.3
From 5a45446cff0daf4ca747257a8779dcd5d9cae1d7 Mon Sep 17 00:00:00 2001
From: Yehuda Katz + Carl Lerche
Date: Fri, 15 May 2009 17:49:11 -0700
Subject: Ported Rescuable to new base
---
.../lib/action_controller/base/chained/filters.rb | 2 +-
.../lib/action_controller/dispatch/middlewares.rb | 1 +
actionpack/lib/action_controller/new_base.rb | 1 +
actionpack/lib/action_controller/new_base/base.rb | 50 +++++++++++---------
.../action_controller/new_base/compatibility.rb | 13 ++++++
actionpack/lib/action_controller/new_base/http.rb | 4 +-
.../lib/action_controller/new_base/rescuable.rb | 53 ++++++++++++++++++++++
.../lib/action_controller/new_base/testing.rb | 2 +-
actionpack/test/abstract_unit2.rb | 12 ++++-
9 files changed, 111 insertions(+), 27 deletions(-)
create mode 100644 actionpack/lib/action_controller/new_base/rescuable.rb
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/base/chained/filters.rb b/actionpack/lib/action_controller/base/chained/filters.rb
index 9022b8b279..98fe306fd5 100644
--- a/actionpack/lib/action_controller/base/chained/filters.rb
+++ b/actionpack/lib/action_controller/base/chained/filters.rb
@@ -160,7 +160,7 @@ module ActionController #:nodoc:
def convert_only_and_except_options_to_sets_of_strings(opts)
[:only, :except].each do |key|
if values = opts[key]
- opts[key] = Array(values).map(&:to_s).to_set
+ opts[key] = Array(values).map {|val| val.to_s }.to_set
end
end
end
diff --git a/actionpack/lib/action_controller/dispatch/middlewares.rb b/actionpack/lib/action_controller/dispatch/middlewares.rb
index f99637b109..0e4ab6fa39 100644
--- a/actionpack/lib/action_controller/dispatch/middlewares.rb
+++ b/actionpack/lib/action_controller/dispatch/middlewares.rb
@@ -6,6 +6,7 @@ use "ActionDispatch::Failsafe"
use "ActionDispatch::ShowExceptions", lambda { ActionController::Base.consider_all_requests_local }
use "ActionDispatch::Rescue", lambda {
controller = (::ApplicationController rescue ActionController::Base)
+ # TODO: Replace with controller.action(:_rescue_action)
controller.method(:rescue_action)
}
diff --git a/actionpack/lib/action_controller/new_base.rb b/actionpack/lib/action_controller/new_base.rb
index 1f215bb6f1..bc47713529 100644
--- a/actionpack/lib/action_controller/new_base.rb
+++ b/actionpack/lib/action_controller/new_base.rb
@@ -7,6 +7,7 @@ module ActionController
autoload :Rails2Compatibility, "action_controller/new_base/compatibility"
autoload :Redirector, "action_controller/new_base/redirector"
autoload :Renderer, "action_controller/new_base/renderer"
+ autoload :Rescue, "action_controller/new_base/rescuable"
autoload :Testing, "action_controller/new_base/testing"
autoload :UrlFor, "action_controller/new_base/url_for"
diff --git a/actionpack/lib/action_controller/new_base/base.rb b/actionpack/lib/action_controller/new_base/base.rb
index 3ee17769a8..c25ffd5c84 100644
--- a/actionpack/lib/action_controller/new_base/base.rb
+++ b/actionpack/lib/action_controller/new_base/base.rb
@@ -12,14 +12,40 @@ module ActionController
include ActionController::Renderer
include ActionController::Layouts
include ActionController::ConditionalGet
-
+
# Legacy modules
include SessionManagement
include ActionDispatch::StatusCodes
-
+
# Rails 2.x compatibility
include ActionController::Rails2Compatibility
-
+
+ # TODO: Extract into its own module
+ # This should be moved together with other normalizing behavior
+ module ImplicitRender
+ def process_action(method_name)
+ ret = super
+ render if response_body.nil?
+ ret
+ end
+
+ def _implicit_render
+ render
+ end
+
+ def method_for_action(action_name)
+ super || begin
+ if view_paths.find_by_parts?(action_name.to_s, {:formats => formats, :locales => [I18n.locale]}, controller_path)
+ "_implicit_render"
+ end
+ end
+ end
+ end
+
+ include ImplicitRender
+
+ include ActionController::Rescue
+
def self.inherited(klass)
::ActionController::Base.subclasses << klass.to_s
super
@@ -113,23 +139,5 @@ module ActionController
super(url, status)
end
-
- def process_action(method_name)
- ret = super
- render if response_body.nil?
- ret
- end
-
- def _implicit_render
- render
- end
-
- def method_for_action(action_name)
- super || begin
- if view_paths.find_by_parts?(action_name.to_s, {:formats => formats, :locales => [I18n.locale]}, controller_path)
- "_implicit_render"
- end
- end
- end
end
end
\ No newline at end of file
diff --git a/actionpack/lib/action_controller/new_base/compatibility.rb b/actionpack/lib/action_controller/new_base/compatibility.rb
index 9884ed12e5..0a283887b6 100644
--- a/actionpack/lib/action_controller/new_base/compatibility.rb
+++ b/actionpack/lib/action_controller/new_base/compatibility.rb
@@ -45,6 +45,14 @@ module ActionController
cattr_accessor :use_accept_header
self.use_accept_header = true
+
+ cattr_accessor :page_cache_directory
+ self.page_cache_directory = defined?(Rails.public_path) ? Rails.public_path : ""
+
+ cattr_reader :cache_store
+
+ cattr_accessor :consider_all_requests_local
+ self.consider_all_requests_local = true
end
module ClassMethods
@@ -53,6 +61,11 @@ module ActionController
def rescue_action(env)
raise env["action_dispatch.rescue.exception"]
end
+
+ # Defines the storage option for cached fragments
+ def cache_store=(store_option)
+ @@cache_store = ActiveSupport::Cache.lookup_store(store_option)
+ end
end
def initialize(*)
diff --git a/actionpack/lib/action_controller/new_base/http.rb b/actionpack/lib/action_controller/new_base/http.rb
index e9a1d5b12f..8891a2a8c3 100644
--- a/actionpack/lib/action_controller/new_base/http.rb
+++ b/actionpack/lib/action_controller/new_base/http.rb
@@ -48,8 +48,6 @@ module ActionController
@_response = ActionDispatch::Response.new
@_response.request = request
process(name)
- @_response.body = response_body
- @_response.prepare!
to_rack
end
@@ -62,6 +60,8 @@ module ActionController
# :api: private
def to_rack
+ @_response.body = response_body
+ @_response.prepare!
@_response.to_a
end
end
diff --git a/actionpack/lib/action_controller/new_base/rescuable.rb b/actionpack/lib/action_controller/new_base/rescuable.rb
new file mode 100644
index 0000000000..29ffe19d5f
--- /dev/null
+++ b/actionpack/lib/action_controller/new_base/rescuable.rb
@@ -0,0 +1,53 @@
+module ActionController #:nodoc:
+ # Actions that fail to perform as expected throw exceptions. These
+ # exceptions can either be rescued for the public view (with a nice
+ # user-friendly explanation) or for the developers view (with tons of
+ # debugging information). The developers view is already implemented by
+ # the Action Controller, but the public view should be tailored to your
+ # specific application.
+ #
+ # The default behavior for public exceptions is to render a static html
+ # file with the name of the error code thrown. If no such file exists, an
+ # empty response is sent with the correct status code.
+ #
+ # You can override what constitutes a local request by overriding the
+ # local_request? method in your own controller. Custom rescue
+ # behavior is achieved by overriding the rescue_action_in_public
+ # and rescue_action_locally methods.
+ module Rescue
+ extend ActiveSupport::DependencyModule
+
+ included do
+ include ActiveSupport::Rescuable
+ end
+
+ module ClassMethods
+ # This can be removed once we can move action(:_rescue_action) into middlewares.rb
+ # Currently, it does controller.method(:rescue_action), which is hiding the implementation
+ # difference between the old and new base.
+ def rescue_action(env)
+ action(:_rescue_action).call(env)
+ end
+ end
+
+ attr_internal :rescued_exception
+
+ private
+
+ def method_for_action(action_name)
+ return action_name if self.rescued_exception = request.env.delete("action_dispatch.rescue.exception")
+ super
+ end
+
+ def _rescue_action
+ rescue_with_handler(rescued_exception) || raise(rescued_exception)
+ end
+
+ def process_action(*)
+ super
+ rescue Exception => exception
+ self.rescued_exception = exception
+ _rescue_action
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/new_base/testing.rb b/actionpack/lib/action_controller/new_base/testing.rb
index 106990b9ba..b39d8d539d 100644
--- a/actionpack/lib/action_controller/new_base/testing.rb
+++ b/actionpack/lib/action_controller/new_base/testing.rb
@@ -7,7 +7,7 @@ module ActionController
@_response = response
@_response.request = request
ret = process(request.parameters[:action])
- @_response.body = self.response_body
+ @_response.body = self.response_body || " "
@_response.prepare!
set_test_assigns
ret
diff --git a/actionpack/test/abstract_unit2.rb b/actionpack/test/abstract_unit2.rb
index 932f594ad2..519e6bea36 100644
--- a/actionpack/test/abstract_unit2.rb
+++ b/actionpack/test/abstract_unit2.rb
@@ -11,11 +11,19 @@ require 'action_controller/new_base'
require 'fixture_template'
require 'action_controller/testing/process2'
require 'action_view/test_case'
+require 'action_controller/testing/integration'
+require 'active_support/dependencies'
+
+ActiveSupport::Dependencies.hook!
FIXTURE_LOAD_PATH = File.join(File.dirname(__FILE__), 'fixtures')
module ActionController
-
+ Base.session = {
+ :key => '_testing_session',
+ :secret => '8273f16463985e2b3747dc25e30f2528'
+}
+
class ActionControllerError < StandardError #:nodoc:
end
@@ -126,6 +134,6 @@ module ActionController
"Expected no partials to be rendered"
end
end
- end
+ end
end
end
--
cgit v1.2.3
From 7f318c3ec535afe53733c55cd0ecaccc16a8b944 Mon Sep 17 00:00:00 2001
From: Bryan Helmkamp
Date: Sat, 16 May 2009 14:15:26 -0400
Subject: Instead of checking Rails.env.test? in Failsafe middleware, check
env["rails.raise_exceptions"]
---
actionpack/lib/action_dispatch/middleware/failsafe.rb | 5 ++---
actionpack/test/new_base/render_action_test.rb | 6 ++++--
actionpack/test/new_base/render_test.rb | 6 +++---
3 files changed, 9 insertions(+), 8 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_dispatch/middleware/failsafe.rb b/actionpack/lib/action_dispatch/middleware/failsafe.rb
index 836098482c..389accbc36 100644
--- a/actionpack/lib/action_dispatch/middleware/failsafe.rb
+++ b/actionpack/lib/action_dispatch/middleware/failsafe.rb
@@ -10,9 +10,8 @@ module ActionDispatch
def call(env)
@app.call(env)
rescue Exception => exception
- # Reraise exception in test environment
- if defined?(Rails) && Rails.env.test?
- raise exception
+ if env["rails.raise_exceptions"]
+ raise
else
failsafe_response(exception)
end
diff --git a/actionpack/test/new_base/render_action_test.rb b/actionpack/test/new_base/render_action_test.rb
index f25faee433..96666077d2 100644
--- a/actionpack/test/new_base/render_action_test.rb
+++ b/actionpack/test/new_base/render_action_test.rb
@@ -92,7 +92,7 @@ module RenderAction
test "raises an exception when requesting a layout and none exist" do
assert_raise(ArgumentError, /no default layout for RenderAction::BasicController in/) do
- get "/render_action/basic/hello_world_with_layout"
+ get "/render_action/basic/hello_world_with_layout", {}, "rails.raise_exceptions" => true
end
end
end
@@ -117,7 +117,9 @@ module RenderAction
describe "rendering a normal template with full path with layout => 'greetings'"
test "raises an exception when requesting a layout that does not exist" do
- assert_raise(ActionView::MissingTemplate) { get "/render_action/basic/hello_world_with_custom_layout" }
+ assert_raise(ActionView::MissingTemplate) do
+ get "/render_action/basic/hello_world_with_custom_layout", {}, "rails.raise_exceptions" => true
+ end
end
end
diff --git a/actionpack/test/new_base/render_test.rb b/actionpack/test/new_base/render_test.rb
index b1867fdcc2..16578fbc82 100644
--- a/actionpack/test/new_base/render_test.rb
+++ b/actionpack/test/new_base/render_test.rb
@@ -48,7 +48,7 @@ module Render
test "raises an exception" do
assert_raises(AbstractController::DoubleRenderError) do
- get "/render/double_render"
+ get "/render/double_render", {}, "rails.raise_exceptions" => true
end
end
end
@@ -58,13 +58,13 @@ module Render
test "raises an exception when a method of Object is called" do
assert_raises(AbstractController::ActionNotFound) do
- get "/render/blank_render/clone"
+ get "/render/blank_render/clone", {}, "rails.raise_exceptions" => true
end
end
test "raises an exception when a private method is called" do
assert_raises(AbstractController::ActionNotFound) do
- get "/render/blank_render/secretz"
+ get "/render/blank_render/secretz", {}, "rails.raise_exceptions" => true
end
end
end
--
cgit v1.2.3
From 59c4d9a5b40dca45b095430d43c04d6c6541992d Mon Sep 17 00:00:00 2001
From: Bryan Helmkamp
Date: Sat, 16 May 2009 14:18:10 -0400
Subject: Changelog
---
actionpack/CHANGELOG | 2 ++
1 file changed, 2 insertions(+)
(limited to 'actionpack')
diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG
index 204f5ae272..c1dc6f2ab4 100644
--- a/actionpack/CHANGELOG
+++ b/actionpack/CHANGELOG
@@ -1,5 +1,7 @@
*Edge*
+* Instead of checking Rails.env.test? in Failsafe middleware, check env["rails.raise_exceptions"] [Bryan Helmkamp]
+
* Fixed that TestResponse.cookies was returning cookies unescaped #1867 [Doug McInnes]
--
cgit v1.2.3
From db1bf3650d7450811f5dfddc5c5163a70683e37a Mon Sep 17 00:00:00 2001
From: Yehuda Katz
Date: Sat, 16 May 2009 12:13:41 -0700
Subject: Fix ActionMailer Symbol#to_proc instance
---
actionpack/lib/action_view/template/handlers.rb | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_view/template/handlers.rb b/actionpack/lib/action_view/template/handlers.rb
index 0590372d09..faf54b9fe5 100644
--- a/actionpack/lib/action_view/template/handlers.rb
+++ b/actionpack/lib/action_view/template/handlers.rb
@@ -33,7 +33,7 @@ module ActionView #:nodoc:
end
def template_handler_extensions
- @@template_handlers.keys.map(&:to_s).sort
+ @@template_handlers.keys.map {|key| key.to_s }.sort
end
def registered_template_handler(extension)
--
cgit v1.2.3
From 842dab0c29bb05b98856aeb333bb0c2d14601a50 Mon Sep 17 00:00:00 2001
From: Jeffrey Chupp
Date: Sat, 4 Apr 2009 09:36:32 -0500
Subject: Ensure WhiteListSanitizer allows dl tag [#2393 state:resolved]
Signed-off-by: Pratik Naik
---
actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb b/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb
index ae20f9947c..a992f7d912 100644
--- a/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb
+++ b/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb
@@ -73,7 +73,7 @@ module HTML
# Specifies the default Set of tags that the #sanitize helper will allow unscathed.
self.allowed_tags = Set.new(%w(strong em b i p code pre tt samp kbd var sub
- sup dfn cite big small address hr br div span h1 h2 h3 h4 h5 h6 ul ol li dt dd abbr
+ sup dfn cite big small address hr br div span h1 h2 h3 h4 h5 h6 ul ol li dl dt dd abbr
acronym a img blockquote del ins))
# Specifies the default Set of html attributes that the #sanitize helper will leave
--
cgit v1.2.3
From a9e8c4b37480564d27883dffe9134a9f95796a15 Mon Sep 17 00:00:00 2001
From: Pratik Naik
Date: Sun, 17 May 2009 14:31:54 +0200
Subject: Ensure rake test does not run new base tests as that requires
rack/test
---
actionpack/Rakefile | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'actionpack')
diff --git a/actionpack/Rakefile b/actionpack/Rakefile
index 6ce8179646..41b190130e 100644
--- a/actionpack/Rakefile
+++ b/actionpack/Rakefile
@@ -22,7 +22,7 @@ task :default => [ :test ]
# Run the unit tests
desc "Run all unit tests"
-task :test => [:test_action_pack, :test_active_record_integration, :test_new_base]
+task :test => [:test_action_pack, :test_active_record_integration]
Rake::TestTask.new(:test_action_pack) do |t|
t.libs << "test"
--
cgit v1.2.3
From 53dda29f8b34073a4b135ee224c1d09c1f10de02 Mon Sep 17 00:00:00 2001
From: Brian Lopez
Date: Sun, 17 May 2009 10:37:30 -0500
Subject: Add support for parsing XML and JSON from an IO as well as a string
[#2659 state:resolved]
Signed-off-by: Joshua Peek
---
actionpack/lib/action_dispatch/middleware/params_parser.rb | 8 +++-----
1 file changed, 3 insertions(+), 5 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_dispatch/middleware/params_parser.rb b/actionpack/lib/action_dispatch/middleware/params_parser.rb
index 58d527a6e7..a42c6598e0 100644
--- a/actionpack/lib/action_dispatch/middleware/params_parser.rb
+++ b/actionpack/lib/action_dispatch/middleware/params_parser.rb
@@ -32,16 +32,14 @@ module ActionDispatch
when Proc
strategy.call(request.raw_post)
when :xml_simple, :xml_node
- body = request.raw_post
- body.blank? ? {} : Hash.from_xml(body).with_indifferent_access
+ request.body.size == 0 ? {} : Hash.from_xml(request.body).with_indifferent_access
when :yaml
YAML.load(request.raw_post)
when :json
- body = request.raw_post
- if body.blank?
+ if request.body.size == 0
{}
else
- data = ActiveSupport::JSON.decode(body)
+ data = ActiveSupport::JSON.decode(request.body)
data = {:_json => data} unless data.is_a?(Hash)
data.with_indifferent_access
end
--
cgit v1.2.3
From 11bac700784efe232083f94e3d28d171957e667e Mon Sep 17 00:00:00 2001
From: Lance Ivy
Date: Wed, 15 Apr 2009 16:46:30 -0700
Subject: Ensure auto_link does not ignore multiple trailing punctuations
[#2504 state:resolved]
Signed-off-by: Pratik Naik
---
actionpack/lib/action_view/helpers/text_helper.rb | 13 +++++++------
actionpack/test/template/text_helper_test.rb | 7 +++++++
2 files changed, 14 insertions(+), 6 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_view/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb
index 573b99b96e..8136a1cb13 100644
--- a/actionpack/lib/action_view/helpers/text_helper.rb
+++ b/actionpack/lib/action_view/helpers/text_helper.rb
@@ -535,7 +535,7 @@ module ActionView
link_attributes = html_options.stringify_keys
text.gsub(AUTO_LINK_RE) do
href = $&
- punctuation = ''
+ punctuation = []
left, right = $`, $'
# detect already linked URLs and URLs in the middle of a tag
if left =~ /<[^>]+$/ && right =~ /^[^>]*>/
@@ -543,17 +543,18 @@ module ActionView
href
else
# don't include trailing punctuation character as part of the URL
- if href.sub!(/[^\w\/-]$/, '') and punctuation = $& and opening = BRACKETS[punctuation]
- if href.scan(opening).size > href.scan(punctuation).size
- href << punctuation
- punctuation = ''
+ while href.sub!(/[^\w\/-]$/, '')
+ punctuation.push $&
+ if opening = BRACKETS[punctuation.last] and href.scan(opening).size > href.scan(punctuation.last).size
+ href << punctuation.pop
+ break
end
end
link_text = block_given?? yield(href) : href
href = 'http://' + href unless href.index('http') == 0
- content_tag(:a, h(link_text), link_attributes.merge('href' => href)) + punctuation
+ content_tag(:a, h(link_text), link_attributes.merge('href' => href)) + punctuation.reverse.join('')
end
end
end
diff --git a/actionpack/test/template/text_helper_test.rb b/actionpack/test/template/text_helper_test.rb
index be7163888e..a780bfc606 100644
--- a/actionpack/test/template/text_helper_test.rb
+++ b/actionpack/test/template/text_helper_test.rb
@@ -401,6 +401,13 @@ class TextHelperTest < ActionView::TestCase
auto_link("Welcome to my new blog at http://www.myblog.com/. Please e-mail me at me@email.com.",
:link => :all, :html => { :class => "menu", :target => "_blank" })
end
+
+ def test_auto_link_with_multiple_trailing_punctuations
+ url = "http://youtube.com"
+ url_result = generate_result(url)
+ assert_equal url_result, auto_link(url)
+ assert_equal "(link: #{url_result}).", auto_link("(link: #{url}).")
+ end
def test_cycle_class
value = Cycle.new("one", 2, "3")
--
cgit v1.2.3
From e41984c5f7f38b62c05dfcb54940bf51f6961aeb Mon Sep 17 00:00:00 2001
From: "Thomas E. Glasgow"
Date: Sun, 17 May 2009 18:54:34 +0200
Subject: Simplify filter_chain method implementation [#2327 state:resolved]
Signed-off-by: Pratik Naik
---
actionpack/lib/action_controller/base/chained/filters.rb | 7 +------
1 file changed, 1 insertion(+), 6 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/base/chained/filters.rb b/actionpack/lib/action_controller/base/chained/filters.rb
index 98fe306fd5..e121c0129d 100644
--- a/actionpack/lib/action_controller/base/chained/filters.rb
+++ b/actionpack/lib/action_controller/base/chained/filters.rb
@@ -571,12 +571,7 @@ module ActionController #:nodoc:
# Returns an array of Filter objects for this controller.
def filter_chain
- if chain = read_inheritable_attribute('filter_chain')
- return chain
- else
- write_inheritable_attribute('filter_chain', FilterChain.new)
- return filter_chain
- end
+ read_inheritable_attribute('filter_chain') || write_inheritable_attribute('filter_chain', FilterChain.new)
end
# Returns all the before filters for this class and all its ancestors.
--
cgit v1.2.3
From 98eaa2c6834e418959f2a1a18421e4811167e03b Mon Sep 17 00:00:00 2001
From: Travis Briggs
Date: Wed, 18 Mar 2009 21:51:26 -0400
Subject: Ensure number_to_human_size does not strip zeros from the end [#1763
state:resolved]
Signed-off-by: Pratik Naik
---
actionpack/lib/action_view/helpers/number_helper.rb | 7 ++++++-
actionpack/test/template/number_helper_test.rb | 4 ++++
2 files changed, 10 insertions(+), 1 deletion(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_view/helpers/number_helper.rb b/actionpack/lib/action_view/helpers/number_helper.rb
index c02692b09a..999d5b34fc 100644
--- a/actionpack/lib/action_view/helpers/number_helper.rb
+++ b/actionpack/lib/action_view/helpers/number_helper.rb
@@ -248,6 +248,11 @@ module ActionView
# number_to_human_size(483989, :precision => 0) # => 473 KB
# number_to_human_size(1234567, :precision => 2, :separator => ',') # => 1,18 MB
#
+ # Zeros after the decimal point are always stripped out, regardless of the
+ # specified precision:
+ # helper.number_to_human_size(1234567890123, :precision => 5) # => "1.12283 TB"
+ # helper.number_to_human_size(524288000, :precision=>5) # => "500 MB"
+ #
# You can still use number_to_human_size with the old API that accepts the
# +precision+ as its optional second parameter:
# number_to_human_size(1234567, 2) # => 1.18 MB
@@ -293,7 +298,7 @@ module ActionView
:precision => precision,
:separator => separator,
:delimiter => delimiter
- ).sub(/(\d)(#{escaped_separator}[1-9]*)?0+\z/, '\1\2').sub(/#{escaped_separator}\z/, '')
+ ).sub(/(#{escaped_separator})(\d*[1-9])?0+\z/, '\1\2').sub(/#{escaped_separator}\z/, '')
storage_units_format.gsub(/%n/, formatted_number).gsub(/%u/, unit)
rescue
number
diff --git a/actionpack/test/template/number_helper_test.rb b/actionpack/test/template/number_helper_test.rb
index 29cb60fd73..b6542ef29d 100644
--- a/actionpack/test/template/number_helper_test.rb
+++ b/actionpack/test/template/number_helper_test.rb
@@ -118,6 +118,10 @@ class NumberHelperTest < ActionView::TestCase
assert_equal '1.01 KB', number_to_human_size(1.0123.kilobytes, :precision => 2)
assert_equal '1.01 KB', number_to_human_size(1.0100.kilobytes, :precision => 4)
assert_equal '10 KB', number_to_human_size(10.000.kilobytes, :precision => 4)
+ assert_equal '1 TB', number_to_human_size(1234567890123, :precision => 0)
+ assert_equal '500 MB', number_to_human_size(524288000, :precision=>0)
+ assert_equal '40 KB', number_to_human_size(41010, :precision => 0)
+ assert_equal '40 KB', number_to_human_size(41100, :precision => 0)
end
def test_number_to_human_size_with_custom_delimiter_and_separator
--
cgit v1.2.3
From c3319504f066c9362b4b30e1e15bbd1cadde8e25 Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Sun, 17 May 2009 11:09:14 -0500
Subject: Rescue hack was supposed to be removed. Some how it crept back in.
---
actionpack/lib/action_controller/base/base.rb | 5 ++---
actionpack/lib/action_controller/testing/process.rb | 3 ---
actionpack/test/controller/filters_test.rb | 1 -
actionpack/test/controller/helper_test.rb | 3 ---
4 files changed, 2 insertions(+), 10 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/base/base.rb b/actionpack/lib/action_controller/base/base.rb
index 2813e71d12..c59068c628 100644
--- a/actionpack/lib/action_controller/base/base.rb
+++ b/actionpack/lib/action_controller/base/base.rb
@@ -368,9 +368,8 @@ module ActionController #:nodoc:
attr_reader :template
def action(name, env)
- # HACK: For global rescue to have access to the original request and response
- request = env["action_controller.rescue.request"] ||= ActionDispatch::Request.new(env)
- response = env["action_controller.rescue.response"] ||= ActionDispatch::Response.new
+ request = ActionDispatch::Request.new(env)
+ response = ActionDispatch::Response.new
self.action_name = name && name.to_s
process(request, response).to_a
end
diff --git a/actionpack/lib/action_controller/testing/process.rb b/actionpack/lib/action_controller/testing/process.rb
index 8f4358c33e..8831ff57e2 100644
--- a/actionpack/lib/action_controller/testing/process.rb
+++ b/actionpack/lib/action_controller/testing/process.rb
@@ -132,9 +132,6 @@ module ActionController #:nodoc:
@request.session["flash"] = ActionController::Flash::FlashHash.new.update(flash) if flash
build_request_uri(action, parameters)
- @request.env["action_controller.rescue.request"] = @request
- @request.env["action_controller.rescue.response"] = @response
-
Base.class_eval { include ProcessWithTest } unless Base < ProcessWithTest
env = @request.env
diff --git a/actionpack/test/controller/filters_test.rb b/actionpack/test/controller/filters_test.rb
index 9ad49e9282..afefc6a77e 100644
--- a/actionpack/test/controller/filters_test.rb
+++ b/actionpack/test/controller/filters_test.rb
@@ -607,7 +607,6 @@ class FilterTest < Test::Unit::TestCase
def test_dynamic_dispatch
%w(foo bar baz).each do |action|
request = ActionController::TestRequest.new
- request.env["action_controller.rescue.request"] = request
request.query_parameters[:choose] = action
response = DynamicDispatchController.action.call(request.env).last
assert_equal action, response.body
diff --git a/actionpack/test/controller/helper_test.rb b/actionpack/test/controller/helper_test.rb
index 7b8096fccc..3bbda9eb3a 100644
--- a/actionpack/test/controller/helper_test.rb
+++ b/actionpack/test/controller/helper_test.rb
@@ -104,7 +104,6 @@ class HelperTest < Test::Unit::TestCase
def call_controller(klass, action)
request = ActionController::TestRequest.new
- request.env["action_controller.rescue.request"] = request
klass.action(action).call(request.env)
end
@@ -112,7 +111,6 @@ class HelperTest < Test::Unit::TestCase
assert_equal 'hello: Iz guuut!',
call_controller(Fun::GamesController, "render_hello_world").last.body
# request = ActionController::TestRequest.new
- # request.env["action_controller.rescue.request"] = request
#
# resp = Fun::GamesController.action(:render_hello_world).call(request.env)
# assert_equal 'hello: Iz guuut!', resp.last.body
@@ -217,7 +215,6 @@ class IsolatedHelpersTest < Test::Unit::TestCase
def call_controller(klass, action)
request = ActionController::TestRequest.new
- request.env["action_controller.rescue.request"] = request
klass.action(action).call(request.env)
end
--
cgit v1.2.3
From 8118fca9beec675fba19395e7d1027eaa4b5703a Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Sun, 17 May 2009 12:24:42 -0500
Subject: Merge Failsafe middleware into ShowExceptions
---
.../lib/action_controller/dispatch/middlewares.rb | 1 -
actionpack/lib/action_dispatch.rb | 1 -
.../lib/action_dispatch/middleware/failsafe.rb | 51 -------------
.../action_dispatch/middleware/show_exceptions.rb | 87 ++++++++++------------
actionpack/test/controller/rescue_test.rb | 14 ++++
actionpack/test/dispatch/show_exceptions_test.rb | 5 ++
actionpack/test/new_base/render_action_test.rb | 4 +-
actionpack/test/new_base/render_test.rb | 6 +-
8 files changed, 64 insertions(+), 105 deletions(-)
delete mode 100644 actionpack/lib/action_dispatch/middleware/failsafe.rb
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/dispatch/middlewares.rb b/actionpack/lib/action_controller/dispatch/middlewares.rb
index 0e4ab6fa39..e4e3a704c0 100644
--- a/actionpack/lib/action_controller/dispatch/middlewares.rb
+++ b/actionpack/lib/action_controller/dispatch/middlewares.rb
@@ -2,7 +2,6 @@ use "Rack::Lock", :if => lambda {
!ActionController::Base.allow_concurrency
}
-use "ActionDispatch::Failsafe"
use "ActionDispatch::ShowExceptions", lambda { ActionController::Base.consider_all_requests_local }
use "ActionDispatch::Rescue", lambda {
controller = (::ApplicationController rescue ActionController::Base)
diff --git a/actionpack/lib/action_dispatch.rb b/actionpack/lib/action_dispatch.rb
index 27d229835a..f3c91d8624 100644
--- a/actionpack/lib/action_dispatch.rb
+++ b/actionpack/lib/action_dispatch.rb
@@ -38,7 +38,6 @@ module ActionDispatch
autoload :Response, 'action_dispatch/http/response'
autoload :StatusCodes, 'action_dispatch/http/status_codes'
- autoload :Failsafe, 'action_dispatch/middleware/failsafe'
autoload :ParamsParser, 'action_dispatch/middleware/params_parser'
autoload :Rescue, 'action_dispatch/middleware/rescue'
autoload :ShowExceptions, 'action_dispatch/middleware/show_exceptions'
diff --git a/actionpack/lib/action_dispatch/middleware/failsafe.rb b/actionpack/lib/action_dispatch/middleware/failsafe.rb
deleted file mode 100644
index 389accbc36..0000000000
--- a/actionpack/lib/action_dispatch/middleware/failsafe.rb
+++ /dev/null
@@ -1,51 +0,0 @@
-module ActionDispatch
- class Failsafe
- cattr_accessor :error_file_path
- self.error_file_path = Rails.public_path if defined?(Rails.public_path)
-
- def initialize(app)
- @app = app
- end
-
- def call(env)
- @app.call(env)
- rescue Exception => exception
- if env["rails.raise_exceptions"]
- raise
- else
- failsafe_response(exception)
- end
- end
-
- private
- def failsafe_response(exception)
- log_failsafe_exception(exception)
- [500, {'Content-Type' => 'text/html'}, failsafe_response_body]
- rescue Exception => failsafe_error # Logger or IO errors
- $stderr.puts "Error during failsafe response: #{failsafe_error}"
- end
-
- def failsafe_response_body
- error_path = "#{self.class.error_file_path}/500.html"
- if File.exist?(error_path)
- [File.read(error_path)]
- else
- ["
']]
def initialize(app, consider_all_requests_local = false)
@app = app
@@ -43,34 +40,35 @@ module ActionDispatch
def call(env)
@app.call(env)
rescue Exception => exception
- raise exception if env['rack.test']
+ raise exception if env['action_dispatch.show_exceptions'] == false
+ render_exception(env, exception)
+ end
- log_error(exception) if logger
+ private
+ def render_exception(env, exception)
+ log_error(exception)
- request = Request.new(env)
- if @consider_all_requests_local || local_request?(request)
- rescue_action_locally(request, exception)
- else
- rescue_action_in_public(exception)
+ request = Request.new(env)
+ if @consider_all_requests_local || local_request?(request)
+ rescue_action_locally(request, exception)
+ else
+ rescue_action_in_public(exception)
+ end
+ rescue Exception => failsafe_error
+ $stderr.puts "Error during failsafe response: #{failsafe_error}"
+ FAILSAFE_RESPONSE
end
- end
- private
# Render detailed diagnostics for unhandled exceptions rescued from
# a controller action.
def rescue_action_locally(request, exception)
template = ActionView::Base.new([RESCUES_TEMPLATE_PATH],
- :template => template,
:request => request,
:exception => exception
)
file = "rescues/#{@@rescue_templates[exception.class.name]}.erb"
body = template.render(:file => file, :layout => 'rescues/layout.erb')
-
- headers = {'Content-Type' => 'text/html', 'Content-Length' => body.length.to_s}
- status = status_code(exception)
-
- [status, headers, body]
+ render(status_code(exception), body)
end
# Attempts to render a static error page based on the
@@ -86,11 +84,11 @@ module ActionDispatch
path = "#{public_path}/#{status}.html"
if locale_path && File.exist?(locale_path)
- render_public_file(status, locale_path)
+ render(status, File.read(locale_path))
elsif File.exist?(path)
- render_public_file(status, path)
+ render(status, File.read(path))
else
- [status, {'Content-Type' => 'text/html', 'Content-Length' => '0'}, []]
+ render(status, '')
end
end
@@ -99,24 +97,21 @@ module ActionDispatch
request.remote_addr == LOCALHOST && request.remote_ip == LOCALHOST
end
- def render_public_file(status, path)
- body = File.read(path)
- [status, {'Content-Type' => 'text/html', 'Content-Length' => body.length.to_s}, body]
- end
-
def status_code(exception)
interpret_status(@@rescue_responses[exception.class.name]).to_i
end
+ def render(status, body)
+ [status, {'Content-Type' => 'text/html', 'Content-Length' => body.length.to_s}, body]
+ end
+
def public_path
- if defined?(Rails)
- Rails.public_path
- else
- "public"
- end
+ defined?(Rails.public_path) ? Rails.public_path : 'public_path'
end
- def log_error(exception) #:doc:
+ def log_error(exception)
+ return unless logger
+
ActiveSupport::Deprecation.silence do
if ActionView::TemplateError === exception
logger.fatal(exception.to_s)
@@ -136,9 +131,7 @@ module ActionDispatch
end
def logger
- if defined?(Rails.logger)
- Rails.logger
- end
+ defined?(Rails.logger) ? Rails.logger : Logger.new($stderr)
end
end
end
diff --git a/actionpack/test/controller/rescue_test.rb b/actionpack/test/controller/rescue_test.rb
index f745926b20..490a4ff3b3 100644
--- a/actionpack/test/controller/rescue_test.rb
+++ b/actionpack/test/controller/rescue_test.rb
@@ -1,5 +1,19 @@
require 'abstract_unit'
+module ActionDispatch
+ class ShowExceptions
+ private
+ def public_path
+ "#{FIXTURE_LOAD_PATH}/public"
+ end
+
+ # Silence logger
+ def logger
+ nil
+ end
+ end
+end
+
class RescueController < ActionController::Base
class NotAuthorized < StandardError
end
diff --git a/actionpack/test/dispatch/show_exceptions_test.rb b/actionpack/test/dispatch/show_exceptions_test.rb
index f8f562e7c1..0c0c087340 100644
--- a/actionpack/test/dispatch/show_exceptions_test.rb
+++ b/actionpack/test/dispatch/show_exceptions_test.rb
@@ -6,6 +6,11 @@ module ActionDispatch
def public_path
"#{FIXTURE_LOAD_PATH}/public"
end
+
+ # Silence logger
+ def logger
+ nil
+ end
end
end
diff --git a/actionpack/test/new_base/render_action_test.rb b/actionpack/test/new_base/render_action_test.rb
index 96666077d2..626c7b3540 100644
--- a/actionpack/test/new_base/render_action_test.rb
+++ b/actionpack/test/new_base/render_action_test.rb
@@ -92,7 +92,7 @@ module RenderAction
test "raises an exception when requesting a layout and none exist" do
assert_raise(ArgumentError, /no default layout for RenderAction::BasicController in/) do
- get "/render_action/basic/hello_world_with_layout", {}, "rails.raise_exceptions" => true
+ get "/render_action/basic/hello_world_with_layout", {}, "action_dispatch.show_exceptions" => false
end
end
end
@@ -118,7 +118,7 @@ module RenderAction
test "raises an exception when requesting a layout that does not exist" do
assert_raise(ActionView::MissingTemplate) do
- get "/render_action/basic/hello_world_with_custom_layout", {}, "rails.raise_exceptions" => true
+ get "/render_action/basic/hello_world_with_custom_layout", {}, "action_dispatch.show_exceptions" => false
end
end
end
diff --git a/actionpack/test/new_base/render_test.rb b/actionpack/test/new_base/render_test.rb
index 16578fbc82..ef5e7d89c5 100644
--- a/actionpack/test/new_base/render_test.rb
+++ b/actionpack/test/new_base/render_test.rb
@@ -48,7 +48,7 @@ module Render
test "raises an exception" do
assert_raises(AbstractController::DoubleRenderError) do
- get "/render/double_render", {}, "rails.raise_exceptions" => true
+ get "/render/double_render", {}, "action_dispatch.show_exceptions" => false
end
end
end
@@ -58,13 +58,13 @@ module Render
test "raises an exception when a method of Object is called" do
assert_raises(AbstractController::ActionNotFound) do
- get "/render/blank_render/clone", {}, "rails.raise_exceptions" => true
+ get "/render/blank_render/clone", {}, "action_dispatch.show_exceptions" => false
end
end
test "raises an exception when a private method is called" do
assert_raises(AbstractController::ActionNotFound) do
- get "/render/blank_render/secretz", {}, "rails.raise_exceptions" => true
+ get "/render/blank_render/secretz", {}, "action_dispatch.show_exceptions" => false
end
end
end
--
cgit v1.2.3
From edc9c226d11e6104d191ceeb6416c7062ceda54a Mon Sep 17 00:00:00 2001
From: Mike Breen
Date: Sun, 17 May 2009 19:48:15 +0200
Subject: Add tests for assert_template :template
Signed-off-by: Pratik Naik
---
.../test/controller/action_pack_assertions_test.rb | 23 ++++++++++++++++++++++
1 file changed, 23 insertions(+)
(limited to 'actionpack')
diff --git a/actionpack/test/controller/action_pack_assertions_test.rb b/actionpack/test/controller/action_pack_assertions_test.rb
index 484d3c5ce7..c3c769919a 100644
--- a/actionpack/test/controller/action_pack_assertions_test.rb
+++ b/actionpack/test/controller/action_pack_assertions_test.rb
@@ -12,6 +12,9 @@ class ActionPackAssertionsController < ActionController::Base
# a standard template
def hello_xml_world() render :template => "test/hello_xml_world"; end
+ # a standard partial
+ def partial() render :partial => 'test/partial'; end
+
# a redirect to an internal location
def redirect_internal() redirect_to "/nothing"; end
@@ -331,6 +334,26 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
end
end
+ def test_assert_template_with_partial
+ get :partial
+ assert_template :partial => '_partial'
+ end
+
+ def test_assert_template_with_nil
+ get :nothing
+ assert_template nil
+ end
+
+ def test_assert_template_with_string
+ get :hello_world
+ assert_template 'hello_world'
+ end
+
+ def test_assert_template_with_symbol
+ get :hello_world
+ assert_template :hello_world
+ end
+
# check if we were rendered by a file-based template?
def test_rendered_action
process :nothing
--
cgit v1.2.3
From 092089015b79752c5e9d664b3eeefef9e2223e36 Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Sun, 17 May 2009 13:39:44 -0500
Subject: Extract generic callbacks middleware from dispatcher
---
.../lib/action_controller/dispatch/dispatcher.rb | 100 ++++++++-------------
.../lib/action_controller/dispatch/middlewares.rb | 1 +
actionpack/lib/action_dispatch.rb | 1 +
.../lib/action_dispatch/middleware/callbacks.rb | 40 +++++++++
actionpack/test/controller/dispatcher_test.rb | 34 ++++---
5 files changed, 101 insertions(+), 75 deletions(-)
create mode 100644 actionpack/lib/action_dispatch/middleware/callbacks.rb
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/dispatch/dispatcher.rb b/actionpack/lib/action_controller/dispatch/dispatcher.rb
index 63866caed9..9ad1cadfd3 100644
--- a/actionpack/lib/action_controller/dispatch/dispatcher.rb
+++ b/actionpack/lib/action_controller/dispatch/dispatcher.rb
@@ -1,87 +1,65 @@
+require 'active_support/core_ext/module/delegation'
+
module ActionController
# Dispatches requests to the appropriate controller and takes care of
# reloading the app after each request when Dependencies.load? is true.
class Dispatcher
+ cattr_accessor :prepare_each_request
+ self.prepare_each_request = false
+
+ cattr_accessor :router
+ self.router = Routing::Routes
+
+ cattr_accessor :middleware
+ self.middleware = ActionDispatch::MiddlewareStack.new do |middleware|
+ middlewares = File.join(File.dirname(__FILE__), "middlewares.rb")
+ middleware.instance_eval(File.read(middlewares), middlewares, 1)
+ end
+
class << self
def define_dispatcher_callbacks(cache_classes)
unless cache_classes
+ # Run prepare callbacks before every request in development mode
+ self.prepare_each_request = true
+
# Development mode callbacks
- before_dispatch :reload_application
- after_dispatch :cleanup_application
+ ActionDispatch::Callbacks.before_dispatch do |app|
+ ActionController::Dispatcher.router.reload
+ end
+
+ ActionDispatch::Callbacks.after_dispatch do
+ # Cleanup the application before processing the current request.
+ ActiveRecord::Base.reset_subclasses if defined?(ActiveRecord)
+ ActiveSupport::Dependencies.clear
+ ActiveRecord::Base.clear_reloadable_connections! if defined?(ActiveRecord)
+ end
ActionView::Helpers::AssetTagHelper.cache_asset_timestamps = false
end
if defined?(ActiveRecord)
- to_prepare(:activerecord_instantiate_observers) { ActiveRecord::Base.instantiate_observers }
+ to_prepare(:activerecord_instantiate_observers) do
+ ActiveRecord::Base.instantiate_observers
+ end
end
- after_dispatch :flush_logger if Base.logger && Base.logger.respond_to?(:flush)
+ if Base.logger && Base.logger.respond_to?(:flush)
+ after_dispatch do
+ Base.logger.flush
+ end
+ end
to_prepare do
I18n.reload!
end
end
- # Add a preparation callback. Preparation callbacks are run before every
- # request in development mode, and before the first request in production
- # mode.
- #
- # An optional identifier may be supplied for the callback. If provided,
- # to_prepare may be called again with the same identifier to replace the
- # existing callback. Passing an identifier is a suggested practice if the
- # code adding a preparation block may be reloaded.
- def to_prepare(identifier = nil, &block)
- @prepare_dispatch_callbacks ||= ActiveSupport::Callbacks::CallbackChain.new
- callback = ActiveSupport::Callbacks::Callback.new(:prepare_dispatch, block, :identifier => identifier)
- @prepare_dispatch_callbacks.replace_or_append!(callback)
- end
+ delegate :to_prepare, :prepare_dispatch, :before_dispatch, :after_dispatch,
+ :to => ActionDispatch::Callbacks
- def run_prepare_callbacks
- new.send :run_callbacks, :prepare_dispatch
+ def new
+ @@middleware.build(@@router)
end
end
-
- cattr_accessor :router
- self.router = Routing::Routes
-
- cattr_accessor :middleware
- self.middleware = ActionDispatch::MiddlewareStack.new do |middleware|
- middlewares = File.join(File.dirname(__FILE__), "middlewares.rb")
- middleware.instance_eval(File.read(middlewares), middlewares, 1)
- end
-
- include ActiveSupport::Callbacks
- define_callbacks :prepare_dispatch, :before_dispatch, :after_dispatch
-
- def initialize
- @app = @@middleware.build(@@router)
- freeze
- end
-
- def call(env)
- run_callbacks :before_dispatch
- @app.call(env)
- ensure
- run_callbacks :after_dispatch, :enumerator => :reverse_each
- end
-
- def reload_application
- # Run prepare callbacks before every request in development mode
- run_callbacks :prepare_dispatch
-
- @@router.reload
- end
-
- def cleanup_application
- # Cleanup the application before processing the current request.
- ActiveRecord::Base.reset_subclasses if defined?(ActiveRecord)
- ActiveSupport::Dependencies.clear
- ActiveRecord::Base.clear_reloadable_connections! if defined?(ActiveRecord)
- end
-
- def flush_logger
- Base.logger.flush
- end
end
end
diff --git a/actionpack/lib/action_controller/dispatch/middlewares.rb b/actionpack/lib/action_controller/dispatch/middlewares.rb
index e4e3a704c0..b25ed3fd3f 100644
--- a/actionpack/lib/action_controller/dispatch/middlewares.rb
+++ b/actionpack/lib/action_controller/dispatch/middlewares.rb
@@ -3,6 +3,7 @@ use "Rack::Lock", :if => lambda {
}
use "ActionDispatch::ShowExceptions", lambda { ActionController::Base.consider_all_requests_local }
+use "ActionDispatch::Callbacks", lambda { ActionController::Dispatcher.prepare_each_request }
use "ActionDispatch::Rescue", lambda {
controller = (::ApplicationController rescue ActionController::Base)
# TODO: Replace with controller.action(:_rescue_action)
diff --git a/actionpack/lib/action_dispatch.rb b/actionpack/lib/action_dispatch.rb
index f3c91d8624..6fc4ad3f21 100644
--- a/actionpack/lib/action_dispatch.rb
+++ b/actionpack/lib/action_dispatch.rb
@@ -38,6 +38,7 @@ module ActionDispatch
autoload :Response, 'action_dispatch/http/response'
autoload :StatusCodes, 'action_dispatch/http/status_codes'
+ autoload :Callbacks, 'action_dispatch/middleware/callbacks'
autoload :ParamsParser, 'action_dispatch/middleware/params_parser'
autoload :Rescue, 'action_dispatch/middleware/rescue'
autoload :ShowExceptions, 'action_dispatch/middleware/show_exceptions'
diff --git a/actionpack/lib/action_dispatch/middleware/callbacks.rb b/actionpack/lib/action_dispatch/middleware/callbacks.rb
new file mode 100644
index 0000000000..0a2b4cf5f7
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/callbacks.rb
@@ -0,0 +1,40 @@
+module ActionDispatch
+ class Callbacks
+ include ActiveSupport::Callbacks
+ define_callbacks :prepare, :before, :after
+
+ class << self
+ # DEPRECATED
+ alias_method :prepare_dispatch, :prepare
+ alias_method :before_dispatch, :before
+ alias_method :after_dispatch, :after
+ end
+
+ # Add a preparation callback. Preparation callbacks are run before every
+ # request in development mode, and before the first request in production
+ # mode.
+ #
+ # An optional identifier may be supplied for the callback. If provided,
+ # to_prepare may be called again with the same identifier to replace the
+ # existing callback. Passing an identifier is a suggested practice if the
+ # code adding a preparation block may be reloaded.
+ def self.to_prepare(identifier = nil, &block)
+ @prepare_callbacks ||= ActiveSupport::Callbacks::CallbackChain.new
+ callback = ActiveSupport::Callbacks::Callback.new(:prepare, block, :identifier => identifier)
+ @prepare_callbacks.replace_or_append!(callback)
+ end
+
+ def initialize(app, prepare_each_request = false)
+ @app, @prepare_each_request = app, prepare_each_request
+ run_callbacks :prepare
+ end
+
+ def call(env)
+ run_callbacks :before
+ run_callbacks :prepare if @prepare_each_request
+ @app.call(env)
+ ensure
+ run_callbacks :after, :enumerator => :reverse_each
+ end
+ end
+end
diff --git a/actionpack/test/controller/dispatcher_test.rb b/actionpack/test/controller/dispatcher_test.rb
index b315232a7b..9fae1fcf63 100644
--- a/actionpack/test/controller/dispatcher_test.rb
+++ b/actionpack/test/controller/dispatcher_test.rb
@@ -6,20 +6,20 @@ class DispatcherTest < Test::Unit::TestCase
def setup
ENV['REQUEST_METHOD'] = 'GET'
- Dispatcher.middleware = ActionDispatch::MiddlewareStack.new do |middleware|
- middlewares = File.expand_path(File.join(File.dirname(__FILE__), "../../lib/action_controller/dispatch/middlewares.rb"))
- middleware.instance_eval(File.read(middlewares))
- end
-
# Clear callbacks as they are redefined by Dispatcher#define_dispatcher_callbacks
- Dispatcher.instance_variable_set("@prepare_dispatch_callbacks", ActiveSupport::Callbacks::CallbackChain.new)
- Dispatcher.instance_variable_set("@before_dispatch_callbacks", ActiveSupport::Callbacks::CallbackChain.new)
- Dispatcher.instance_variable_set("@after_dispatch_callbacks", ActiveSupport::Callbacks::CallbackChain.new)
+ ActionDispatch::Callbacks.instance_variable_set("@prepare_callbacks", ActiveSupport::Callbacks::CallbackChain.new)
+ ActionDispatch::Callbacks.instance_variable_set("@before_callbacks", ActiveSupport::Callbacks::CallbackChain.new)
+ ActionDispatch::Callbacks.instance_variable_set("@after_callbacks", ActiveSupport::Callbacks::CallbackChain.new)
+ @old_router, Dispatcher.router = Dispatcher.router, mock()
+ Dispatcher.router.stubs(:call).returns([200, {}, 'response'])
+ Dispatcher.router.stubs(:reload)
Dispatcher.stubs(:require_dependency)
end
def teardown
+ Dispatcher.router = @old_router
+ @dispatcher = nil
ENV.delete 'REQUEST_METHOD'
end
@@ -29,12 +29,12 @@ class DispatcherTest < Test::Unit::TestCase
end
def test_reloads_routes_before_dispatch_if_in_loading_mode
- ActionController::Routing::Routes.expects(:reload).once
+ Dispatcher.router.expects(:reload).once
dispatch(false)
end
def test_leaves_dependencies_after_dispatch_if_not_in_loading_mode
- ActionController::Routing::Routes.expects(:reload).never
+ Dispatcher.router.expects(:reload).never
ActiveSupport::Dependencies.expects(:clear).never
dispatch
@@ -55,7 +55,7 @@ class DispatcherTest < Test::Unit::TestCase
assert_nil a || b || c
# Run callbacks
- Dispatcher.run_prepare_callbacks
+ dispatch
assert_equal 1, a
assert_equal 2, b
@@ -72,16 +72,22 @@ class DispatcherTest < Test::Unit::TestCase
Dispatcher.to_prepare(:unique_id) { |*args| a = b = 1 }
Dispatcher.to_prepare(:unique_id) { |*args| a = 2 }
- Dispatcher.run_prepare_callbacks
+ dispatch
assert_equal 2, a
assert_equal nil, b
end
private
def dispatch(cache_classes = true)
- ActionController::Routing::RouteSet.any_instance.stubs(:call).returns([200, {}, 'response'])
+ ActionController::Dispatcher.prepare_each_request = false
Dispatcher.define_dispatcher_callbacks(cache_classes)
- Dispatcher.new.call({'rack.input' => StringIO.new('')})
+ Dispatcher.middleware = ActionDispatch::MiddlewareStack.new do |middleware|
+ middlewares = File.expand_path(File.join(File.dirname(__FILE__), "../../lib/action_controller/dispatch/middlewares.rb"))
+ middleware.instance_eval(File.read(middlewares))
+ end
+
+ @dispatcher ||= Dispatcher.new
+ @dispatcher.call({'rack.input' => StringIO.new(''), 'action_dispatch.show_exceptions' => false})
end
def assert_subclasses(howmany, klass, message = klass.subclasses.inspect)
--
cgit v1.2.3
From 01d7acd11d631d980497870aad1af42a0c66115c Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Sun, 17 May 2009 14:42:36 -0500
Subject: Fix reset_session with ActiveRecord store [#2200 state:resolved]
---
actionpack/test/activerecord/active_record_store_test.rb | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/test/activerecord/active_record_store_test.rb b/actionpack/test/activerecord/active_record_store_test.rb
index 663cd259c8..47f8496181 100644
--- a/actionpack/test/activerecord/active_record_store_test.rb
+++ b/actionpack/test/activerecord/active_record_store_test.rb
@@ -28,9 +28,9 @@ class ActiveRecordStoreTest < ActionController::IntegrationTest
end
def call_reset_session
- session[:bar]
+ session[:foo]
reset_session
- session[:bar] = "baz"
+ session[:foo] = "baz"
head :ok
end
@@ -91,7 +91,7 @@ class ActiveRecordStoreTest < ActionController::IntegrationTest
get '/get_session_value'
assert_response :success
- assert_equal 'foo: nil', response.body
+ assert_equal 'foo: "baz"', response.body
get '/get_session_id'
assert_response :success
--
cgit v1.2.3
From b0de061e7b8d3c291a328f6b0b9bfc5f48b2f907 Mon Sep 17 00:00:00 2001
From: Brian Lopez
Date: Sun, 17 May 2009 16:09:28 -0500
Subject: Allow ParamsParser to parse YAML from the request body IO directly
Signed-off-by: Joshua Peek
---
actionpack/lib/action_dispatch/middleware/params_parser.rb | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_dispatch/middleware/params_parser.rb b/actionpack/lib/action_dispatch/middleware/params_parser.rb
index a42c6598e0..e83cf9236b 100644
--- a/actionpack/lib/action_dispatch/middleware/params_parser.rb
+++ b/actionpack/lib/action_dispatch/middleware/params_parser.rb
@@ -34,7 +34,7 @@ module ActionDispatch
when :xml_simple, :xml_node
request.body.size == 0 ? {} : Hash.from_xml(request.body).with_indifferent_access
when :yaml
- YAML.load(request.raw_post)
+ YAML.load(request.body)
when :json
if request.body.size == 0
{}
--
cgit v1.2.3
From 195fadbfd31294d43634afb7bbf4f0ffc86b470a Mon Sep 17 00:00:00 2001
From: Pratik Naik
Date: Mon, 18 May 2009 16:59:37 +0200
Subject: Ensure HTTP Digest auth uses appropriate HTTP method [#2490
state:resolved] [Steve Madsen]
---
.../action_controller/base/http_authentication.rb | 3 ++-
.../controller/http_digest_authentication_test.rb | 23 +++++++++++++++++++---
2 files changed, 22 insertions(+), 4 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/base/http_authentication.rb b/actionpack/lib/action_controller/base/http_authentication.rb
index fa8ecea408..2893290efb 100644
--- a/actionpack/lib/action_controller/base/http_authentication.rb
+++ b/actionpack/lib/action_controller/base/http_authentication.rb
@@ -194,9 +194,10 @@ module ActionController
if valid_nonce && realm == credentials[:realm] && opaque == credentials[:opaque]
password = password_procedure.call(credentials[:username])
+ method = request.env['rack.methodoverride.original_method'] || request.env['REQUEST_METHOD']
[true, false].any? do |password_is_ha1|
- expected = expected_response(request.env['REQUEST_METHOD'], request.env['REQUEST_URI'], credentials, password, password_is_ha1)
+ expected = expected_response(method, request.env['REQUEST_URI'], credentials, password, password_is_ha1)
expected == credentials[:response]
end
end
diff --git a/actionpack/test/controller/http_digest_authentication_test.rb b/actionpack/test/controller/http_digest_authentication_test.rb
index 7bebc8cd2a..b8a2205ce6 100644
--- a/actionpack/test/controller/http_digest_authentication_test.rb
+++ b/actionpack/test/controller/http_digest_authentication_test.rb
@@ -149,6 +149,16 @@ class HttpDigestAuthenticationTest < ActionController::TestCase
assert_equal 'Definitely Maybe', @response.body
end
+ test "authentication request with _method" do
+ @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please', :method => :post)
+ @request.env['rack.methodoverride.original_method'] = 'POST'
+ put :display
+
+ assert_response :success
+ assert assigns(:logged_in)
+ assert_equal 'Definitely Maybe', @response.body
+ end
+
private
def encode_credentials(options)
@@ -159,15 +169,22 @@ class HttpDigestAuthenticationTest < ActionController::TestCase
# to prevent tampering of timestamp
ActionController::Base.session_options[:secret] = "session_options_secret"
- # Perform unauthenticated GET to retrieve digest parameters to use on subsequent request
- get :index
+ # Perform unauthenticated request to retrieve digest parameters to use on subsequent request
+ method = options.delete(:method) || 'GET'
+
+ case method.to_s.upcase
+ when 'GET'
+ get :index
+ when 'POST'
+ post :index
+ end
assert_response :unauthorized
credentials = decode_credentials(@response.headers['WWW-Authenticate'])
credentials.merge!(options)
credentials.reverse_merge!(:uri => "#{@request.env['REQUEST_URI']}")
- ActionController::HttpAuthentication::Digest.encode_credentials("GET", credentials, password, options[:password_is_ha1])
+ ActionController::HttpAuthentication::Digest.encode_credentials(method, credentials, password, options[:password_is_ha1])
end
def decode_credentials(header)
--
cgit v1.2.3
From 5e190ef138a034bf86419ce4f4c343ae16bfc77b Mon Sep 17 00:00:00 2001
From: Andy Stewart
Date: Wed, 28 Jan 2009 16:45:28 +0000
Subject: Truncate helper accepts a :separator for a more legible result [#1807
state:resolved]
Signed-off-by: Pratik Naik
---
actionpack/lib/action_view/helpers/text_helper.rb | 7 ++++++-
actionpack/test/template/text_helper_test.rb | 3 +++
2 files changed, 9 insertions(+), 1 deletion(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_view/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb
index 8136a1cb13..ad0733a7e1 100644
--- a/actionpack/lib/action_view/helpers/text_helper.rb
+++ b/actionpack/lib/action_view/helpers/text_helper.rb
@@ -34,12 +34,16 @@ module ActionView
# Truncates a given +text+ after a given :length if +text+ is longer than :length
# (defaults to 30). The last characters will be replaced with the :omission (defaults to "...").
+ # Pass a :separator to truncate +text+ at a natural break.
#
# ==== Examples
#
# truncate("Once upon a time in a world far far away")
# # => Once upon a time in a world f...
#
+ # truncate("Once upon a time in a world far far away", :separator => ' ')
+ # # => Once upon a time in a world...
+ #
# truncate("Once upon a time in a world far far away", :length => 14)
# # => Once upon a...
#
@@ -71,7 +75,8 @@ module ActionView
if text
l = options[:length] - options[:omission].mb_chars.length
chars = text.mb_chars
- (chars.length > options[:length] ? chars[0...l] + options[:omission] : text).to_s
+ stop = options[:separator] ? (chars.rindex(options[:separator].mb_chars, l) || l) : l
+ (chars.length > options[:length] ? chars[0...stop] + options[:omission] : text).to_s
end
end
diff --git a/actionpack/test/template/text_helper_test.rb b/actionpack/test/template/text_helper_test.rb
index a780bfc606..706b5085f4 100644
--- a/actionpack/test/template/text_helper_test.rb
+++ b/actionpack/test/template/text_helper_test.rb
@@ -49,6 +49,9 @@ class TextHelperTest < ActionView::TestCase
assert_equal "This is a string that wil[...]", truncate("This is a string that will go longer then the default truncate length of 30", :omission => "[...]")
assert_equal "Hello W...", truncate("Hello World!", :length => 10)
assert_equal "Hello[...]", truncate("Hello World!", :omission => "[...]", :length => 10)
+ assert_equal "Hello[...]", truncate("Hello Big World!", :omission => "[...]", :length => 13, :separator => ' ')
+ assert_equal "Hello Big[...]", truncate("Hello Big World!", :omission => "[...]", :length => 14, :separator => ' ')
+ assert_equal "Hello Big[...]", truncate("Hello Big World!", :omission => "[...]", :length => 15, :separator => ' ')
end
if RUBY_VERSION < '1.9.0'
--
cgit v1.2.3
From 07f733c6315980bde120c98c6b8a25e2773ee6bf Mon Sep 17 00:00:00 2001
From: Yehuda Katz + Carl Lerche
Date: Mon, 18 May 2009 16:15:43 -0700
Subject: Ported simple benchmarking in new base
---
actionpack/Rakefile | 4 ++--
actionpack/lib/action_controller/abstract.rb | 1 +
.../lib/action_controller/abstract/benchmarker.rb | 28 ++++++++++++++++++++++
.../lib/action_controller/abstract/logger.rb | 1 +
.../action_controller/base/chained/benchmarking.rb | 2 +-
actionpack/lib/action_controller/new_base/base.rb | 1 +
actionpack/test/controller/logging_test.rb | 5 ++++
7 files changed, 39 insertions(+), 3 deletions(-)
create mode 100644 actionpack/lib/action_controller/abstract/benchmarker.rb
(limited to 'actionpack')
diff --git a/actionpack/Rakefile b/actionpack/Rakefile
index 41b190130e..57c3276cb9 100644
--- a/actionpack/Rakefile
+++ b/actionpack/Rakefile
@@ -21,8 +21,8 @@ task :default => [ :test ]
# Run the unit tests
-desc "Run all unit tests"
-task :test => [:test_action_pack, :test_active_record_integration]
+desc "Run all unit tests" # Do not remove :test_new_base
+task :test => [:test_action_pack, :test_active_record_integration, :test_new_base]
Rake::TestTask.new(:test_action_pack) do |t|
t.libs << "test"
diff --git a/actionpack/lib/action_controller/abstract.rb b/actionpack/lib/action_controller/abstract.rb
index 48e33282ec..d6b7a44f5f 100644
--- a/actionpack/lib/action_controller/abstract.rb
+++ b/actionpack/lib/action_controller/abstract.rb
@@ -3,6 +3,7 @@ require "active_support/core_ext/module/delegation"
module AbstractController
autoload :Base, "action_controller/abstract/base"
+ autoload :Benchmarker, "action_controller/abstract/benchmarker"
autoload :Callbacks, "action_controller/abstract/callbacks"
autoload :Helpers, "action_controller/abstract/helpers"
autoload :Layouts, "action_controller/abstract/layouts"
diff --git a/actionpack/lib/action_controller/abstract/benchmarker.rb b/actionpack/lib/action_controller/abstract/benchmarker.rb
new file mode 100644
index 0000000000..9f5889c704
--- /dev/null
+++ b/actionpack/lib/action_controller/abstract/benchmarker.rb
@@ -0,0 +1,28 @@
+module AbstractController
+ module Benchmarker
+ extend ActiveSupport::DependencyModule
+
+ depends_on Logger
+
+ module ClassMethods
+ def benchmark(title, log_level = ::Logger::DEBUG, use_silence = true)
+ if logger && logger.level >= log_level
+ result = nil
+ ms = Benchmark.ms { result = use_silence ? silence { yield } : yield }
+ logger.add(log_level, "#{title} (#{('%.1f' % ms)}ms)")
+ result
+ else
+ yield
+ end
+ end
+
+ # Silences the logger for the duration of the block.
+ def silence
+ old_logger_level, logger.level = logger.level, ::Logger::ERROR if logger
+ yield
+ ensure
+ logger.level = old_logger_level if logger
+ end
+ end
+ end
+end
\ No newline at end of file
diff --git a/actionpack/lib/action_controller/abstract/logger.rb b/actionpack/lib/action_controller/abstract/logger.rb
index 750a5c9fb6..980ede0bed 100644
--- a/actionpack/lib/action_controller/abstract/logger.rb
+++ b/actionpack/lib/action_controller/abstract/logger.rb
@@ -1,4 +1,5 @@
require 'active_support/core_ext/class/attribute_accessors'
+require 'active_support/core_ext/logger'
module AbstractController
module Logger
diff --git a/actionpack/lib/action_controller/base/chained/benchmarking.rb b/actionpack/lib/action_controller/base/chained/benchmarking.rb
index 66e9e9c31d..57a1ac8314 100644
--- a/actionpack/lib/action_controller/base/chained/benchmarking.rb
+++ b/actionpack/lib/action_controller/base/chained/benchmarking.rb
@@ -21,7 +21,7 @@ module ActionController #:nodoc:
# easy to include benchmarking statements in production software that will remain inexpensive because the benchmark
# will only be conducted if the log level is low enough.
def benchmark(title, log_level = Logger::DEBUG, use_silence = true)
- if logger && logger.level == log_level
+ if logger && logger.level >= log_level
result = nil
ms = Benchmark.ms { result = use_silence ? silence { yield } : yield }
logger.add(log_level, "#{title} (#{('%.1f' % ms)}ms)")
diff --git a/actionpack/lib/action_controller/new_base/base.rb b/actionpack/lib/action_controller/new_base/base.rb
index c25ffd5c84..756a0799fe 100644
--- a/actionpack/lib/action_controller/new_base/base.rb
+++ b/actionpack/lib/action_controller/new_base/base.rb
@@ -2,6 +2,7 @@ module ActionController
class Base < Http
abstract!
+ include AbstractController::Benchmarker
include AbstractController::Callbacks
include AbstractController::Helpers
include AbstractController::Logger
diff --git a/actionpack/test/controller/logging_test.rb b/actionpack/test/controller/logging_test.rb
index 1f3ff4ef52..75afa2d133 100644
--- a/actionpack/test/controller/logging_test.rb
+++ b/actionpack/test/controller/logging_test.rb
@@ -11,6 +11,11 @@ class LoggingTest < ActionController::TestCase
class MockLogger
attr_reader :logged
+ attr_accessor :level
+
+ def initialize
+ @level = Logger::DEBUG
+ end
def method_missing(method, *args)
@logged ||= []
--
cgit v1.2.3
From 4a6f4b92ad2f48dc7906d223fe4708d36624bd50 Mon Sep 17 00:00:00 2001
From: Pratik Naik
Date: Tue, 19 May 2009 23:48:05 +0200
Subject: Change integration test helpers to accept Rack environment instead of
just HTTP Headers.
Before : get '/path', {}, 'Accept' => 'text/javascript'
After : get '/path', {}, 'HTTP_ACCEPT' => 'text/javascript'
---
.../lib/action_controller/testing/integration.rb | 10 ++++-----
actionpack/test/controller/integration_test.rb | 24 +++++++++++-----------
2 files changed, 16 insertions(+), 18 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/testing/integration.rb b/actionpack/lib/action_controller/testing/integration.rb
index d6991ab4f5..a8e8f16d6c 100644
--- a/actionpack/lib/action_controller/testing/integration.rb
+++ b/actionpack/lib/action_controller/testing/integration.rb
@@ -62,8 +62,8 @@ module ActionController
# with 'HTTP_' if not already.
def xml_http_request(request_method, path, parameters = nil, headers = nil)
headers ||= {}
- headers['X-Requested-With'] = 'XMLHttpRequest'
- headers['Accept'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
+ headers['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
+ headers['HTTP_ACCEPT'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
process(request_method, path, parameters, headers)
end
alias xhr :xml_http_request
@@ -228,7 +228,7 @@ module ActionController
private
# Performs the actual request.
- def process(method, path, parameters = nil, headers = nil)
+ def process(method, path, parameters = nil, rack_environment = nil)
if path =~ %r{://}
location = URI.parse(path)
https! URI::HTTPS === location if location.scheme
@@ -265,9 +265,7 @@ module ActionController
}
env = Rack::MockRequest.env_for(path, opts)
- (headers || {}).each do |key, value|
- key = key.to_s.upcase.gsub(/-/, "_")
- key = "HTTP_#{key}" unless env.has_key?(key) || key =~ /^HTTP_/
+ (rack_environment || {}).each do |key, value|
env[key] = value
end
diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb
index c616107324..a2b3ad2106 100644
--- a/actionpack/test/controller/integration_test.rb
+++ b/actionpack/test/controller/integration_test.rb
@@ -123,8 +123,8 @@ class SessionTest < Test::Unit::TestCase
def test_xml_http_request_get
path = "/index"; params = "blah"; headers = {:location => 'blah'}
headers_after_xhr = headers.merge(
- "X-Requested-With" => "XMLHttpRequest",
- "Accept" => "text/javascript, text/html, application/xml, text/xml, */*"
+ "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest",
+ "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*"
)
@session.expects(:process).with(:get,path,params,headers_after_xhr)
@session.xml_http_request(:get,path,params,headers)
@@ -133,8 +133,8 @@ class SessionTest < Test::Unit::TestCase
def test_xml_http_request_post
path = "/index"; params = "blah"; headers = {:location => 'blah'}
headers_after_xhr = headers.merge(
- "X-Requested-With" => "XMLHttpRequest",
- "Accept" => "text/javascript, text/html, application/xml, text/xml, */*"
+ "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest",
+ "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*"
)
@session.expects(:process).with(:post,path,params,headers_after_xhr)
@session.xml_http_request(:post,path,params,headers)
@@ -143,8 +143,8 @@ class SessionTest < Test::Unit::TestCase
def test_xml_http_request_put
path = "/index"; params = "blah"; headers = {:location => 'blah'}
headers_after_xhr = headers.merge(
- "X-Requested-With" => "XMLHttpRequest",
- "Accept" => "text/javascript, text/html, application/xml, text/xml, */*"
+ "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest",
+ "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*"
)
@session.expects(:process).with(:put,path,params,headers_after_xhr)
@session.xml_http_request(:put,path,params,headers)
@@ -153,8 +153,8 @@ class SessionTest < Test::Unit::TestCase
def test_xml_http_request_delete
path = "/index"; params = "blah"; headers = {:location => 'blah'}
headers_after_xhr = headers.merge(
- "X-Requested-With" => "XMLHttpRequest",
- "Accept" => "text/javascript, text/html, application/xml, text/xml, */*"
+ "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest",
+ "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*"
)
@session.expects(:process).with(:delete,path,params,headers_after_xhr)
@session.xml_http_request(:delete,path,params,headers)
@@ -163,17 +163,17 @@ class SessionTest < Test::Unit::TestCase
def test_xml_http_request_head
path = "/index"; params = "blah"; headers = {:location => 'blah'}
headers_after_xhr = headers.merge(
- "X-Requested-With" => "XMLHttpRequest",
- "Accept" => "text/javascript, text/html, application/xml, text/xml, */*"
+ "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest",
+ "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*"
)
@session.expects(:process).with(:head,path,params,headers_after_xhr)
@session.xml_http_request(:head,path,params,headers)
end
def test_xml_http_request_override_accept
- path = "/index"; params = "blah"; headers = {:location => 'blah', "Accept" => "application/xml"}
+ path = "/index"; params = "blah"; headers = {:location => 'blah', "HTTP_ACCEPT" => "application/xml"}
headers_after_xhr = headers.merge(
- "X-Requested-With" => "XMLHttpRequest"
+ "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest"
)
@session.expects(:process).with(:post,path,params,headers_after_xhr)
@session.xml_http_request(:post,path,params,headers)
--
cgit v1.2.3
From f503a5dc97d18794cc0eda5ffe77e2cd7d762d47 Mon Sep 17 00:00:00 2001
From: Pratik Naik
Date: Tue, 19 May 2009 23:57:49 +0200
Subject: Missing CHANGELOG entry for 4a6f4b92ad2f
---
actionpack/CHANGELOG | 5 +++++
1 file changed, 5 insertions(+)
(limited to 'actionpack')
diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG
index c1dc6f2ab4..e3ad19558e 100644
--- a/actionpack/CHANGELOG
+++ b/actionpack/CHANGELOG
@@ -1,5 +1,10 @@
*Edge*
+* Change integration test helpers to accept Rack environment instead of just HTTP Headers [Pratik Naik]
+
+ Before : get '/path', {}, 'Accept' => 'text/javascript'
+ After : get '/path', {}, 'HTTP_ACCEPT' => 'text/javascript'
+
* Instead of checking Rails.env.test? in Failsafe middleware, check env["rails.raise_exceptions"] [Bryan Helmkamp]
* Fixed that TestResponse.cookies was returning cookies unescaped #1867 [Doug McInnes]
--
cgit v1.2.3
From d8fffe7b23acce42bc3941d7bba47e07a66aed67 Mon Sep 17 00:00:00 2001
From: Pratik Naik
Date: Wed, 20 May 2009 00:06:14 +0200
Subject: Replace ad hoc Rack::Test with ActionController::IntegrationTest
---
actionpack/Rakefile | 2 +-
actionpack/test/new_base/test_helper.rb | 16 +++++++---------
2 files changed, 8 insertions(+), 10 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/Rakefile b/actionpack/Rakefile
index 57c3276cb9..6ce8179646 100644
--- a/actionpack/Rakefile
+++ b/actionpack/Rakefile
@@ -21,7 +21,7 @@ task :default => [ :test ]
# Run the unit tests
-desc "Run all unit tests" # Do not remove :test_new_base
+desc "Run all unit tests"
task :test => [:test_action_pack, :test_active_record_integration, :test_new_base]
Rake::TestTask.new(:test_action_pack) do |t|
diff --git a/actionpack/test/new_base/test_helper.rb b/actionpack/test/new_base/test_helper.rb
index ec7dbffaae..9401e692f1 100644
--- a/actionpack/test/new_base/test_helper.rb
+++ b/actionpack/test/new_base/test_helper.rb
@@ -20,8 +20,8 @@ require 'action_controller/abstract'
require 'action_controller/new_base'
require 'pp' # require 'pp' early to prevent hidden_methods from not picking up the pretty-print methods until too late
-require 'rubygems'
-require 'rack/test'
+require 'action_controller/testing/process'
+require 'action_controller/testing/integration'
module Rails
def self.env
@@ -32,9 +32,7 @@ module Rails
end
# Temporary base class
-class Rack::TestCase < ActiveSupport::TestCase
- include Rack::Test::Methods
-
+class Rack::TestCase < ActionController::IntegrationTest
setup do
ActionController::Base.session_options[:key] = "abc"
ActionController::Base.session_options[:secret] = ("*" * 30)
@@ -82,7 +80,7 @@ class Rack::TestCase < ActiveSupport::TestCase
end
def assert_body(body)
- assert_equal body, Array.wrap(last_response.body).join
+ assert_equal body, Array.wrap(response.body).join
end
def self.assert_body(body)
@@ -92,7 +90,7 @@ class Rack::TestCase < ActiveSupport::TestCase
end
def assert_status(code)
- assert_equal code, last_response.status
+ assert_equal code, response.status
end
def self.assert_status(code)
@@ -110,7 +108,7 @@ class Rack::TestCase < ActiveSupport::TestCase
end
def assert_content_type(type)
- assert_equal type, last_response.headers["Content-Type"]
+ assert_equal type, response.headers["Content-Type"]
end
def self.assert_content_type(type)
@@ -120,7 +118,7 @@ class Rack::TestCase < ActiveSupport::TestCase
end
def assert_header(name, value)
- assert_equal value, last_response.headers[name]
+ assert_equal value, response.headers[name]
end
def self.assert_header(name, value)
--
cgit v1.2.3
From 26f2be01c2d537aac6d484c8a1ed2df92aa52f00 Mon Sep 17 00:00:00 2001
From: Yehuda Katz + Carl Lerche
Date: Tue, 19 May 2009 18:02:03 -0700
Subject: Modify caching to use new included helper
---
actionpack/lib/action_controller/caching.rb | 30 ++++++++++++++---------------
1 file changed, 15 insertions(+), 15 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/caching.rb b/actionpack/lib/action_controller/caching.rb
index ffd8081edc..2f2eec10f6 100644
--- a/actionpack/lib/action_controller/caching.rb
+++ b/actionpack/lib/action_controller/caching.rb
@@ -24,31 +24,31 @@ module ActionController #:nodoc:
# ActionController::Base.cache_store = :mem_cache_store, "localhost"
# ActionController::Base.cache_store = MyOwnStore.new("parameter")
module Caching
+ extend ActiveSupport::DependencyModule
+
autoload :Actions, 'action_controller/caching/actions'
autoload :Fragments, 'action_controller/caching/fragments'
autoload :Pages, 'action_controller/caching/pages'
autoload :Sweeper, 'action_controller/caching/sweeping'
autoload :Sweeping, 'action_controller/caching/sweeping'
- def self.included(base) #:nodoc:
- base.class_eval do
- @@cache_store = nil
- cattr_reader :cache_store
+ included do
+ @@cache_store = nil
+ cattr_reader :cache_store
- # Defines the storage option for cached fragments
- def self.cache_store=(store_option)
- @@cache_store = ActiveSupport::Cache.lookup_store(store_option)
- end
+ # Defines the storage option for cached fragments
+ def self.cache_store=(store_option)
+ @@cache_store = ActiveSupport::Cache.lookup_store(store_option)
+ end
- include Pages, Actions, Fragments
- include Sweeping if defined?(ActiveRecord)
+ include Pages, Actions, Fragments
+ include Sweeping if defined?(ActiveRecord)
- @@perform_caching = true
- cattr_accessor :perform_caching
+ @@perform_caching = true
+ cattr_accessor :perform_caching
- def self.cache_configured?
- perform_caching && cache_store
- end
+ def self.cache_configured?
+ perform_caching && cache_store
end
end
--
cgit v1.2.3
From 0e7da0e4a06f78ab39b0e90daadfc223b8f1738a Mon Sep 17 00:00:00 2001
From: Yehuda Katz + Carl Lerche
Date: Tue, 19 May 2009 18:04:17 -0700
Subject: Include caching module into new base
---
actionpack/lib/action_controller/new_base.rb | 1 +
actionpack/lib/action_controller/new_base/base.rb | 1 +
2 files changed, 2 insertions(+)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/new_base.rb b/actionpack/lib/action_controller/new_base.rb
index bc47713529..078f66ced1 100644
--- a/actionpack/lib/action_controller/new_base.rb
+++ b/actionpack/lib/action_controller/new_base.rb
@@ -13,6 +13,7 @@ module ActionController
# Ported modules
# require 'action_controller/routing'
+ autoload :Caching, 'action_controller/caching'
autoload :Dispatcher, 'action_controller/dispatch/dispatcher'
autoload :PolymorphicRoutes, 'action_controller/routing/generation/polymorphic_routes'
autoload :RecordIdentifier, 'action_controller/record_identifier'
diff --git a/actionpack/lib/action_controller/new_base/base.rb b/actionpack/lib/action_controller/new_base/base.rb
index 756a0799fe..7f830307b6 100644
--- a/actionpack/lib/action_controller/new_base/base.rb
+++ b/actionpack/lib/action_controller/new_base/base.rb
@@ -17,6 +17,7 @@ module ActionController
# Legacy modules
include SessionManagement
include ActionDispatch::StatusCodes
+ include ActionController::Caching
# Rails 2.x compatibility
include ActionController::Rails2Compatibility
--
cgit v1.2.3
From 67cc021d019515c94d4bcc4c3c7060c9a2594c87 Mon Sep 17 00:00:00 2001
From: Yehuda Katz + Carl Lerche
Date: Tue, 19 May 2009 18:05:16 -0700
Subject: Modified caching implementation to work with NewBase
---
.../lib/action_controller/caching/actions.rb | 22 +++++++++++++++++++---
.../lib/action_controller/new_base/renderer.rb | 5 +++++
2 files changed, 24 insertions(+), 3 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/caching/actions.rb b/actionpack/lib/action_controller/caching/actions.rb
index 2b822b52c8..430db3932f 100644
--- a/actionpack/lib/action_controller/caching/actions.rb
+++ b/actionpack/lib/action_controller/caching/actions.rb
@@ -61,8 +61,14 @@ module ActionController #:nodoc:
filter_options = { :only => actions, :if => options.delete(:if), :unless => options.delete(:unless) }
cache_filter = ActionCacheFilter.new(:layout => options.delete(:layout), :cache_path => options.delete(:cache_path), :store_options => options)
- around_filter(filter_options) do |controller, action|
- cache_filter.filter(controller, action)
+
+ # TODO: Remove this once new base is swapped in.
+ if defined?(Http)
+ around_filter cache_filter, filter_options
+ else
+ around_filter(filter_options) do |controller, action|
+ cache_filter.filter(controller, action)
+ end
end
end
end
@@ -85,14 +91,22 @@ module ActionController #:nodoc:
@options = options
end
+ # TODO: Remove once New Base is merged
def filter(controller, action)
should_continue = before(controller)
action.call if should_continue
after(controller)
end
+ def around_process_action(controller)
+ should_continue = before(controller)
+ yield if should_continue
+ after(controller)
+ end
+
def before(controller)
cache_path = ActionCachePath.new(controller, path_options_for(controller, @options.slice(:cache_path)))
+
if cache = controller.read_fragment(cache_path.path, @options[:store_options])
controller.rendered_action_cache = true
set_content_type!(controller, cache_path.extension)
@@ -129,7 +143,9 @@ module ActionController #:nodoc:
end
def content_for_layout(controller)
- controller.template.layout && controller.template.instance_variable_get('@cached_content_for_layout')
+ # TODO: Remove this when new base is merged in
+ template = controller.respond_to?(:template) ? controller.template : controller._action_view
+ template.layout && template.instance_variable_get('@cached_content_for_layout')
end
end
diff --git a/actionpack/lib/action_controller/new_base/renderer.rb b/actionpack/lib/action_controller/new_base/renderer.rb
index 8a9f230603..9253df53a1 100644
--- a/actionpack/lib/action_controller/new_base/renderer.rb
+++ b/actionpack/lib/action_controller/new_base/renderer.rb
@@ -9,6 +9,11 @@ module ActionController
super
end
+ def response_body=(body)
+ response.body = body if response
+ super
+ end
+
def render_to_body(options)
_process_options(options)
--
cgit v1.2.3
From 321168b17bce2e73ab7ba22309491ad5c245dcf8 Mon Sep 17 00:00:00 2001
From: Yehuda Katz + Carl Lerche
Date: Tue, 19 May 2009 18:08:04 -0700
Subject: Make old caching tests pass on new base.
---
actionpack/lib/action_controller/new_base/compatibility.rb | 4 ++++
actionpack/lib/action_controller/new_base/http.rb | 1 -
actionpack/lib/action_controller/new_base/url_for.rb | 5 +++++
3 files changed, 9 insertions(+), 1 deletion(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/new_base/compatibility.rb b/actionpack/lib/action_controller/new_base/compatibility.rb
index 0a283887b6..0098c0747e 100644
--- a/actionpack/lib/action_controller/new_base/compatibility.rb
+++ b/actionpack/lib/action_controller/new_base/compatibility.rb
@@ -55,6 +55,10 @@ module ActionController
self.consider_all_requests_local = true
end
+ # For old tests
+ def initialize_template_class(*) end
+ def assign_shortcuts(*) end
+
module ClassMethods
def protect_from_forgery() end
def consider_all_requests_local() end
diff --git a/actionpack/lib/action_controller/new_base/http.rb b/actionpack/lib/action_controller/new_base/http.rb
index 8891a2a8c3..17466a2d52 100644
--- a/actionpack/lib/action_controller/new_base/http.rb
+++ b/actionpack/lib/action_controller/new_base/http.rb
@@ -60,7 +60,6 @@ module ActionController
# :api: private
def to_rack
- @_response.body = response_body
@_response.prepare!
@_response.to_a
end
diff --git a/actionpack/lib/action_controller/new_base/url_for.rb b/actionpack/lib/action_controller/new_base/url_for.rb
index af5b21012b..94de9fab50 100644
--- a/actionpack/lib/action_controller/new_base/url_for.rb
+++ b/actionpack/lib/action_controller/new_base/url_for.rb
@@ -1,5 +1,10 @@
module ActionController
module UrlFor
+ def process_action(*)
+ initialize_current_url
+ super
+ end
+
def initialize_current_url
@url = UrlRewriter.new(request, params.clone)
end
--
cgit v1.2.3
From 0029d5e5943dd20d38485ac7127cc150659da9e5 Mon Sep 17 00:00:00 2001
From: Bryan Helmkamp
Date: Mon, 11 May 2009 23:04:39 -0400
Subject: Integrating Rack::MockSession (from Rack::Test)
---
.../lib/action_controller/testing/integration.rb | 25 +++++++++++-----------
actionpack/test/controller/integration_test.rb | 6 +++---
2 files changed, 16 insertions(+), 15 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/testing/integration.rb b/actionpack/lib/action_controller/testing/integration.rb
index a8e8f16d6c..31afd54258 100644
--- a/actionpack/lib/action_controller/testing/integration.rb
+++ b/actionpack/lib/action_controller/testing/integration.rb
@@ -1,6 +1,8 @@
require 'stringio'
require 'uri'
require 'active_support/test_case'
+require 'rack/test'
+require 'rack/mock_session'
module ActionController
module Integration #:nodoc:
@@ -121,6 +123,8 @@ module ActionController
# IntegrationTest#open_session, rather than instantiating
# Integration::Session directly.
class Session
+ DEFAULT_HOST = "www.example.com"
+
include Test::Unit::Assertions
include ActionDispatch::Assertions
include ActionController::TestProcess
@@ -145,7 +149,9 @@ module ActionController
# A map of the cookies returned by the last response, and which will be
# sent with the next request.
- attr_reader :cookies
+ def cookies
+ @mock_session.cookie_jar
+ end
# A reference to the controller instance used by the last request.
attr_reader :controller
@@ -172,11 +178,11 @@ module ActionController
# session.reset!
def reset!
@https = false
- @cookies = {}
+ @mock_session = Rack::MockSession.new(@app, DEFAULT_HOST)
@controller = @request = @response = nil
@request_count = 0
- self.host = "www.example.com"
+ self.host = DEFAULT_HOST
self.remote_addr = "127.0.0.1"
self.accept = "text/xml,application/xml,application/xhtml+xml," +
"text/html;q=0.9,text/plain;q=0.8,image/png," +
@@ -227,6 +233,7 @@ module ActionController
end
private
+
# Performs the actual request.
def process(method, path, parameters = nil, rack_environment = nil)
if path =~ %r{://}
@@ -258,10 +265,7 @@ module ActionController
"HTTP_HOST" => host,
"REMOTE_ADDR" => remote_addr,
"CONTENT_TYPE" => "application/x-www-form-urlencoded",
- "HTTP_ACCEPT" => accept,
- "HTTP_COOKIE" => cookies.inject("") { |string, (name, value)|
- string << "#{name}=#{value}; "
- }
+ "HTTP_ACCEPT" => accept
}
env = Rack::MockRequest.env_for(path, opts)
@@ -269,15 +273,12 @@ module ActionController
env[key] = value
end
- app = Rack::Lint.new(@app)
- status, headers, body = app.call(env)
- mock_response = ::Rack::MockResponse.new(status, headers, body)
+ @mock_session.request(URI.parse(path), env)
@request_count += 1
@request = ActionDispatch::Request.new(env)
- @response = ActionDispatch::TestResponse.from_response(mock_response)
+ @response = ActionDispatch::TestResponse.from_response(@mock_session.last_response)
- @cookies.merge!(@response.cookies)
@html_document = nil
if @controller = ActionController::Base.last_instantiation
diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb
index a2b3ad2106..eae6835714 100644
--- a/actionpack/test/controller/integration_test.rb
+++ b/actionpack/test/controller/integration_test.rb
@@ -253,7 +253,7 @@ class IntegrationProcessTest < ActionController::IntegrationTest
assert_response 200
assert_response :success
assert_response :ok
- assert_equal({}, cookies)
+ assert_equal({}, cookies.to_hash)
assert_equal "OK", body
assert_equal "OK", response.body
assert_kind_of HTML::Document, html_document
@@ -269,7 +269,7 @@ class IntegrationProcessTest < ActionController::IntegrationTest
assert_response 201
assert_response :success
assert_response :created
- assert_equal({}, cookies)
+ assert_equal({}, cookies.to_hash)
assert_equal "Created", body
assert_equal "Created", response.body
assert_kind_of HTML::Document, html_document
@@ -287,7 +287,7 @@ class IntegrationProcessTest < ActionController::IntegrationTest
assert_response 410
assert_response :gone
assert_equal "cookie_1=; path=/\ncookie_3=chocolate; path=/", headers["Set-Cookie"]
- assert_equal({"cookie_1"=>nil, "cookie_2"=>"oatmeal", "cookie_3"=>"chocolate"}, cookies)
+ assert_equal({"cookie_1"=>"", "cookie_2"=>"oatmeal", "cookie_3"=>"chocolate"}, cookies.to_hash)
assert_equal "Gone", response.body
end
end
--
cgit v1.2.3
From df0faea378034b031f49995f06c8bf108a0b5530 Mon Sep 17 00:00:00 2001
From: Bryan Helmkamp
Date: Tue, 12 May 2009 01:37:19 -0400
Subject: Refactor ActionController instantiation capture
---
.../lib/action_controller/testing/integration.rb | 24 +++++++++-------------
1 file changed, 10 insertions(+), 14 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/testing/integration.rb b/actionpack/lib/action_controller/testing/integration.rb
index 31afd54258..717b77674c 100644
--- a/actionpack/lib/action_controller/testing/integration.rb
+++ b/actionpack/lib/action_controller/testing/integration.rb
@@ -249,8 +249,6 @@ module ActionController
end
end
- ActionController::Base.clear_last_instantiation!
-
opts = {
:method => method,
:params => parameters,
@@ -273,18 +271,15 @@ module ActionController
env[key] = value
end
- @mock_session.request(URI.parse(path), env)
+ @controller = ActionController::Base.capture_instantiation do
+ @mock_session.request(URI.parse(path), env)
+ end
@request_count += 1
@request = ActionDispatch::Request.new(env)
@response = ActionDispatch::TestResponse.from_response(@mock_session.last_response)
-
@html_document = nil
- if @controller = ActionController::Base.last_instantiation
- @controller.send(:set_test_assigns)
- end
-
return response.status
end
@@ -305,11 +300,10 @@ module ActionController
# A module used to extend ActionController::Base, so that integration tests
# can capture the controller used to satisfy a request.
module ControllerCapture #:nodoc:
- def self.included(base)
- base.extend(ClassMethods)
- base.class_eval do
- alias_method_chain :initialize, :capture
- end
+ extend ActiveSupport::DependencyModule
+
+ included do
+ alias_method_chain :initialize, :capture
end
def initialize_with_capture(*args)
@@ -320,8 +314,10 @@ module ActionController
module ClassMethods #:nodoc:
mattr_accessor :last_instantiation
- def clear_last_instantiation!
+ def capture_instantiation
self.last_instantiation = nil
+ yield
+ return last_instantiation
end
end
end
--
cgit v1.2.3
From 6761759a90c08b9db8d5720a8ee4c4329a547caf Mon Sep 17 00:00:00 2001
From: Joshua Peek
Date: Tue, 19 May 2009 22:42:59 -0500
Subject: Temporarily bundle rack-test while MockSession is baking
---
.../lib/action_controller/testing/integration.rb | 3 +-
actionpack/lib/action_dispatch.rb | 2 +
.../vendor/rack-test/rack/mock_session.rb | 50 +++++
.../action_dispatch/vendor/rack-test/rack/test.rb | 239 +++++++++++++++++++++
.../vendor/rack-test/rack/test/cookie_jar.rb | 169 +++++++++++++++
.../vendor/rack-test/rack/test/methods.rb | 45 ++++
.../rack-test/rack/test/mock_digest_request.rb | 27 +++
.../vendor/rack-test/rack/test/uploaded_file.rb | 36 ++++
.../vendor/rack-test/rack/test/utils.rb | 75 +++++++
9 files changed, 645 insertions(+), 1 deletion(-)
create mode 100644 actionpack/lib/action_dispatch/vendor/rack-test/rack/mock_session.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack-test/rack/test.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack-test/rack/test/cookie_jar.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack-test/rack/test/methods.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack-test/rack/test/mock_digest_request.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack-test/rack/test/uploaded_file.rb
create mode 100644 actionpack/lib/action_dispatch/vendor/rack-test/rack/test/utils.rb
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/testing/integration.rb b/actionpack/lib/action_controller/testing/integration.rb
index 717b77674c..cc157816e2 100644
--- a/actionpack/lib/action_controller/testing/integration.rb
+++ b/actionpack/lib/action_controller/testing/integration.rb
@@ -1,8 +1,9 @@
require 'stringio'
require 'uri'
require 'active_support/test_case'
-require 'rack/test'
+
require 'rack/mock_session'
+require 'rack/test/cookie_jar'
module ActionController
module Integration #:nodoc:
diff --git a/actionpack/lib/action_dispatch.rb b/actionpack/lib/action_dispatch.rb
index 6fc4ad3f21..f9003c51ea 100644
--- a/actionpack/lib/action_dispatch.rb
+++ b/actionpack/lib/action_dispatch.rb
@@ -33,6 +33,8 @@ end
require 'rack'
+$:.unshift "#{File.dirname(__FILE__)}/action_dispatch/vendor/rack-test"
+
module ActionDispatch
autoload :Request, 'action_dispatch/http/request'
autoload :Response, 'action_dispatch/http/response'
diff --git a/actionpack/lib/action_dispatch/vendor/rack-test/rack/mock_session.rb b/actionpack/lib/action_dispatch/vendor/rack-test/rack/mock_session.rb
new file mode 100644
index 0000000000..eba6226538
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack-test/rack/mock_session.rb
@@ -0,0 +1,50 @@
+module Rack
+
+ class MockSession
+ attr_writer :cookie_jar
+ attr_reader :last_response
+
+ def initialize(app, default_host = Rack::Test::DEFAULT_HOST)
+ @app = app
+ @default_host = default_host
+ end
+
+ def clear_cookies
+ @cookie_jar = Rack::Test::CookieJar.new([], @default_host)
+ end
+
+ def set_cookie(cookie, uri = nil)
+ cookie_jar.merge(cookie, uri)
+ end
+
+ def request(uri, env)
+ env["HTTP_COOKIE"] ||= cookie_jar.for(uri)
+ @last_request = Rack::Request.new(env)
+ status, headers, body = @app.call(@last_request.env)
+ @last_response = MockResponse.new(status, headers, body, env["rack.errors"].flush)
+ cookie_jar.merge(last_response.headers["Set-Cookie"], uri)
+
+ @last_response
+ end
+
+ # Return the last request issued in the session. Raises an error if no
+ # requests have been sent yet.
+ def last_request
+ raise Rack::Test::Error.new("No request yet. Request a page first.") unless @last_request
+ @last_request
+ end
+
+ # Return the last response received in the session. Raises an error if
+ # no requests have been sent yet.
+ def last_response
+ raise Rack::Test::Error.new("No response yet. Request a page first.") unless @last_response
+ @last_response
+ end
+
+ def cookie_jar
+ @cookie_jar ||= Rack::Test::CookieJar.new([], @default_host)
+ end
+
+ end
+
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-test/rack/test.rb b/actionpack/lib/action_dispatch/vendor/rack-test/rack/test.rb
new file mode 100644
index 0000000000..70384b1d76
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack-test/rack/test.rb
@@ -0,0 +1,239 @@
+unless $LOAD_PATH.include?(File.expand_path(File.dirname(__FILE__) + "/.."))
+ $LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__) + "/.."))
+end
+
+require "uri"
+require "rack"
+require "rack/mock_session"
+require "rack/test/cookie_jar"
+require "rack/test/mock_digest_request"
+require "rack/test/utils"
+require "rack/test/methods"
+require "rack/test/uploaded_file"
+
+module Rack
+ module Test
+
+ VERSION = "0.3.0"
+
+ DEFAULT_HOST = "example.org"
+ MULTIPART_BOUNDARY = "----------XnJLe9ZIbbGUYtzPQJ16u1"
+
+ # The common base class for exceptions raised by Rack::Test
+ class Error < StandardError; end
+
+ class Session
+ extend Forwardable
+ include Rack::Test::Utils
+
+ def_delegators :@rack_mock_session, :clear_cookies, :set_cookie, :last_response, :last_request
+
+ # Initialize a new session for the given Rack app
+ def initialize(app, default_host = DEFAULT_HOST)
+ @headers = {}
+ @default_host = default_host
+ @rack_mock_session = Rack::MockSession.new(app, default_host)
+ end
+
+ # Issue a GET request for the given URI with the given params and Rack
+ # environment. Stores the issues request object in #last_request and
+ # the app's response in #last_response. Yield #last_response to a block
+ # if given.
+ #
+ # Example:
+ # get "/"
+ def get(uri, params = {}, env = {}, &block)
+ env = env_for(uri, env.merge(:method => "GET", :params => params))
+ process_request(uri, env, &block)
+ end
+
+ # Issue a POST request for the given URI. See #get
+ #
+ # Example:
+ # post "/signup", "name" => "Bryan"
+ def post(uri, params = {}, env = {}, &block)
+ env = env_for(uri, env.merge(:method => "POST", :params => params))
+ process_request(uri, env, &block)
+ end
+
+ # Issue a PUT request for the given URI. See #get
+ #
+ # Example:
+ # put "/"
+ def put(uri, params = {}, env = {}, &block)
+ env = env_for(uri, env.merge(:method => "PUT", :params => params))
+ process_request(uri, env, &block)
+ end
+
+ # Issue a DELETE request for the given URI. See #get
+ #
+ # Example:
+ # delete "/"
+ def delete(uri, params = {}, env = {}, &block)
+ env = env_for(uri, env.merge(:method => "DELETE", :params => params))
+ process_request(uri, env, &block)
+ end
+
+ # Issue a HEAD request for the given URI. See #get
+ #
+ # Example:
+ # head "/"
+ def head(uri, params = {}, env = {}, &block)
+ env = env_for(uri, env.merge(:method => "HEAD", :params => params))
+ process_request(uri, env, &block)
+ end
+
+ # Issue a request to the Rack app for the given URI and optional Rack
+ # environment. Stores the issues request object in #last_request and
+ # the app's response in #last_response. Yield #last_response to a block
+ # if given.
+ #
+ # Example:
+ # request "/"
+ def request(uri, env = {}, &block)
+ env = env_for(uri, env)
+ process_request(uri, env, &block)
+ end
+
+ # Set a header to be included on all subsequent requests through the
+ # session. Use a value of nil to remove a previously configured header.
+ #
+ # Example:
+ # header "User-Agent", "Firefox"
+ def header(name, value)
+ if value.nil?
+ @headers.delete(name)
+ else
+ @headers[name] = value
+ end
+ end
+
+ # Set the username and password for HTTP Basic authorization, to be
+ # included in subsequent requests in the HTTP_AUTHORIZATION header.
+ #
+ # Example:
+ # basic_authorize "bryan", "secret"
+ def basic_authorize(username, password)
+ encoded_login = ["#{username}:#{password}"].pack("m*")
+ header('HTTP_AUTHORIZATION', "Basic #{encoded_login}")
+ end
+
+ alias_method :authorize, :basic_authorize
+
+ def digest_authorize(username, password)
+ @digest_username = username
+ @digest_password = password
+ end
+
+ # Rack::Test will not follow any redirects automatically. This method
+ # will follow the redirect returned in the last response. If the last
+ # response was not a redirect, an error will be raised.
+ def follow_redirect!
+ unless last_response.redirect?
+ raise Error.new("Last response was not a redirect. Cannot follow_redirect!")
+ end
+
+ get(last_response["Location"])
+ end
+
+ private
+
+ def env_for(path, env)
+ uri = URI.parse(path)
+ uri.host ||= @default_host
+
+ env = default_env.merge(env)
+
+ env.update("HTTPS" => "on") if URI::HTTPS === uri
+ env["X-Requested-With"] = "XMLHttpRequest" if env[:xhr]
+
+ if (env[:method] == "POST" || env["REQUEST_METHOD"] == "POST") && !env.has_key?(:input)
+ env["CONTENT_TYPE"] = "application/x-www-form-urlencoded"
+
+ multipart = (Hash === env[:params]) &&
+ env[:params].any? { |_, v| UploadedFile === v }
+
+ if multipart
+ env[:input] = multipart_body(env.delete(:params))
+ env["CONTENT_LENGTH"] ||= env[:input].length.to_s
+ env["CONTENT_TYPE"] = "multipart/form-data; boundary=#{MULTIPART_BOUNDARY}"
+ else
+ env[:input] = params_to_string(env.delete(:params))
+ end
+ end
+
+ params = env[:params] || {}
+ params.update(parse_query(uri.query))
+
+ uri.query = requestify(params)
+
+ if env.has_key?(:cookie)
+ set_cookie(env.delete(:cookie), uri)
+ end
+
+ Rack::MockRequest.env_for(uri.to_s, env)
+ end
+
+ def process_request(uri, env)
+ uri = URI.parse(uri)
+ uri.host ||= @default_host
+
+ @rack_mock_session.request(uri, env)
+
+ if retry_with_digest_auth?(env)
+ auth_env = env.merge({
+ "HTTP_AUTHORIZATION" => digest_auth_header,
+ "rack-test.digest_auth_retry" => true
+ })
+ auth_env.delete('rack.request')
+ process_request(uri.path, auth_env)
+ else
+ yield last_response if block_given?
+
+ last_response
+ end
+ end
+
+ def digest_auth_header
+ challenge = last_response["WWW-Authenticate"].split(" ", 2).last
+ params = Rack::Auth::Digest::Params.parse(challenge)
+
+ params.merge!({
+ "username" => @digest_username,
+ "nc" => "00000001",
+ "cnonce" => "nonsensenonce",
+ "uri" => last_request.path_info,
+ "method" => last_request.env["REQUEST_METHOD"],
+ })
+
+ params["response"] = MockDigestRequest.new(params).response(@digest_password)
+
+ "Digest #{params}"
+ end
+
+ def retry_with_digest_auth?(env)
+ last_response.status == 401 &&
+ digest_auth_configured? &&
+ !env["rack-test.digest_auth_retry"]
+ end
+
+ def digest_auth_configured?
+ @digest_username
+ end
+
+ def default_env
+ { "rack.test" => true, "REMOTE_ADDR" => "127.0.0.1" }.merge(@headers)
+ end
+
+ def params_to_string(params)
+ case params
+ when Hash then requestify(params)
+ when nil then ""
+ else params
+ end
+ end
+
+ end
+
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-test/rack/test/cookie_jar.rb b/actionpack/lib/action_dispatch/vendor/rack-test/rack/test/cookie_jar.rb
new file mode 100644
index 0000000000..d58c914c9b
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack-test/rack/test/cookie_jar.rb
@@ -0,0 +1,169 @@
+require "uri"
+module Rack
+ module Test
+
+ class Cookie
+ include Rack::Utils
+
+ # :api: private
+ attr_reader :name, :value
+
+ # :api: private
+ def initialize(raw, uri = nil, default_host = DEFAULT_HOST)
+ @default_host = default_host
+ uri ||= default_uri
+
+ # separate the name / value pair from the cookie options
+ @name_value_raw, options = raw.split(/[;,] */n, 2)
+
+ @name, @value = parse_query(@name_value_raw, ';').to_a.first
+ @options = parse_query(options, ';')
+
+ @options["domain"] ||= (uri.host || default_host)
+ @options["path"] ||= uri.path.sub(/\/[^\/]*\Z/, "")
+ end
+
+ def replaces?(other)
+ [name.downcase, domain, path] == [other.name.downcase, other.domain, other.path]
+ end
+
+ # :api: private
+ def raw
+ @name_value_raw
+ end
+
+ # :api: private
+ def empty?
+ @value.nil? || @value.empty?
+ end
+
+ # :api: private
+ def domain
+ @options["domain"]
+ end
+
+ def secure?
+ @options.has_key?("secure")
+ end
+
+ # :api: private
+ def path
+ @options["path"].strip || "/"
+ end
+
+ # :api: private
+ def expires
+ Time.parse(@options["expires"]) if @options["expires"]
+ end
+
+ # :api: private
+ def expired?
+ expires && expires < Time.now
+ end
+
+ # :api: private
+ def valid?(uri)
+ uri ||= default_uri
+
+ if uri.host.nil?
+ uri.host = @default_host
+ end
+
+ (!secure? || (secure? && uri.scheme == "https")) &&
+ uri.host =~ Regexp.new("#{Regexp.escape(domain)}$", Regexp::IGNORECASE) &&
+ uri.path =~ Regexp.new("^#{Regexp.escape(path)}")
+ end
+
+ # :api: private
+ def matches?(uri)
+ ! expired? && valid?(uri)
+ end
+
+ # :api: private
+ def <=>(other)
+ # Orders the cookies from least specific to most
+ [name, path, domain.reverse] <=> [other.name, other.path, other.domain.reverse]
+ end
+
+ protected
+
+ def default_uri
+ URI.parse("//" + @default_host + "/")
+ end
+
+ end
+
+ class CookieJar
+
+ # :api: private
+ def initialize(cookies = [], default_host = DEFAULT_HOST)
+ @default_host = default_host
+ @cookies = cookies
+ @cookies.sort!
+ end
+
+ def [](name)
+ cookies = hash_for(nil)
+ # TODO: Should be case insensitive
+ cookies[name] && cookies[name].value
+ end
+
+ def []=(name, value)
+ # TODO: needs proper escaping
+ merge("#{name}=#{value}")
+ end
+
+ def merge(raw_cookies, uri = nil)
+ return unless raw_cookies
+
+ raw_cookies.each_line do |raw_cookie|
+ cookie = Cookie.new(raw_cookie, uri, @default_host)
+ self << cookie if cookie.valid?(uri)
+ end
+ end
+
+ def <<(new_cookie)
+ @cookies.reject! do |existing_cookie|
+ new_cookie.replaces?(existing_cookie)
+ end
+
+ @cookies << new_cookie
+ @cookies.sort!
+ end
+
+ # :api: private
+ def for(uri)
+ hash_for(uri).values.map { |c| c.raw }.join(';')
+ end
+
+ def to_hash
+ cookies = {}
+
+ hash_for(nil).each do |name, cookie|
+ cookies[name] = cookie.value
+ end
+
+ return cookies
+ end
+
+ protected
+
+ def hash_for(uri = nil)
+ cookies = {}
+
+ # The cookies are sorted by most specific first. So, we loop through
+ # all the cookies in order and add it to a hash by cookie name if
+ # the cookie can be sent to the current URI. It's added to the hash
+ # so that when we are done, the cookies will be unique by name and
+ # we'll have grabbed the most specific to the URI.
+ @cookies.each do |cookie|
+ cookies[cookie.name] = cookie if cookie.matches?(uri)
+ end
+
+ return cookies
+ end
+
+ end
+
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-test/rack/test/methods.rb b/actionpack/lib/action_dispatch/vendor/rack-test/rack/test/methods.rb
new file mode 100644
index 0000000000..a191fa23d8
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack-test/rack/test/methods.rb
@@ -0,0 +1,45 @@
+require "forwardable"
+
+module Rack
+ module Test
+ module Methods
+ extend Forwardable
+
+ def rack_test_session
+ @_rack_test_session ||= Rack::Test::Session.new(app)
+ end
+
+ def rack_mock_session
+ @_rack_mock_session ||= Rack::MockSession.new(app)
+ end
+
+ METHODS = [
+ :request,
+
+ # HTTP verbs
+ :get,
+ :post,
+ :put,
+ :delete,
+ :head,
+
+ # Redirects
+ :follow_redirect!,
+
+ # Header-related features
+ :header,
+ :set_cookie,
+ :clear_cookies,
+ :authorize,
+ :basic_authorize,
+ :digest_authorize,
+
+ # Expose the last request and response
+ :last_response,
+ :last_request
+ ]
+
+ def_delegators :rack_test_session, *METHODS
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-test/rack/test/mock_digest_request.rb b/actionpack/lib/action_dispatch/vendor/rack-test/rack/test/mock_digest_request.rb
new file mode 100644
index 0000000000..81c398ba51
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack-test/rack/test/mock_digest_request.rb
@@ -0,0 +1,27 @@
+module Rack
+ module Test
+
+ class MockDigestRequest
+ def initialize(params)
+ @params = params
+ end
+
+ def method_missing(sym)
+ if @params.has_key? k = sym.to_s
+ return @params[k]
+ end
+
+ super
+ end
+
+ def method
+ @params['method']
+ end
+
+ def response(password)
+ Rack::Auth::Digest::MD5.new(nil).send :digest, self, password
+ end
+ end
+
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-test/rack/test/uploaded_file.rb b/actionpack/lib/action_dispatch/vendor/rack-test/rack/test/uploaded_file.rb
new file mode 100644
index 0000000000..239302fbe4
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack-test/rack/test/uploaded_file.rb
@@ -0,0 +1,36 @@
+require "tempfile"
+
+module Rack
+ module Test
+
+ class UploadedFile
+ # The filename, *not* including the path, of the "uploaded" file
+ attr_reader :original_filename
+
+ # The content type of the "uploaded" file
+ attr_accessor :content_type
+
+ def initialize(path, content_type = "text/plain", binary = false)
+ raise "#{path} file does not exist" unless ::File.exist?(path)
+ @content_type = content_type
+ @original_filename = ::File.basename(path)
+ @tempfile = Tempfile.new(@original_filename)
+ @tempfile.set_encoding(Encoding::BINARY) if @tempfile.respond_to?(:set_encoding)
+ @tempfile.binmode if binary
+ FileUtils.copy_file(path, @tempfile.path)
+ end
+
+ def path
+ @tempfile.path
+ end
+
+ alias_method :local_path, :path
+
+ def method_missing(method_name, *args, &block) #:nodoc:
+ @tempfile.__send__(method_name, *args, &block)
+ end
+
+ end
+
+ end
+end
diff --git a/actionpack/lib/action_dispatch/vendor/rack-test/rack/test/utils.rb b/actionpack/lib/action_dispatch/vendor/rack-test/rack/test/utils.rb
new file mode 100644
index 0000000000..d25b849709
--- /dev/null
+++ b/actionpack/lib/action_dispatch/vendor/rack-test/rack/test/utils.rb
@@ -0,0 +1,75 @@
+module Rack
+ module Test
+
+ module Utils
+ include Rack::Utils
+
+ def requestify(value, prefix = nil)
+ case value
+ when Array
+ value.map do |v|
+ requestify(v, "#{prefix}[]")
+ end.join("&")
+ when Hash
+ value.map do |k, v|
+ requestify(v, prefix ? "#{prefix}[#{escape(k)}]" : escape(k))
+ end.join("&")
+ else
+ "#{prefix}=#{escape(value)}"
+ end
+ end
+
+ module_function :requestify
+
+ def multipart_requestify(params, first=true)
+ p = Hash.new
+
+ params.each do |key, value|
+ k = first ? key.to_s : "[#{key}]"
+
+ if Hash === value
+ multipart_requestify(value, false).each do |subkey, subvalue|
+ p[k + subkey] = subvalue
+ end
+ else
+ p[k] = value
+ end
+ end
+
+ return p
+ end
+
+ module_function :multipart_requestify
+
+ def multipart_body(params)
+ multipart_requestify(params).map do |key, value|
+ if value.respond_to?(:original_filename)
+ ::File.open(value.path, "rb") do |f|
+ f.set_encoding(Encoding::BINARY) if f.respond_to?(:set_encoding)
+
+ <<-EOF
+--#{MULTIPART_BOUNDARY}\r
+Content-Disposition: form-data; name="#{key}"; filename="#{escape(value.original_filename)}"\r
+Content-Type: #{value.content_type}\r
+Content-Length: #{::File.stat(value.path).size}\r
+\r
+#{f.read}\r
+EOF
+ end
+ else
+<<-EOF
+--#{MULTIPART_BOUNDARY}\r
+Content-Disposition: form-data; name="#{key}"\r
+\r
+#{value}\r
+EOF
+ end
+ end.join("")+"--#{MULTIPART_BOUNDARY}--\r"
+ end
+
+ module_function :multipart_body
+
+ end
+
+ end
+end
--
cgit v1.2.3
From c03b0ca7eb7e73587005e1440bf90cd01ed10aa5 Mon Sep 17 00:00:00 2001
From: Pratik Naik
Date: Wed, 20 May 2009 21:15:06 +0200
Subject: Replace the class level Rack::Test DSL with the regular integration
tests DSL
---
actionpack/test/new_base/base_test.rb | 80 ++---
actionpack/test/new_base/content_type_test.rb | 120 +++----
actionpack/test/new_base/etag_test.rb | 23 +-
actionpack/test/new_base/render_action_test.rb | 388 ++++++++++-----------
.../test/new_base/render_implicit_action_test.rb | 28 +-
actionpack/test/new_base/render_layout_test.rb | 64 ++--
actionpack/test/new_base/render_template_test.rb | 87 +++--
actionpack/test/new_base/render_test.rb | 45 ++-
actionpack/test/new_base/render_text_test.rb | 151 ++++----
actionpack/test/new_base/test_helper.rb | 55 +--
10 files changed, 477 insertions(+), 564 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/test/new_base/base_test.rb b/actionpack/test/new_base/base_test.rb
index a32653f128..d9d552f9e5 100644
--- a/actionpack/test/new_base/base_test.rb
+++ b/actionpack/test/new_base/base_test.rb
@@ -10,78 +10,60 @@ module Dispatching
def modify_response_body
self.response_body = "success"
end
-
+
def modify_response_body_twice
ret = (self.response_body = "success")
self.response_body = "#{ret}!"
end
-
+
def modify_response_headers
-
end
end
-
- class TestSimpleDispatch < SimpleRouteCase
-
- get "/dispatching/simple/index"
-
- test "sets the body" do
+
+ class EmptyController < ActionController::Base ; end
+
+ module Submodule
+ class ContainedEmptyController < ActionController::Base ; end
+ end
+
+ class BaseTest < SimpleRouteCase
+ # :api: plugin
+ test "simple dispatching" do
+ get "/dispatching/simple/index"
+
assert_body "success"
- end
-
- test "sets the status code" do
assert_status 200
- end
-
- test "sets the content type" do
assert_content_type "text/html; charset=utf-8"
- end
-
- test "sets the content length" do
assert_header "Content-Length", "7"
end
-
- end
-
- # :api: plugin
- class TestDirectResponseMod < SimpleRouteCase
- get "/dispatching/simple/modify_response_body"
-
- test "sets the body" do
+
+ # :api: plugin
+ test "directly modifying response body" do
+ get "/dispatching/simple/modify_response_body"
+
assert_body "success"
+ assert_header "Content-Length", "7" # setting the body manually sets the content length
end
-
- test "setting the body manually sets the content length" do
- assert_header "Content-Length", "7"
- end
- end
-
- # :api: plugin
- class TestDirectResponseModTwice < SimpleRouteCase
- get "/dispatching/simple/modify_response_body_twice"
-
- test "self.response_body= returns the body being set" do
+
+ # :api: plugin
+ test "directly modifying response body twice" do
+ get "/dispatching/simple/modify_response_body_twice"
+
assert_body "success!"
- end
-
- test "updating the response body updates the content length" do
assert_header "Content-Length", "8"
end
- end
-
- class EmptyController < ActionController::Base ; end
- module Submodule
- class ContainedEmptyController < ActionController::Base ; end
- end
- class ControllerClassTests < Test::Unit::TestCase
- def test_controller_path
+ test "controller path" do
assert_equal 'dispatching/empty', EmptyController.controller_path
assert_equal EmptyController.controller_path, EmptyController.new.controller_path
+ end
+
+ test "namespaced controller path" do
assert_equal 'dispatching/submodule/contained_empty', Submodule::ContainedEmptyController.controller_path
assert_equal Submodule::ContainedEmptyController.controller_path, Submodule::ContainedEmptyController.new.controller_path
end
- def test_controller_name
+
+ test "controller name" do
assert_equal 'empty', EmptyController.controller_name
assert_equal 'contained_empty', Submodule::ContainedEmptyController.controller_name
end
diff --git a/actionpack/test/new_base/content_type_test.rb b/actionpack/test/new_base/content_type_test.rb
index a5c04e9cb6..82b817a5a3 100644
--- a/actionpack/test/new_base/content_type_test.rb
+++ b/actionpack/test/new_base/content_type_test.rb
@@ -5,107 +5,107 @@ module ContentType
def index
render :text => "Hello world!"
end
-
+
def set_on_response_obj
response.content_type = Mime::RSS
render :text => "Hello world!"
end
-
+
def set_on_render
render :text => "Hello world!", :content_type => Mime::RSS
end
end
-
- class TestDefault < SimpleRouteCase
- describe "a default response is HTML and UTF8"
-
- get "/content_type/base"
- assert_body "Hello world!"
- assert_header "Content-Type", "text/html; charset=utf-8"
- end
-
- class TestSetOnResponseObj < SimpleRouteCase
- describe "setting the content type of the response directly on the response object"
-
- get "/content_type/base/set_on_response_obj"
- assert_body "Hello world!"
- assert_header "Content-Type", "application/rss+xml; charset=utf-8"
- end
-
- class TestSetOnRender < SimpleRouteCase
- describe "setting the content type of the response as an option to render"
-
- get "/content_type/base/set_on_render"
- assert_body "Hello world!"
- assert_header "Content-Type", "application/rss+xml; charset=utf-8"
- end
-
+
class ImpliedController < ActionController::Base
+ # Template's mime type is used if no content_type is specified
+
self.view_paths = [ActionView::Template::FixturePath.new(
"content_type/implied/i_am_html_erb.html.erb" => "Hello world!",
"content_type/implied/i_am_xml_erb.xml.erb" => "Hello world!",
"content_type/implied/i_am_html_builder.html.builder" => "xml.p 'Hello'",
"content_type/implied/i_am_xml_builder.xml.builder" => "xml.awesome 'Hello'"
)]
-
+
def i_am_html_erb() end
def i_am_xml_erb() end
def i_am_html_builder() end
def i_am_xml_builder() end
end
-
- class TestImpliedController < SimpleRouteCase
- describe "the template's mime type is used if no content_type is specified"
-
+
+ class CharsetController < ActionController::Base
+ def set_on_response_obj
+ response.charset = "utf-16"
+ render :text => "Hello world!"
+ end
+
+ def set_as_nil_on_response_obj
+ response.charset = nil
+ render :text => "Hello world!"
+ end
+ end
+
+ class ExplicitContentTypeTest < SimpleRouteCase
+ test "default response is HTML and UTF8" do
+ get "/content_type/base"
+
+ assert_body "Hello world!"
+ assert_header "Content-Type", "text/html; charset=utf-8"
+ end
+
+ test "setting the content type of the response directly on the response object" do
+ get "/content_type/base/set_on_response_obj"
+
+ assert_body "Hello world!"
+ assert_header "Content-Type", "application/rss+xml; charset=utf-8"
+ end
+
+ test "setting the content type of the response as an option to render" do
+ get "/content_type/base/set_on_render"
+
+ assert_body "Hello world!"
+ assert_header "Content-Type", "application/rss+xml; charset=utf-8"
+ end
+ end
+
+ class ImpliedContentTypeTest < SimpleRouteCase
test "sets Content-Type as text/html when rendering *.html.erb" do
get "/content_type/implied/i_am_html_erb"
+
assert_header "Content-Type", "text/html; charset=utf-8"
end
test "sets Content-Type as application/xml when rendering *.xml.erb" do
get "/content_type/implied/i_am_xml_erb"
+
assert_header "Content-Type", "application/xml; charset=utf-8"
end
test "sets Content-Type as text/html when rendering *.html.builder" do
get "/content_type/implied/i_am_html_builder"
+
assert_header "Content-Type", "text/html; charset=utf-8"
end
test "sets Content-Type as application/xml when rendering *.xml.builder" do
get "/content_type/implied/i_am_xml_builder"
+
assert_header "Content-Type", "application/xml; charset=utf-8"
end
-
end
-end
-module Charset
- class BaseController < ActionController::Base
- def set_on_response_obj
- response.charset = "utf-16"
- render :text => "Hello world!"
+ class ExplicitCharsetTest < SimpleRouteCase
+ test "setting the charset of the response directly on the response object" do
+ get "/content_type/charset/set_on_response_obj"
+
+ assert_body "Hello world!"
+ assert_header "Content-Type", "text/html; charset=utf-16"
end
-
- def set_as_nil_on_response_obj
- response.charset = nil
- render :text => "Hello world!"
+
+ test "setting the charset of the response as nil directly on the response object" do
+ get "/content_type/charset/set_as_nil_on_response_obj"
+
+ assert_body "Hello world!"
+ assert_header "Content-Type", "text/html; charset=utf-8"
end
end
-
- class TestSetOnResponseObj < SimpleRouteCase
- describe "setting the charset of the response directly on the response object"
-
- get "/charset/base/set_on_response_obj"
- assert_body "Hello world!"
- assert_header "Content-Type", "text/html; charset=utf-16"
- end
-
- class TestSetAsNilOnResponseObj < SimpleRouteCase
- describe "setting the charset of the response as nil directly on the response object"
-
- get "/charset/base/set_as_nil_on_response_obj"
- assert_body "Hello world!"
- assert_header "Content-Type", "text/html; charset=utf-8"
- end
-end
\ No newline at end of file
+end
diff --git a/actionpack/test/new_base/etag_test.rb b/actionpack/test/new_base/etag_test.rb
index 7af5febfb3..c77636bb64 100644
--- a/actionpack/test/new_base/etag_test.rb
+++ b/actionpack/test/new_base/etag_test.rb
@@ -1,47 +1,46 @@
require File.join(File.expand_path(File.dirname(__FILE__)), "test_helper")
module Etags
-
class BasicController < ActionController::Base
-
self.view_paths = [ActionView::Template::FixturePath.new(
"etags/basic/base.html.erb" => "Hello from without_layout.html.erb",
"layouts/etags.html.erb" => "teh <%= yield %> tagz"
)]
-
+
def without_layout
render :action => "base"
end
-
+
def with_layout
render :action => "base", :layout => "etag"
end
-
end
-
- class TestBasic < SimpleRouteCase
+
+ class EtagTest < SimpleRouteCase
describe "Rendering without any special etag options returns an etag that is an MD5 hash of its text"
-
+
test "an action without a layout" do
get "/etags/basic/without_layout"
+
body = "Hello from without_layout.html.erb"
assert_body body
assert_header "Etag", etag_for(body)
assert_status 200
end
-
+
test "an action with a layout" do
get "/etags/basic/with_layout"
+
body = "teh Hello from without_layout.html.erb tagz"
assert_body body
assert_header "Etag", etag_for(body)
assert_status 200
end
-
+
+ private
+
def etag_for(text)
%("#{Digest::MD5.hexdigest(text)}")
end
end
-
-
end
\ No newline at end of file
diff --git a/actionpack/test/new_base/render_action_test.rb b/actionpack/test/new_base/render_action_test.rb
index 626c7b3540..4402eadf42 100644
--- a/actionpack/test/new_base/render_action_test.rb
+++ b/actionpack/test/new_base/render_action_test.rb
@@ -1,26 +1,24 @@
require File.join(File.expand_path(File.dirname(__FILE__)), "test_helper")
module RenderAction
-
# This has no layout and it works
class BasicController < ActionController::Base
-
self.view_paths = [ActionView::Template::FixturePath.new(
"render_action/basic/hello_world.html.erb" => "Hello world!"
)]
-
+
def hello_world
render :action => "hello_world"
end
-
+
def hello_world_as_string
render "hello_world"
end
-
+
def hello_world_as_string_with_options
render "hello_world", :status => 404
end
-
+
def hello_world_as_symbol
render :hello_world
end
@@ -28,107 +26,95 @@ module RenderAction
def hello_world_with_symbol
render :action => :hello_world
end
-
+
def hello_world_with_layout
render :action => "hello_world", :layout => true
end
-
+
def hello_world_with_layout_false
render :action => "hello_world", :layout => false
end
-
+
def hello_world_with_layout_nil
render :action => "hello_world", :layout => nil
end
-
+
def hello_world_with_custom_layout
render :action => "hello_world", :layout => "greetings"
end
-
- end
-
- class TestBasic < SimpleRouteCase
- describe "Rendering an action using :action => "
-
- get "/render_action/basic/hello_world"
- assert_body "Hello world!"
- assert_status 200
- end
-
- class TestWithString < SimpleRouteCase
- describe "Render an action using 'hello_world'"
-
- get "/render_action/basic/hello_world_as_string"
- assert_body "Hello world!"
- assert_status 200
- end
-
- class TestWithStringAndOptions < SimpleRouteCase
- describe "Render an action using 'hello_world'"
-
- get "/render_action/basic/hello_world_as_string_with_options"
- assert_body "Hello world!"
- assert_status 404
- end
-
- class TestAsSymbol < SimpleRouteCase
- describe "Render an action using :hello_world"
-
- get "/render_action/basic/hello_world_as_symbol"
- assert_body "Hello world!"
- assert_status 200
+
end
-
- class TestWithSymbol < SimpleRouteCase
- describe "Render an action using :action => :hello_world"
-
- get "/render_action/basic/hello_world_with_symbol"
- assert_body "Hello world!"
- assert_status 200
+
+ class RenderActionTest < SimpleRouteCase
+ test "rendering an action using :action => " do
+ get "/render_action/basic/hello_world"
+
+ assert_body "Hello world!"
+ assert_status 200
+ end
+
+ test "rendering an action using ''" do
+ get "/render_action/basic/hello_world_as_string"
+
+ assert_body "Hello world!"
+ assert_status 200
+ end
+
+ test "rendering an action using '' and options" do
+ get "/render_action/basic/hello_world_as_string_with_options"
+
+ assert_body "Hello world!"
+ assert_status 404
+ end
+
+ test "rendering an action using :action" do
+ get "/render_action/basic/hello_world_as_symbol"
+
+ assert_body "Hello world!"
+ assert_status 200
+ end
+
+ test "rendering an action using :action => :hello_world" do
+ get "/render_action/basic/hello_world_with_symbol"
+
+ assert_body "Hello world!"
+ assert_status 200
+ end
end
-
- class TestLayoutTrue < SimpleRouteCase
- describe "rendering a normal template with full path with layout => true"
-
- test "raises an exception when requesting a layout and none exist" do
- assert_raise(ArgumentError, /no default layout for RenderAction::BasicController in/) do
+
+ class RenderLayoutTest < SimpleRouteCase
+ describe "Both .html.erb and application.html.erb are missing"
+
+ test "rendering with layout => true" do
+ assert_raise(ArgumentError, /no default layout for RenderAction::BasicController in/) do
get "/render_action/basic/hello_world_with_layout", {}, "action_dispatch.show_exceptions" => false
end
end
- end
-
- class TestLayoutFalse < SimpleRouteCase
- describe "rendering a normal template with full path with layout => false"
-
- get "/render_action/basic/hello_world_with_layout_false"
- assert_body "Hello world!"
- assert_status 200
- end
-
- class TestLayoutNil < SimpleRouteCase
- describe "rendering a normal template with full path with layout => :nil"
-
- get "/render_action/basic/hello_world_with_layout_nil"
- assert_body "Hello world!"
- assert_status 200
- end
-
- class TestCustomLayout < SimpleRouteCase
- describe "rendering a normal template with full path with layout => 'greetings'"
-
- test "raises an exception when requesting a layout that does not exist" do
+
+ test "rendering with layout => false" do
+ get "/render_action/basic/hello_world_with_layout_false"
+
+ assert_body "Hello world!"
+ assert_status 200
+ end
+
+ test "rendering with layout => :nil" do
+ get "/render_action/basic/hello_world_with_layout_nil"
+
+ assert_body "Hello world!"
+ assert_status 200
+ end
+
+ test "rendering with layout => 'greetings'" do
assert_raise(ActionView::MissingTemplate) do
get "/render_action/basic/hello_world_with_custom_layout", {}, "action_dispatch.show_exceptions" => false
end
end
end
-
end
module RenderActionWithApplicationLayout
-
# # ==== Render actions with layouts ====
-
class BasicController < ::ApplicationController
# Set the view path to an application view structure with layouts
self.view_paths = self.view_paths = [ActionView::Template::FixturePath.new(
@@ -138,205 +124,197 @@ module RenderActionWithApplicationLayout
"layouts/greetings.html.erb" => "Greetings <%= yield %> Bai",
"layouts/builder.html.builder" => "xml.html do\n xml << yield\nend"
)]
-
+
def hello_world
render :action => "hello_world"
end
-
+
def hello_world_with_layout
render :action => "hello_world", :layout => true
end
-
+
def hello_world_with_layout_false
render :action => "hello_world", :layout => false
end
-
+
def hello_world_with_layout_nil
render :action => "hello_world", :layout => nil
end
-
+
def hello_world_with_custom_layout
render :action => "hello_world", :layout => "greetings"
end
-
+
def with_builder_and_layout
render :action => "hello", :layout => "builder"
end
end
-
- class TestDefaultLayout < SimpleRouteCase
- describe %(
- Render hello_world and implicitly use application.html.erb as a layout if
- no layout is specified and no controller layout is present
- )
-
- get "/render_action_with_application_layout/basic/hello_world"
- assert_body "OHAI Hello World! KTHXBAI"
- assert_status 200
- end
-
- class TestLayoutTrue < SimpleRouteCase
- describe "rendering a normal template with full path with layout => true"
-
- get "/render_action_with_application_layout/basic/hello_world_with_layout"
- assert_body "OHAI Hello World! KTHXBAI"
- assert_status 200
- end
-
- class TestLayoutFalse < SimpleRouteCase
- describe "rendering a normal template with full path with layout => false"
-
- get "/render_action_with_application_layout/basic/hello_world_with_layout_false"
- assert_body "Hello World!"
- assert_status 200
- end
-
- class TestLayoutNil < SimpleRouteCase
- describe "rendering a normal template with full path with layout => :nil"
-
- get "/render_action_with_application_layout/basic/hello_world_with_layout_nil"
- assert_body "Hello World!"
- assert_status 200
- end
-
- class TestCustomLayout < SimpleRouteCase
- describe "rendering a normal template with full path with layout => 'greetings'"
-
- get "/render_action_with_application_layout/basic/hello_world_with_custom_layout"
- assert_body "Greetings Hello World! Bai"
- assert_status 200
+
+ class LayoutTest < SimpleRouteCase
+ describe "Only application.html.erb is present and .html.erb is missing"
+
+ test "rendering implicit application.html.erb as layout" do
+ get "/render_action_with_application_layout/basic/hello_world"
+
+ assert_body "OHAI Hello World! KTHXBAI"
+ assert_status 200
+ end
+
+ test "rendering with layout => true" do
+ get "/render_action_with_application_layout/basic/hello_world_with_layout"
+
+ assert_body "OHAI Hello World! KTHXBAI"
+ assert_status 200
+ end
+
+ test "rendering with layout => false" do
+ get "/render_action_with_application_layout/basic/hello_world_with_layout_false"
+
+ assert_body "Hello World!"
+ assert_status 200
+ end
+
+ test "rendering with layout => :nil" do
+ get "/render_action_with_application_layout/basic/hello_world_with_layout_nil"
+
+ assert_body "Hello World!"
+ assert_status 200
+ end
+
+ test "rendering with layout => 'greetings'" do
+ get "/render_action_with_application_layout/basic/hello_world_with_custom_layout"
+
+ assert_body "Greetings Hello World! Bai"
+ assert_status 200
+ end
end
-
+
class TestLayout < SimpleRouteCase
testing BasicController
-
+
test "builder works with layouts" do
get :with_builder_and_layout
assert_response "\n
Omg
\n\n"
end
end
-
+
end
module RenderActionWithControllerLayout
-
class BasicController < ActionController::Base
self.view_paths = self.view_paths = [ActionView::Template::FixturePath.new(
"render_action_with_controller_layout/basic/hello_world.html.erb" => "Hello World!",
"layouts/render_action_with_controller_layout/basic.html.erb" => "With Controller Layout! <%= yield %> KTHXBAI"
)]
-
+
def hello_world
render :action => "hello_world"
end
-
+
def hello_world_with_layout
render :action => "hello_world", :layout => true
end
-
+
def hello_world_with_layout_false
render :action => "hello_world", :layout => false
end
-
+
def hello_world_with_layout_nil
render :action => "hello_world", :layout => nil
end
-
+
def hello_world_with_custom_layout
render :action => "hello_world", :layout => "greetings"
end
end
-
- class TestControllerLayout < SimpleRouteCase
- describe "Render hello_world and implicitly use .html.erb as a layout."
- get "/render_action_with_controller_layout/basic/hello_world"
- assert_body "With Controller Layout! Hello World! KTHXBAI"
- assert_status 200
- end
-
- class TestLayoutTrue < SimpleRouteCase
- describe "rendering a normal template with full path with layout => true"
-
- get "/render_action_with_controller_layout/basic/hello_world_with_layout"
- assert_body "With Controller Layout! Hello World! KTHXBAI"
- assert_status 200
- end
-
- class TestLayoutFalse < SimpleRouteCase
- describe "rendering a normal template with full path with layout => false"
-
- get "/render_action_with_controller_layout/basic/hello_world_with_layout_false"
- assert_body "Hello World!"
- assert_status 200
- end
-
- class TestLayoutNil < SimpleRouteCase
- describe "rendering a normal template with full path with layout => :nil"
-
- get "/render_action_with_controller_layout/basic/hello_world_with_layout_nil"
- assert_body "Hello World!"
- assert_status 200
+ class ControllerLayoutTest < SimpleRouteCase
+ describe "Only .html.erb is present and application.html.erb is missing"
+
+ test "render hello_world and implicitly use .html.erb as a layout." do
+ get "/render_action_with_controller_layout/basic/hello_world"
+
+ assert_body "With Controller Layout! Hello World! KTHXBAI"
+ assert_status 200
+ end
+
+ test "rendering with layout => true" do
+ get "/render_action_with_controller_layout/basic/hello_world_with_layout"
+
+ assert_body "With Controller Layout! Hello World! KTHXBAI"
+ assert_status 200
+ end
+
+ test "rendering with layout => false" do
+ get "/render_action_with_controller_layout/basic/hello_world_with_layout_false"
+
+ assert_body "Hello World!"
+ assert_status 200
+ end
+
+ test "rendering with layout => :nil" do
+ get "/render_action_with_controller_layout/basic/hello_world_with_layout_nil"
+
+ assert_body "Hello World!"
+ assert_status 200
+ end
end
-
end
module RenderActionWithBothLayouts
-
class BasicController < ActionController::Base
self.view_paths = [ActionView::Template::FixturePath.new({
"render_action_with_both_layouts/basic/hello_world.html.erb" => "Hello World!",
"layouts/application.html.erb" => "OHAI <%= yield %> KTHXBAI",
"layouts/render_action_with_both_layouts/basic.html.erb" => "With Controller Layout! <%= yield %> KTHXBAI"
})]
-
+
def hello_world
render :action => "hello_world"
end
-
+
def hello_world_with_layout
render :action => "hello_world", :layout => true
end
-
+
def hello_world_with_layout_false
render :action => "hello_world", :layout => false
end
-
+
def hello_world_with_layout_nil
render :action => "hello_world", :layout => nil
end
end
-
- class TestControllerLayoutFirst < SimpleRouteCase
- describe "Render hello_world and implicitly use .html.erb over application.html.erb as a layout"
- get "/render_action_with_both_layouts/basic/hello_world"
- assert_body "With Controller Layout! Hello World! KTHXBAI"
- assert_status 200
- end
-
- class TestLayoutTrue < SimpleRouteCase
- describe "rendering a normal template with full path with layout => true"
-
- get "/render_action_with_both_layouts/basic/hello_world_with_layout"
- assert_body "With Controller Layout! Hello World! KTHXBAI"
- assert_status 200
- end
-
- class TestLayoutFalse < SimpleRouteCase
- describe "rendering a normal template with full path with layout => false"
-
- get "/render_action_with_both_layouts/basic/hello_world_with_layout_false"
- assert_body "Hello World!"
- assert_status 200
- end
-
- class TestLayoutNil < SimpleRouteCase
- describe "rendering a normal template with full path with layout => :nil"
-
- get "/render_action_with_both_layouts/basic/hello_world_with_layout_nil"
- assert_body "Hello World!"
- assert_status 200
+ class ControllerLayoutTest < SimpleRouteCase
+ describe "Both .html.erb and application.html.erb are present"
+
+ test "rendering implicitly use .html.erb over application.html.erb as a layout" do
+ get "/render_action_with_both_layouts/basic/hello_world"
+
+ assert_body "With Controller Layout! Hello World! KTHXBAI"
+ assert_status 200
+ end
+
+ test "rendering with layout => true" do
+ get "/render_action_with_both_layouts/basic/hello_world_with_layout"
+
+ assert_body "With Controller Layout! Hello World! KTHXBAI"
+ assert_status 200
+ end
+
+ test "rendering with layout => false" do
+ get "/render_action_with_both_layouts/basic/hello_world_with_layout_false"
+
+ assert_body "Hello World!"
+ assert_status 200
+ end
+
+ test "rendering with layout => :nil" do
+ get "/render_action_with_both_layouts/basic/hello_world_with_layout_nil"
+
+ assert_body "Hello World!"
+ assert_status 200
+ end
end
-
end
\ No newline at end of file
diff --git a/actionpack/test/new_base/render_implicit_action_test.rb b/actionpack/test/new_base/render_implicit_action_test.rb
index 58f5cec181..2846df48da 100644
--- a/actionpack/test/new_base/render_implicit_action_test.rb
+++ b/actionpack/test/new_base/render_implicit_action_test.rb
@@ -10,19 +10,19 @@ module RenderImplicitAction
def hello_world() end
end
- class TestImplicitRender < SimpleRouteCase
- describe "render a simple action with new explicit call to render"
-
- get "/render_implicit_action/simple/hello_world"
- assert_body "Hello world!"
- assert_status 200
- end
-
- class TestImplicitWithSpecialCharactersRender < SimpleRouteCase
- describe "render an action with a missing method and has special characters"
-
- get "/render_implicit_action/simple/hyphen-ated"
- assert_body "Hello hyphen-ated!"
- assert_status 200
+ class RenderImplicitActionTest < SimpleRouteCase
+ test "render a simple action with new explicit call to render" do
+ get "/render_implicit_action/simple/hello_world"
+
+ assert_body "Hello world!"
+ assert_status 200
+ end
+
+ test "render an action with a missing method and has special characters" do
+ get "/render_implicit_action/simple/hyphen-ated"
+
+ assert_body "Hello hyphen-ated!"
+ assert_status 200
+ end
end
end
\ No newline at end of file
diff --git a/actionpack/test/new_base/render_layout_test.rb b/actionpack/test/new_base/render_layout_test.rb
index dc858b4f5c..76bd5175a3 100644
--- a/actionpack/test/new_base/render_layout_test.rb
+++ b/actionpack/test/new_base/render_layout_test.rb
@@ -2,69 +2,65 @@ require File.join(File.expand_path(File.dirname(__FILE__)), "test_helper")
module ControllerLayouts
class ImplicitController < ::ApplicationController
-
self.view_paths = [ActionView::Template::FixturePath.new(
"layouts/application.html.erb" => "OMG <%= yield %> KTHXBAI",
"layouts/override.html.erb" => "Override! <%= yield %>",
"basic.html.erb" => "Hello world!",
"controller_layouts/implicit/layout_false.html.erb" => "hai(layout_false.html.erb)"
)]
-
+
def index
render :template => "basic"
end
-
+
def override
render :template => "basic", :layout => "override"
end
-
+
def layout_false
render :layout => false
end
-
+
def builder_override
-
end
end
-
- class TestImplicitLayout < SimpleRouteCase
- describe "rendering a normal template, but using the implicit layout"
-
- get "/controller_layouts/implicit/index"
- assert_body "OMG Hello world! KTHXBAI"
- assert_status 200
- end
-
+
class ImplicitNameController < ::ApplicationController
-
self.view_paths = [ActionView::Template::FixturePath.new(
"layouts/controller_layouts/implicit_name.html.erb" => "OMGIMPLICIT <%= yield %> KTHXBAI",
"basic.html.erb" => "Hello world!"
)]
-
+
def index
render :template => "basic"
end
end
-
- class TestImplicitNamedLayout < SimpleRouteCase
- describe "rendering a normal template, but using an implicit NAMED layout"
-
- get "/controller_layouts/implicit_name/index"
- assert_body "OMGIMPLICIT Hello world! KTHXBAI"
- assert_status 200
- end
-
- class TestOverridingImplicitLayout < SimpleRouteCase
- describe "overriding an implicit layout with render :layout option"
-
- get "/controller_layouts/implicit/override"
- assert_body "Override! Hello world!"
+
+ class RenderLayoutTest < SimpleRouteCase
+ test "rendering a normal template, but using the implicit layout" do
+ get "/controller_layouts/implicit/index"
+
+ assert_body "OMG Hello world! KTHXBAI"
+ assert_status 200
+ end
+
+ test "rendering a normal template, but using an implicit NAMED layout" do
+ get "/controller_layouts/implicit_name/index"
+
+ assert_body "OMGIMPLICIT Hello world! KTHXBAI"
+ assert_status 200
+ end
+
+ test "overriding an implicit layout with render :layout option" do
+ get "/controller_layouts/implicit/override"
+ assert_body "Override! Hello world!"
+ end
+
end
-
- class TestLayoutOptions < SimpleRouteCase
+
+ class LayoutOptionsTest < SimpleRouteCase
testing ControllerLayouts::ImplicitController
-
+
test "rendering with :layout => false leaves out the implicit layout" do
get :layout_false
assert_response "hai(layout_false.html.erb)"
diff --git a/actionpack/test/new_base/render_template_test.rb b/actionpack/test/new_base/render_template_test.rb
index 6c50ae4203..face5b7571 100644
--- a/actionpack/test/new_base/render_template_test.rb
+++ b/actionpack/test/new_base/render_template_test.rb
@@ -79,7 +79,6 @@ module RenderTemplate
end
class WithLayoutController < ::ApplicationController
-
self.view_paths = [ActionView::Template::FixturePath.new(
"test/basic.html.erb" => "Hello from basic.html.erb",
"shared.html.erb" => "Elastica",
@@ -108,46 +107,45 @@ module RenderTemplate
end
end
- class TestTemplateRenderWithLayout < SimpleRouteCase
- describe "rendering a normal template with full path with layout"
-
- get "/render_template/with_layout"
- assert_body "Hello from basic.html.erb, I'm here!"
- assert_status 200
- end
-
- class TestTemplateRenderWithLayoutTrue < SimpleRouteCase
- describe "rendering a normal template with full path with layout => :true"
-
- get "/render_template/with_layout/with_layout"
- assert_body "Hello from basic.html.erb, I'm here!"
- assert_status 200
- end
-
- class TestTemplateRenderWithLayoutFalse < SimpleRouteCase
- describe "rendering a normal template with full path with layout => :false"
-
- get "/render_template/with_layout/with_layout_false"
- assert_body "Hello from basic.html.erb"
- assert_status 200
- end
-
- class TestTemplateRenderWithLayoutNil < SimpleRouteCase
- describe "rendering a normal template with full path with layout => :nil"
-
- get "/render_template/with_layout/with_layout_nil"
- assert_body "Hello from basic.html.erb"
- assert_status 200
- end
-
- class TestTemplateRenderWithCustomLayout < SimpleRouteCase
- describe "rendering a normal template with full path with layout => 'greetings'"
-
- get "/render_template/with_layout/with_custom_layout"
- assert_body "Hello from basic.html.erb, I wish thee well."
- assert_status 200
+ class TestWithLayout < SimpleRouteCase
+ describe "Rendering with :template using implicit or explicit layout"
+
+ test "rendering with implicit layout" do
+ get "/render_template/with_layout"
+
+ assert_body "Hello from basic.html.erb, I'm here!"
+ assert_status 200
+ end
+
+ test "rendering with layout => :true" do
+ get "/render_template/with_layout/with_layout"
+
+ assert_body "Hello from basic.html.erb, I'm here!"
+ assert_status 200
+ end
+
+ test "rendering with layout => :false" do
+ get "/render_template/with_layout/with_layout_false"
+
+ assert_body "Hello from basic.html.erb"
+ assert_status 200
+ end
+
+ test "rendering with layout => :nil" do
+ get "/render_template/with_layout/with_layout_nil"
+
+ assert_body "Hello from basic.html.erb"
+ assert_status 200
+ end
+
+ test "rendering layout => 'greetings'" do
+ get "/render_template/with_layout/with_custom_layout"
+
+ assert_body "Hello from basic.html.erb, I wish thee well."
+ assert_status 200
+ end
end
-
+
module Compatibility
class WithoutLayoutController < ActionController::Base
self.view_paths = [ActionView::Template::FixturePath.new(
@@ -161,11 +159,12 @@ module RenderTemplate
end
class TestTemplateRenderWithForwardSlash < SimpleRouteCase
- describe "rendering a normal template with full path starting with a leading slash"
+ test "rendering a normal template with full path starting with a leading slash" do
+ get "/render_template/compatibility/without_layout/with_forward_slash"
- get "/render_template/compatibility/without_layout/with_forward_slash"
- assert_body "Hello from basic.html.erb"
- assert_status 200
+ assert_body "Hello from basic.html.erb"
+ assert_status 200
+ end
end
end
end
\ No newline at end of file
diff --git a/actionpack/test/new_base/render_test.rb b/actionpack/test/new_base/render_test.rb
index ef5e7d89c5..ed3d50fa0b 100644
--- a/actionpack/test/new_base/render_test.rb
+++ b/actionpack/test/new_base/render_test.rb
@@ -8,60 +8,57 @@ module Render
"render/blank_render/access_action_name.html.erb" => "Action Name: <%= action_name %>",
"render/blank_render/access_controller_name.html.erb" => "Controller Name: <%= controller_name %>"
)]
-
+
def index
render
end
-
+
def access_request
render :action => "access_request"
end
-
+
def render_action_name
render :action => "access_action_name"
end
-
- private
-
+
+ private
+
def secretz
render :text => "FAIL WHALE!"
end
end
-
- class TestBlankRender < SimpleRouteCase
- describe "Render with blank"
- get "/render/blank_render"
- assert_body "Hello world!"
- assert_status 200
- end
-
class DoubleRenderController < ActionController::Base
def index
render :text => "hello"
render :text => "world"
end
end
-
- class TestBasic < SimpleRouteCase
- describe "Rendering more than once"
-
- test "raises an exception" do
+
+ class RenderTest < SimpleRouteCase
+ test "render with blank" do
+ get "/render/blank_render"
+
+ assert_body "Hello world!"
+ assert_status 200
+ end
+
+ test "rendering more than once raises an exception" do
assert_raises(AbstractController::DoubleRenderError) do
get "/render/double_render", {}, "action_dispatch.show_exceptions" => false
end
end
end
-
+
class TestOnlyRenderPublicActions < SimpleRouteCase
describe "Only public methods on actual controllers are callable actions"
-
+
test "raises an exception when a method of Object is called" do
assert_raises(AbstractController::ActionNotFound) do
get "/render/blank_render/clone", {}, "action_dispatch.show_exceptions" => false
end
end
-
+
test "raises an exception when a private method is called" do
assert_raises(AbstractController::ActionNotFound) do
get "/render/blank_render/secretz", {}, "action_dispatch.show_exceptions" => false
@@ -74,12 +71,12 @@ module Render
get "/render/blank_render/access_request"
assert_body "The request: GET"
end
-
+
test "The action_name is accessible in the view" do
get "/render/blank_render/render_action_name"
assert_body "Action Name: render_action_name"
end
-
+
test "The controller_name is accessible in the view" do
get "/render/blank_render/access_controller_name"
assert_body "Controller Name: blank_render"
diff --git a/actionpack/test/new_base/render_text_test.rb b/actionpack/test/new_base/render_text_test.rb
index 39f2f7abbf..69594e4b64 100644
--- a/actionpack/test/new_base/render_text_test.rb
+++ b/actionpack/test/new_base/render_text_test.rb
@@ -11,15 +11,7 @@ module RenderText
render :text => "hello david"
end
end
-
- class TestSimpleTextRenderWithNoLayout < SimpleRouteCase
- describe "Rendering text from a action with default options renders the text with the layout"
-
- get "/render_text/simple"
- assert_body "hello david"
- assert_status 200
- end
-
+
class WithLayoutController < ::ApplicationController
self.view_paths = [ActionView::Template::FixturePath.new(
"layouts/application.html.erb" => "<%= yield %>, I'm here!",
@@ -73,76 +65,77 @@ module RenderText
end
end
- class TestSimpleTextRenderWithLayout < SimpleRouteCase
- describe "Rendering text from a action with default options renders the text without the layout"
-
- get "/render_text/with_layout"
- assert_body "hello david"
- assert_status 200
- end
-
- class TestTextRenderWithStatus < SimpleRouteCase
- describe "Rendering text, while also providing a custom status code"
-
- get "/render_text/with_layout/custom_code"
- assert_body "hello world"
- assert_status 404
- end
-
- class TestTextRenderWithNil < SimpleRouteCase
- describe "Rendering text with nil returns a single space character"
-
- get "/render_text/with_layout/with_nil"
- assert_body " "
- assert_status 200
- end
-
- class TestTextRenderWithNilAndStatus < SimpleRouteCase
- describe "Rendering text with nil and custom status code returns a single space character with the status"
-
- get "/render_text/with_layout/with_nil_and_status"
- assert_body " "
- assert_status 403
- end
-
- class TestTextRenderWithFalse < SimpleRouteCase
- describe "Rendering text with false returns the string 'false'"
-
- get "/render_text/with_layout/with_false"
- assert_body "false"
- assert_status 200
- end
-
- class TestTextRenderWithLayoutTrue < SimpleRouteCase
- describe "Rendering text with :layout => true"
-
- get "/render_text/with_layout/with_layout_true"
- assert_body "hello world, I'm here!"
- assert_status 200
- end
-
- class TestTextRenderWithCustomLayout < SimpleRouteCase
- describe "Rendering text with :layout => 'greetings'"
-
- get "/render_text/with_layout/with_custom_layout"
- assert_body "hello world, I wish thee well."
- assert_status 200
- end
-
- class TestTextRenderWithLayoutFalse < SimpleRouteCase
- describe "Rendering text with :layout => false"
-
- get "/render_text/with_layout/with_layout_false"
- assert_body "hello world"
- assert_status 200
- end
-
- class TestTextRenderWithLayoutNil < SimpleRouteCase
- describe "Rendering text with :layout => nil"
-
- get "/render_text/with_layout/with_layout_nil"
- assert_body "hello world"
- assert_status 200
+ class RenderTextTest < SimpleRouteCase
+ describe "Rendering text using render :text"
+
+ test "rendering text from a action with default options renders the text with the layout" do
+ get "/render_text/simple"
+ assert_body "hello david"
+ assert_status 200
+ end
+
+ test "rendering text from a action with default options renders the text without the layout" do
+ get "/render_text/with_layout"
+
+ assert_body "hello david"
+ assert_status 200
+ end
+
+ test "rendering text, while also providing a custom status code" do
+ get "/render_text/with_layout/custom_code"
+
+ assert_body "hello world"
+ assert_status 404
+ end
+
+ test "rendering text with nil returns a single space character" do
+ get "/render_text/with_layout/with_nil"
+
+ assert_body " "
+ assert_status 200
+ end
+
+ test "Rendering text with nil and custom status code returns a single space character with the status" do
+ get "/render_text/with_layout/with_nil_and_status"
+
+ assert_body " "
+ assert_status 403
+ end
+
+ test "rendering text with false returns the string 'false'" do
+ get "/render_text/with_layout/with_false"
+
+ assert_body "false"
+ assert_status 200
+ end
+
+ test "rendering text with :layout => true" do
+ get "/render_text/with_layout/with_layout_true"
+
+ assert_body "hello world, I'm here!"
+ assert_status 200
+ end
+
+ test "rendering text with :layout => 'greetings'" do
+ get "/render_text/with_layout/with_custom_layout"
+
+ assert_body "hello world, I wish thee well."
+ assert_status 200
+ end
+
+ test "rendering text with :layout => false" do
+ get "/render_text/with_layout/with_layout_false"
+
+ assert_body "hello world"
+ assert_status 200
+ end
+
+ test "rendering text with :layout => nil" do
+ get "/render_text/with_layout/with_layout_nil"
+
+ assert_body "hello world"
+ assert_status 200
+ end
end
end
diff --git a/actionpack/test/new_base/test_helper.rb b/actionpack/test/new_base/test_helper.rb
index 9401e692f1..89c1290063 100644
--- a/actionpack/test/new_base/test_helper.rb
+++ b/actionpack/test/new_base/test_helper.rb
@@ -36,13 +36,13 @@ class Rack::TestCase < ActionController::IntegrationTest
setup do
ActionController::Base.session_options[:key] = "abc"
ActionController::Base.session_options[:secret] = ("*" * 30)
-
+
controllers = ActionController::Base.subclasses.map do |k|
k.underscore.sub(/_controller$/, '')
end
-
+
ActionController::Routing.use_controllers!(controllers)
-
+
# Move into a bootloader
ActionController::Base.subclasses.each do |klass|
klass = klass.constantize
@@ -50,13 +50,13 @@ class Rack::TestCase < ActionController::IntegrationTest
klass.class_eval do
_write_layout_method
end
- end
+ end
end
-
+
def app
@app ||= ActionController::Dispatcher.new
end
-
+
def self.testing(klass = nil)
if klass
@testing = "/#{klass.name.underscore}".sub!(/_controller$/, '')
@@ -64,13 +64,7 @@ class Rack::TestCase < ActionController::IntegrationTest
@testing
end
end
-
- def self.get(url)
- setup do |test|
- test.get url
- end
- end
-
+
def get(thing, *args)
if thing.is_a?(Symbol)
super("#{self.class.testing}/#{thing}")
@@ -78,27 +72,15 @@ class Rack::TestCase < ActionController::IntegrationTest
super
end
end
-
+
def assert_body(body)
assert_equal body, Array.wrap(response.body).join
end
-
- def self.assert_body(body)
- test "body is set to '#{body}'" do
- assert_body body
- end
- end
-
+
def assert_status(code)
assert_equal code, response.status
end
-
- def self.assert_status(code)
- test "status code is set to #{code}" do
- assert_status code
- end
- end
-
+
def assert_response(body, status = 200, headers = {})
assert_body body
assert_status status
@@ -106,27 +88,14 @@ class Rack::TestCase < ActionController::IntegrationTest
assert_header header, value
end
end
-
+
def assert_content_type(type)
assert_equal type, response.headers["Content-Type"]
end
-
- def self.assert_content_type(type)
- test "content type is set to #{type}" do
- assert_content_type(type)
- end
- end
-
+
def assert_header(name, value)
assert_equal value, response.headers[name]
end
-
- def self.assert_header(name, value)
- test "'#{name}' header is set to #{value.inspect}" do
- assert_header(name, value)
- end
- end
-
end
class ::ApplicationController < ActionController::Base
--
cgit v1.2.3
From 01f032f256f96f65e154061b582fbb4b32e4a692 Mon Sep 17 00:00:00 2001
From: Yehuda Katz + Carl Lerche
Date: Wed, 20 May 2009 15:33:08 -0700
Subject: Added responds_to to new base.
---
.../lib/action_controller/abstract/layouts.rb | 7 +-
.../lib/action_controller/base/mime_responds.rb | 215 ++++++++++-----------
actionpack/lib/action_controller/new_base.rb | 1 +
actionpack/lib/action_controller/new_base/base.rb | 1 +
.../action_controller/new_base/compatibility.rb | 11 +-
.../lib/action_controller/new_base/renderer.rb | 2 +-
.../lib/action_controller/new_base/testing.rb | 2 +-
.../lib/action_controller/testing/process.rb | 1 +
actionpack/lib/action_view/template/text.rb | 7 +-
actionpack/test/controller/caching_test.rb | 2 +
actionpack/test/controller/mime_responds_test.rb | 24 ++-
11 files changed, 148 insertions(+), 125 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_controller/abstract/layouts.rb b/actionpack/lib/action_controller/abstract/layouts.rb
index 35d5e85ed9..96cb05972f 100644
--- a/actionpack/lib/action_controller/abstract/layouts.rb
+++ b/actionpack/lib/action_controller/abstract/layouts.rb
@@ -66,7 +66,12 @@ module AbstractController
raise ArgumentError, "String, false, or nil expected; you passed #{name.inspect}"
end
- name && view_paths.find_by_parts(name, {:formats => formats}, "layouts")
+ name && view_paths.find_by_parts(name, {:formats => formats}, _layout_prefix(name))
+ end
+
+ # TODO: Decide if this is the best hook point for the feature
+ def _layout_prefix(name)
+ "layouts"
end
def _default_layout(require_layout = false)
diff --git a/actionpack/lib/action_controller/base/mime_responds.rb b/actionpack/lib/action_controller/base/mime_responds.rb
index 1003e61a0b..e560376e0d 100644
--- a/actionpack/lib/action_controller/base/mime_responds.rb
+++ b/actionpack/lib/action_controller/base/mime_responds.rb
@@ -1,111 +1,103 @@
module ActionController #:nodoc:
module MimeResponds #:nodoc:
- def self.included(base)
- base.module_eval do
- include ActionController::MimeResponds::InstanceMethods
- end
- end
-
- module InstanceMethods
- # Without web-service support, an action which collects the data for displaying a list of people
- # might look something like this:
- #
- # def index
- # @people = Person.find(:all)
- # end
- #
- # Here's the same action, with web-service support baked in:
- #
- # def index
- # @people = Person.find(:all)
- #
- # respond_to do |format|
- # format.html
- # format.xml { render :xml => @people.to_xml }
- # end
- # end
- #
- # What that says is, "if the client wants HTML in response to this action, just respond as we
- # would have before, but if the client wants XML, return them the list of people in XML format."
- # (Rails determines the desired response format from the HTTP Accept header submitted by the client.)
- #
- # Supposing you have an action that adds a new person, optionally creating their company
- # (by name) if it does not already exist, without web-services, it might look like this:
- #
- # def create
- # @company = Company.find_or_create_by_name(params[:company][:name])
- # @person = @company.people.create(params[:person])
- #
- # redirect_to(person_list_url)
- # end
- #
- # Here's the same action, with web-service support baked in:
- #
- # def create
- # company = params[:person].delete(:company)
- # @company = Company.find_or_create_by_name(company[:name])
- # @person = @company.people.create(params[:person])
- #
- # respond_to do |format|
- # format.html { redirect_to(person_list_url) }
- # format.js
- # format.xml { render :xml => @person.to_xml(:include => @company) }
- # end
- # end
- #
- # If the client wants HTML, we just redirect them back to the person list. If they want Javascript
- # (format.js), then it is an RJS request and we render the RJS template associated with this action.
- # Lastly, if the client wants XML, we render the created person as XML, but with a twist: we also
- # include the person's company in the rendered XML, so you get something like this:
- #
- #
- # ...
- # ...
- #
- # ...
- # ...
- # ...
- #
- #
- #
- # Note, however, the extra bit at the top of that action:
- #
- # company = params[:person].delete(:company)
- # @company = Company.find_or_create_by_name(company[:name])
- #
- # This is because the incoming XML document (if a web-service request is in process) can only contain a
- # single root-node. So, we have to rearrange things so that the request looks like this (url-encoded):
- #
- # person[name]=...&person[company][name]=...&...
- #
- # And, like this (xml-encoded):
- #
- #
- # ...
- #
- # ...
- #
- #
- #
- # In other words, we make the request so that it operates on a single entity's person. Then, in the action,
- # we extract the company data from the request, find or create the company, and then create the new person
- # with the remaining data.
- #
- # Note that you can define your own XML parameter parser which would allow you to describe multiple entities
- # in a single request (i.e., by wrapping them all in a single root node), but if you just go with the flow
- # and accept Rails' defaults, life will be much easier.
- #
- # If you need to use a MIME type which isn't supported by default, you can register your own handlers in
- # environment.rb as follows.
- #
- # Mime::Type.register "image/jpg", :jpg
- def respond_to(*types, &block)
- raise ArgumentError, "respond_to takes either types or a block, never both" unless types.any? ^ block
- block ||= lambda { |responder| types.each { |type| responder.send(type) } }
- responder = Responder.new(self)
- block.call(responder)
- responder.respond
- end
+ # Without web-service support, an action which collects the data for displaying a list of people
+ # might look something like this:
+ #
+ # def index
+ # @people = Person.find(:all)
+ # end
+ #
+ # Here's the same action, with web-service support baked in:
+ #
+ # def index
+ # @people = Person.find(:all)
+ #
+ # respond_to do |format|
+ # format.html
+ # format.xml { render :xml => @people.to_xml }
+ # end
+ # end
+ #
+ # What that says is, "if the client wants HTML in response to this action, just respond as we
+ # would have before, but if the client wants XML, return them the list of people in XML format."
+ # (Rails determines the desired response format from the HTTP Accept header submitted by the client.)
+ #
+ # Supposing you have an action that adds a new person, optionally creating their company
+ # (by name) if it does not already exist, without web-services, it might look like this:
+ #
+ # def create
+ # @company = Company.find_or_create_by_name(params[:company][:name])
+ # @person = @company.people.create(params[:person])
+ #
+ # redirect_to(person_list_url)
+ # end
+ #
+ # Here's the same action, with web-service support baked in:
+ #
+ # def create
+ # company = params[:person].delete(:company)
+ # @company = Company.find_or_create_by_name(company[:name])
+ # @person = @company.people.create(params[:person])
+ #
+ # respond_to do |format|
+ # format.html { redirect_to(person_list_url) }
+ # format.js
+ # format.xml { render :xml => @person.to_xml(:include => @company) }
+ # end
+ # end
+ #
+ # If the client wants HTML, we just redirect them back to the person list. If they want Javascript
+ # (format.js), then it is an RJS request and we render the RJS template associated with this action.
+ # Lastly, if the client wants XML, we render the created person as XML, but with a twist: we also
+ # include the person's company in the rendered XML, so you get something like this:
+ #
+ #
+ # ...
+ # ...
+ #
+ # ...
+ # ...
+ # ...
+ #
+ #
+ #
+ # Note, however, the extra bit at the top of that action:
+ #
+ # company = params[:person].delete(:company)
+ # @company = Company.find_or_create_by_name(company[:name])
+ #
+ # This is because the incoming XML document (if a web-service request is in process) can only contain a
+ # single root-node. So, we have to rearrange things so that the request looks like this (url-encoded):
+ #
+ # person[name]=...&person[company][name]=...&...
+ #
+ # And, like this (xml-encoded):
+ #
+ #
+ # ...
+ #
+ # ...
+ #
+ #
+ #
+ # In other words, we make the request so that it operates on a single entity's person. Then, in the action,
+ # we extract the company data from the request, find or create the company, and then create the new person
+ # with the remaining data.
+ #
+ # Note that you can define your own XML parameter parser which would allow you to describe multiple entities
+ # in a single request (i.e., by wrapping them all in a single root node), but if you just go with the flow
+ # and accept Rails' defaults, life will be much easier.
+ #
+ # If you need to use a MIME type which isn't supported by default, you can register your own handlers in
+ # environment.rb as follows.
+ #
+ # Mime::Type.register "image/jpg", :jpg
+ def respond_to(*types, &block)
+ raise ArgumentError, "respond_to takes either types or a block, never both" unless types.any? ^ block
+ block ||= lambda { |responder| types.each { |type| responder.send(type) } }
+ responder = Responder.new(self)
+ block.call(responder)
+ responder.respond
end
class Responder #:nodoc:
@@ -127,8 +119,15 @@ module ActionController #:nodoc:
@order << mime_type
@responses[mime_type] ||= Proc.new do
- @controller.template.formats = [mime_type.to_sym]
- @response.content_type = mime_type.to_s
+ # TODO: Remove this when new base is merged in
+ if defined?(Http)
+ @controller.formats = [mime_type.to_sym]
+ @controller.template.formats = [mime_type.to_sym]
+ else
+ @controller.template.formats = [mime_type.to_sym]
+ @response.content_type = mime_type.to_s
+ end
+
block_given? ? block.call : @controller.send(:render, :action => @controller.action_name)
end
end
diff --git a/actionpack/lib/action_controller/new_base.rb b/actionpack/lib/action_controller/new_base.rb
index 078f66ced1..3fc5d82d01 100644
--- a/actionpack/lib/action_controller/new_base.rb
+++ b/actionpack/lib/action_controller/new_base.rb
@@ -15,6 +15,7 @@ module ActionController
# require 'action_controller/routing'
autoload :Caching, 'action_controller/caching'
autoload :Dispatcher, 'action_controller/dispatch/dispatcher'
+ autoload :MimeResponds, 'action_controller/base/mime_responds'
autoload :PolymorphicRoutes, 'action_controller/routing/generation/polymorphic_routes'
autoload :RecordIdentifier, 'action_controller/record_identifier'
autoload :Resources, 'action_controller/routing/resources'
diff --git a/actionpack/lib/action_controller/new_base/base.rb b/actionpack/lib/action_controller/new_base/base.rb
index 7f830307b6..3d8d46c9c2 100644
--- a/actionpack/lib/action_controller/new_base/base.rb
+++ b/actionpack/lib/action_controller/new_base/base.rb
@@ -18,6 +18,7 @@ module ActionController
include SessionManagement
include ActionDispatch::StatusCodes
include ActionController::Caching
+ include ActionController::MimeResponds
# Rails 2.x compatibility
include ActionController::Rails2Compatibility
diff --git a/actionpack/lib/action_controller/new_base/compatibility.rb b/actionpack/lib/action_controller/new_base/compatibility.rb
index 0098c0747e..c861af2fa2 100644
--- a/actionpack/lib/action_controller/new_base/compatibility.rb
+++ b/actionpack/lib/action_controller/new_base/compatibility.rb
@@ -59,6 +59,11 @@ module ActionController
def initialize_template_class(*) end
def assign_shortcuts(*) end
+ # TODO: Remove this after we flip
+ def template
+ _action_view
+ end
+
module ClassMethods
def protect_from_forgery() end
def consider_all_requests_local() end
@@ -95,10 +100,8 @@ module ActionController
super || (respond_to?(:method_missing) && "_handle_method_missing")
end
- def _layout_for_name(name)
- name &&= name.sub(%r{^/?layouts/}, '')
- super
+ def _layout_prefix(name)
+ super unless name =~ /\blayouts/
end
-
end
end
\ No newline at end of file
diff --git a/actionpack/lib/action_controller/new_base/renderer.rb b/actionpack/lib/action_controller/new_base/renderer.rb
index 9253df53a1..276816a6f5 100644
--- a/actionpack/lib/action_controller/new_base/renderer.rb
+++ b/actionpack/lib/action_controller/new_base/renderer.rb
@@ -18,7 +18,7 @@ module ActionController
_process_options(options)
if options.key?(:text)
- options[:_template] = ActionView::TextTemplate.new(_text(options))
+ options[:_template] = ActionView::TextTemplate.new(_text(options), formats.first)
template = nil
elsif options.key?(:inline)
handler = ActionView::Template.handler_class_for_extension(options[:type] || "erb")
diff --git a/actionpack/lib/action_controller/new_base/testing.rb b/actionpack/lib/action_controller/new_base/testing.rb
index b39d8d539d..0659d81710 100644
--- a/actionpack/lib/action_controller/new_base/testing.rb
+++ b/actionpack/lib/action_controller/new_base/testing.rb
@@ -7,7 +7,7 @@ module ActionController
@_response = response
@_response.request = request
ret = process(request.parameters[:action])
- @_response.body = self.response_body || " "
+ @_response.body ||= self.response_body || " "
@_response.prepare!
set_test_assigns
ret
diff --git a/actionpack/lib/action_controller/testing/process.rb b/actionpack/lib/action_controller/testing/process.rb
index 8831ff57e2..9647f8ce45 100644
--- a/actionpack/lib/action_controller/testing/process.rb
+++ b/actionpack/lib/action_controller/testing/process.rb
@@ -41,6 +41,7 @@ module ActionController #:nodoc:
end
def recycle!
+ @formats = nil
@env.delete_if { |k, v| k =~ /^(action_dispatch|rack)\.request/ }
@env.delete_if { |k, v| k =~ /^action_dispatch\.rescue/ }
@env['action_dispatch.request.query_parameters'] = {}
diff --git a/actionpack/lib/action_view/template/text.rb b/actionpack/lib/action_view/template/text.rb
index a777021a12..927a0d7a72 100644
--- a/actionpack/lib/action_view/template/text.rb
+++ b/actionpack/lib/action_view/template/text.rb
@@ -1,11 +1,16 @@
module ActionView #:nodoc:
class TextTemplate < String #:nodoc:
+ def initialize(string, content_type = Mime[:html])
+ super(string)
+ @content_type = Mime[content_type]
+ end
+
def identifier() self end
def render(*) self end
- def mime_type() Mime::HTML end
+ def mime_type() @content_type end
def partial?() false end
end
diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb
index 560c09509b..c286976315 100644
--- a/actionpack/test/controller/caching_test.rb
+++ b/actionpack/test/controller/caching_test.rb
@@ -48,6 +48,8 @@ class PageCachingTest < ActionController::TestCase
super
ActionController::Base.perform_caching = true
+ ActionController::Routing::Routes.clear!
+
ActionController::Routing::Routes.draw do |map|
map.main '', :controller => 'posts'
map.formatted_posts 'posts.:format', :controller => 'posts'
diff --git a/actionpack/test/controller/mime_responds_test.rb b/actionpack/test/controller/mime_responds_test.rb
index 7cd5145a2f..3b8babb84c 100644
--- a/actionpack/test/controller/mime_responds_test.rb
+++ b/actionpack/test/controller/mime_responds_test.rb
@@ -437,7 +437,7 @@ class MimeControllerTest < ActionController::TestCase
@controller.instance_eval do
def render(*args)
unless args.empty?
- @action = args.first[:action]
+ @action = args.first[:action] || action_name
end
response.body = "#{@action} - #{@template.formats}"
end
@@ -490,14 +490,15 @@ class PostController < AbstractPostController
end
end
- protected
- def with_iphone
- Mime::Type.register_alias("text/html", :iphone)
- request.format = "iphone" if request.env["HTTP_ACCEPT"] == "text/iphone"
- yield
- ensure
- Mime.module_eval { remove_const :IPHONE if const_defined?(:IPHONE) }
- end
+protected
+
+ def with_iphone
+ Mime::Type.register_alias("text/html", :iphone)
+ request.format = "iphone" if request.env["HTTP_ACCEPT"] == "text/iphone"
+ yield
+ ensure
+ Mime.module_eval { remove_const :IPHONE if const_defined?(:IPHONE) }
+ end
end
class SuperPostController < PostController
@@ -509,6 +510,11 @@ class SuperPostController < PostController
end
end
+if ENV["new_base"]
+ PostController._write_layout_method
+ SuperPostController._write_layout_method
+end
+
class MimeControllerLayoutsTest < ActionController::TestCase
tests PostController
--
cgit v1.2.3
From 77d955c51740216131fc0b130d5cb37fcd18d071 Mon Sep 17 00:00:00 2001
From: Yehuda Katz + Carl Lerche
Date: Wed, 20 May 2009 15:54:29 -0700
Subject: Added passing old tests on new base to the main test runner
---
actionpack/Rakefile | 13 ++++++++++++-
1 file changed, 12 insertions(+), 1 deletion(-)
(limited to 'actionpack')
diff --git a/actionpack/Rakefile b/actionpack/Rakefile
index 6ce8179646..f1f407c008 100644
--- a/actionpack/Rakefile
+++ b/actionpack/Rakefile
@@ -22,7 +22,7 @@ task :default => [ :test ]
# Run the unit tests
desc "Run all unit tests"
-task :test => [:test_action_pack, :test_active_record_integration, :test_new_base]
+task :test => [:test_action_pack, :test_active_record_integration, :test_new_base, :test_new_base_on_old_tests]
Rake::TestTask.new(:test_action_pack) do |t|
t.libs << "test"
@@ -55,6 +55,17 @@ Rake::TestTask.new(:test_new_base) do |t|
t.verbose = true
end
+desc 'Old Controller Tests on New Base'
+Rake::TestTask.new(:test_new_base_on_old_tests) do |t|
+ ENV['new_base'] = "true"
+ t.libs << "test"
+ # content_type mime_responds layout
+ t.test_files = %w(
+ addresses_render base benchmark caching capture dispatcher record_identifier
+ redirect render rescue url_rewriter webservice
+ ).map { |name| "test/controller/#{name}_test.rb" }
+end
+
# Genereate the RDoc documentation
--
cgit v1.2.3
From b46c9071c382b48c5ff349fbe61854683663a866 Mon Sep 17 00:00:00 2001
From: Jeremy Kemper
Date: Wed, 20 May 2009 16:00:16 -0700
Subject: Ruby 1.9 stdlib gems don't recognize .pre yet
---
actionpack/lib/action_dispatch.rb | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_dispatch.rb b/actionpack/lib/action_dispatch.rb
index f9003c51ea..ee162765cb 100644
--- a/actionpack/lib/action_dispatch.rb
+++ b/actionpack/lib/action_dispatch.rb
@@ -27,7 +27,7 @@ require 'active_support'
begin
gem 'rack', '~> 1.1.pre'
-rescue Gem::LoadError
+rescue Gem::LoadError, ArgumentError
$:.unshift "#{File.dirname(__FILE__)}/action_dispatch/vendor/rack-1.1.pre"
end
--
cgit v1.2.3
From c86ec82cf63938f691c9ae4f5a4d72bea9e8a9c7 Mon Sep 17 00:00:00 2001
From: Jeremy Kemper
Date: Wed, 20 May 2009 16:00:50 -0700
Subject: Wrap string body in an array
---
actionpack/lib/action_dispatch/middleware/show_exceptions.rb | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'actionpack')
diff --git a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb
index 108355da63..4d598669c7 100644
--- a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb
+++ b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb
@@ -102,7 +102,7 @@ module ActionDispatch
end
def render(status, body)
- [status, {'Content-Type' => 'text/html', 'Content-Length' => body.length.to_s}, body]
+ [status, {'Content-Type' => 'text/html', 'Content-Length' => body.length.to_s}, [body]]
end
def public_path
--
cgit v1.2.3
From 205cfe2163d9eb6ee801a23f550e960136b5680e Mon Sep 17 00:00:00 2001
From: Jeremy Kemper
Date: Wed, 20 May 2009 16:23:55 -0700
Subject: Massage setup for old tests on new base
---
actionpack/Rakefile | 3 +-
actionpack/test/abstract_unit.rb | 4 -
actionpack/test/abstract_unit2.rb | 139 -----------------------------
actionpack/test/new_base/abstract_unit.rb | 141 ++++++++++++++++++++++++++++++
4 files changed, 142 insertions(+), 145 deletions(-)
delete mode 100644 actionpack/test/abstract_unit2.rb
create mode 100644 actionpack/test/new_base/abstract_unit.rb
(limited to 'actionpack')
diff --git a/actionpack/Rakefile b/actionpack/Rakefile
index f1f407c008..af14e592c0 100644
--- a/actionpack/Rakefile
+++ b/actionpack/Rakefile
@@ -57,8 +57,7 @@ end
desc 'Old Controller Tests on New Base'
Rake::TestTask.new(:test_new_base_on_old_tests) do |t|
- ENV['new_base'] = "true"
- t.libs << "test"
+ t.libs << "test/new_base" << "test"
# content_type mime_responds layout
t.test_files = %w(
addresses_render base benchmark caching capture dispatcher record_identifier
diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb
index 7982f06545..f6f62bcf83 100644
--- a/actionpack/test/abstract_unit.rb
+++ b/actionpack/test/abstract_unit.rb
@@ -1,6 +1,3 @@
-if ENV["new_base"]
- require "abstract_unit2"
-else
$:.unshift(File.dirname(__FILE__) + '/../lib')
$:.unshift(File.dirname(__FILE__) + '/../../activesupport/lib')
$:.unshift(File.dirname(__FILE__) + '/fixtures/helpers')
@@ -41,4 +38,3 @@ ORIGINAL_LOCALES = I18n.available_locales.map {|locale| locale.to_s }.sort
FIXTURE_LOAD_PATH = File.join(File.dirname(__FILE__), 'fixtures')
ActionController::Base.view_paths = FIXTURE_LOAD_PATH
-end
\ No newline at end of file
diff --git a/actionpack/test/abstract_unit2.rb b/actionpack/test/abstract_unit2.rb
deleted file mode 100644
index 519e6bea36..0000000000
--- a/actionpack/test/abstract_unit2.rb
+++ /dev/null
@@ -1,139 +0,0 @@
-$:.unshift(File.dirname(__FILE__) + '/../lib')
-$:.unshift(File.dirname(__FILE__) + '/../../activesupport/lib')
-$:.unshift(File.dirname(__FILE__) + '/lib')
-
-
-require 'test/unit'
-require 'active_support'
-require 'active_support/test_case'
-require 'action_controller/abstract'
-require 'action_controller/new_base'
-require 'fixture_template'
-require 'action_controller/testing/process2'
-require 'action_view/test_case'
-require 'action_controller/testing/integration'
-require 'active_support/dependencies'
-
-ActiveSupport::Dependencies.hook!
-
-FIXTURE_LOAD_PATH = File.join(File.dirname(__FILE__), 'fixtures')
-
-module ActionController
- Base.session = {
- :key => '_testing_session',
- :secret => '8273f16463985e2b3747dc25e30f2528'
-}
-
- class ActionControllerError < StandardError #:nodoc:
- end
-
- class SessionRestoreError < ActionControllerError #:nodoc:
- end
-
- class RenderError < ActionControllerError #:nodoc:
- end
-
- class RoutingError < ActionControllerError #:nodoc:
- attr_reader :failures
- def initialize(message, failures=[])
- super(message)
- @failures = failures
- end
- end
-
- class MethodNotAllowed < ActionControllerError #:nodoc:
- attr_reader :allowed_methods
-
- def initialize(*allowed_methods)
- super("Only #{allowed_methods.to_sentence(:locale => :en)} requests are allowed.")
- @allowed_methods = allowed_methods
- end
-
- def allowed_methods_header
- allowed_methods.map { |method_symbol| method_symbol.to_s.upcase } * ', '
- end
-
- def handle_response!(response)
- response.headers['Allow'] ||= allowed_methods_header
- end
- end
-
- class NotImplemented < MethodNotAllowed #:nodoc:
- end
-
- class UnknownController < ActionControllerError #:nodoc:
- end
-
- class MissingFile < ActionControllerError #:nodoc:
- end
-
- class RenderError < ActionControllerError #:nodoc:
- end
-
- class SessionOverflowError < ActionControllerError #:nodoc:
- DEFAULT_MESSAGE = 'Your session data is larger than the data column in which it is to be stored. You must increase the size of your data column if you intend to store large data.'
-
- def initialize(message = nil)
- super(message || DEFAULT_MESSAGE)
- end
- end
-
- class UnknownHttpMethod < ActionControllerError #:nodoc:
- end
-
- class Base
- include ActionController::Testing
- end
-
- Base.view_paths = FIXTURE_LOAD_PATH
-
- class TestCase
- include TestProcess
- setup do
- ActionController::Routing::Routes.draw do |map|
- map.connect ':controller/:action/:id'
- end
- end
-
- def assert_template(options = {}, message = nil)
- validate_request!
-
- hax = @controller._action_view.instance_variable_get(:@_rendered)
-
- case options
- when NilClass, String
- rendered = (hax[:template] || []).map { |t| t.identifier }
- msg = build_message(message,
- "expecting > but rendering with >",
- options, rendered.join(', '))
- assert_block(msg) do
- if options.nil?
- hax[:template].blank?
- else
- rendered.any? { |t| t.match(options) }
- end
- end
- when Hash
- if expected_partial = options[:partial]
- partials = hax[:partials]
- if expected_count = options[:count]
- found = partials.detect { |p, _| p.identifier.match(expected_partial) }
- actual_count = found.nil? ? 0 : found.second
- msg = build_message(message,
- "expecting ? to be rendered ? time(s) but rendered ? time(s)",
- expected_partial, expected_count, actual_count)
- assert(actual_count == expected_count.to_i, msg)
- else
- msg = build_message(message,
- "expecting partial > but action rendered >",
- options[:partial], partials.keys)
- assert(partials.keys.any? { |p| p.identifier.match(expected_partial) }, msg)
- end
- else
- assert hax[:partials].empty?,
- "Expected no partials to be rendered"
- end
- end
- end
- end
-end
diff --git a/actionpack/test/new_base/abstract_unit.rb b/actionpack/test/new_base/abstract_unit.rb
new file mode 100644
index 0000000000..e72165ee67
--- /dev/null
+++ b/actionpack/test/new_base/abstract_unit.rb
@@ -0,0 +1,141 @@
+$:.unshift(File.dirname(__FILE__) + '/../../lib')
+$:.unshift(File.dirname(__FILE__) + '/../../../activesupport/lib')
+$:.unshift(File.dirname(__FILE__) + '/../lib')
+
+ENV['new_base'] = "true"
+$stderr.puts "Running old tests on new_base"
+
+require 'test/unit'
+require 'active_support'
+require 'active_support/test_case'
+require 'action_controller/abstract'
+require 'action_controller/new_base'
+require 'fixture_template'
+require 'action_controller/testing/process2'
+require 'action_view/test_case'
+require 'action_controller/testing/integration'
+require 'active_support/dependencies'
+
+ActiveSupport::Dependencies.hook!
+
+FIXTURE_LOAD_PATH = File.join(File.dirname(__FILE__), '../fixtures')
+
+module ActionController
+ Base.session = {
+ :key => '_testing_session',
+ :secret => '8273f16463985e2b3747dc25e30f2528'
+}
+
+ class ActionControllerError < StandardError #:nodoc:
+ end
+
+ class SessionRestoreError < ActionControllerError #:nodoc:
+ end
+
+ class RenderError < ActionControllerError #:nodoc:
+ end
+
+ class RoutingError < ActionControllerError #:nodoc:
+ attr_reader :failures
+ def initialize(message, failures=[])
+ super(message)
+ @failures = failures
+ end
+ end
+
+ class MethodNotAllowed < ActionControllerError #:nodoc:
+ attr_reader :allowed_methods
+
+ def initialize(*allowed_methods)
+ super("Only #{allowed_methods.to_sentence(:locale => :en)} requests are allowed.")
+ @allowed_methods = allowed_methods
+ end
+
+ def allowed_methods_header
+ allowed_methods.map { |method_symbol| method_symbol.to_s.upcase } * ', '
+ end
+
+ def handle_response!(response)
+ response.headers['Allow'] ||= allowed_methods_header
+ end
+ end
+
+ class NotImplemented < MethodNotAllowed #:nodoc:
+ end
+
+ class UnknownController < ActionControllerError #:nodoc:
+ end
+
+ class MissingFile < ActionControllerError #:nodoc:
+ end
+
+ class RenderError < ActionControllerError #:nodoc:
+ end
+
+ class SessionOverflowError < ActionControllerError #:nodoc:
+ DEFAULT_MESSAGE = 'Your session data is larger than the data column in which it is to be stored. You must increase the size of your data column if you intend to store large data.'
+
+ def initialize(message = nil)
+ super(message || DEFAULT_MESSAGE)
+ end
+ end
+
+ class UnknownHttpMethod < ActionControllerError #:nodoc:
+ end
+
+ class Base
+ include ActionController::Testing
+ end
+
+ Base.view_paths = FIXTURE_LOAD_PATH
+
+ class TestCase
+ include TestProcess
+ setup do
+ ActionController::Routing::Routes.draw do |map|
+ map.connect ':controller/:action/:id'
+ end
+ end
+
+ def assert_template(options = {}, message = nil)
+ validate_request!
+
+ hax = @controller._action_view.instance_variable_get(:@_rendered)
+
+ case options
+ when NilClass, String
+ rendered = (hax[:template] || []).map { |t| t.identifier }
+ msg = build_message(message,
+ "expecting > but rendering with >",
+ options, rendered.join(', '))
+ assert_block(msg) do
+ if options.nil?
+ hax[:template].blank?
+ else
+ rendered.any? { |t| t.match(options) }
+ end
+ end
+ when Hash
+ if expected_partial = options[:partial]
+ partials = hax[:partials]
+ if expected_count = options[:count]
+ found = partials.detect { |p, _| p.identifier.match(expected_partial) }
+ actual_count = found.nil? ? 0 : found.second
+ msg = build_message(message,
+ "expecting ? to be rendered ? time(s) but rendered ? time(s)",
+ expected_partial, expected_count, actual_count)
+ assert(actual_count == expected_count.to_i, msg)
+ else
+ msg = build_message(message,
+ "expecting partial > but action rendered >",
+ options[:partial], partials.keys)
+ assert(partials.keys.any? { |p| p.identifier.match(expected_partial) }, msg)
+ end
+ else
+ assert hax[:partials].empty?,
+ "Expected no partials to be rendered"
+ end
+ end
+ end
+ end
+end
--
cgit v1.2.3
From 8e7a87d299483fce6af3be89e50deae43055a96f Mon Sep 17 00:00:00 2001
From: Pratik Naik
Date: Thu, 21 May 2009 01:38:48 +0200
Subject: Make ActionController::Flash work with new_base
---
actionpack/Rakefile | 2 +-
.../lib/action_controller/base/chained/flash.rb | 74 +++++++++++++++-------
actionpack/lib/action_controller/new_base.rb | 5 +-
actionpack/lib/action_controller/new_base/base.rb | 3 +
actionpack/lib/action_controller/new_base/http.rb | 2 +-
.../lib/action_controller/new_base/session.rb | 11 ++++
actionpack/test/controller/flash_test.rb | 49 +++++++-------
7 files changed, 97 insertions(+), 49 deletions(-)
create mode 100644 actionpack/lib/action_controller/new_base/session.rb
(limited to 'actionpack')
diff --git a/actionpack/Rakefile b/actionpack/Rakefile
index af14e592c0..2a456ebb05 100644
--- a/actionpack/Rakefile
+++ b/actionpack/Rakefile
@@ -61,7 +61,7 @@ Rake::TestTask.new(:test_new_base_on_old_tests) do |t|
# content_type mime_responds layout
t.test_files = %w(
addresses_render base benchmark caching capture dispatcher record_identifier
- redirect render rescue url_rewriter webservice
+ redirect render rescue url_rewriter webservice flash
).map { |name| "test/controller/#{name}_test.rb" }
end
diff --git a/actionpack/lib/action_controller/base/chained/flash.rb b/actionpack/lib/action_controller/base/chained/flash.rb
index 56ee9c67e2..6bd482d85a 100644
--- a/actionpack/lib/action_controller/base/chained/flash.rb
+++ b/actionpack/lib/action_controller/base/chained/flash.rb
@@ -26,9 +26,18 @@ module ActionController #:nodoc:
#
# See docs on the FlashHash class for more details about the flash.
module Flash
- def self.included(base)
- base.class_eval do
- include InstanceMethods
+ extend ActiveSupport::DependencyModule
+
+ # TODO : Remove the defined? check when new base is the main base
+ depends_on Session if defined?(ActionController::Http)
+
+ included do
+ # TODO : Remove the defined? check when new base is the main base
+ if defined?(ActionController::Http)
+ include InstanceMethodsForNewBase
+ else
+ include InstanceMethodsForBase
+
alias_method_chain :perform_action, :flash
alias_method_chain :reset_session, :flash
end
@@ -135,29 +144,50 @@ module ActionController #:nodoc:
end
end
- module InstanceMethods #:nodoc:
+ module InstanceMethodsForBase #:nodoc:
protected
- def perform_action_with_flash
- perform_action_without_flash
- remove_instance_variable(:@_flash) if defined? @_flash
- end
- def reset_session_with_flash
- reset_session_without_flash
- remove_instance_variable(:@_flash) if defined? @_flash
- end
+ def perform_action_with_flash
+ perform_action_without_flash
+ remove_instance_variable(:@_flash) if defined?(@_flash)
+ end
- # Access the contents of the flash. Use flash["notice"] to
- # read a notice you put there or flash["notice"] = "hello"
- # to put a new one.
- def flash #:doc:
- unless defined? @_flash
- @_flash = session["flash"] ||= FlashHash.new
- @_flash.sweep
- end
+ def reset_session_with_flash
+ reset_session_without_flash
+ remove_instance_variable(:@_flash) if defined?(@_flash)
+ end
+ end
- @_flash
- end
+ module InstanceMethodsForNewBase #:nodoc:
+ protected
+
+ def reset_session
+ super
+ remove_flash_instance_variable
+ end
+
+ def process_action(method_name)
+ super
+ remove_flash_instance_variable
+ end
+
+ def remove_flash_instance_variable
+ remove_instance_variable(:@_flash) if defined?(@_flash)
+ end
+ end
+
+ protected
+
+ # Access the contents of the flash. Use flash["notice"] to
+ # read a notice you put there or flash["notice"] = "hello"
+ # to put a new one.
+ def flash #:doc:
+ unless defined?(@_flash)
+ @_flash = session["flash"] ||= FlashHash.new
+ @_flash.sweep
+ end
+
+ @_flash
end
end
end
diff --git a/actionpack/lib/action_controller/new_base.rb b/actionpack/lib/action_controller/new_base.rb
index 3fc5d82d01..d2f6514ff9 100644
--- a/actionpack/lib/action_controller/new_base.rb
+++ b/actionpack/lib/action_controller/new_base.rb
@@ -10,7 +10,8 @@ module ActionController
autoload :Rescue, "action_controller/new_base/rescuable"
autoload :Testing, "action_controller/new_base/testing"
autoload :UrlFor, "action_controller/new_base/url_for"
-
+ autoload :Session, "action_controller/new_base/session"
+
# Ported modules
# require 'action_controller/routing'
autoload :Caching, 'action_controller/caching'
@@ -23,6 +24,8 @@ module ActionController
autoload :TestCase, 'action_controller/testing/test_case'
autoload :UrlRewriter, 'action_controller/routing/generation/url_rewriter'
autoload :UrlWriter, 'action_controller/routing/generation/url_rewriter'
+
+ autoload :Flash, 'action_controller/base/chained/flash'
require 'action_controller/routing'
end
diff --git a/actionpack/lib/action_controller/new_base/base.rb b/actionpack/lib/action_controller/new_base/base.rb
index 3d8d46c9c2..eff7297973 100644
--- a/actionpack/lib/action_controller/new_base/base.rb
+++ b/actionpack/lib/action_controller/new_base/base.rb
@@ -14,6 +14,9 @@ module ActionController
include ActionController::Layouts
include ActionController::ConditionalGet
+ include ActionController::Session
+ include ActionController::Flash
+
# Legacy modules
include SessionManagement
include ActionDispatch::StatusCodes
diff --git a/actionpack/lib/action_controller/new_base/http.rb b/actionpack/lib/action_controller/new_base/http.rb
index 17466a2d52..2525e221a6 100644
--- a/actionpack/lib/action_controller/new_base/http.rb
+++ b/actionpack/lib/action_controller/new_base/http.rb
@@ -37,7 +37,7 @@ module ActionController
end
delegate :headers, :to => "@_response"
-
+
def params
@_params ||= @_request.parameters
end
diff --git a/actionpack/lib/action_controller/new_base/session.rb b/actionpack/lib/action_controller/new_base/session.rb
new file mode 100644
index 0000000000..a8715555fb
--- /dev/null
+++ b/actionpack/lib/action_controller/new_base/session.rb
@@ -0,0 +1,11 @@
+module ActionController
+ module Session
+ def session
+ @_request.session
+ end
+
+ def reset_session
+ @_request.reset_session
+ end
+ end
+end
diff --git a/actionpack/test/controller/flash_test.rb b/actionpack/test/controller/flash_test.rb
index ef60cae0ff..84e27d7779 100644
--- a/actionpack/test/controller/flash_test.rb
+++ b/actionpack/test/controller/flash_test.rb
@@ -60,6 +60,7 @@ class FlashTest < ActionController::TestCase
def std_action
@flash_copy = {}.update(flash)
+ render :nothing => true
end
def filter_halting_action
@@ -79,64 +80,64 @@ class FlashTest < ActionController::TestCase
get :set_flash
get :use_flash
- assert_equal "hello", @controller.template.assigns["flash_copy"]["that"]
- assert_equal "hello", @controller.template.assigns["flashy"]
+ assert_equal "hello", assigns["flash_copy"]["that"]
+ assert_equal "hello", assigns["flashy"]
get :use_flash
- assert_nil @controller.template.assigns["flash_copy"]["that"], "On second flash"
+ assert_nil assigns["flash_copy"]["that"], "On second flash"
end
def test_keep_flash
get :set_flash
get :use_flash_and_keep_it
- assert_equal "hello", @controller.template.assigns["flash_copy"]["that"]
- assert_equal "hello", @controller.template.assigns["flashy"]
+ assert_equal "hello", assigns["flash_copy"]["that"]
+ assert_equal "hello", assigns["flashy"]
get :use_flash
- assert_equal "hello", @controller.template.assigns["flash_copy"]["that"], "On second flash"
+ assert_equal "hello", assigns["flash_copy"]["that"], "On second flash"
get :use_flash
- assert_nil @controller.template.assigns["flash_copy"]["that"], "On third flash"
+ assert_nil assigns["flash_copy"]["that"], "On third flash"
end
def test_flash_now
get :set_flash_now
- assert_equal "hello", @controller.template.assigns["flash_copy"]["that"]
- assert_equal "bar" , @controller.template.assigns["flash_copy"]["foo"]
- assert_equal "hello", @controller.template.assigns["flashy"]
+ assert_equal "hello", assigns["flash_copy"]["that"]
+ assert_equal "bar" , assigns["flash_copy"]["foo"]
+ assert_equal "hello", assigns["flashy"]
get :attempt_to_use_flash_now
- assert_nil @controller.template.assigns["flash_copy"]["that"]
- assert_nil @controller.template.assigns["flash_copy"]["foo"]
- assert_nil @controller.template.assigns["flashy"]
+ assert_nil assigns["flash_copy"]["that"]
+ assert_nil assigns["flash_copy"]["foo"]
+ assert_nil assigns["flashy"]
end
def test_update_flash
get :set_flash
get :use_flash_and_update_it
- assert_equal "hello", @controller.template.assigns["flash_copy"]["that"]
- assert_equal "hello again", @controller.template.assigns["flash_copy"]["this"]
+ assert_equal "hello", assigns["flash_copy"]["that"]
+ assert_equal "hello again", assigns["flash_copy"]["this"]
get :use_flash
- assert_nil @controller.template.assigns["flash_copy"]["that"], "On second flash"
- assert_equal "hello again", @controller.template.assigns["flash_copy"]["this"], "On second flash"
+ assert_nil assigns["flash_copy"]["that"], "On second flash"
+ assert_equal "hello again", assigns["flash_copy"]["this"], "On second flash"
end
def test_flash_after_reset_session
get :use_flash_after_reset_session
- assert_equal "hello", @controller.template.assigns["flashy_that"]
- assert_equal "good-bye", @controller.template.assigns["flashy_this"]
- assert_nil @controller.template.assigns["flashy_that_reset"]
+ assert_equal "hello", assigns["flashy_that"]
+ assert_equal "good-bye", assigns["flashy_this"]
+ assert_nil assigns["flashy_that_reset"]
end
def test_sweep_after_halted_filter_chain
get :std_action
- assert_nil @controller.template.assigns["flash_copy"]["foo"]
+ assert_nil assigns["flash_copy"]["foo"]
get :filter_halting_action
- assert_equal "bar", @controller.template.assigns["flash_copy"]["foo"]
+ assert_equal "bar", assigns["flash_copy"]["foo"]
get :std_action # follow redirection
- assert_equal "bar", @controller.template.assigns["flash_copy"]["foo"]
+ assert_equal "bar", assigns["flash_copy"]["foo"]
get :std_action
- assert_nil @controller.template.assigns["flash_copy"]["foo"]
+ assert_nil assigns["flash_copy"]["foo"]
end
end
--
cgit v1.2.3
From c4a6109286909c394e8c5bfc471a1eb9de245d2b Mon Sep 17 00:00:00 2001
From: Yehuda Katz + Carl Lerche
Date: Wed, 20 May 2009 16:52:56 -0700
Subject: Got controller/mime_responds_test.rb running on the new base
---
actionpack/Rakefile | 7 ++++---
actionpack/test/abstract_unit.rb | 2 ++
actionpack/test/controller/mime_responds_test.rb | 26 ++++++++++++++----------
actionpack/test/new_base/abstract_unit.rb | 3 +++
4 files changed, 24 insertions(+), 14 deletions(-)
(limited to 'actionpack')
diff --git a/actionpack/Rakefile b/actionpack/Rakefile
index 2a456ebb05..86f7adaee3 100644
--- a/actionpack/Rakefile
+++ b/actionpack/Rakefile
@@ -58,10 +58,11 @@ end
desc 'Old Controller Tests on New Base'
Rake::TestTask.new(:test_new_base_on_old_tests) do |t|
t.libs << "test/new_base" << "test"
- # content_type mime_responds layout
+ # content_type layout
+ # Dir.glob( "test/{dispatch,template}/**/*_test.rb" ).sort +
t.test_files = %w(
- addresses_render base benchmark caching capture dispatcher record_identifier
- redirect render rescue url_rewriter webservice flash
+ addresses_render base benchmark caching capture dispatcher flash mime_responds
+ record_identifier redirect render rescue url_rewriter webservice
).map { |name| "test/controller/#{name}_test.rb" }
end
diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb
index f6f62bcf83..5ae54d097a 100644
--- a/actionpack/test/abstract_unit.rb
+++ b/actionpack/test/abstract_unit.rb
@@ -23,6 +23,8 @@ require 'action_controller'
require 'action_controller/testing/process'
require 'action_view/test_case'
+$tags[:old_base] = true
+
# Show backtraces for deprecated behavior for quicker cleanup.
ActiveSupport::Deprecation.debug = true
diff --git a/actionpack/test/controller/mime_responds_test.rb b/actionpack/test/controller/mime_responds_test.rb
index 3b8babb84c..56b49251c6 100644
--- a/actionpack/test/controller/mime_responds_test.rb
+++ b/actionpack/test/controller/mime_responds_test.rb
@@ -375,9 +375,11 @@ class MimeControllerTest < ActionController::TestCase
end
def test_rjs_type_skips_layout
- @request.accept = "text/javascript"
- get :all_types_with_layout
- assert_equal 'RJS for all_types_with_layout', @response.body
+ pending(:new_base) do
+ @request.accept = "text/javascript"
+ get :all_types_with_layout
+ assert_equal 'RJS for all_types_with_layout', @response.body
+ end
end
def test_html_type_with_layout
@@ -510,7 +512,7 @@ class SuperPostController < PostController
end
end
-if ENV["new_base"]
+if defined?(ActionController::Http)
PostController._write_layout_method
SuperPostController._write_layout_method
end
@@ -532,14 +534,16 @@ class MimeControllerLayoutsTest < ActionController::TestCase
assert_equal 'Hello iPhone', @response.body
end
- def test_format_with_inherited_layouts
- @controller = SuperPostController.new
+ for_tag(:old_base) do
+ def test_format_with_inherited_layouts
+ @controller = SuperPostController.new
- get :index
- assert_equal 'Super Firefox', @response.body
+ get :index
+ assert_equal 'Super Firefox', @response.body
- @request.accept = "text/iphone"
- get :index
- assert_equal '
"))
- assert_equal("Weirdos", sanitizer.sanitize("Wei<a onclick='alert(document.cookie);'/>rdos"))
- assert_equal("This is a test.", sanitizer.sanitize("This is a test."))
- assert_equal(
- %{This is a test.\n\n\nIt no longer contains any HTML.\n}, sanitizer.sanitize(
- %{This is a test.\n\n\n\n
It no longer contains any HTML.
\n}))
- assert_equal "This has a here.", sanitizer.sanitize("This has a here.")
- assert_equal "This has a here.", sanitizer.sanitize("This has a ]]> here.")
- assert_equal "This has an unclosed ", sanitizer.sanitize("This has an unclosed ]] here...")
- [nil, '', ' '].each { |blank| assert_equal blank, sanitizer.sanitize(blank) }
- end
-
- def test_strip_links
- sanitizer = HTML::LinkSanitizer.new
- assert_equal "Dont touch me", sanitizer.sanitize("Dont touch me")
- assert_equal "on my mind\nall day long", sanitizer.sanitize("on my mind\nall day long")
- assert_equal "0wn3d", sanitizer.sanitize("0wn3d")
- assert_equal "Magic", sanitizer.sanitize("Magic")
- assert_equal "FrrFox", sanitizer.sanitize("FrrFox")
- assert_equal "My mind\nall day long", sanitizer.sanitize("My mind\nall day long")
- assert_equal "all day long", sanitizer.sanitize("<a href='hello'>all day long</a>")
-
- assert_equal "", ''
- end
-
- def test_sanitize_plaintext
- raw = "foo"
- assert_sanitized raw, "foo"
- end
-
- def test_sanitize_script
- assert_sanitized "a b cd e f", "a b cd e f"
- end
-
- # fucked
- def test_sanitize_js_handlers
- raw = %{onthis="do that" hello}
- assert_sanitized raw, %{onthis="do that" hello}
- end
-
- def test_sanitize_javascript_href
- raw = %{href="javascript:bang" foo, bar}
- assert_sanitized raw, %{href="javascript:bang" foo, bar}
- end
-
- def test_sanitize_image_src
- raw = %{src="javascript:bang" foo, bar}
- assert_sanitized raw, %{src="javascript:bang" foo, bar}
- end
-
- HTML::WhiteListSanitizer.allowed_tags.each do |tag_name|
- define_method "test_should_allow_#{tag_name}_tag" do
- assert_sanitized "start <#{tag_name} title=\"1\" onclick=\"foo\">foo bar baz#{tag_name}> end", %(start <#{tag_name} title="1">foo bar baz#{tag_name}> end)
- end
- end
-
- def test_should_allow_anchors
- assert_sanitized %(), %()
- end
-
- # RFC 3986, sec 4.2
- def test_allow_colons_in_path_component
- assert_sanitized("foo")
- end
-
- %w(src width height alt).each do |img_attr|
- define_method "test_should_allow_image_#{img_attr}_attribute" do
- assert_sanitized %(), %()
- end
- end
-
- def test_should_handle_non_html
- assert_sanitized 'abc'
- end
-
- def test_should_handle_blank_text
- assert_sanitized nil
- assert_sanitized ''
- end
-
- def test_should_allow_custom_tags
- text = "foo"
- sanitizer = HTML::WhiteListSanitizer.new
- assert_equal(text, sanitizer.sanitize(text, :tags => %w(u)))
- end
-
- def test_should_allow_only_custom_tags
- text = "foo with bar"
- sanitizer = HTML::WhiteListSanitizer.new
- assert_equal("foo with bar", sanitizer.sanitize(text, :tags => %w(u)))
- end
-
- def test_should_allow_custom_tags_with_attributes
- text = %(
foo
)
- sanitizer = HTML::WhiteListSanitizer.new
- assert_equal(text, sanitizer.sanitize(text))
- end
-
- def test_should_allow_custom_tags_with_custom_attributes
- text = %(
Lorem ipsum
)
- sanitizer = HTML::WhiteListSanitizer.new
- assert_equal(text, sanitizer.sanitize(text, :attributes => ['foo']))
- end
-
- [%w(img src), %w(a href)].each do |(tag, attr)|
- define_method "test_should_strip_#{attr}_attribute_in_#{tag}_with_bad_protocols" do
- assert_sanitized %(<#{tag} #{attr}="javascript:bang" title="1">boo#{tag}>), %(<#{tag} title="1">boo#{tag}>)
- end
- end
-
- def test_should_flag_bad_protocols
- sanitizer = HTML::WhiteListSanitizer.new
- %w(about chrome data disk hcp help javascript livescript lynxcgi lynxexec ms-help ms-its mhtml mocha opera res resource shell vbscript view-source vnd.ms.radio wysiwyg).each do |proto|
- assert sanitizer.send(:contains_bad_protocols?, 'src', "#{proto}://bad")
- end
- end
-
- def test_should_accept_good_protocols
- sanitizer = HTML::WhiteListSanitizer.new
- HTML::WhiteListSanitizer.allowed_protocols.each do |proto|
- assert !sanitizer.send(:contains_bad_protocols?, 'src', "#{proto}://good")
- end
- end
-
- def test_should_reject_hex_codes_in_protocol
- assert_sanitized %(1), "1"
- assert @sanitizer.send(:contains_bad_protocols?, 'src', "%6A%61%76%61%73%63%72%69%70%74%3A%61%6C%65%72%74%28%22%58%53%53%22%29")
- end
-
- def test_should_block_script_tag
- assert_sanitized %(), ""
- end
-
- [%(),
- %(),
- %(),
- %(">),
- %(),
- %(),
- %(),
- %(),
- %(),
- %(),
- %(),
- %(),
- %(),
- %(),
- %()].each_with_index do |img_hack, i|
- define_method "test_should_not_fall_for_xss_image_hack_#{i+1}" do
- assert_sanitized img_hack, ""
- end
- end
-
- def test_should_sanitize_tag_broken_up_by_null
- assert_sanitized %(alert(\"XSS\")), "alert(\"XSS\")"
- end
-
- def test_should_sanitize_invalid_script_tag
- assert_sanitized %(), ""
- end
-
- def test_should_sanitize_script_tag_with_multiple_open_brackets
- assert_sanitized %(<), "<"
- assert_sanitized %(