aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--actionmailer/test/abstract_unit.rb1
-rw-r--r--actionmailer/test/mail_service_test.rb2
-rw-r--r--actionpack/CHANGELOG2
-rw-r--r--actionpack/lib/action_controller.rb5
-rw-r--r--actionpack/lib/action_controller/base.rb1
-rw-r--r--actionpack/lib/action_controller/caching.rb1
-rw-r--r--actionpack/lib/action_controller/cgi_process.rb5
-rw-r--r--actionpack/lib/action_controller/cookies.rb2
-rw-r--r--actionpack/lib/action_controller/dispatcher.rb14
-rw-r--r--actionpack/lib/action_controller/http_authentication.rb2
-rw-r--r--actionpack/lib/action_controller/integration.rb2
-rw-r--r--actionpack/lib/action_controller/rack_ext.rb3
-rw-r--r--actionpack/lib/action_controller/rack_ext/lock.rb21
-rw-r--r--actionpack/lib/action_controller/rack_ext/multipart.rb22
-rw-r--r--actionpack/lib/action_controller/rack_ext/parse_query.rb17
-rwxr-xr-xactionpack/lib/action_controller/request.rb31
-rw-r--r--actionpack/lib/action_controller/rescue.rb2
-rw-r--r--actionpack/lib/action_controller/response.rb41
-rw-r--r--actionpack/lib/action_controller/session/abstract_store.rb61
-rw-r--r--actionpack/lib/action_controller/session/cookie_store.rb13
-rw-r--r--actionpack/lib/action_controller/streaming.rb2
-rw-r--r--actionpack/lib/action_controller/test_process.rb8
-rw-r--r--actionpack/lib/action_controller/url_encoded_pair_parser.rb155
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack.rb87
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/adapter/camping.rb22
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/abstract/handler.rb37
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/abstract/request.rb37
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/basic.rb58
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/digest/md5.rb124
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/digest/nonce.rb51
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/digest/params.rb55
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/digest/request.rb40
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/openid.rb480
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/builder.rb67
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/cascade.rb36
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/commonlogger.rb61
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/conditionalget.rb45
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/content_length.rb27
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/deflater.rb85
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/directory.rb151
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/file.rb88
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/handler.rb48
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/cgi.rb57
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/evented_mongrel.rb8
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/fastcgi.rb86
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/lsws.rb52
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/mongrel.rb82
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/scgi.rb57
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/swiftiplied_mongrel.rb8
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/thin.rb15
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/webrick.rb61
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/head.rb19
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/lint.rb476
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/lobster.rb65
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/lock.rb16
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/methodoverride.rb27
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/mime.rb204
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/mock.rb160
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/recursive.rb57
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/reloader.rb64
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/request.rb241
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/response.rb177
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/session/abstract/id.rb142
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/session/cookie.rb91
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/session/memcache.rb109
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/session/pool.rb100
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/showexceptions.rb349
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/showstatus.rb106
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/static.rb38
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/urlmap.rb51
-rw-r--r--actionpack/lib/action_controller/vendor/rack-1.0/rack/utils.rb379
-rw-r--r--actionpack/lib/action_controller/verification.rb2
-rw-r--r--actionpack/lib/action_view.rb1
-rw-r--r--actionpack/lib/action_view/base.rb11
-rw-r--r--actionpack/lib/action_view/helpers/date_helper.rb2
-rw-r--r--actionpack/lib/action_view/helpers/form_helper.rb30
-rw-r--r--actionpack/lib/action_view/helpers/form_options_helper.rb107
-rw-r--r--actionpack/lib/action_view/helpers/text_helper.rb2
-rw-r--r--actionpack/lib/action_view/helpers/translation_helper.rb20
-rw-r--r--actionpack/lib/action_view/paths.rb18
-rw-r--r--actionpack/lib/action_view/reloadable_template.rb120
-rw-r--r--actionpack/lib/action_view/renderable.rb5
-rw-r--r--actionpack/lib/action_view/template.rb103
-rw-r--r--actionpack/test/abstract_unit.rb5
-rw-r--r--actionpack/test/active_record_unit.rb3
-rw-r--r--actionpack/test/controller/cookie_test.rb2
-rw-r--r--actionpack/test/controller/http_digest_authentication_test.rb11
-rw-r--r--actionpack/test/controller/integration_test.rb2
-rw-r--r--actionpack/test/controller/rack_test.rb20
-rw-r--r--actionpack/test/controller/rescue_test.rb7
-rw-r--r--actionpack/test/controller/session/cookie_store_test.rb32
-rw-r--r--actionpack/test/controller/session/mem_cache_store_test.rb19
-rw-r--r--actionpack/test/controller/session/test_session_test.rb2
-rw-r--r--actionpack/test/controller/view_paths_test.rb26
-rw-r--r--actionpack/test/fixtures/test/hello_world.erb~1
-rw-r--r--actionpack/test/fixtures/test/hello_world.pt-BR.html.erb1
-rw-r--r--actionpack/test/fixtures/test/render_implicit_html_template_from_xhr_request.da.html.erb1
-rw-r--r--actionpack/test/fixtures/test/utf8.html.erb2
-rw-r--r--actionpack/test/template/compiled_templates_test.rb120
-rw-r--r--actionpack/test/template/date_helper_test.rb28
-rw-r--r--actionpack/test/template/form_helper_test.rb110
-rw-r--r--actionpack/test/template/form_options_helper_test.rb181
-rw-r--r--actionpack/test/template/render_test.rb69
-rw-r--r--actionpack/test/template/translation_helper_test.rb6
-rw-r--r--activerecord/Rakefile4
-rw-r--r--activerecord/lib/active_record/migration.rb6
-rw-r--r--activerecord/lib/active_record/nested_attributes.rb246
-rw-r--r--activerecord/test/cases/nested_attributes_test.rb288
-rw-r--r--activerecord/test/models/pirate.rb2
-rw-r--r--activerecord/test/models/ship.rb4
-rw-r--r--activeresource/Rakefile2
-rw-r--r--activeresource/lib/active_resource/base.rb12
-rw-r--r--activeresource/lib/active_resource/http_mock.rb66
-rw-r--r--activeresource/lib/active_resource/validations.rb2
-rw-r--r--activeresource/test/setter_trap.rb5
-rw-r--r--activesupport/CHANGELOG9
-rw-r--r--activesupport/lib/active_support/core_ext/array.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/array/wrapper.rb24
-rw-r--r--activesupport/lib/active_support/core_ext/string/inflections.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/time/conversions.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/try.rb1
-rw-r--r--activesupport/lib/active_support/inflections.rb1
-rw-r--r--activesupport/lib/active_support/json/decoding.rb5
-rw-r--r--activesupport/lib/active_support/json/encoders/hash.rb19
-rw-r--r--activesupport/lib/active_support/testing/assertions.rb18
-rw-r--r--activesupport/lib/active_support/testing/core_ext/test.rb6
-rw-r--r--activesupport/lib/active_support/testing/core_ext/test/unit/assertions.rb72
-rw-r--r--activesupport/lib/active_support/testing/setup_and_teardown.rb2
-rw-r--r--activesupport/lib/active_support/time_with_zone.rb5
-rw-r--r--activesupport/lib/active_support/vendor.rb2
-rw-r--r--activesupport/test/core_ext/array_ext_test.rb34
-rw-r--r--activesupport/test/core_ext/date_ext_test.rb12
-rw-r--r--activesupport/test/core_ext/duration_test.rb24
-rw-r--r--activesupport/test/core_ext/time_ext_test.rb4
-rw-r--r--activesupport/test/core_ext/time_with_zone_test.rb416
-rw-r--r--activesupport/test/inflector_test_cases.rb3
-rw-r--r--activesupport/test/json/decoding_test.rb3
-rw-r--r--activesupport/test/test_test.rb7
-rw-r--r--activesupport/test/time_zone_test.rb92
-rw-r--r--railties/environments/production.rb1
-rw-r--r--railties/environments/test.rb1
-rw-r--r--railties/html/500.html3
-rw-r--r--railties/lib/console_app.rb1
-rw-r--r--railties/lib/fcgi_handler.rb22
-rw-r--r--railties/lib/initializer.rb9
-rw-r--r--railties/lib/rails/plugin/loader.rb2
-rw-r--r--railties/lib/rails_generator/generators/applications/app/template_runner.rb10
-rw-r--r--railties/lib/rails_generator/generators/components/scaffold/templates/functional_test.rb8
-rw-r--r--railties/test/abstract_unit.rb8
-rw-r--r--railties/test/error_page_test.rb40
-rw-r--r--railties/test/fcgi_dispatcher_test.rb69
-rw-r--r--railties/test/generators/rails_template_runner_test.rb16
-rw-r--r--railties/test/initializer_test.rb20
-rw-r--r--railties/test/plugin_loader_test.rb2
154 files changed, 6598 insertions, 1394 deletions
diff --git a/actionmailer/test/abstract_unit.rb b/actionmailer/test/abstract_unit.rb
index 51b375fef3..3e7725570f 100644
--- a/actionmailer/test/abstract_unit.rb
+++ b/actionmailer/test/abstract_unit.rb
@@ -19,6 +19,7 @@ ActionView::Template.register_template_handler :bak, lambda { |template| "Lame b
$:.unshift "#{File.dirname(__FILE__)}/fixtures/helpers"
+ActionView::Base.cache_template_loading = true
FIXTURE_LOAD_PATH = File.join(File.dirname(__FILE__), 'fixtures')
ActionMailer::Base.template_root = FIXTURE_LOAD_PATH
diff --git a/actionmailer/test/mail_service_test.rb b/actionmailer/test/mail_service_test.rb
index 1e04531753..0934d3537f 100644
--- a/actionmailer/test/mail_service_test.rb
+++ b/actionmailer/test/mail_service_test.rb
@@ -975,7 +975,7 @@ end
class InheritableTemplateRootTest < Test::Unit::TestCase
def test_attr
- expected = "#{File.dirname(__FILE__)}/fixtures/path.with.dots"
+ expected = ("#{File.dirname(__FILE__)}/fixtures/path.with.dots").sub(/\.\//, '')
assert_equal expected, FunkyPathMailer.template_root.to_s
sub = Class.new(FunkyPathMailer)
diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG
index 41e3be8b35..546adeb61d 100644
--- a/actionpack/CHANGELOG
+++ b/actionpack/CHANGELOG
@@ -1,5 +1,7 @@
*Edge*
+* Added partial scoping to TranslationHelper#translate, so if you call translate(".foo") from the people/index.html.erb template, you'll actually be calling I18n.translate("people.index.foo") [DHH]
+
* Fix a syntax error in current_page?() that was prevent matches against URL's with multiple query parameters #1385, #1868 [chris finne/Andrew White]
* Added localized rescue template when I18n.locale is set (ex: public/404.da.html) #1835 [José Valim]
diff --git a/actionpack/lib/action_controller.rb b/actionpack/lib/action_controller.rb
index 3e77970367..1a3e05cc86 100644
--- a/actionpack/lib/action_controller.rb
+++ b/actionpack/lib/action_controller.rb
@@ -31,9 +31,7 @@ rescue LoadError
end
end
-gem 'rack', '>= 0.9.0'
-require 'rack'
-require 'action_controller/rack_ext'
+require 'action_controller/vendor/rack-1.0/rack'
module ActionController
# TODO: Review explicit to see if they will automatically be handled by
@@ -77,7 +75,6 @@ module ActionController
autoload :UploadedFile, 'action_controller/uploaded_file'
autoload :UploadedStringIO, 'action_controller/uploaded_file'
autoload :UploadedTempfile, 'action_controller/uploaded_file'
- autoload :UrlEncodedPairParser, 'action_controller/url_encoded_pair_parser'
autoload :UrlRewriter, 'action_controller/url_rewriter'
autoload :UrlWriter, 'action_controller/url_rewriter'
autoload :Verification, 'action_controller/verification'
diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb
index 1af4133ce2..1eda6e3f04 100644
--- a/actionpack/lib/action_controller/base.rb
+++ b/actionpack/lib/action_controller/base.rb
@@ -913,6 +913,7 @@ module ActionController #:nodoc:
layout = pick_layout(options)
response.layout = layout.path_without_format_and_extension if layout
logger.info("Rendering template within #{layout.path_without_format_and_extension}") if logger && layout
+ layout = layout.path_without_format_and_extension if layout
if content_type = options[:content_type]
response.content_type = content_type.to_s
diff --git a/actionpack/lib/action_controller/caching.rb b/actionpack/lib/action_controller/caching.rb
index 1d14df0052..80d13e25f1 100644
--- a/actionpack/lib/action_controller/caching.rb
+++ b/actionpack/lib/action_controller/caching.rb
@@ -27,6 +27,7 @@ module ActionController #:nodoc:
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:
diff --git a/actionpack/lib/action_controller/cgi_process.rb b/actionpack/lib/action_controller/cgi_process.rb
index 7e5e95e135..54ff04cfd2 100644
--- a/actionpack/lib/action_controller/cgi_process.rb
+++ b/actionpack/lib/action_controller/cgi_process.rb
@@ -47,6 +47,11 @@ module ActionController #:nodoc:
out.sync = false if out.respond_to?(:sync=)
headers['Status'] = status.to_s
+
+ if headers.include?('Set-Cookie')
+ headers['cookie'] = headers.delete('Set-Cookie').split("\n")
+ end
+
out.write(cgi.header(headers))
body.each { |part|
diff --git a/actionpack/lib/action_controller/cookies.rb b/actionpack/lib/action_controller/cookies.rb
index 840ceb5abd..ca380e98d0 100644
--- a/actionpack/lib/action_controller/cookies.rb
+++ b/actionpack/lib/action_controller/cookies.rb
@@ -41,7 +41,7 @@ module ActionController #:nodoc:
# * <tt>:expires</tt> - The time at which this cookie expires, as a Time object.
# * <tt>:secure</tt> - Whether this cookie is a only transmitted to HTTPS servers.
# Default is +false+.
- # * <tt>:http_only</tt> - Whether this cookie is accessible via scripting or
+ # * <tt>:httponly</tt> - Whether this cookie is accessible via scripting or
# only HTTP. Defaults to +false+.
module Cookies
def self.included(base)
diff --git a/actionpack/lib/action_controller/dispatcher.rb b/actionpack/lib/action_controller/dispatcher.rb
index 781bc48887..e91babde10 100644
--- a/actionpack/lib/action_controller/dispatcher.rb
+++ b/actionpack/lib/action_controller/dispatcher.rb
@@ -7,7 +7,6 @@ module ActionController
unless cache_classes
# Development mode callbacks
before_dispatch :reload_application
- after_dispatch :cleanup_application
ActionView::Helpers::AssetTagHelper.cache_asset_timestamps = false
end
@@ -89,20 +88,17 @@ module ActionController
end
def reload_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)
+
# Run prepare callbacks before every request in development mode
run_callbacks :prepare_dispatch
Routing::Routes.reload
end
- # Cleanup the application by clearing out loaded classes so they can
- # be reloaded on the next request without restarting the server.
- def cleanup_application
- 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
diff --git a/actionpack/lib/action_controller/http_authentication.rb b/actionpack/lib/action_controller/http_authentication.rb
index 5d915fda08..2ccbc22420 100644
--- a/actionpack/lib/action_controller/http_authentication.rb
+++ b/actionpack/lib/action_controller/http_authentication.rb
@@ -183,7 +183,7 @@ module ActionController
if valid_nonce && realm == credentials[:realm] && opaque(request.session.session_id) == credentials[:opaque]
password = password_procedure.call(credentials[:username])
- expected = expected_response(request.env['REQUEST_METHOD'], request.url, credentials, password)
+ expected = expected_response(request.env['REQUEST_METHOD'], credentials[:uri], credentials, password)
expected == credentials[:response]
end
end
diff --git a/actionpack/lib/action_controller/integration.rb b/actionpack/lib/action_controller/integration.rb
index a0e894108d..1c05ab0bf6 100644
--- a/actionpack/lib/action_controller/integration.rb
+++ b/actionpack/lib/action_controller/integration.rb
@@ -327,7 +327,7 @@ module ActionController
@headers = Rack::Utils::HeaderHash.new(headers)
- (@headers['Set-Cookie'] || []).each do |cookie|
+ (@headers['Set-Cookie'] || "").split("\n").each do |cookie|
name, value = cookie.match(/^([^=]*)=([^;]*);/)[1,2]
@cookies[name] = value
end
diff --git a/actionpack/lib/action_controller/rack_ext.rb b/actionpack/lib/action_controller/rack_ext.rb
deleted file mode 100644
index 2ba6654e3d..0000000000
--- a/actionpack/lib/action_controller/rack_ext.rb
+++ /dev/null
@@ -1,3 +0,0 @@
-require 'action_controller/rack_ext/lock'
-require 'action_controller/rack_ext/multipart'
-require 'action_controller/rack_ext/parse_query'
diff --git a/actionpack/lib/action_controller/rack_ext/lock.rb b/actionpack/lib/action_controller/rack_ext/lock.rb
deleted file mode 100644
index 9bf1889065..0000000000
--- a/actionpack/lib/action_controller/rack_ext/lock.rb
+++ /dev/null
@@ -1,21 +0,0 @@
-module Rack
- # Rack::Lock was commited to Rack core
- # http://github.com/rack/rack/commit/7409b0c
- # Remove this when Rack 1.0 is released
- unless defined? Lock
- class Lock
- FLAG = 'rack.multithread'.freeze
-
- def initialize(app, lock = Mutex.new)
- @app, @lock = app, lock
- end
-
- def call(env)
- old, env[FLAG] = env[FLAG], false
- @lock.synchronize { @app.call(env) }
- ensure
- env[FLAG] = old
- end
- end
- end
-end
diff --git a/actionpack/lib/action_controller/rack_ext/multipart.rb b/actionpack/lib/action_controller/rack_ext/multipart.rb
deleted file mode 100644
index 3b142307e9..0000000000
--- a/actionpack/lib/action_controller/rack_ext/multipart.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-module Rack
- module Utils
- module Multipart
- class << self
- def parse_multipart_with_rewind(env)
- result = parse_multipart_without_rewind(env)
-
- begin
- env['rack.input'].rewind if env['rack.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
-
- result
- end
-
- alias_method_chain :parse_multipart, :rewind
- end
- end
- end
-end
diff --git a/actionpack/lib/action_controller/rack_ext/parse_query.rb b/actionpack/lib/action_controller/rack_ext/parse_query.rb
deleted file mode 100644
index b1acef8e72..0000000000
--- a/actionpack/lib/action_controller/rack_ext/parse_query.rb
+++ /dev/null
@@ -1,17 +0,0 @@
-# Rack does not automatically cleanup Safari 2 AJAX POST body
-# This has not yet been commited to Rack, please +1 this ticket:
-# http://rack.lighthouseapp.com/projects/22435/tickets/19
-
-module Rack
- module Utils
- alias_method :parse_query_without_ajax_body_cleanup, :parse_query
- module_function :parse_query_without_ajax_body_cleanup
-
- def parse_query(qs, d = '&;')
- qs = qs.dup
- qs.chop! if qs[-1] == 0
- parse_query_without_ajax_body_cleanup(qs, d)
- end
- module_function :parse_query
- end
-end
diff --git a/actionpack/lib/action_controller/request.rb b/actionpack/lib/action_controller/request.rb
index 935326c347..0e95cfc147 100755
--- a/actionpack/lib/action_controller/request.rb
+++ b/actionpack/lib/action_controller/request.rb
@@ -417,15 +417,15 @@ EOM
FORM_DATA_MEDIA_TYPES.include?(content_type.to_s)
end
- # Override Rack's GET method to support nested query strings
+ # Override Rack's GET method to support indifferent access
def GET
- @env["action_controller.request.query_parameters"] ||= UrlEncodedPairParser.parse_query_parameters(query_string)
+ @env["action_controller.request.query_parameters"] ||= normalize_parameters(super)
end
alias_method :query_parameters, :GET
- # Override Rack's POST method to support nested query strings
+ # Override Rack's POST method to support indifferent access
def POST
- @env["action_controller.request.request_parameters"] ||= UrlEncodedPairParser.parse_hash_parameters(super)
+ @env["action_controller.request.request_parameters"] ||= normalize_parameters(super)
end
alias_method :request_parameters, :POST
@@ -461,5 +461,28 @@ EOM
def named_host?(host)
!(host.nil? || /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.match(host))
end
+
+ # Convert nested Hashs to HashWithIndifferentAccess and replace
+ # file upload hashs with UploadedFile objects
+ def normalize_parameters(value)
+ case value
+ when Hash
+ if value.has_key?(:tempfile)
+ upload = value[:tempfile]
+ upload.extend(UploadedFile)
+ upload.original_path = value[:filename]
+ upload.content_type = value[:type]
+ upload
+ else
+ h = {}
+ value.each { |k, v| h[k] = normalize_parameters(v) }
+ h.with_indifferent_access
+ end
+ when Array
+ value.map { |e| normalize_parameters(e) }
+ else
+ value
+ end
+ end
end
end
diff --git a/actionpack/lib/action_controller/rescue.rb b/actionpack/lib/action_controller/rescue.rb
index ec61715b57..242c8da920 100644
--- a/actionpack/lib/action_controller/rescue.rb
+++ b/actionpack/lib/action_controller/rescue.rb
@@ -38,7 +38,7 @@ module ActionController #:nodoc:
'ActionView::TemplateError' => 'template_error'
}
- RESCUES_TEMPLATE_PATH = ActionView::Template::EagerPath.new(
+ RESCUES_TEMPLATE_PATH = ActionView::Template::EagerPath.new_and_loaded(
File.join(File.dirname(__FILE__), "templates"))
def self.included(base) #:nodoc:
diff --git a/actionpack/lib/action_controller/response.rb b/actionpack/lib/action_controller/response.rb
index 27860a6207..ccff473df0 100644
--- a/actionpack/lib/action_controller/response.rb
+++ b/actionpack/lib/action_controller/response.rb
@@ -41,7 +41,7 @@ module ActionController # :nodoc:
def initialize
@status = 200
- @header = DEFAULT_HEADERS.dup
+ @header = Rack::Utils::HeaderHash.new(DEFAULT_HEADERS)
@writer = lambda { |x| @body << x }
@block = nil
@@ -144,7 +144,6 @@ module ActionController # :nodoc:
set_content_length!
convert_content_type!
convert_language!
- convert_expires!
convert_cookies!
end
@@ -167,33 +166,15 @@ module ActionController # :nodoc:
str
end
- # Over Rack::Response#set_cookie to add HttpOnly option
def set_cookie(key, value)
- case value
- when Hash
- domain = "; domain=" + value[:domain] if value[:domain]
- path = "; path=" + value[:path] if value[:path]
- # According to RFC 2109, we need dashes here.
- # N.B.: cgi.rb uses spaces...
- expires = "; expires=" + value[:expires].clone.gmtime.
- strftime("%a, %d-%b-%Y %H:%M:%S GMT") if value[:expires]
- secure = "; secure" if value[:secure]
- httponly = "; HttpOnly" if value[:http_only]
- value = value[:value]
- end
- value = [value] unless Array === value
- cookie = ::Rack::Utils.escape(key) + "=" +
- value.map { |v| ::Rack::Utils.escape v }.join("&") +
- "#{domain}#{path}#{expires}#{secure}#{httponly}"
-
- case self["Set-Cookie"]
- when Array
- self["Set-Cookie"] << cookie
- when String
- self["Set-Cookie"] = [self["Set-Cookie"], cookie]
- when nil
- self["Set-Cookie"] = cookie
+ if value.has_key?(:http_only)
+ ActiveSupport::Deprecation.warn(
+ "The :http_only option in ActionController::Response#set_cookie " +
+ "has been renamed. Please use :httponly instead.", caller)
+ value[:httponly] ||= value.delete(:http_only)
end
+
+ super(key, value)
end
private
@@ -236,7 +217,7 @@ module ActionController # :nodoc:
elsif length = headers['Content-Length']
headers['Content-Length'] = length.to_s
elsif !body.respond_to?(:call) && (!status || status.to_s[0..2] != '304')
- headers["Content-Length"] = body.size.to_s
+ headers["Content-Length"] = (body.respond_to?(:bytesize) ? body.bytesize : body.size).to_s
end
end
@@ -244,10 +225,6 @@ module ActionController # :nodoc:
headers["Content-Language"] = headers.delete("language") if headers["language"]
end
- def convert_expires!
- headers["Expires"] = headers.delete("") if headers["expires"]
- end
-
def convert_cookies!
headers['Set-Cookie'] = Array(headers['Set-Cookie']).compact
end
diff --git a/actionpack/lib/action_controller/session/abstract_store.rb b/actionpack/lib/action_controller/session/abstract_store.rb
index 9434c2e05e..f6369abf15 100644
--- a/actionpack/lib/action_controller/session/abstract_store.rb
+++ b/actionpack/lib/action_controller/session/abstract_store.rb
@@ -17,16 +17,11 @@ module ActionController
@loaded = false
end
- def id
- load! unless @loaded
- @id
- end
-
def session_id
ActiveSupport::Deprecation.warn(
- "ActionController::Session::AbstractStore::SessionHash#session_id" +
- "has been deprecated.Please use #id instead.", caller)
- id
+ "ActionController::Session::AbstractStore::SessionHash#session_id " +
+ "has been deprecated. Please use request.session_options[:id] instead.", caller)
+ @env[ENV_SESSION_OPTIONS_KEY][:id]
end
def [](key)
@@ -47,20 +42,45 @@ module ActionController
def data
ActiveSupport::Deprecation.warn(
- "ActionController::Session::AbstractStore::SessionHash#data" +
- "has been deprecated.Please use #to_hash instead.", caller)
+ "ActionController::Session::AbstractStore::SessionHash#data " +
+ "has been deprecated. Please use #to_hash instead.", caller)
to_hash
end
+ def inspect
+ load! unless @loaded
+ super
+ end
+
private
def loaded?
@loaded
end
def load!
- @id, session = @by.send(:load_session, @env)
- replace(session)
- @loaded = true
+ stale_session_check! do
+ id, session = @by.send(:load_session, @env)
+ (@env[ENV_SESSION_OPTIONS_KEY] ||= {})[:id] = id
+ replace(session)
+ @loaded = true
+ end
+ end
+
+ def stale_session_check!
+ yield
+ rescue ArgumentError => argument_error
+ if argument_error.message =~ %r{undefined class/module ([\w:]*\w)}
+ begin
+ # 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"
+ end
+
+ retry
+ else
+ raise
+ end
end
end
@@ -107,11 +127,7 @@ module ActionController
if !session_data.is_a?(AbstractStore::SessionHash) || session_data.send(:loaded?) || options[:expire_after]
session_data.send(:load!) if session_data.is_a?(AbstractStore::SessionHash) && !session_data.send(:loaded?)
- if session_data.is_a?(AbstractStore::SessionHash)
- sid = session_data.id
- else
- sid = generate_sid
- end
+ sid = options[:id] || generate_sid
unless set_session(env, sid, session_data.to_hash)
return response
@@ -128,12 +144,9 @@ module ActionController
cookie << "; HttpOnly" if options[:httponly]
headers = response[1]
- case a = headers[SET_COOKIE]
- when Array
- a << cookie
- when String
- headers[SET_COOKIE] = [a, cookie]
- when nil
+ unless headers[SET_COOKIE].blank?
+ headers[SET_COOKIE] << "\n#{cookie}"
+ else
headers[SET_COOKIE] = cookie
end
end
diff --git a/actionpack/lib/action_controller/session/cookie_store.rb b/actionpack/lib/action_controller/session/cookie_store.rb
index 5a728d1877..a2543c1824 100644
--- a/actionpack/lib/action_controller/session/cookie_store.rb
+++ b/actionpack/lib/action_controller/session/cookie_store.rb
@@ -88,7 +88,7 @@ module ActionController
def call(env)
env[ENV_SESSION_KEY] = AbstractStore::SessionHash.new(self, env)
- env[ENV_SESSION_OPTIONS_KEY] = @default_options
+ env[ENV_SESSION_OPTIONS_KEY] = @default_options.dup
status, headers, body = @app.call(env)
@@ -108,12 +108,9 @@ module ActionController
end
cookie = build_cookie(@key, cookie.merge(options))
- case headers[HTTP_SET_COOKIE]
- when Array
- headers[HTTP_SET_COOKIE] << cookie
- when String
- headers[HTTP_SET_COOKIE] = [headers[HTTP_SET_COOKIE], cookie]
- when nil
+ unless headers[HTTP_SET_COOKIE].blank?
+ headers[HTTP_SET_COOKIE] << "\n#{cookie}"
+ else
headers[HTTP_SET_COOKIE] = cookie
end
end
@@ -133,7 +130,7 @@ module ActionController
expires = "; expires=" + value[:expires].clone.gmtime.
strftime("%a, %d-%b-%Y %H:%M:%S GMT") if value[:expires]
secure = "; secure" if value[:secure]
- httponly = "; httponly" if value[:httponly]
+ httponly = "; HttpOnly" if value[:httponly]
value = value[:value]
end
value = [value] unless Array === value
diff --git a/actionpack/lib/action_controller/streaming.rb b/actionpack/lib/action_controller/streaming.rb
index f6c01925a7..9f80f48c3d 100644
--- a/actionpack/lib/action_controller/streaming.rb
+++ b/actionpack/lib/action_controller/streaming.rb
@@ -160,7 +160,7 @@ module ActionController #:nodoc:
end
content_type = content_type.to_s.strip # fixes a problem with extra '\r' with some browsers
- headers.update(
+ headers.merge!(
'Content-Length' => options[:length],
'Content-Type' => content_type,
'Content-Disposition' => disposition,
diff --git a/actionpack/lib/action_controller/test_process.rb b/actionpack/lib/action_controller/test_process.rb
index 4b5fc3a3c1..dbaec00bee 100644
--- a/actionpack/lib/action_controller/test_process.rb
+++ b/actionpack/lib/action_controller/test_process.rb
@@ -4,8 +4,12 @@ module ActionController #:nodoc:
attr_accessor :query_parameters, :path, :session
attr_accessor :host
- def initialize
- super(Rack::MockRequest.env_for("/"))
+ def self.new(env = {})
+ super
+ end
+
+ def initialize(env = {})
+ super(Rack::MockRequest.env_for("/").merge(env))
@query_parameters = {}
@session = TestSession.new
diff --git a/actionpack/lib/action_controller/url_encoded_pair_parser.rb b/actionpack/lib/action_controller/url_encoded_pair_parser.rb
deleted file mode 100644
index b17b8a31aa..0000000000
--- a/actionpack/lib/action_controller/url_encoded_pair_parser.rb
+++ /dev/null
@@ -1,155 +0,0 @@
-module ActionController
- class UrlEncodedPairParser < StringScanner #:nodoc:
- class << self
- def parse_query_parameters(query_string)
- return {} if query_string.blank?
-
- pairs = query_string.split('&').collect do |chunk|
- next if chunk.empty?
- key, value = chunk.split('=', 2)
- next if key.empty?
- value = value.nil? ? nil : CGI.unescape(value)
- [ CGI.unescape(key), value ]
- end.compact
-
- new(pairs).result
- end
-
- def parse_hash_parameters(params)
- parser = new
-
- params = params.dup
- until params.empty?
- for key, value in params
- if key.blank?
- params.delete(key)
- elsif value.is_a?(Array)
- parser.parse(key, get_typed_value(value.shift))
- params.delete(key) if value.empty?
- else
- parser.parse(key, get_typed_value(value))
- params.delete(key)
- end
- end
- end
-
- parser.result
- end
-
- private
- def get_typed_value(value)
- case value
- when String
- value
- when NilClass
- ''
- when Array
- value.map { |v| get_typed_value(v) }
- when Hash
- if value.has_key?(:tempfile) && !value[:filename].blank?
- upload = value[:tempfile]
- upload.extend(UploadedFile)
- upload.original_path = value[:filename]
- upload.content_type = value[:type]
- upload
- else
- nil
- end
- else
- raise "Unknown form value: #{value.inspect}"
- end
- end
- end
-
- attr_reader :top, :parent, :result
-
- def initialize(pairs = [])
- super('')
- @result = {}
- pairs.each { |key, value| parse(key, value) }
- end
-
- KEY_REGEXP = %r{([^\[\]=&]+)}
- BRACKETED_KEY_REGEXP = %r{\[([^\[\]=&]+)\]}
-
- # Parse the query string
- def parse(key, value)
- self.string = key
- @top, @parent = result, nil
-
- # First scan the bare key
- key = scan(KEY_REGEXP) or return
- key = post_key_check(key)
-
- # Then scan as many nestings as present
- until eos?
- r = scan(BRACKETED_KEY_REGEXP) or return
- key = self[1]
- key = post_key_check(key)
- end
-
- bind(key, value)
- end
-
- private
- # After we see a key, we must look ahead to determine our next action. Cases:
- #
- # [] follows the key. Then the value must be an array.
- # = follows the key. (A value comes next)
- # & or the end of string follows the key. Then the key is a flag.
- # otherwise, a hash follows the key.
- def post_key_check(key)
- if scan(/\[\]/) # a[b][] indicates that b is an array
- container(key, Array)
- nil
- elsif check(/\[[^\]]/) # a[b] indicates that a is a hash
- container(key, Hash)
- nil
- else # End of key? We do nothing.
- key
- end
- end
-
- # Add a container to the stack.
- def container(key, klass)
- type_conflict! klass, top[key] if top.is_a?(Hash) && top.key?(key) && ! top[key].is_a?(klass)
- value = bind(key, klass.new)
- type_conflict! klass, value unless value.is_a?(klass)
- push(value)
- end
-
- # Push a value onto the 'stack', which is actually only the top 2 items.
- def push(value)
- @parent, @top = @top, value
- end
-
- # Bind a key (which may be nil for items in an array) to the provided value.
- def bind(key, value)
- if top.is_a? Array
- if key
- if top[-1].is_a?(Hash) && ! top[-1].key?(key)
- top[-1][key] = value
- else
- top << {key => value}.with_indifferent_access
- end
- push top.last
- return top[key]
- else
- top << value
- return value
- end
- elsif top.is_a? Hash
- key = CGI.unescape(key)
- parent << (@top = {}) if top.key?(key) && parent.is_a?(Array)
- top[key] ||= value
- return top[key]
- else
- raise ArgumentError, "Don't know what to do: top is #{top.inspect}"
- end
- end
-
- def type_conflict!(klass, value)
- raise TypeError, "Conflicting types for parameter containers. Expected an instance of #{klass} but found an instance of #{value.class}. This can be caused by colliding Array and Hash parameters like qs[]=value&qs[key]=value. (The parameters received were #{value.inspect}.)"
- end
- end
-end
diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack.rb
new file mode 100644
index 0000000000..6c03b55552
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack.rb
@@ -0,0 +1,87 @@
+# Copyright (C) 2007, 2008, 2009 Christian Neukirchen <purl.org/net/chneukirchen>
+#
+# Rack is freely distributable under the terms of an MIT-style license.
+# See COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+$:.unshift(File.expand_path(File.dirname(__FILE__)))
+
+
+# The Rack main module, serving as a namespace for all core Rack
+# modules and classes.
+#
+# All modules meant for use in your application are <tt>autoload</tt>ed here,
+# so it should be enough just to <tt>require rack.rb</tt> in your code.
+
+module Rack
+ # The Rack protocol version number implemented.
+ VERSION = [0,1]
+
+ # 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
+ "0.4"
+ end
+
+ autoload :Builder, "rack/builder"
+ autoload :Cascade, "rack/cascade"
+ autoload :CommonLogger, "rack/commonlogger"
+ autoload :ConditionalGet, "rack/conditionalget"
+ autoload :ContentLength, "rack/content_length"
+ 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_controller/vendor/rack-1.0/rack/adapter/camping.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/adapter/camping.rb
new file mode 100644
index 0000000000..63bc787f54
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/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_controller/vendor/rack-1.0/rack/auth/abstract/handler.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/abstract/handler.rb
new file mode 100644
index 0000000000..8489c9b9c4
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/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, &authenticator)
+ @app, @authenticator = app, 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_controller/vendor/rack-1.0/rack/auth/abstract/request.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/abstract/request.rb
new file mode 100644
index 0000000000..1d9ccec685
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/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_controller/vendor/rack-1.0/rack/auth/basic.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/basic.rb
new file mode 100644
index 0000000000..9557224648
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/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: <tt>example/protectedlobster.rb</tt>
+
+ 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_controller/vendor/rack-1.0/rack/auth/digest/md5.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/digest/md5.rb
new file mode 100644
index 0000000000..6d2bd29c2e
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/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(app)
+ 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_controller/vendor/rack-1.0/rack/auth/digest/nonce.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/digest/nonce.rb
new file mode 100644
index 0000000000..dbe109f29a
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/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_controller/vendor/rack-1.0/rack/auth/digest/params.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/digest/params.rb
new file mode 100644
index 0000000000..730e2efdc8
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/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_controller/vendor/rack-1.0/rack/auth/digest/request.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/digest/request.rb
new file mode 100644
index 0000000000..a40f57b7f1
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/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['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_controller/vendor/rack-1.0/rack/auth/openid.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/openid.rb
new file mode 100644
index 0000000000..c5f6a5143e
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/openid.rb
@@ -0,0 +1,480 @@
+# AUTHOR: blink <blinketje@gmail.com>; 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
+ #
+ # <tt>:return_to</tt> 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 <tt>:return_to</tt> is not
+ # provided, return_to will be the current url which allows flexibility
+ # with caveats.
+ #
+ # <tt>:session_key</tt> defines the key to the session hash in the env.
+ # It defaults to 'rack.session'.
+ #
+ # <tt>:openid_param</tt> 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'.
+ #
+ # <tt>:store</tt> defined what OpenID Store to use for persistant
+ # information. By default a Store::Memory will be used.
+ #
+ # <tt>:immediate</tt> as true will make initial requests to be of an
+ # immediate type. This is false by default. See OpenID specification
+ # documentation.
+ #
+ # <tt>:extensions</tt> 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 <tt>:openid</tt> 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 <tt>options[:openid_param]</tt> 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']
+ #
+ # <tt>env['rack.auth.openid.request']</tt> is the openid checkid request
+ # instance.
+ #
+ # <tt>session[:openid_param]</tt> is set to the openid identifier
+ # provided by the user.
+ #
+ # <tt>session[:return_to]</tt> 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']
+ #
+ # <tt>env['rack.auth.openid.response']</tt> 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 '<html><head><title>Confirm...</title></head><body>'
+ r.write oid.form_markup(realm, return_to, immediate)
+ r.write '</body></html>'
+ 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_controller/vendor/rack-1.0/rack/builder.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/builder.rb
new file mode 100644
index 0000000000..25994d5a44
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/builder.rb
@@ -0,0 +1,67 @@
+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 << if block_given?
+ lambda { |app| middleware.new(app, *args, &block) }
+ else
+ lambda { |app| middleware.new(app, *args) }
+ end
+ 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_controller/vendor/rack-1.0/rack/cascade.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/cascade.rb
new file mode 100644
index 0000000000..a038aa1105
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/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_controller/vendor/rack-1.0/rack/commonlogger.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/commonlogger.rb
new file mode 100644
index 0000000000..5e68ac626d
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/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_controller/vendor/rack-1.0/rack/conditionalget.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/conditionalget.rb
new file mode 100644
index 0000000000..7bec824181
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/conditionalget.rb
@@ -0,0 +1,45 @@
+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
+ 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_controller/vendor/rack-1.0/rack/content_length.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/content_length.rb
new file mode 100644
index 0000000000..bce22a32c5
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/content_length.rb
@@ -0,0 +1,27 @@
+require 'rack/utils'
+
+module Rack
+ # Sets the Content-Length header on responses with fixed-length bodies.
+ class ContentLength
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ status, headers, body = @app.call(env)
+ headers = Utils::HeaderHash.new(headers)
+
+ if !Utils::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 + part.length }
+ headers['Content-Length'] = length.to_s
+ end
+
+ [status, headers, body]
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/deflater.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/deflater.rb
new file mode 100644
index 0000000000..3e66680092
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/deflater.rb
@@ -0,0 +1,85 @@
+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"
+ mtime = headers.key?("Last-Modified") ?
+ Time.httpdate(headers["Last-Modified"]) : Time.now
+ body = self.class.gzip(body, mtime)
+ size = body.respond_to?(:bytesize) ? body.bytesize : body.size
+ headers = headers.merge("Content-Encoding" => "gzip", "Content-Length" => size.to_s)
+ [status, headers, [body]]
+ when "deflate"
+ body = self.class.deflate(body)
+ size = body.respond_to?(:bytesize) ? body.bytesize : body.size
+ headers = headers.merge("Content-Encoding" => "deflate", "Content-Length" => size.to_s)
+ [status, headers, [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
+
+ def self.gzip(body, mtime)
+ io = StringIO.new
+ gzip = Zlib::GzipWriter.new(io)
+ gzip.mtime = mtime
+
+ # TODO: Add streaming
+ body.each { |part| gzip << part }
+
+ gzip.close
+ return io.string
+ end
+
+ 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
+ ]
+
+ # Loosely based on Mongrel's Deflate handler
+ def self.deflate(body)
+ deflater = Zlib::Deflate.new(*DEFLATE_ARGS)
+
+ # TODO: Add streaming
+ body.each { |part| deflater << part }
+
+ return deflater.finish
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/directory.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/directory.rb
new file mode 100644
index 0000000000..56ee5e7b60
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/directory.rb
@@ -0,0 +1,151 @@
+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 = "<tr><td class='name'><a href='%s'>%s</a></td><td class='size'>%s</td><td class='type'>%s</td><td class='mtime'>%s</td></tr>"
+ DIR_PAGE = <<-PAGE
+<html><head>
+ <title>%s</title>
+ <meta http-equiv="content-type" content="text/html; charset=utf-8" />
+ <style type='text/css'>
+table { width:100%%; }
+.name { text-align:left; }
+.size, .mtime { text-align:right; }
+.type { width:11em; }
+.mtime { width:15em; }
+ </style>
+</head><body>
+<h1>%s</h1>
+<hr />
+<table>
+ <tr>
+ <th class='name'>Name</th>
+ <th class='size'>Size</th>
+ <th class='type'>Type</th>
+ <th class='mtime'>Last Modified</th>
+ </tr>
+%s
+</table>
+<hr />
+</body></html>
+ 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 = body.respond_to?(:bytesize) ? body.bytesize : body.size
+ 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
+
+ @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 = body.respond_to?(:bytesize) ? body.bytesize : body.size
+ 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_controller/vendor/rack-1.0/rack/file.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/file.rb
new file mode 100644
index 0000000000..7869227a36
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/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 = body.first.size
+ 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_controller/vendor/rack-1.0/rack/handler.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler.rb
new file mode 100644
index 0000000000..1018af64c7
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler.rb
@@ -0,0 +1,48 @@
+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 <tt>MyHandler.run(myapp)</tt>.
+ # 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_controller/vendor/rack-1.0/rack/handler/cgi.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/cgi.rb
new file mode 100644
index 0000000000..f2c976cf46
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/cgi.rb
@@ -0,0 +1,57 @@
+module Rack
+ module Handler
+ class CGI
+ def self.run(app, options=nil)
+ serve app
+ end
+
+ def self.serve(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_controller/vendor/rack-1.0/rack/handler/evented_mongrel.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/evented_mongrel.rb
new file mode 100644
index 0000000000..0f5cbf7293
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/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_controller/vendor/rack-1.0/rack/handler/fastcgi.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/fastcgi.rb
new file mode 100644
index 0000000000..f03e1615c9
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/fastcgi.rb
@@ -0,0 +1,86 @@
+require 'fcgi'
+require 'socket'
+
+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)
+ 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_controller/vendor/rack-1.0/rack/handler/lsws.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/lsws.rb
new file mode 100644
index 0000000000..1f850fc77b
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/lsws.rb
@@ -0,0 +1,52 @@
+require 'lsapi'
+#require 'cgi'
+module Rack
+ module Handler
+ class LSWS
+ def self.run(app, options=nil)
+ while LSAPI.accept != nil
+ serve app
+ end
+ end
+ def self.serve(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" => 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_controller/vendor/rack-1.0/rack/handler/mongrel.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/mongrel.rb
new file mode 100644
index 0000000000..178a1a8fe4
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/mongrel.rb
@@ -0,0 +1,82 @@
+require 'mongrel'
+require 'stringio'
+
+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 = 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_controller/vendor/rack-1.0/rack/handler/scgi.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/scgi.rb
new file mode 100644
index 0000000000..fd18a8359b
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/scgi.rb
@@ -0,0 +1,57 @@
+require 'scgi'
+require 'stringio'
+
+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 = 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_controller/vendor/rack-1.0/rack/handler/swiftiplied_mongrel.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/swiftiplied_mongrel.rb
new file mode 100644
index 0000000000..4bafd0b953
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/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_controller/vendor/rack-1.0/rack/handler/thin.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/thin.rb
new file mode 100644
index 0000000000..7ad088b36a
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/thin.rb
@@ -0,0 +1,15 @@
+require "thin"
+
+module Rack
+ module Handler
+ class Thin
+ def self.run(app, options={})
+ 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_controller/vendor/rack-1.0/rack/handler/webrick.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/webrick.rb
new file mode 100644
index 0000000000..40be79de13
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/webrick.rb
@@ -0,0 +1,61 @@
+require 'webrick'
+require 'stringio'
+
+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 = 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"] ||= "/"
+ env.delete "PATH_INFO" if env["PATH_INFO"] == ""
+
+ 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_controller/vendor/rack-1.0/rack/head.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/head.rb
new file mode 100644
index 0000000000..deab822a99
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/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_controller/vendor/rack-1.0/rack/lint.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/lint.rb
new file mode 100644
index 0000000000..7eb05437f0
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/lint.rb
@@ -0,0 +1,476 @@
+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.
+
+ ## <tt>REQUEST_METHOD</tt>:: The HTTP request method, such as
+ ## "GET" or "POST". This cannot ever
+ ## be an empty string, and so is
+ ## always required.
+
+ ## <tt>SCRIPT_NAME</tt>:: 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.
+
+ ## <tt>PATH_INFO</tt>:: 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.
+
+ ## <tt>QUERY_STRING</tt>:: The portion of the request URL that
+ ## follows the <tt>?</tt>, if any. May be
+ ## empty, but is always required!
+
+ ## <tt>SERVER_NAME</tt>, <tt>SERVER_PORT</tt>:: When combined with <tt>SCRIPT_NAME</tt> and <tt>PATH_INFO</tt>, these variables can be used to complete the URL. Note, however, that <tt>HTTP_HOST</tt>, if present, should be used in preference to <tt>SERVER_NAME</tt> for reconstructing the request URL. <tt>SERVER_NAME</tt> and <tt>SERVER_PORT</tt> can never be empty strings, and so are always required.
+
+ ## <tt>HTTP_</tt> Variables:: Variables corresponding to the
+ ## client-supplied HTTP request
+ ## headers (i.e., variables whose
+ ## names begin with <tt>HTTP_</tt>). 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:
+
+ ## <tt>rack.version</tt>:: The Array [0,1], representing this version of Rack.
+ ## <tt>rack.url_scheme</tt>:: +http+ or +https+, depending on the request URL.
+ ## <tt>rack.input</tt>:: See below, the input stream.
+ ## <tt>rack.errors</tt>:: See below, the error stream.
+ ## <tt>rack.multithread</tt>:: true if the application object may be simultaneously invoked by another thread in the same process, false otherwise.
+ ## <tt>rack.multiprocess</tt>:: true if an equivalent application object may be simultaneously invoked by another process, false otherwise.
+ ## <tt>rack.run_once</tt>:: 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 <tt>rack.</tt>
+ ## 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
+ ## <tt>HTTP_CONTENT_TYPE</tt> or <tt>HTTP_CONTENT_LENGTH</tt>
+ ## (use the versions without <tt>HTTP_</tt>).
+ %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:
+
+ ## * <tt>rack.version</tt> must be an array of Integers.
+ assert("rack.version must be an Array, was #{env["rack.version"].class}") {
+ env["rack.version"].instance_of? Array
+ }
+ ## * <tt>rack.url_scheme</tt> 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 <tt>rack.input</tt>.
+ check_input env["rack.input"]
+ ## * There must be a valid error stream in <tt>rack.errors</tt>.
+ check_error env["rack.errors"]
+
+ ## * The <tt>REQUEST_METHOD</tt> must be a valid token.
+ assert("REQUEST_METHOD unknown: #{env["REQUEST_METHOD"]}") {
+ env["REQUEST_METHOD"] =~ /\A[0-9A-Za-z!\#$%&'*+.^_`|~-]+\z/
+ }
+
+ ## * The <tt>SCRIPT_NAME</tt>, if non-empty, must start with <tt>/</tt>
+ assert("SCRIPT_NAME must start with /") {
+ !env.include?("SCRIPT_NAME") ||
+ env["SCRIPT_NAME"] == "" ||
+ env["SCRIPT_NAME"] =~ /\A\//
+ }
+ ## * The <tt>PATH_INFO</tt>, if non-empty, must start with <tt>/</tt>
+ assert("PATH_INFO must start with /") {
+ !env.include?("PATH_INFO") ||
+ env["PATH_INFO"] == "" ||
+ env["PATH_INFO"] =~ /\A\//
+ }
+ ## * The <tt>CONTENT_LENGTH</tt>, 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 <tt>SCRIPT_NAME</tt> or <tt>PATH_INFO</tt> must be
+ ## set. <tt>PATH_INFO</tt> should be <tt>/</tt> if
+ ## <tt>SCRIPT_NAME</tt> 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"]
+ }
+ ## <tt>SCRIPT_NAME</tt> never should be <tt>/</tt>, 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 <tt>:</tt> or newlines in their name,
+ assert("header names must not contain : or \\n") { key !~ /[:\n]/ }
+ ## contain keys names that end in <tt>-</tt> or <tt>_</tt>,
+ assert("header names must not end in - or _") { key !~ /[-_]\z/ }
+ ## but only contain keys that consist of
+ ## letters, digits, <tt>_</tt> or <tt>-</tt> 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 <tt>Content-Type</tt>, 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)
+ chunked_response = false
+ headers.each { |key, value|
+ if key.downcase == 'transfer-encoding'
+ chunked_response = value.downcase != 'identity'
+ end
+ }
+
+ headers.each { |key, value|
+ if key.downcase == 'content-length'
+ ## There must be a <tt>Content-Length</tt>, except when the
+ ## +Status+ is 1xx, 204 or 304, in which case there must be none
+ ## given.
+ assert("Content-Length header found in #{status} response, not allowed") {
+ not Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
+ }
+
+ assert('Content-Length header should not be used if body is chunked') {
+ not chunked_response
+ }
+
+ bytes = 0
+ string_body = true
+
+ @body.each { |part|
+ unless part.kind_of?(String)
+ string_body = false
+ break
+ end
+
+ bytes += (part.respond_to?(:bytesize) ? part.bytesize : part.size)
+ }
+
+ 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
+
+ return
+ end
+ }
+
+ if [ String, Array ].include?(@body.class) && !chunked_response
+ assert('No Content-Length header found') {
+ Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
+ }
+ 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_controller/vendor/rack-1.0/rack/lobster.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/lobster.rb
new file mode 100644
index 0000000000..f63f419a49
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/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 = ["<title>Lobstericious!</title>",
+ "<pre>", lobster, "</pre>",
+ "<a href='#{href}'>flip!</a>"]
+ length = content.inject(0) { |a,e| a+e.size }.to_s
+ [200, {"Content-Type" => "text/html", "Content-Length" => length}, content]
+ }
+
+ def call(env)
+ req = Request.new(env)
+ if req.GET["flip"] == "left"
+ lobster = LobsterString.split("\n").
+ map { |line| line.ljust(42).reverse }.
+ join("\n")
+ href = "?flip=right"
+ elsif req.GET["flip"] == "crash"
+ raise "Lobster crashed"
+ else
+ lobster = LobsterString
+ href = "?flip=left"
+ end
+
+ res = Response.new
+ res.write "<title>Lobstericious!</title>"
+ res.write "<pre>"
+ res.write lobster
+ res.write "</pre>"
+ res.write "<p><a href='#{href}'>flip!</a></p>"
+ res.write "<p><a href='?flip=crash'>crash!</a></p>"
+ res.finish
+ end
+
+ end
+end
+
+if $0 == __FILE__
+ require 'rack'
+ require 'rack/showexceptions'
+ Rack::Handler::WEBrick.run \
+ Rack::ShowExceptions.new(Rack::Lint.new(Rack::Lobster.new)),
+ :Port => 9292
+end
diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/lock.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/lock.rb
new file mode 100644
index 0000000000..93238528c4
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/lock.rb
@@ -0,0 +1,16 @@
+module Rack
+ class Lock
+ FLAG = 'rack.multithread'.freeze
+
+ def initialize(app, lock = Mutex.new)
+ @app, @lock = app, lock
+ end
+
+ def call(env)
+ old, env[FLAG] = env[FLAG], false
+ @lock.synchronize { @app.call(env) }
+ ensure
+ env[FLAG] = old
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/methodoverride.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/methodoverride.rb
new file mode 100644
index 0000000000..0eed29f471
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/methodoverride.rb
@@ -0,0 +1,27 @@
+module Rack
+ class MethodOverride
+ HTTP_METHODS = %w(GET HEAD PUT POST DELETE OPTIONS)
+
+ METHOD_OVERRIDE_PARAM_KEY = "_method".freeze
+ HTTP_METHOD_OVERRIDE_HEADER = "HTTP_X_HTTP_METHOD_OVERRIDE".freeze
+
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ if env["REQUEST_METHOD"] == "POST"
+ req = Request.new(env)
+ method = req.POST[METHOD_OVERRIDE_PARAM_KEY] ||
+ env[HTTP_METHOD_OVERRIDE_HEADER]
+ method = method.to_s.upcase
+ if HTTP_METHODS.include?(method)
+ env["rack.methodoverride.original_method"] = env["REQUEST_METHOD"]
+ env["REQUEST_METHOD"] = method
+ end
+ end
+
+ @app.call(env)
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/mime.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/mime.rb
new file mode 100644
index 0000000000..5a6a73a97b
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/mime.rb
@@ -0,0 +1,204 @@
+module Rack
+ module Mime
+ # Returns String with mime type if found, otherwise use +fallback+.
+ # +ext+ should be filename extension in the '.ext' format that
+ # File.extname(file) returns.
+ # +fallback+ may be any object
+ #
+ # Also see the documentation for MIME_TYPES
+ #
+ # Usage:
+ # Rack::Mime.mime_type('.foo')
+ #
+ # This is a shortcut for:
+ # Rack::Mime::MIME_TYPES.fetch('.foo', 'application/octet-stream')
+
+ def mime_type(ext, fallback='application/octet-stream')
+ MIME_TYPES.fetch(ext, fallback)
+ end
+ module_function :mime_type
+
+ # List of most common mime-types, selected various sources
+ # according to their usefulness in a webserving scope for Ruby
+ # users.
+ #
+ # To amend this list with your local mime.types list you can use:
+ #
+ # require 'webrick/httputils'
+ # list = WEBrick::HTTPUtils.load_mime_types('/etc/mime.types')
+ # Rack::Mime::MIME_TYPES.merge!(list)
+ #
+ # To add the list mongrel provides, use:
+ #
+ # require 'mongrel/handlers'
+ # Rack::Mime::MIME_TYPES.merge!(Mongrel::DirHandler::MIME_TYPES)
+
+ MIME_TYPES = {
+ ".3gp" => "video/3gpp",
+ ".a" => "application/octet-stream",
+ ".ai" => "application/postscript",
+ ".aif" => "audio/x-aiff",
+ ".aiff" => "audio/x-aiff",
+ ".asc" => "application/pgp-signature",
+ ".asf" => "video/x-ms-asf",
+ ".asm" => "text/x-asm",
+ ".asx" => "video/x-ms-asf",
+ ".atom" => "application/atom+xml",
+ ".au" => "audio/basic",
+ ".avi" => "video/x-msvideo",
+ ".bat" => "application/x-msdownload",
+ ".bin" => "application/octet-stream",
+ ".bmp" => "image/bmp",
+ ".bz2" => "application/x-bzip2",
+ ".c" => "text/x-c",
+ ".cab" => "application/vnd.ms-cab-compressed",
+ ".cc" => "text/x-c",
+ ".chm" => "application/vnd.ms-htmlhelp",
+ ".class" => "application/octet-stream",
+ ".com" => "application/x-msdownload",
+ ".conf" => "text/plain",
+ ".cpp" => "text/x-c",
+ ".crt" => "application/x-x509-ca-cert",
+ ".css" => "text/css",
+ ".csv" => "text/csv",
+ ".cxx" => "text/x-c",
+ ".deb" => "application/x-debian-package",
+ ".der" => "application/x-x509-ca-cert",
+ ".diff" => "text/x-diff",
+ ".djv" => "image/vnd.djvu",
+ ".djvu" => "image/vnd.djvu",
+ ".dll" => "application/x-msdownload",
+ ".dmg" => "application/octet-stream",
+ ".doc" => "application/msword",
+ ".dot" => "application/msword",
+ ".dtd" => "application/xml-dtd",
+ ".dvi" => "application/x-dvi",
+ ".ear" => "application/java-archive",
+ ".eml" => "message/rfc822",
+ ".eps" => "application/postscript",
+ ".exe" => "application/x-msdownload",
+ ".f" => "text/x-fortran",
+ ".f77" => "text/x-fortran",
+ ".f90" => "text/x-fortran",
+ ".flv" => "video/x-flv",
+ ".for" => "text/x-fortran",
+ ".gem" => "application/octet-stream",
+ ".gemspec" => "text/x-script.ruby",
+ ".gif" => "image/gif",
+ ".gz" => "application/x-gzip",
+ ".h" => "text/x-c",
+ ".hh" => "text/x-c",
+ ".htm" => "text/html",
+ ".html" => "text/html",
+ ".ico" => "image/vnd.microsoft.icon",
+ ".ics" => "text/calendar",
+ ".ifb" => "text/calendar",
+ ".iso" => "application/octet-stream",
+ ".jar" => "application/java-archive",
+ ".java" => "text/x-java-source",
+ ".jnlp" => "application/x-java-jnlp-file",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".js" => "application/javascript",
+ ".json" => "application/json",
+ ".log" => "text/plain",
+ ".m3u" => "audio/x-mpegurl",
+ ".m4v" => "video/mp4",
+ ".man" => "text/troff",
+ ".mathml" => "application/mathml+xml",
+ ".mbox" => "application/mbox",
+ ".mdoc" => "text/troff",
+ ".me" => "text/troff",
+ ".mid" => "audio/midi",
+ ".midi" => "audio/midi",
+ ".mime" => "message/rfc822",
+ ".mml" => "application/mathml+xml",
+ ".mng" => "video/x-mng",
+ ".mov" => "video/quicktime",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mp4v" => "video/mp4",
+ ".mpeg" => "video/mpeg",
+ ".mpg" => "video/mpeg",
+ ".ms" => "text/troff",
+ ".msi" => "application/x-msdownload",
+ ".odp" => "application/vnd.oasis.opendocument.presentation",
+ ".ods" => "application/vnd.oasis.opendocument.spreadsheet",
+ ".odt" => "application/vnd.oasis.opendocument.text",
+ ".ogg" => "application/ogg",
+ ".p" => "text/x-pascal",
+ ".pas" => "text/x-pascal",
+ ".pbm" => "image/x-portable-bitmap",
+ ".pdf" => "application/pdf",
+ ".pem" => "application/x-x509-ca-cert",
+ ".pgm" => "image/x-portable-graymap",
+ ".pgp" => "application/pgp-encrypted",
+ ".pkg" => "application/octet-stream",
+ ".pl" => "text/x-script.perl",
+ ".pm" => "text/x-script.perl-module",
+ ".png" => "image/png",
+ ".pnm" => "image/x-portable-anymap",
+ ".ppm" => "image/x-portable-pixmap",
+ ".pps" => "application/vnd.ms-powerpoint",
+ ".ppt" => "application/vnd.ms-powerpoint",
+ ".ps" => "application/postscript",
+ ".psd" => "image/vnd.adobe.photoshop",
+ ".py" => "text/x-script.python",
+ ".qt" => "video/quicktime",
+ ".ra" => "audio/x-pn-realaudio",
+ ".rake" => "text/x-script.ruby",
+ ".ram" => "audio/x-pn-realaudio",
+ ".rar" => "application/x-rar-compressed",
+ ".rb" => "text/x-script.ruby",
+ ".rdf" => "application/rdf+xml",
+ ".roff" => "text/troff",
+ ".rpm" => "application/x-redhat-package-manager",
+ ".rss" => "application/rss+xml",
+ ".rtf" => "application/rtf",
+ ".ru" => "text/x-script.ruby",
+ ".s" => "text/x-asm",
+ ".sgm" => "text/sgml",
+ ".sgml" => "text/sgml",
+ ".sh" => "application/x-sh",
+ ".sig" => "application/pgp-signature",
+ ".snd" => "audio/basic",
+ ".so" => "application/octet-stream",
+ ".svg" => "image/svg+xml",
+ ".svgz" => "image/svg+xml",
+ ".swf" => "application/x-shockwave-flash",
+ ".t" => "text/troff",
+ ".tar" => "application/x-tar",
+ ".tbz" => "application/x-bzip-compressed-tar",
+ ".tcl" => "application/x-tcl",
+ ".tex" => "application/x-tex",
+ ".texi" => "application/x-texinfo",
+ ".texinfo" => "application/x-texinfo",
+ ".text" => "text/plain",
+ ".tif" => "image/tiff",
+ ".tiff" => "image/tiff",
+ ".torrent" => "application/x-bittorrent",
+ ".tr" => "text/troff",
+ ".txt" => "text/plain",
+ ".vcf" => "text/x-vcard",
+ ".vcs" => "text/x-vcalendar",
+ ".vrml" => "model/vrml",
+ ".war" => "application/java-archive",
+ ".wav" => "audio/x-wav",
+ ".wma" => "audio/x-ms-wma",
+ ".wmv" => "video/x-ms-wmv",
+ ".wmx" => "video/x-ms-wmx",
+ ".wrl" => "model/vrml",
+ ".wsdl" => "application/wsdl+xml",
+ ".xbm" => "image/x-xbitmap",
+ ".xhtml" => "application/xhtml+xml",
+ ".xls" => "application/vnd.ms-excel",
+ ".xml" => "application/xml",
+ ".xpm" => "image/x-xpixmap",
+ ".xsl" => "application/xml",
+ ".xslt" => "application/xslt+xml",
+ ".yaml" => "text/yaml",
+ ".yml" => "text/yaml",
+ ".zip" => "application/zip",
+ }
+ end
+end
diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/mock.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/mock.rb
new file mode 100644
index 0000000000..70852da3db
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/mock.rb
@@ -0,0 +1,160 @@
+require 'uri'
+require 'stringio'
+require 'rack/lint'
+require 'rack/utils'
+require 'rack/response'
+
+module Rack
+ # Rack::MockRequest helps testing your Rack application without
+ # actually using HTTP.
+ #
+ # After performing a request on a URL with get/post/put/delete, it
+ # returns a MockResponse with useful helper methods for effective
+ # testing.
+ #
+ # You can pass a hash with additional configuration to the
+ # get/post/put/delete.
+ # <tt>:input</tt>:: A String or IO-like to be used as rack.input.
+ # <tt>:fatal</tt>:: Raise a FatalWarning if the app writes to rack.errors.
+ # <tt>:lint</tt>:: If true, wrap the application in a Rack::Lint.
+
+ class MockRequest
+ class FatalWarning < RuntimeError
+ end
+
+ class FatalWarner
+ def puts(warning)
+ raise FatalWarning, warning
+ end
+
+ def write(warning)
+ raise FatalWarning, warning
+ end
+
+ def flush
+ end
+
+ def string
+ ""
+ end
+ end
+
+ DEFAULT_ENV = {
+ "rack.version" => [0,1],
+ "rack.input" => StringIO.new,
+ "rack.errors" => StringIO.new,
+ "rack.multithread" => true,
+ "rack.multiprocess" => true,
+ "rack.run_once" => false,
+ }
+
+ def initialize(app)
+ @app = app
+ end
+
+ def get(uri, opts={}) request("GET", uri, opts) end
+ def post(uri, opts={}) request("POST", uri, opts) end
+ def put(uri, opts={}) request("PUT", uri, opts) end
+ def delete(uri, opts={}) request("DELETE", uri, opts) end
+
+ def request(method="GET", uri="", opts={})
+ env = self.class.env_for(uri, opts.merge(:method => method))
+
+ if opts[:lint]
+ app = Rack::Lint.new(@app)
+ else
+ app = @app
+ end
+
+ errors = env["rack.errors"]
+ MockResponse.new(*(app.call(env) + [errors]))
+ end
+
+ # Return the Rack environment used for a request to +uri+.
+ def self.env_for(uri="", opts={})
+ uri = URI(uri)
+ env = DEFAULT_ENV.dup
+
+ env["REQUEST_METHOD"] = opts[:method] || "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["SCRIPT_NAME"] = opts[:script_name] || ""
+
+ if opts[:fatal]
+ env["rack.errors"] = FatalWarner.new
+ else
+ env["rack.errors"] = StringIO.new
+ 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
+
+ # Rack::MockResponse provides useful helpers for testing your apps.
+ # Usually, you don't create the MockResponse on your own, but use
+ # MockRequest.
+
+ class MockResponse
+ def initialize(status, headers, body, errors=StringIO.new(""))
+ @status = status.to_i
+
+ @original_headers = headers
+ @headers = Rack::Utils::HeaderHash.new
+ headers.each { |field, values|
+ @headers[field] = values
+ @headers[field] = "" if values.empty?
+ }
+
+ @body = ""
+ body.each { |part| @body << part }
+
+ @errors = errors.string
+ end
+
+ # Status
+ attr_reader :status
+
+ # Headers
+ attr_reader :headers, :original_headers
+
+ def [](field)
+ headers[field]
+ end
+
+
+ # Body
+ attr_reader :body
+
+ def =~(other)
+ @body =~ other
+ end
+
+ def match(other)
+ @body.match other
+ end
+
+
+ # Errors
+ attr_accessor :errors
+
+
+ include Response::Helpers
+ end
+end
diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/recursive.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/recursive.rb
new file mode 100644
index 0000000000..bf8b965925
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/recursive.rb
@@ -0,0 +1,57 @@
+require 'uri'
+
+module Rack
+ # Rack::ForwardRequest gets caught by Rack::Recursive and redirects
+ # the current request to the app at +url+.
+ #
+ # raise ForwardRequest.new("/not-found")
+ #
+
+ class ForwardRequest < Exception
+ attr_reader :url, :env
+
+ def initialize(url, env={})
+ @url = URI(url)
+ @env = env
+
+ @env["PATH_INFO"] = @url.path
+ @env["QUERY_STRING"] = @url.query if @url.query
+ @env["HTTP_HOST"] = @url.host if @url.host
+ @env["HTTP_PORT"] = @url.port if @url.port
+ @env["rack.url_scheme"] = @url.scheme if @url.scheme
+
+ super "forwarding to #{url}"
+ end
+ end
+
+ # Rack::Recursive allows applications called down the chain to
+ # include data from other applications (by using
+ # <tt>rack['rack.recursive.include'][...]</tt> or raise a
+ # ForwardRequest to redirect internally.
+
+ class Recursive
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ @script_name = env["SCRIPT_NAME"]
+ @app.call(env.merge('rack.recursive.include' => method(:include)))
+ rescue ForwardRequest => req
+ call(env.merge(req.env))
+ end
+
+ def include(env, path)
+ unless path.index(@script_name) == 0 && (path[@script_name.size] == ?/ ||
+ path[@script_name.size].nil?)
+ raise ArgumentError, "can only include below #{@script_name}, not #{path}"
+ end
+
+ env = env.merge("PATH_INFO" => path, "SCRIPT_NAME" => @script_name,
+ "REQUEST_METHOD" => "GET",
+ "CONTENT_LENGTH" => "0", "CONTENT_TYPE" => "",
+ "rack.input" => StringIO.new(""))
+ @app.call(env)
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/reloader.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/reloader.rb
new file mode 100644
index 0000000000..b17d8c0926
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/reloader.rb
@@ -0,0 +1,64 @@
+require 'thread'
+
+module Rack
+ # Rack::Reloader checks on every request, but at most every +secs+
+ # seconds, if a file loaded changed, and reloads it, logging to
+ # rack.errors.
+ #
+ # It is recommended you use ShowExceptions to catch SyntaxErrors etc.
+
+ class Reloader
+ def initialize(app, secs=10)
+ @app = app
+ @secs = secs # reload every @secs seconds max
+ @last = Time.now
+ end
+
+ def call(env)
+ if Time.now > @last + @secs
+ Thread.exclusive {
+ reload!(env['rack.errors'])
+ @last = Time.now
+ }
+ end
+
+ @app.call(env)
+ end
+
+ def reload!(stderr=$stderr)
+ need_reload = $LOADED_FEATURES.find_all { |loaded|
+ begin
+ if loaded =~ /\A[.\/]/ # absolute filename or 1.9
+ abs = loaded
+ else
+ abs = $LOAD_PATH.map { |path| ::File.join(path, loaded) }.
+ find { |file| ::File.exist? file }
+ end
+
+ if abs
+ ::File.mtime(abs) > @last - @secs rescue false
+ else
+ false
+ end
+ end
+ }
+
+ need_reload.each { |l|
+ $LOADED_FEATURES.delete l
+ }
+
+ need_reload.each { |to_load|
+ begin
+ if require to_load
+ stderr.puts "#{self.class}: reloaded `#{to_load}'"
+ end
+ rescue LoadError, SyntaxError => e
+ raise e # Possibly ShowExceptions
+ end
+ }
+
+ stderr.flush
+ need_reload
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/request.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/request.rb
new file mode 100644
index 0000000000..d77fa26575
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/request.rb
@@ -0,0 +1,241 @@
+require 'rack/utils'
+
+module Rack
+ # Rack::Request provides a convenient interface to a Rack
+ # environment. It is stateless, the environment +env+ passed to the
+ # constructor will be directly modified.
+ #
+ # req = Rack::Request.new(env)
+ # req.post?
+ # req.params["data"]
+ #
+ # The environment hash passed will store a reference to the Request object
+ # instantiated so that it will only instantiate if an instance of the Request
+ # object doesn't already exist.
+
+ class Request
+ # The environment of the request.
+ attr_reader :env
+
+ def self.new(env)
+ if self == Rack::Request
+ env["rack.request"] ||= super
+ else
+ super
+ end
+ end
+
+ def initialize(env)
+ @env = env
+ end
+
+ def body; @env["rack.input"] end
+ def scheme; @env["rack.url_scheme"] end
+ def script_name; @env["SCRIPT_NAME"].to_s end
+ def path_info; @env["PATH_INFO"].to_s end
+ def port; @env["SERVER_PORT"].to_i end
+ def request_method; @env["REQUEST_METHOD"] end
+ def query_string; @env["QUERY_STRING"].to_s end
+ def content_length; @env['CONTENT_LENGTH'] end
+ def content_type; @env['CONTENT_TYPE'] end
+
+ # The media type (type/subtype) portion of the CONTENT_TYPE header
+ # without any media type parameters. e.g., when CONTENT_TYPE is
+ # "text/plain;charset=utf-8", the media-type is "text/plain".
+ #
+ # For more information on the use of media types in HTTP, see:
+ # http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7
+ def media_type
+ content_type && content_type.split(/\s*[;,]\s*/, 2)[0].downcase
+ end
+
+ # The media type parameters provided in CONTENT_TYPE as a Hash, or
+ # an empty Hash if no CONTENT_TYPE or media-type parameters were
+ # provided. e.g., when the CONTENT_TYPE is "text/plain;charset=utf-8",
+ # this method responds with the following Hash:
+ # { 'charset' => 'utf-8' }
+ def media_type_params
+ return {} if content_type.nil?
+ content_type.split(/\s*[;,]\s*/)[1..-1].
+ collect { |s| s.split('=', 2) }.
+ inject({}) { |hash,(k,v)| hash[k.downcase] = v ; hash }
+ end
+
+ # The character set of the request body if a "charset" media type
+ # parameter was given, or nil if no "charset" was specified. Note
+ # that, per RFC2616, text/* media types that specify no explicit
+ # charset are to be considered ISO-8859-1.
+ def content_charset
+ media_type_params['charset']
+ end
+
+ def host
+ # Remove port number.
+ (@env["HTTP_HOST"] || @env["SERVER_NAME"]).gsub(/:\d+\z/, '')
+ end
+
+ def script_name=(s); @env["SCRIPT_NAME"] = s.to_s end
+ def path_info=(s); @env["PATH_INFO"] = s.to_s end
+
+ def get?; request_method == "GET" end
+ def post?; request_method == "POST" end
+ def put?; request_method == "PUT" end
+ def delete?; request_method == "DELETE" end
+ def head?; request_method == "HEAD" end
+
+ # The set of form-data media-types. Requests that do not indicate
+ # one of the media types presents in this list will not be eligible
+ # for form-data / param parsing.
+ FORM_DATA_MEDIA_TYPES = [
+ nil,
+ 'application/x-www-form-urlencoded',
+ 'multipart/form-data'
+ ]
+
+ # Determine whether the request body contains form-data by checking
+ # the request media_type against registered form-data media-types:
+ # "application/x-www-form-urlencoded" and "multipart/form-data". The
+ # list of form-data media types can be modified through the
+ # +FORM_DATA_MEDIA_TYPES+ array.
+ def form_data?
+ FORM_DATA_MEDIA_TYPES.include?(media_type)
+ end
+
+ # Returns the data recieved in the query string.
+ def GET
+ if @env["rack.request.query_string"] == query_string
+ @env["rack.request.query_hash"]
+ else
+ @env["rack.request.query_string"] = query_string
+ @env["rack.request.query_hash"] =
+ Utils.parse_nested_query(query_string)
+ end
+ end
+
+ # Returns the data recieved in the request body.
+ #
+ # This method support both application/x-www-form-urlencoded and
+ # multipart/form-data.
+ def POST
+ if @env["rack.request.form_input"].eql? @env["rack.input"]
+ @env["rack.request.form_hash"]
+ elsif form_data?
+ @env["rack.request.form_input"] = @env["rack.input"]
+ unless @env["rack.request.form_hash"] =
+ Utils::Multipart.parse_multipart(env)
+ form_vars = @env["rack.input"].read
+
+ # Fix for Safari Ajax postings that always append \0
+ form_vars.sub!(/\0\z/, '')
+
+ @env["rack.request.form_vars"] = form_vars
+ @env["rack.request.form_hash"] = Utils.parse_nested_query(form_vars)
+
+ begin
+ @env["rack.input"].rewind if @env["rack.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
+ end
+ @env["rack.request.form_hash"]
+ else
+ {}
+ end
+ end
+
+ # The union of GET and POST data.
+ def params
+ self.put? ? self.GET : self.GET.update(self.POST)
+ rescue EOFError => e
+ self.GET
+ end
+
+ # shortcut for request.params[key]
+ def [](key)
+ params[key.to_s]
+ end
+
+ # shortcut for request.params[key] = value
+ def []=(key, value)
+ params[key.to_s] = value
+ end
+
+ # like Hash#values_at
+ def values_at(*keys)
+ keys.map{|key| params[key] }
+ end
+
+ # the referer of the client or '/'
+ def referer
+ @env['HTTP_REFERER'] || '/'
+ end
+ alias referrer referer
+
+
+ def cookies
+ return {} unless @env["HTTP_COOKIE"]
+
+ if @env["rack.request.cookie_string"] == @env["HTTP_COOKIE"]
+ @env["rack.request.cookie_hash"]
+ else
+ @env["rack.request.cookie_string"] = @env["HTTP_COOKIE"]
+ # According to RFC 2109:
+ # If multiple cookies satisfy the criteria above, they are ordered in
+ # the Cookie header such that those with more specific Path attributes
+ # precede those with less specific. Ordering with respect to other
+ # attributes (e.g., Domain) is unspecified.
+ @env["rack.request.cookie_hash"] =
+ Utils.parse_query(@env["rack.request.cookie_string"], ';,').inject({}) {|h,(k,v)|
+ h[k] = Array === v ? v.first : v
+ h
+ }
+ end
+ end
+
+ def xhr?
+ @env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest"
+ end
+
+ # Tries to return a remake of the original request URL as a string.
+ def url
+ url = scheme + "://"
+ url << host
+
+ if scheme == "https" && port != 443 ||
+ scheme == "http" && port != 80
+ url << ":#{port}"
+ end
+
+ url << fullpath
+
+ url
+ end
+
+ def fullpath
+ path = script_name + path_info
+ path << "?" << query_string unless query_string.empty?
+ path
+ end
+
+ def accept_encoding
+ @env["HTTP_ACCEPT_ENCODING"].to_s.split(/,\s*/).map do |part|
+ m = /^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$/.match(part) # From WEBrick
+
+ if m
+ [m[1], (m[2] || 1.0).to_f]
+ else
+ raise "Invalid value for Accept-Encoding: #{part.inspect}"
+ end
+ end
+ end
+
+ def ip
+ if addr = @env['HTTP_X_FORWARDED_FOR']
+ addr.split(',').last.strip
+ else
+ @env['REMOTE_ADDR']
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/response.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/response.rb
new file mode 100644
index 0000000000..a593110139
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/response.rb
@@ -0,0 +1,177 @@
+require 'rack/request'
+require 'rack/utils'
+
+module Rack
+ # Rack::Response provides a convenient interface to create a Rack
+ # response.
+ #
+ # It allows setting of headers and cookies, and provides useful
+ # defaults (a OK response containing HTML).
+ #
+ # You can use Response#write to iteratively generate your response,
+ # but note that this is buffered by Rack::Response until you call
+ # +finish+. +finish+ however can take a block inside which calls to
+ # +write+ are syncronous with the Rack response.
+ #
+ # Your application's +call+ should end returning Response#finish.
+
+ class Response
+ def initialize(body=[], status=200, header={}, &block)
+ @status = status
+ @header = Utils::HeaderHash.new({"Content-Type" => "text/html"}.
+ merge(header))
+
+ @writer = lambda { |x| @body << x }
+ @block = nil
+ @length = 0
+
+ @body = []
+
+ if body.respond_to? :to_str
+ write body.to_str
+ elsif body.respond_to?(:each)
+ body.each { |part|
+ write part.to_s
+ }
+ else
+ raise TypeError, "stringable or iterable required"
+ end
+
+ yield self if block_given?
+ end
+
+ attr_reader :header
+ attr_accessor :status, :body
+
+ def [](key)
+ header[key]
+ end
+
+ def []=(key, value)
+ header[key] = value
+ end
+
+ def set_cookie(key, value)
+ case value
+ when Hash
+ domain = "; domain=" + value[:domain] if value[:domain]
+ path = "; path=" + value[:path] if value[:path]
+ # According to RFC 2109, we need dashes here.
+ # N.B.: cgi.rb uses spaces...
+ expires = "; expires=" + value[:expires].clone.gmtime.
+ strftime("%a, %d-%b-%Y %H:%M:%S GMT") if value[:expires]
+ secure = "; secure" if value[:secure]
+ httponly = "; HttpOnly" if value[:httponly]
+ value = value[:value]
+ end
+ value = [value] unless Array === value
+ cookie = Utils.escape(key) + "=" +
+ value.map { |v| Utils.escape v }.join("&") +
+ "#{domain}#{path}#{expires}#{secure}#{httponly}"
+
+ case self["Set-Cookie"]
+ when Array
+ self["Set-Cookie"] << cookie
+ when String
+ self["Set-Cookie"] = [self["Set-Cookie"], cookie]
+ when nil
+ self["Set-Cookie"] = cookie
+ end
+ end
+
+ def delete_cookie(key, value={})
+ unless Array === self["Set-Cookie"]
+ self["Set-Cookie"] = [self["Set-Cookie"]].compact
+ end
+
+ self["Set-Cookie"].reject! { |cookie|
+ cookie =~ /\A#{Utils.escape(key)}=/
+ }
+
+ set_cookie(key,
+ {:value => '', :path => nil, :domain => nil,
+ :expires => Time.at(0) }.merge(value))
+ end
+
+
+ def finish(&block)
+ @block = block
+
+ if [204, 304].include?(status.to_i)
+ header.delete "Content-Type"
+ [status.to_i, header.to_hash, []]
+ else
+ [status.to_i, header.to_hash, self]
+ end
+ end
+ alias to_a finish # For *response
+
+ def each(&callback)
+ @body.each(&callback)
+ @writer = callback
+ @block.call(self) if @block
+ end
+
+ # Append to body and update Content-Length.
+ #
+ # NOTE: Do not mix #write and direct #body access!
+ #
+ def write(str)
+ s = str.to_s
+ @length += s.size
+ @writer.call s
+
+ header["Content-Length"] = @length.to_s
+ str
+ end
+
+ def close
+ body.close if body.respond_to?(:close)
+ end
+
+ def empty?
+ @block == nil && @body.empty?
+ end
+
+ alias headers header
+
+ module Helpers
+ def invalid?; @status < 100 || @status >= 600; end
+
+ def informational?; @status >= 100 && @status < 200; end
+ def successful?; @status >= 200 && @status < 300; end
+ def redirection?; @status >= 300 && @status < 400; end
+ def client_error?; @status >= 400 && @status < 500; end
+ def server_error?; @status >= 500 && @status < 600; end
+
+ def ok?; @status == 200; end
+ def forbidden?; @status == 403; end
+ def not_found?; @status == 404; end
+
+ def redirect?; [301, 302, 303, 307].include? @status; end
+ def empty?; [201, 204, 304].include? @status; end
+
+ # Headers
+ attr_reader :headers, :original_headers
+
+ def include?(header)
+ !!headers[header]
+ end
+
+ def content_type
+ headers["Content-Type"]
+ end
+
+ def content_length
+ cl = headers["Content-Length"]
+ cl ? cl.to_i : cl
+ end
+
+ def location
+ headers["Location"]
+ end
+ end
+
+ include Helpers
+ end
+end
diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/session/abstract/id.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/session/abstract/id.rb
new file mode 100644
index 0000000000..218144c17f
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/session/abstract/id.rb
@@ -0,0 +1,142 @@
+# AUTHOR: blink <blinketje@gmail.com>; blink#ruby-lang@irc.freenode.net
+# bugrep: Andreas Zehnder
+
+require 'time'
+require 'rack/request'
+require 'rack/response'
+
+module Rack
+
+ module Session
+
+ module Abstract
+
+ # ID sets up a basic framework for implementing an id based sessioning
+ # service. Cookies sent to the client for maintaining sessions will only
+ # contain an id reference. Only #get_session and #set_session are
+ # required to be overwritten.
+ #
+ # All parameters are optional.
+ # * :key determines the name of the cookie, by default it is
+ # 'rack.session'
+ # * :path, :domain, :expire_after, :secure, and :httponly set the related
+ # cookie options as by Rack::Response#add_cookie
+ # * :defer will not set a cookie in the response.
+ # * :renew (implementation dependent) will prompt the generation of a new
+ # session id, and migration of data to be referenced at the new id. If
+ # :defer is set, it will be overridden and the cookie will be set.
+ # * :sidbits sets the number of bits in length that a generated session
+ # id will be.
+ #
+ # These options can be set on a per request basis, at the location of
+ # env['rack.session.options']. Additionally the id of the session can be
+ # found within the options hash at the key :id. It is highly not
+ # recommended to change its value.
+ #
+ # Is Rack::Utils::Context compatible.
+
+ class ID
+ DEFAULT_OPTIONS = {
+ :path => '/',
+ :domain => nil,
+ :expire_after => nil,
+ :secure => false,
+ :httponly => true,
+ :defer => false,
+ :renew => false,
+ :sidbits => 128
+ }
+
+ attr_reader :key, :default_options
+ def initialize(app, options={})
+ @app = app
+ @key = options[:key] || "rack.session"
+ @default_options = self.class::DEFAULT_OPTIONS.merge(options)
+ end
+
+ def call(env)
+ context(env)
+ end
+
+ def context(env, app=@app)
+ load_session(env)
+ status, headers, body = app.call(env)
+ commit_session(env, status, headers, body)
+ end
+
+ private
+
+ # Generate a new session id using Ruby #rand. The size of the
+ # session id is controlled by the :sidbits option.
+ # Monkey patch this to use custom methods for session id generation.
+
+ def generate_sid
+ "%0#{@default_options[:sidbits] / 4}x" %
+ rand(2**@default_options[:sidbits] - 1)
+ end
+
+ # Extracts the session id from provided cookies and passes it and the
+ # environment to #get_session. It then sets the resulting session into
+ # 'rack.session', and places options and session metadata into
+ # 'rack.session.options'.
+
+ def load_session(env)
+ request = Rack::Request.new(env)
+ session_id = request.cookies[@key]
+
+ begin
+ session_id, session = get_session(env, session_id)
+ env['rack.session'] = session
+ rescue
+ env['rack.session'] = Hash.new
+ end
+
+ env['rack.session.options'] = @default_options.
+ merge(:id => session_id)
+ end
+
+ # Acquires the session from the environment and the session id from
+ # the session options and passes them to #set_session. If successful
+ # and the :defer option is not true, a cookie will be added to the
+ # response with the session's id.
+
+ def commit_session(env, status, headers, body)
+ session = env['rack.session']
+ options = env['rack.session.options']
+ session_id = options[:id]
+
+ if not session_id = set_session(env, session_id, session, options)
+ env["rack.errors"].puts("Warning! #{self.class.name} failed to save session. Content dropped.")
+ [status, headers, body]
+ elsif options[:defer] and not options[:renew]
+ env["rack.errors"].puts("Defering cookie for #{session_id}") if $VERBOSE
+ [status, headers, body]
+ else
+ cookie = Hash.new
+ cookie[:value] = session_id
+ cookie[:expires] = Time.now + options[:expire_after] unless options[:expire_after].nil?
+ response = Rack::Response.new(body, status, headers)
+ response.set_cookie(@key, cookie.merge(options))
+ response.to_a
+ end
+ end
+
+ # All thread safety and session retrival proceedures should occur here.
+ # Should return [session_id, session].
+ # If nil is provided as the session id, generation of a new valid id
+ # should occur within.
+
+ def get_session(env, sid)
+ raise '#get_session not implemented.'
+ end
+
+ # All thread safety and session storage proceedures should occur here.
+ # Should return true or false dependant on whether or not the session
+ # was saved or not.
+ def set_session(env, sid, session, options)
+ raise '#set_session not implemented.'
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/session/cookie.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/session/cookie.rb
new file mode 100644
index 0000000000..eace9bd0c6
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/session/cookie.rb
@@ -0,0 +1,91 @@
+require 'openssl'
+require 'rack/request'
+require 'rack/response'
+
+module Rack
+
+ module Session
+
+ # Rack::Session::Cookie provides simple cookie based session management.
+ # The session is a Ruby Hash stored as base64 encoded marshalled data
+ # set to :key (default: rack.session).
+ # When the secret key is set, cookie data is checked for data integrity.
+ #
+ # Example:
+ #
+ # use Rack::Session::Cookie, :key => 'rack.session',
+ # :domain => 'foo.com',
+ # :path => '/',
+ # :expire_after => 2592000,
+ # :secret => 'change_me'
+ #
+ # All parameters are optional.
+
+ class Cookie
+
+ def initialize(app, options={})
+ @app = app
+ @key = options[:key] || "rack.session"
+ @secret = options[:secret]
+ @default_options = {:domain => nil,
+ :path => "/",
+ :expire_after => nil}.merge(options)
+ end
+
+ def call(env)
+ load_session(env)
+ status, headers, body = @app.call(env)
+ commit_session(env, status, headers, body)
+ end
+
+ private
+
+ def load_session(env)
+ request = Rack::Request.new(env)
+ session_data = request.cookies[@key]
+
+ if @secret && session_data
+ session_data, digest = session_data.split("--")
+ session_data = nil unless digest == generate_hmac(session_data)
+ end
+
+ begin
+ session_data = session_data.unpack("m*").first
+ session_data = Marshal.load(session_data)
+ env["rack.session"] = session_data
+ rescue
+ env["rack.session"] = Hash.new
+ end
+
+ env["rack.session.options"] = @default_options.dup
+ end
+
+ def commit_session(env, status, headers, body)
+ session_data = Marshal.dump(env["rack.session"])
+ session_data = [session_data].pack("m*")
+
+ if @secret
+ session_data = "#{session_data}--#{generate_hmac(session_data)}"
+ end
+
+ if session_data.size > (4096 - @key.size)
+ env["rack.errors"].puts("Warning! Rack::Session::Cookie data size exceeds 4K. Content dropped.")
+ [status, headers, body]
+ else
+ options = env["rack.session.options"]
+ cookie = Hash.new
+ cookie[:value] = session_data
+ cookie[:expires] = Time.now + options[:expire_after] unless options[:expire_after].nil?
+ response = Rack::Response.new(body, status, headers)
+ response.set_cookie(@key, cookie.merge(options))
+ response.to_a
+ end
+ end
+
+ def generate_hmac(data)
+ OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA1.new, @secret, data)
+ end
+
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/session/memcache.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/session/memcache.rb
new file mode 100644
index 0000000000..4a65cbf35d
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/session/memcache.rb
@@ -0,0 +1,109 @@
+# AUTHOR: blink <blinketje@gmail.com>; blink#ruby-lang@irc.freenode.net
+
+require 'rack/session/abstract/id'
+require 'memcache'
+
+module Rack
+ module Session
+ # Rack::Session::Memcache provides simple cookie based session management.
+ # Session data is stored in memcached. The corresponding session key is
+ # maintained in the cookie.
+ # You may treat Session::Memcache as you would Session::Pool with the
+ # following caveats.
+ #
+ # * Setting :expire_after to 0 would note to the Memcache server to hang
+ # onto the session data until it would drop it according to it's own
+ # specifications. However, the cookie sent to the client would expire
+ # immediately.
+ #
+ # Note that memcache does drop data before it may be listed to expire. For
+ # a full description of behaviour, please see memcache's documentation.
+
+ class Memcache < Abstract::ID
+ attr_reader :mutex, :pool
+ DEFAULT_OPTIONS = Abstract::ID::DEFAULT_OPTIONS.merge \
+ :namespace => 'rack:session',
+ :memcache_server => 'localhost:11211'
+
+ def initialize(app, options={})
+ super
+
+ @mutex = Mutex.new
+ @pool = MemCache.
+ new @default_options[:memcache_server], @default_options
+ raise 'No memcache servers' unless @pool.servers.any?{|s|s.alive?}
+ end
+
+ def generate_sid
+ loop do
+ sid = super
+ break sid unless @pool.get(sid, true)
+ end
+ end
+
+ def get_session(env, sid)
+ session = @pool.get(sid) if sid
+ @mutex.lock if env['rack.multithread']
+ unless sid and session
+ env['rack.errors'].puts("Session '#{sid.inspect}' not found, initializing...") if $VERBOSE and not sid.nil?
+ session = {}
+ sid = generate_sid
+ ret = @pool.add sid, session
+ raise "Session collision on '#{sid.inspect}'" unless /^STORED/ =~ ret
+ end
+ session.instance_variable_set('@old', {}.merge(session))
+ return [sid, session]
+ rescue MemCache::MemCacheError, Errno::ECONNREFUSED # MemCache server cannot be contacted
+ warn "#{self} is unable to find server."
+ warn $!.inspect
+ return [ nil, {} ]
+ ensure
+ @mutex.unlock if env['rack.multithread']
+ end
+
+ def set_session(env, session_id, new_session, options)
+ expiry = options[:expire_after]
+ expiry = expiry.nil? ? 0 : expiry + 1
+
+ @mutex.lock if env['rack.multithread']
+ session = @pool.get(session_id) || {}
+ if options[:renew] or options[:drop]
+ @pool.delete session_id
+ return false if options[:drop]
+ session_id = generate_sid
+ @pool.add session_id, 0 # so we don't worry about cache miss on #set
+ end
+ old_session = new_session.instance_variable_get('@old') || {}
+ session = merge_sessions session_id, old_session, new_session, session
+ @pool.set session_id, session, expiry
+ return session_id
+ rescue MemCache::MemCacheError, Errno::ECONNREFUSED # MemCache server cannot be contacted
+ warn "#{self} is unable to find server."
+ warn $!.inspect
+ return false
+ ensure
+ @mutex.unlock if env['rack.multithread']
+ end
+
+ private
+
+ def merge_sessions sid, old, new, cur=nil
+ cur ||= {}
+ unless Hash === old and Hash === new
+ warn 'Bad old or new sessions provided.'
+ return cur
+ end
+
+ delete = old.keys - new.keys
+ warn "//@#{sid}: delete #{delete*','}" if $VERBOSE and not delete.empty?
+ delete.each{|k| cur.delete k }
+
+ update = new.keys.select{|k| new[k] != old[k] }
+ warn "//@#{sid}: update #{update*','}" if $VERBOSE and not update.empty?
+ update.each{|k| cur[k] = new[k] }
+
+ cur
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/session/pool.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/session/pool.rb
new file mode 100644
index 0000000000..f6f87408bb
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/session/pool.rb
@@ -0,0 +1,100 @@
+# AUTHOR: blink <blinketje@gmail.com>; blink#ruby-lang@irc.freenode.net
+# THANKS:
+# apeiros, for session id generation, expiry setup, and threadiness
+# sergio, threadiness and bugreps
+
+require 'rack/session/abstract/id'
+require 'thread'
+
+module Rack
+ module Session
+ # Rack::Session::Pool provides simple cookie based session management.
+ # Session data is stored in a hash held by @pool.
+ # In the context of a multithreaded environment, sessions being
+ # committed to the pool is done in a merging manner.
+ #
+ # The :drop option is available in rack.session.options if you with to
+ # explicitly remove the session from the session cache.
+ #
+ # Example:
+ # myapp = MyRackApp.new
+ # sessioned = Rack::Session::Pool.new(myapp,
+ # :domain => 'foo.com',
+ # :expire_after => 2592000
+ # )
+ # Rack::Handler::WEBrick.run sessioned
+
+ class Pool < Abstract::ID
+ attr_reader :mutex, :pool
+ DEFAULT_OPTIONS = Abstract::ID::DEFAULT_OPTIONS.merge :drop => false
+
+ def initialize(app, options={})
+ super
+ @pool = Hash.new
+ @mutex = Mutex.new
+ end
+
+ def generate_sid
+ loop do
+ sid = super
+ break sid unless @pool.key? sid
+ end
+ end
+
+ def get_session(env, sid)
+ session = @pool[sid] if sid
+ @mutex.lock if env['rack.multithread']
+ unless sid and session
+ env['rack.errors'].puts("Session '#{sid.inspect}' not found, initializing...") if $VERBOSE and not sid.nil?
+ session = {}
+ sid = generate_sid
+ @pool.store sid, session
+ end
+ session.instance_variable_set('@old', {}.merge(session))
+ return [sid, session]
+ ensure
+ @mutex.unlock if env['rack.multithread']
+ end
+
+ def set_session(env, session_id, new_session, options)
+ @mutex.lock if env['rack.multithread']
+ session = @pool[session_id]
+ if options[:renew] or options[:drop]
+ @pool.delete session_id
+ return false if options[:drop]
+ session_id = generate_sid
+ @pool.store session_id, 0
+ end
+ old_session = new_session.instance_variable_get('@old') || {}
+ session = merge_sessions session_id, old_session, new_session, session
+ @pool.store session_id, session
+ return session_id
+ rescue
+ warn "#{new_session.inspect} has been lost."
+ warn $!.inspect
+ ensure
+ @mutex.unlock if env['rack.multithread']
+ end
+
+ private
+
+ def merge_sessions sid, old, new, cur=nil
+ cur ||= {}
+ unless Hash === old and Hash === new
+ warn 'Bad old or new sessions provided.'
+ return cur
+ end
+
+ delete = old.keys - new.keys
+ warn "//@#{sid}: dropping #{delete*','}" if $DEBUG and not delete.empty?
+ delete.each{|k| cur.delete k }
+
+ update = new.keys.select{|k| new[k] != old[k] }
+ warn "//@#{sid}: updating #{update*','}" if $DEBUG and not update.empty?
+ update.each{|k| cur[k] = new[k] }
+
+ cur
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/showexceptions.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/showexceptions.rb
new file mode 100644
index 0000000000..697bc41fdb
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/showexceptions.rb
@@ -0,0 +1,349 @@
+require 'ostruct'
+require 'erb'
+require 'rack/request'
+require 'rack/utils'
+
+module Rack
+ # Rack::ShowExceptions catches all exceptions raised from the app it
+ # wraps. It shows a useful backtrace with the sourcefile and
+ # clickable context, the whole Rack environment and the request
+ # data.
+ #
+ # Be careful when you use this on public-facing sites as it could
+ # reveal information helpful to attackers.
+
+ class ShowExceptions
+ CONTEXT = 7
+
+ def initialize(app)
+ @app = app
+ @template = ERB.new(TEMPLATE)
+ end
+
+ def call(env)
+ @app.call(env)
+ rescue StandardError, LoadError, SyntaxError => e
+ backtrace = pretty(env, e)
+ [500,
+ {"Content-Type" => "text/html",
+ "Content-Length" => backtrace.join.size.to_s},
+ backtrace]
+ end
+
+ def pretty(env, exception)
+ req = Rack::Request.new(env)
+ path = (req.script_name + req.path_info).squeeze("/")
+
+ frames = exception.backtrace.map { |line|
+ frame = OpenStruct.new
+ if line =~ /(.*?):(\d+)(:in `(.*)')?/
+ frame.filename = $1
+ frame.lineno = $2.to_i
+ frame.function = $4
+
+ begin
+ lineno = frame.lineno-1
+ lines = ::File.readlines(frame.filename)
+ frame.pre_context_lineno = [lineno-CONTEXT, 0].max
+ frame.pre_context = lines[frame.pre_context_lineno...lineno]
+ frame.context_line = lines[lineno].chomp
+ frame.post_context_lineno = [lineno+CONTEXT, lines.size].min
+ frame.post_context = lines[lineno+1..frame.post_context_lineno]
+ rescue
+ end
+
+ frame
+ else
+ nil
+ end
+ }.compact
+
+ env["rack.errors"].puts "#{exception.class}: #{exception.message}"
+ env["rack.errors"].puts exception.backtrace.map { |l| "\t" + l }
+ env["rack.errors"].flush
+
+ [@template.result(binding)]
+ 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 <djangoproject.com>
+# 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'
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
+<html lang="en">
+<head>
+ <meta http-equiv="content-type" content="text/html; charset=utf-8" />
+ <meta name="robots" content="NONE,NOARCHIVE" />
+ <title><%=h exception.class %> at <%=h path %></title>
+ <style type="text/css">
+ html * { padding:0; margin:0; }
+ body * { padding:10px 20px; }
+ body * * { padding:0; }
+ body { font:small sans-serif; }
+ body>div { border-bottom:1px solid #ddd; }
+ h1 { font-weight:normal; }
+ h2 { margin-bottom:.8em; }
+ h2 span { font-size:80%; color:#666; font-weight:normal; }
+ h3 { margin:1em 0 .5em 0; }
+ h4 { margin:0 0 .5em 0; font-weight: normal; }
+ table {
+ border:1px solid #ccc; border-collapse: collapse; background:white; }
+ tbody td, tbody th { vertical-align:top; padding:2px 3px; }
+ thead th {
+ padding:1px 6px 1px 3px; background:#fefefe; text-align:left;
+ font-weight:normal; font-size:11px; border:1px solid #ddd; }
+ tbody th { text-align:right; color:#666; padding-right:.5em; }
+ table.vars { margin:5px 0 2px 40px; }
+ table.vars td, table.req td { font-family:monospace; }
+ table td.code { width:100%;}
+ table td.code div { overflow:hidden; }
+ table.source th { color:#666; }
+ table.source td {
+ font-family:monospace; white-space:pre; border-bottom:1px solid #eee; }
+ ul.traceback { list-style-type:none; }
+ ul.traceback li.frame { margin-bottom:1em; }
+ div.context { margin: 10px 0; }
+ div.context ol {
+ padding-left:30px; margin:0 10px; list-style-position: inside; }
+ div.context ol li {
+ font-family:monospace; white-space:pre; color:#666; cursor:pointer; }
+ div.context ol.context-line li { color:black; background-color:#ccc; }
+ div.context ol.context-line li span { float: right; }
+ div.commands { margin-left: 40px; }
+ div.commands a { color:black; text-decoration:none; }
+ #summary { background: #ffc; }
+ #summary h2 { font-weight: normal; color: #666; }
+ #summary ul#quicklinks { list-style-type: none; margin-bottom: 2em; }
+ #summary ul#quicklinks li { float: left; padding: 0 1em; }
+ #summary ul#quicklinks>li+li { border-left: 1px #666 solid; }
+ #explanation { background:#eee; }
+ #template, #template-not-exist { background:#f6f6f6; }
+ #template-not-exist ul { margin: 0 0 0 20px; }
+ #traceback { background:#eee; }
+ #requestinfo { background:#f6f6f6; padding-left:120px; }
+ #summary table { border:none; background:transparent; }
+ #requestinfo h2, #requestinfo h3 { position:relative; margin-left:-100px; }
+ #requestinfo h3 { margin-bottom:-1em; }
+ .error { background: #ffc; }
+ .specific { color:#cc3300; font-weight:bold; }
+ </style>
+ <script type="text/javascript">
+ //<!--
+ function getElementsByClassName(oElm, strTagName, strClassName){
+ // Written by Jonathan Snook, http://www.snook.ca/jon;
+ // Add-ons by Robert Nyman, http://www.robertnyman.com
+ var arrElements = (strTagName == "*" && document.all)? document.all :
+ oElm.getElementsByTagName(strTagName);
+ var arrReturnElements = new Array();
+ strClassName = strClassName.replace(/\-/g, "\\-");
+ var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$$)");
+ var oElement;
+ for(var i=0; i<arrElements.length; i++){
+ oElement = arrElements[i];
+ if(oRegExp.test(oElement.className)){
+ arrReturnElements.push(oElement);
+ }
+ }
+ return (arrReturnElements)
+ }
+ function hideAll(elems) {
+ for (var e = 0; e < elems.length; e++) {
+ elems[e].style.display = 'none';
+ }
+ }
+ window.onload = function() {
+ hideAll(getElementsByClassName(document, 'table', 'vars'));
+ hideAll(getElementsByClassName(document, 'ol', 'pre-context'));
+ hideAll(getElementsByClassName(document, 'ol', 'post-context'));
+ }
+ function toggle() {
+ for (var i = 0; i < arguments.length; i++) {
+ var e = document.getElementById(arguments[i]);
+ if (e) {
+ e.style.display = e.style.display == 'none' ? 'block' : 'none';
+ }
+ }
+ return false;
+ }
+ function varToggle(link, id) {
+ toggle('v' + id);
+ var s = link.getElementsByTagName('span')[0];
+ var uarr = String.fromCharCode(0x25b6);
+ var darr = String.fromCharCode(0x25bc);
+ s.innerHTML = s.innerHTML == uarr ? darr : uarr;
+ return false;
+ }
+ //-->
+ </script>
+</head>
+<body>
+
+<div id="summary">
+ <h1><%=h exception.class %> at <%=h path %></h1>
+ <h2><%=h exception.message %></h2>
+ <table><tr>
+ <th>Ruby</th>
+ <td><code><%=h frames.first.filename %></code>: in <code><%=h frames.first.function %></code>, line <%=h frames.first.lineno %></td>
+ </tr><tr>
+ <th>Web</th>
+ <td><code><%=h req.request_method %> <%=h(req.host + path)%></code></td>
+ </tr></table>
+
+ <h3>Jump to:</h3>
+ <ul id="quicklinks">
+ <li><a href="#get-info">GET</a></li>
+ <li><a href="#post-info">POST</a></li>
+ <li><a href="#cookie-info">Cookies</a></li>
+ <li><a href="#env-info">ENV</a></li>
+ </ul>
+</div>
+
+<div id="traceback">
+ <h2>Traceback <span>(innermost first)</span></h2>
+ <ul class="traceback">
+<% frames.each { |frame| %>
+ <li class="frame">
+ <code><%=h frame.filename %></code>: in <code><%=h frame.function %></code>
+
+ <% if frame.context_line %>
+ <div class="context" id="c<%=h frame.object_id %>">
+ <% if frame.pre_context %>
+ <ol start="<%=h frame.pre_context_lineno+1 %>" class="pre-context" id="pre<%=h frame.object_id %>">
+ <% frame.pre_context.each { |line| %>
+ <li onclick="toggle('pre<%=h frame.object_id %>', 'post<%=h frame.object_id %>')"><%=h line %></li>
+ <% } %>
+ </ol>
+ <% end %>
+
+ <ol start="<%=h frame.lineno %>" class="context-line">
+ <li onclick="toggle('pre<%=h frame.object_id %>', 'post<%=h frame.object_id %>')"><%=h frame.context_line %><span>...</span></li></ol>
+
+ <% if frame.post_context %>
+ <ol start='<%=h frame.lineno+1 %>' class="post-context" id="post<%=h frame.object_id %>">
+ <% frame.post_context.each { |line| %>
+ <li onclick="toggle('pre<%=h frame.object_id %>', 'post<%=h frame.object_id %>')"><%=h line %></li>
+ <% } %>
+ </ol>
+ <% end %>
+ </div>
+ <% end %>
+ </li>
+<% } %>
+ </ul>
+</div>
+
+<div id="requestinfo">
+ <h2>Request information</h2>
+
+ <h3 id="get-info">GET</h3>
+ <% unless req.GET.empty? %>
+ <table class="req">
+ <thead>
+ <tr>
+ <th>Variable</th>
+ <th>Value</th>
+ </tr>
+ </thead>
+ <tbody>
+ <% req.GET.sort_by { |k, v| k.to_s }.each { |key, val| %>
+ <tr>
+ <td><%=h key %></td>
+ <td class="code"><div><%=h val.inspect %></div></td>
+ </tr>
+ <% } %>
+ </tbody>
+ </table>
+ <% else %>
+ <p>No GET data.</p>
+ <% end %>
+
+ <h3 id="post-info">POST</h3>
+ <% unless req.POST.empty? %>
+ <table class="req">
+ <thead>
+ <tr>
+ <th>Variable</th>
+ <th>Value</th>
+ </tr>
+ </thead>
+ <tbody>
+ <% req.POST.sort_by { |k, v| k.to_s }.each { |key, val| %>
+ <tr>
+ <td><%=h key %></td>
+ <td class="code"><div><%=h val.inspect %></div></td>
+ </tr>
+ <% } %>
+ </tbody>
+ </table>
+ <% else %>
+ <p>No POST data.</p>
+ <% end %>
+
+
+ <h3 id="cookie-info">COOKIES</h3>
+ <% unless req.cookies.empty? %>
+ <table class="req">
+ <thead>
+ <tr>
+ <th>Variable</th>
+ <th>Value</th>
+ </tr>
+ </thead>
+ <tbody>
+ <% req.cookies.each { |key, val| %>
+ <tr>
+ <td><%=h key %></td>
+ <td class="code"><div><%=h val.inspect %></div></td>
+ </tr>
+ <% } %>
+ </tbody>
+ </table>
+ <% else %>
+ <p>No cookie data.</p>
+ <% end %>
+
+ <h3 id="env-info">Rack ENV</h3>
+ <table class="req">
+ <thead>
+ <tr>
+ <th>Variable</th>
+ <th>Value</th>
+ </tr>
+ </thead>
+ <tbody>
+ <% env.sort_by { |k, v| k.to_s }.each { |key, val| %>
+ <tr>
+ <td><%=h key %></td>
+ <td class="code"><div><%=h val %></div></td>
+ </tr>
+ <% } %>
+ </tbody>
+ </table>
+
+</div>
+
+<div id="explanation">
+ <p>
+ You're seeing this error because you use <code>Rack::ShowExceptions</code>.
+ </p>
+</div>
+
+</body>
+</html>
+HTML
+
+ # :startdoc:
+ end
+end
diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/showstatus.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/showstatus.rb
new file mode 100644
index 0000000000..5f13404dce
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/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 <tt>rack.showstatus.detail</tt>
+ # 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 = body.respond_to?(:bytesize) ? body.bytesize : body.size
+ [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 <djangoproject.com>
+# 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'
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
+<html lang="en">
+<head>
+ <meta http-equiv="content-type" content="text/html; charset=utf-8" />
+ <title><%=h message %> at <%=h req.script_name + req.path_info %></title>
+ <meta name="robots" content="NONE,NOARCHIVE" />
+ <style type="text/css">
+ html * { padding:0; margin:0; }
+ body * { padding:10px 20px; }
+ body * * { padding:0; }
+ body { font:small sans-serif; background:#eee; }
+ body>div { border-bottom:1px solid #ddd; }
+ h1 { font-weight:normal; margin-bottom:.4em; }
+ h1 span { font-size:60%; color:#666; font-weight:normal; }
+ table { border:none; border-collapse: collapse; width:100%; }
+ td, th { vertical-align:top; padding:2px 3px; }
+ th { width:12em; text-align:right; color:#666; padding-right:.5em; }
+ #info { background:#f6f6f6; }
+ #info ol { margin: 0.5em 4em; }
+ #info ol li { font-family: monospace; }
+ #summary { background: #ffc; }
+ #explanation { background:#eee; border-bottom: 0px none; }
+ </style>
+</head>
+<body>
+ <div id="summary">
+ <h1><%=h message %> <span>(<%= status.to_i %>)</span></h1>
+ <table class="meta">
+ <tr>
+ <th>Request Method:</th>
+ <td><%=h req.request_method %></td>
+ </tr>
+ <tr>
+ <th>Request URL:</th>
+ <td><%=h req.url %></td>
+ </tr>
+ </table>
+ </div>
+ <div id="info">
+ <p><%= detail %></p>
+ </div>
+
+ <div id="explanation">
+ <p>
+ You're seeing this error because you use <code>Rack::ShowStatus</code>.
+ </p>
+ </div>
+</body>
+</html>
+HTML
+
+ # :startdoc:
+ end
+end
diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/static.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/static.rb
new file mode 100644
index 0000000000..168e8f83b2
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/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_controller/vendor/rack-1.0/rack/urlmap.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/urlmap.rb
new file mode 100644
index 0000000000..eb1457a850
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/urlmap.rb
@@ -0,0 +1,51 @@
+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 <tt>http://</tt> or <tt>https://</tt>.
+ #
+ # 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)
+ @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_controller/vendor/rack-1.0/rack/utils.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/utils.rb
new file mode 100644
index 0000000000..f352cb6783
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/utils.rb
@@ -0,0 +1,379 @@
+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("&", "&amp;").
+ gsub("<", "&lt;").
+ gsub(">", "&gt;").
+ gsub("'", "&#39;").
+ gsub('"', "&quot;")
+ 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
+
+ # 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)
+
+ 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/lib/action_controller/verification.rb b/actionpack/lib/action_controller/verification.rb
index 7bf09ba6ea..c62b81b666 100644
--- a/actionpack/lib/action_controller/verification.rb
+++ b/actionpack/lib/action_controller/verification.rb
@@ -90,7 +90,7 @@ module ActionController #:nodoc:
def verify_action(options) #:nodoc:
if prereqs_invalid?(options)
flash.update(options[:add_flash]) if options[:add_flash]
- response.headers.update(options[:add_headers]) if options[:add_headers]
+ response.headers.merge!(options[:add_headers]) if options[:add_headers]
apply_remaining_actions(options) unless performed?
end
end
diff --git a/actionpack/lib/action_view.rb b/actionpack/lib/action_view.rb
index 0b710bd8d9..1f1ff9dd05 100644
--- a/actionpack/lib/action_view.rb
+++ b/actionpack/lib/action_view.rb
@@ -44,6 +44,7 @@ module ActionView
autoload :Renderable, 'action_view/renderable'
autoload :RenderablePartial, 'action_view/renderable_partial'
autoload :Template, 'action_view/template'
+ autoload :ReloadableTemplate, 'action_view/reloadable_template'
autoload :TemplateError, 'action_view/template_error'
autoload :TemplateHandler, 'action_view/template_handler'
autoload :TemplateHandlers, 'action_view/template_handlers'
diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb
index 70a0ba91a7..4198725e0d 100644
--- a/actionpack/lib/action_view/base.rb
+++ b/actionpack/lib/action_view/base.rb
@@ -182,6 +182,15 @@ module ActionView #:nodoc:
# that alert()s the caught exception (and then re-raises it).
cattr_accessor :debug_rjs
+ # Specify whether templates should be cached. Otherwise the file we be read everytime it is accessed.
+ # Automaticaly reloading templates are not thread safe and should only be used in development mode.
+ @@cache_template_loading = false
+ cattr_accessor :cache_template_loading
+
+ def self.cache_template_loading?
+ ActionController::Base.allow_concurrency || cache_template_loading
+ end
+
attr_internal :request
delegate :request_forgery_protection_token, :template, :params, :session, :cookies, :response, :headers,
@@ -222,6 +231,8 @@ module ActionView #:nodoc:
def view_paths=(paths)
@view_paths = self.class.process_view_paths(paths)
+ # we might be using ReloadableTemplates, so we need to let them know this a new request
+ @view_paths.load!
end
# Returns the result of a render that's dictated by the options hash. The primary options are:
diff --git a/actionpack/lib/action_view/helpers/date_helper.rb b/actionpack/lib/action_view/helpers/date_helper.rb
index b4c1adbe76..b7ef1fb90d 100644
--- a/actionpack/lib/action_view/helpers/date_helper.rb
+++ b/actionpack/lib/action_view/helpers/date_helper.rb
@@ -931,7 +931,7 @@ module ActionView
end
def default_datetime(options)
- return if options[:include_blank]
+ return if options[:include_blank] || options[:prompt]
case options[:default]
when nil
diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb
index 37400bdbf7..4fef2b443e 100644
--- a/actionpack/lib/action_view/helpers/form_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_helper.rb
@@ -755,7 +755,9 @@ module ActionView
end
options["checked"] = "checked" if checked
add_default_name_and_id(options)
- tag("input", options) << tag("input", "name" => options["name"], "type" => "hidden", "value" => options['disabled'] && checked ? checked_value : unchecked_value)
+ hidden = tag("input", "name" => options["name"], "type" => "hidden", "value" => options['disabled'] && checked ? checked_value : unchecked_value)
+ checkbox = tag("input", options)
+ hidden + checkbox
end
def to_boolean_select_tag(options = {})
@@ -964,24 +966,34 @@ module ActionView
def fields_for_with_nested_attributes(association_name, args, block)
name = "#{object_name}[#{association_name}_attributes]"
association = @object.send(association_name)
+ explicit_object = args.first if args.first.respond_to?(:new_record?)
if association.is_a?(Array)
- children = args.first.respond_to?(:new_record?) ? [args.first] : association
+ children = explicit_object ? [explicit_object] : association
+ explicit_child_index = args.last[:child_index] if args.last.is_a?(Hash)
children.map do |child|
- child_name = "#{name}[#{ child.new_record? ? new_child_id : child.id }]"
- @template.fields_for(child_name, child, *args, &block)
+ fields_for_nested_model("#{name}[#{explicit_child_index || nested_child_index}]", child, args, block)
end.join
else
- object = args.first.respond_to?(:new_record?) ? args.first : association
+ fields_for_nested_model(name, explicit_object || association, args, block)
+ end
+ end
+
+ def fields_for_nested_model(name, object, args, block)
+ if object.new_record?
@template.fields_for(name, object, *args, &block)
+ else
+ @template.fields_for(name, object, *args) do |builder|
+ @template.concat builder.hidden_field(:id)
+ block.call(builder)
+ end
end
end
- def new_child_id
- value = (@child_counter ||= 1)
- @child_counter += 1
- "new_#{value}"
+ def nested_child_index
+ @nested_child_index ||= -1
+ @nested_child_index += 1
end
end
end
diff --git a/actionpack/lib/action_view/helpers/form_options_helper.rb b/actionpack/lib/action_view/helpers/form_options_helper.rb
index 54c82cbd1d..6b385ef77d 100644
--- a/actionpack/lib/action_view/helpers/form_options_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_options_helper.rb
@@ -6,9 +6,7 @@ module ActionView
module Helpers
# Provides a number of methods for turning different kinds of containers into a set of option tags.
# == Options
- # The <tt>collection_select</tt>, <tt>country_select</tt>, <tt>select</tt>,
- # and <tt>time_zone_select</tt> methods take an <tt>options</tt> parameter,
- # a hash.
+ # The <tt>collection_select</tt>, <tt>select</tt> and <tt>time_zone_select</tt> methods take an <tt>options</tt> parameter, a hash:
#
# * <tt>:include_blank</tt> - set to true or a prompt string if the first option element of the select element is a blank. Useful if there is not a default value required for the select element.
#
@@ -28,7 +26,7 @@ module ActionView
#
# Example with @post.person_id => 2:
#
- # select("post", "person_id", Person.find(:all).collect {|p| [ p.name, p.id ] }, {:include_blank => 'None'})
+ # select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {:include_blank => 'None'})
#
# could become:
#
@@ -43,7 +41,7 @@ module ActionView
#
# Example:
#
- # select("post", "person_id", Person.find(:all).collect {|p| [ p.name, p.id ] }, {:prompt => 'Select Person'})
+ # select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {:prompt => 'Select Person'})
#
# could become:
#
@@ -68,6 +66,36 @@ module ActionView
# <option value="rock">rock</option>
# <option value="country">country</option>
# </select>
+ #
+ # * <tt>:disabled</tt> - can be a single value or an array of values that will be disabled options in the final output.
+ #
+ # Example:
+ #
+ # select("post", "category", Post::CATEGORIES, {:disabled => 'restricted'})
+ #
+ # could become:
+ #
+ # <select name="post[category]">
+ # <option></option>
+ # <option>joke</option>
+ # <option>poem</option>
+ # <option disabled="disabled">restricted</option>
+ # </select>
+ #
+ # When used with the <tt>collection_select</tt> helper, <tt>:disabled</tt> can also be a Proc that identifies those options that should be disabled.
+ #
+ # Example:
+ #
+ # collection_select(:post, :category_id, Category.all, :id, :name, {:disabled => lambda{|category| category.archived? }})
+ #
+ # If the categories "2008 stuff" and "Christmas" return true when the method <tt>archived?</tt> is called, this would return:
+ # <select name="post[category_id]">
+ # <option value="1" disabled="disabled">2008 stuff</option>
+ # <option value="2" disabled="disabled">Christmas</option>
+ # <option value="3">Jokes</option>
+ # <option value="4">Poems</option>
+ # </select>
+ #
module FormOptionsHelper
include ERB::Util
@@ -76,7 +104,7 @@ module ActionView
# See options_for_select for the required format of the choices parameter.
#
# Example with @post.person_id => 1:
- # select("post", "person_id", Person.find(:all).collect {|p| [ p.name, p.id ] }, { :include_blank => true })
+ # select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, { :include_blank => true })
#
# could become:
#
@@ -94,7 +122,8 @@ module ActionView
# In addition, this allows a single partial to be used to generate form inputs for both edit and create forms.
#
# By default, <tt>post.person_id</tt> is the selected option. Specify <tt>:selected => value</tt> to use a different selection
- # or <tt>:selected => nil</tt> to leave all options unselected.
+ # or <tt>:selected => nil</tt> to leave all options unselected. Similarly, you can specify values to be disabled in the option
+ # tags by specifying the <tt>:disabled</tt> option. This can either be a single value or an array of values to be disabled.
def select(object, method, choices, options = {}, html_options = {})
InstanceTag.new(object, method, self, options.delete(:object)).to_select_tag(choices, options, html_options)
end
@@ -120,7 +149,7 @@ module ActionView
# end
#
# Sample usage (selecting the associated Author for an instance of Post, <tt>@post</tt>):
- # collection_select(:post, :author_id, Author.find(:all), :id, :name_with_initial, {:prompt => true})
+ # collection_select(:post, :author_id, Author.all, :id, :name_with_initial, {:prompt => true})
#
# If <tt>@post.author_id</tt> is already <tt>1</tt>, this would return:
# <select name="post[author_id]">
@@ -186,14 +215,29 @@ module ActionView
# options_for_select([ "VISA", "MasterCard", "Discover" ], ["VISA", "Discover"])
# <option selected="selected">VISA</option>\n<option>MasterCard</option>\n<option selected="selected">Discover</option>
#
+ # If you wish to specify disabled option tags, set +selected+ to be a hash, with <tt>:disabled</tt> being either a value
+ # or array of values to be disabled. In this case, you can use <tt>:selected</tt> to specify selected option tags.
+ #
+ # Examples:
+ # options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], :disabled => "Super Platinum")
+ # <option value="Free">Free</option>\n<option value="Basic">Basic</option>\n<option value="Advanced">Advanced</option>\n<option value="Super Platinum" disabled="disabled">Super Platinum</option>
+ #
+ # options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], :disabled => ["Advanced", "Super Platinum"])
+ # <option value="Free">Free</option>\n<option value="Basic">Basic</option>\n<option value="Advanced" disabled="disabled">Advanced</option>\n<option value="Super Platinum" disabled="disabled">Super Platinum</option>
+ #
+ # options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], :selected => "Free", :disabled => "Super Platinum")
+ # <option value="Free" selected="selected">Free</option>\n<option value="Basic">Basic</option>\n<option value="Advanced">Advanced</option>\n<option value="Super Platinum" disabled="disabled">Super Platinum</option>
+ #
# 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)
container = container.to_a if Hash === container
+ selected, disabled = extract_selected_and_disabled(selected)
options_for_select = container.inject([]) do |options, element|
text, value = option_text_and_value(element)
selected_attribute = ' selected="selected"' if option_value_selected?(value, selected)
- options << %(<option value="#{html_escape(value.to_s)}"#{selected_attribute}>#{html_escape(text.to_s)}</option>)
+ disabled_attribute = ' disabled="disabled"' if disabled && option_value_selected?(value, disabled)
+ options << %(<option value="#{html_escape(value.to_s)}"#{selected_attribute}#{disabled_attribute}>#{html_escape(text.to_s)}</option>)
end
options_for_select.join("\n")
@@ -209,8 +253,15 @@ module ActionView
# This is more often than not used inside a #select_tag like this example:
# select_tag 'person', options_from_collection_for_select(@people, 'id', 'name')
#
- # If +selected+ is specified, the element returning a match on +value_method+ will get the selected option tag.
- # Be sure to specify the same class as the +value_method+ when specifying a selected option.
+ # If +selected+ is specified as a value or array of values, the element(s) returning a match on +value_method+
+ # will be selected option tag(s).
+ #
+ # If +selected+ is specified as a Proc, those members of the collection that return true for the anonymous
+ # function are the selected values.
+ #
+ # +selected+ can also be a hash, specifying both <tt>:selected</tt> and/or <tt>:disabled</tt> values as required.
+ #
+ # Be sure to specify the same class as the +value_method+ when specifying selected or disabled options.
# Failure to do this will produce undesired results. Example:
# options_from_collection_for_select(@people, 'id', 'name', '1')
# Will not select a person with the id of 1 because 1 (an Integer) is not the same as '1' (a string)
@@ -220,7 +271,12 @@ module ActionView
options = collection.map do |element|
[element.send(text_method), element.send(value_method)]
end
- options_for_select(options, selected)
+ selected, disabled = extract_selected_and_disabled(selected)
+ select_deselect = {}
+ select_deselect[:selected] = extract_values_from_collection(collection, value_method, selected)
+ select_deselect[:disabled] = extract_values_from_collection(collection, value_method, disabled)
+
+ options_for_select(options, select_deselect)
end
# Returns a string of <tt><option></tt> tags, like <tt>options_from_collection_for_select</tt>, but
@@ -238,7 +294,8 @@ module ActionView
# +collection+, returns a value to be used as the contents of its <tt><option></tt> tag.
# * +selected_key+ - A value equal to the +value+ attribute for one of the <tt><option></tt> tags,
# which will have the +selected+ attribute set. Corresponds to the return value of one of the calls
- # to +option_key_method+. If +nil+, no selection is made.
+ # to +option_key_method+. If +nil+, no selection is made. Can also be a hash if disabled values are
+ # to be specified.
#
# Example object structure for use with this method:
# class Continent < ActiveRecord::Base
@@ -388,6 +445,24 @@ module ActionView
value == selected
end
end
+
+ def extract_selected_and_disabled(selected)
+ if selected.is_a?(Hash)
+ [selected[:selected], selected[:disabled]]
+ else
+ [selected, nil]
+ end
+ end
+
+ def extract_values_from_collection(collection, value_method, selected)
+ if selected.is_a?(Proc)
+ collection.map do |element|
+ element.send(value_method) if selected.call(element)
+ end.compact
+ else
+ selected
+ end
+ end
end
class InstanceTag #:nodoc:
@@ -398,16 +473,18 @@ module ActionView
add_default_name_and_id(html_options)
value = value(object)
selected_value = options.has_key?(:selected) ? options[:selected] : value
- content_tag("select", add_options(options_for_select(choices, selected_value), options, selected_value), html_options)
+ disabled_value = options.has_key?(:disabled) ? options[:disabled] : nil
+ content_tag("select", add_options(options_for_select(choices, :selected => selected_value, :disabled => disabled_value), options, selected_value), html_options)
end
def to_collection_select_tag(collection, value_method, text_method, options, html_options)
html_options = html_options.stringify_keys
add_default_name_and_id(html_options)
value = value(object)
+ disabled_value = options.has_key?(:disabled) ? options[:disabled] : nil
selected_value = options.has_key?(:selected) ? options[:selected] : value
content_tag(
- "select", add_options(options_from_collection_for_select(collection, value_method, text_method, selected_value), options, value), html_options
+ "select", add_options(options_from_collection_for_select(collection, value_method, text_method, :selected => selected_value, :disabled => disabled_value), options, value), html_options
)
end
diff --git a/actionpack/lib/action_view/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb
index b1eb6891fa..63fe0c1c57 100644
--- a/actionpack/lib/action_view/helpers/text_helper.rb
+++ b/actionpack/lib/action_view/helpers/text_helper.rb
@@ -107,7 +107,7 @@ module ActionView
text
else
match = Array(phrases).map { |p| Regexp.escape(p) }.join('|')
- text.gsub(/(#{match})(?!(?:[^<]*?)?(?:["'])[^<>]*>)/i, options[:highlighter])
+ text.gsub(/(#{match})(?!(?:[^<]*?)(?:["'])[^<>]*>)/i, options[:highlighter])
end
end
diff --git a/actionpack/lib/action_view/helpers/translation_helper.rb b/actionpack/lib/action_view/helpers/translation_helper.rb
index dc41ef5305..4aed10f640 100644
--- a/actionpack/lib/action_view/helpers/translation_helper.rb
+++ b/actionpack/lib/action_view/helpers/translation_helper.rb
@@ -3,19 +3,37 @@ require 'action_view/helpers/tag_helper'
module ActionView
module Helpers
module TranslationHelper
+ # Delegates to I18n#translate but also performs two additional functions. First, it'll catch MissingTranslationData exceptions
+ # and turn them into inline spans that contains the missing key, such that you can see in a view what is missing where.
+ #
+ # Second, it'll scope the key by the current partial if the key starts with a period. So if you call translate(".foo") from the
+ # people/index.html.erb template, you'll actually be calling I18n.translate("people.index.foo"). This makes it less repetitive
+ # to translate many keys within the same partials and gives you a simple framework for scoping them consistently. If you don't
+ # prepend the key with a period, nothing is converted.
def translate(key, options = {})
options[:raise] = true
- I18n.translate(key, options)
+ I18n.translate(scope_key_by_partial(key), options)
rescue I18n::MissingTranslationData => e
keys = I18n.send(:normalize_translation_keys, e.locale, e.key, e.options[:scope])
content_tag('span', keys.join(', '), :class => 'translation_missing')
end
alias :t :translate
+ # Delegates to I18n.localize with no additional functionality.
def localize(*args)
I18n.localize *args
end
alias :l :localize
+
+
+ private
+ def scope_key_by_partial(key)
+ if key.to_s.first == "."
+ template.path_without_format_and_extension.gsub(%r{/_?}, ".") + key.to_s
+ else
+ key
+ end
+ end
end
end
end \ No newline at end of file
diff --git a/actionpack/lib/action_view/paths.rb b/actionpack/lib/action_view/paths.rb
index c7d6fd696a..41f9f486e5 100644
--- a/actionpack/lib/action_view/paths.rb
+++ b/actionpack/lib/action_view/paths.rb
@@ -2,16 +2,16 @@ module ActionView #:nodoc:
class PathSet < Array #:nodoc:
def self.type_cast(obj)
if obj.is_a?(String)
- if !Object.const_defined?(:Rails) || Rails.configuration.cache_classes
- Template::EagerPath.new(obj)
+ if Base.cache_template_loading?
+ Template::EagerPath.new(obj.to_s)
else
- Template::Path.new(obj)
+ ReloadableTemplate::ReloadablePath.new(obj.to_s)
end
else
obj
end
end
-
+
def initialize(*args)
super(*args).map! { |obj| self.class.type_cast(obj) }
end
@@ -35,6 +35,10 @@ module ActionView #:nodoc:
def unshift(*objs)
super(*objs.map { |obj| self.class.type_cast(obj) })
end
+
+ def load!
+ each(&:load!)
+ end
def find_template(original_template_path, format = nil)
return original_template_path if original_template_path.respond_to?(:render)
@@ -50,12 +54,16 @@ module ActionView #:nodoc:
elsif template = load_path[template_path]
return template
# Try to find html version if the format is javascript
+ elsif format == :js && template = load_path["#{template_path}.#{I18n.locale}.html"]
+ return template
elsif format == :js && template = load_path["#{template_path}.html"]
return template
end
end
- Template.new(original_template_path, self)
+ return Template.new(original_template_path, original_template_path =~ /\A\// ? "" : ".") if File.file?(original_template_path)
+
+ raise MissingTemplate.new(self, original_template_path, format)
end
end
end
diff --git a/actionpack/lib/action_view/reloadable_template.rb b/actionpack/lib/action_view/reloadable_template.rb
new file mode 100644
index 0000000000..3081be60fd
--- /dev/null
+++ b/actionpack/lib/action_view/reloadable_template.rb
@@ -0,0 +1,120 @@
+module ActionView #:nodoc:
+ class ReloadableTemplate < Template
+
+ class TemplateDeleted < ActionView::ActionViewError
+ end
+
+ class ReloadablePath < Template::Path
+
+ def initialize(path)
+ super
+ @paths = {}
+ new_request!
+ end
+
+ def new_request!
+ @disk_cache = {}
+ end
+ alias_method :load!, :new_request!
+
+ def [](path)
+ if found_template = @paths[path]
+ begin
+ found_template.reset_cache_if_stale!
+ rescue TemplateDeleted
+ unregister_template(found_template)
+ self[path]
+ end
+ else
+ load_all_templates_from_dir(templates_dir_from_path(path))
+ @paths[path]
+ end
+ end
+
+ def register_template_from_file(template_file_path)
+ if !@paths[template_relative_path = template_file_path.split("#{@path}/").last] && File.file?(template_file_path)
+ register_template(ReloadableTemplate.new(template_relative_path, self))
+ end
+ end
+
+ def register_template(template)
+ template.accessible_paths.each do |path|
+ @paths[path] = template
+ end
+ end
+
+ # remove (probably deleted) template from cache
+ def unregister_template(template)
+ template.accessible_paths.each do |template_path|
+ @paths.delete(template_path) if @paths[template_path] == template
+ end
+ # fill in any newly created gaps
+ @paths.values.uniq.each do |template|
+ template.accessible_paths.each {|path| @paths[path] ||= template}
+ end
+ end
+
+ # load all templates from the directory of the requested template
+ def load_all_templates_from_dir(dir)
+ # hit disk only once per template-dir/request
+ @disk_cache[dir] ||= template_files_from_dir(dir).each {|template_file| register_template_from_file(template_file)}
+ end
+
+ def templates_dir_from_path(path)
+ dirname = File.dirname(path)
+ File.join(@path, dirname == '.' ? '' : dirname)
+ end
+
+ # get all the template filenames from the dir
+ def template_files_from_dir(dir)
+ Dir.glob(File.join(dir, '*'))
+ end
+
+ end
+
+ module Unfreezable
+ def freeze; self; end
+ end
+
+ def initialize(*args)
+ super
+ @compiled_methods = []
+
+ # we don't ever want to get frozen
+ extend Unfreezable
+ end
+
+ def mtime
+ File.mtime(filename)
+ end
+
+ attr_accessor :previously_last_modified
+
+ def stale?
+ previously_last_modified.nil? || previously_last_modified < mtime
+ rescue Errno::ENOENT => e
+ undef_my_compiled_methods!
+ raise TemplateDeleted
+ end
+
+ def reset_cache_if_stale!
+ if stale?
+ flush_cache 'source', 'compiled_source'
+ undef_my_compiled_methods!
+ @previously_last_modified = mtime
+ end
+ self
+ end
+
+ def undef_my_compiled_methods!
+ @compiled_methods.each {|comp_method| ActionView::Base::CompiledTemplates.send(:remove_method, comp_method)}
+ @compiled_methods.clear
+ end
+
+ def compile!(render_symbol, local_assigns)
+ super
+ @compiled_methods << render_symbol
+ end
+
+ end
+end
diff --git a/actionpack/lib/action_view/renderable.rb b/actionpack/lib/action_view/renderable.rb
index 153e14f68b..41080ed629 100644
--- a/actionpack/lib/action_view/renderable.rb
+++ b/actionpack/lib/action_view/renderable.rb
@@ -1,3 +1,5 @@
+# encoding: utf-8
+
module ActionView
# NOTE: The template that this mixin is being included into is frozen
# so you cannot set or modify any instance variables
@@ -16,7 +18,6 @@ module ActionView
def compiled_source
handler.call(self)
end
- memoize :compiled_source
def method_name_without_locals
['_run', extension, method_segment].compact.join('_')
@@ -78,6 +79,8 @@ module ActionView
begin
ActionView::Base::CompiledTemplates.module_eval(source, filename, 0)
+ rescue Errno::ENOENT => e
+ raise e # Missing template file, re-raise for Base to rescue
rescue Exception => e # errors from template code
if logger = defined?(ActionController) && Base.logger
logger.debug "ERROR: compiling #{render_symbol} RAISED #{e}"
diff --git a/actionpack/lib/action_view/template.rb b/actionpack/lib/action_view/template.rb
index 553158b82a..b8e2165ddf 100644
--- a/actionpack/lib/action_view/template.rb
+++ b/actionpack/lib/action_view/template.rb
@@ -6,7 +6,12 @@ module ActionView #:nodoc:
def initialize(path)
raise ArgumentError, "path already is a Path class" if path.is_a?(Path)
- @path = path.freeze
+ @path = expand_path(path).freeze
+ end
+
+ def expand_path(path)
+ # collapse any directory dots in path ('.' or '..')
+ path.starts_with?('/') ? File.expand_path(path) : File.expand_path(path, '/').from(1)
end
def to_s
@@ -39,30 +44,26 @@ module ActionView #:nodoc:
# etc. A format must be supplied to match a formated file. +hello/index+
# will never match +hello/index.html.erb+.
def [](path)
- templates_in_path do |template|
- if template.accessible_paths.include?(path)
- return template
- end
- end
- nil
end
-
- private
- def templates_in_path
- (Dir.glob("#{@path}/**/*/**") | Dir.glob("#{@path}/**")).each do |file|
- yield create_template(file) unless File.directory?(file)
- end
- end
-
- def create_template(file)
- Template.new(file.split("#{self}/").last, self)
+
+ def load!
+ end
+
+ def self.new_and_loaded(path)
+ returning new(path) do |path|
+ path.load!
end
+ end
end
class EagerPath < Path
def initialize(path)
super
+ end
+ def load!
+ return if @loaded
+
@paths = {}
templates_in_path do |template|
template.load!
@@ -71,11 +72,24 @@ module ActionView #:nodoc:
end
end
@paths.freeze
+ @loaded = true
end
def [](path)
+ load! unless @loaded
@paths[path]
end
+
+ private
+ def templates_in_path
+ (Dir.glob("#{@path}/**/*/**") | Dir.glob("#{@path}/**")).each do |file|
+ yield create_template(file) unless File.directory?(file)
+ end
+ end
+
+ def create_template(file)
+ Template.new(file.split("#{self}/").last, self)
+ end
end
extend TemplateHandlers
@@ -97,9 +111,9 @@ module ActionView #:nodoc:
attr_accessor :locale, :name, :format, :extension
delegate :to_s, :to => :path
- def initialize(template_path, load_paths = [])
+ def initialize(template_path, load_path)
template_path = template_path.dup
- @load_path, @filename = find_full_path(template_path, load_paths)
+ @load_path, @filename = load_path, File.join(load_path, template_path)
@base_path, @name, @locale, @format, @extension = split(template_path)
@base_path.to_s.gsub!(/\/$/, '') # Push to split method
@@ -163,11 +177,6 @@ module ActionView #:nodoc:
@@exempt_from_layout.any? { |exempted| path =~ exempted }
end
- def mtime
- File.mtime(filename)
- end
- memoize :mtime
-
def source
File.read(filename)
end
@@ -190,16 +199,7 @@ module ActionView #:nodoc:
end
end
- def stale?
- File.mtime(filename) > mtime
- end
-
- def recompile?
- !@cached
- end
-
def load!
- @cached = true
freeze
end
@@ -212,15 +212,6 @@ module ActionView #:nodoc:
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
-
# Returns file split into an array
# [base_path, name, locale, format, extension]
def split(file)
@@ -236,24 +227,24 @@ module ActionView #:nodoc:
format = nil
extension = nil
- if m = extensions.match(/^(\w+)?\.?(\w+)?\.?(\w+)?\.?/)
- if valid_locale?(m[1]) && m[2] && valid_extension?(m[3]) # All three
- locale = m[1]
- format = m[2]
- extension = m[3]
- elsif m[1] && m[2] && valid_extension?(m[3]) # Multipart formats
- format = "#{m[1]}.#{m[2]}"
- extension = m[3]
- elsif valid_locale?(m[1]) && valid_extension?(m[2]) # locale and extension
- locale = m[1]
- extension = m[2]
- elsif valid_extension?(m[2]) # format and extension
+ 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 valid_extension?(m[1]) # Just extension
+ 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[1]
+ format = m[0]
end
end
diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb
index c3717a60b8..cdeee934d0 100644
--- a/actionpack/test/abstract_unit.rb
+++ b/actionpack/test/abstract_unit.rb
@@ -34,7 +34,12 @@ 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
FIXTURE_LOAD_PATH = File.join(File.dirname(__FILE__), 'fixtures')
+ActionView::Base.cache_template_loading = true
ActionController::Base.view_paths = FIXTURE_LOAD_PATH
+CACHED_VIEW_PATHS = ActionView::Base.cache_template_loading? ?
+ ActionController::Base.view_paths :
+ ActionController::Base.view_paths.map {|path| ActionView::Template::EagerPath.new(path.to_s)}
diff --git a/actionpack/test/active_record_unit.rb b/actionpack/test/active_record_unit.rb
index d8d2e00dc2..9e0c66055d 100644
--- a/actionpack/test/active_record_unit.rb
+++ b/actionpack/test/active_record_unit.rb
@@ -51,7 +51,8 @@ class ActiveRecordTestConnector
if Object.const_defined?(:ActiveRecord)
defaults = { :database => ':memory:' }
begin
- options = defaults.merge :adapter => 'sqlite3', :timeout => 500
+ adapter = defined?(JRUBY_VERSION) ? 'jdbcsqlite3' : 'sqlite3'
+ options = defaults.merge :adapter => adapter, :timeout => 500
ActiveRecord::Base.establish_connection(options)
ActiveRecord::Base.configurations = { 'sqlite3_ar_integration' => options }
ActiveRecord::Base.connection
diff --git a/actionpack/test/controller/cookie_test.rb b/actionpack/test/controller/cookie_test.rb
index 9508348ca1..657be3c4e4 100644
--- a/actionpack/test/controller/cookie_test.rb
+++ b/actionpack/test/controller/cookie_test.rb
@@ -33,7 +33,7 @@ class CookieTest < ActionController::TestCase
end
def authenticate_with_http_only
- cookies["user_name"] = { :value => "david", :http_only => true }
+ cookies["user_name"] = { :value => "david", :httponly => true }
end
def rescue_action(e)
diff --git a/actionpack/test/controller/http_digest_authentication_test.rb b/actionpack/test/controller/http_digest_authentication_test.rb
index 59f7a403b5..4913e7633b 100644
--- a/actionpack/test/controller/http_digest_authentication_test.rb
+++ b/actionpack/test/controller/http_digest_authentication_test.rb
@@ -107,6 +107,15 @@ class HttpDigestAuthenticationTest < ActionController::TestCase
assert_equal 'Definitely Maybe', @response.body
end
+ test "authentication request with relative URI" do
+ @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:uri => "/", :username => 'pretty', :password => 'please')
+ get :display
+
+ assert_response :success
+ assert assigns(:logged_in)
+ assert_equal 'Definitely Maybe', @response.body
+ end
+
private
def encode_credentials(options)
@@ -120,7 +129,7 @@ class HttpDigestAuthenticationTest < ActionController::TestCase
credentials = decode_credentials(@response.headers['WWW-Authenticate'])
credentials.merge!(options)
- credentials.merge!(:uri => "http://#{@request.host}#{@request.env['REQUEST_URI']}")
+ credentials.reverse_merge!(:uri => "http://#{@request.host}#{@request.env['REQUEST_URI']}")
ActionController::HttpAuthentication::Digest.encode_credentials("GET", credentials, password)
end
diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb
index 57517e45a7..b3f40fbe95 100644
--- a/actionpack/test/controller/integration_test.rb
+++ b/actionpack/test/controller/integration_test.rb
@@ -296,7 +296,7 @@ class IntegrationProcessTest < ActionController::IntegrationTest
assert_equal "Gone", status_message
assert_response 410
assert_response :gone
- assert_equal ["cookie_1=; path=/", "cookie_3=chocolate; path=/"], headers["Set-Cookie"]
+ 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 "Gone", response.body
end
diff --git a/actionpack/test/controller/rack_test.rb b/actionpack/test/controller/rack_test.rb
index e458ab6738..b550d3db78 100644
--- a/actionpack/test/controller/rack_test.rb
+++ b/actionpack/test/controller/rack_test.rb
@@ -219,7 +219,7 @@ class RackResponseTest < BaseRackTest
"Content-Type" => "text/html; charset=utf-8",
"Cache-Control" => "private, max-age=0, must-revalidate",
"ETag" => '"65a8e27d8879283831b664bd8b7f0ad4"',
- "Set-Cookie" => [],
+ "Set-Cookie" => "",
"Content-Length" => "13"
}, headers)
@@ -228,6 +228,21 @@ class RackResponseTest < BaseRackTest
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) }
@@ -238,9 +253,8 @@ class RackResponseTest < BaseRackTest
assert_equal 200, status
assert_equal({
"Content-Type" => "text/html; charset=utf-8",
- "Content-Length" => "",
"Cache-Control" => "no-cache",
- "Set-Cookie" => []
+ "Set-Cookie" => ""
}, headers)
parts = []
diff --git a/actionpack/test/controller/rescue_test.rb b/actionpack/test/controller/rescue_test.rb
index d7c9499157..5709f37e05 100644
--- a/actionpack/test/controller/rescue_test.rb
+++ b/actionpack/test/controller/rescue_test.rb
@@ -198,13 +198,6 @@ class RescueControllerTest < ActionController::TestCase
end
def test_rescue_action_in_public_with_localized_error_file
- # Reload and register danish language for testing
- I18n.reload!
- I18n.backend.store_translations 'da', {}
-
- # Ensure original are still the same since we are reindexing view paths
- assert_equal ORIGINAL_LOCALES, I18n.available_locales.map(&:to_s).sort
-
# Change locale
old_locale = I18n.locale
I18n.locale = :da
diff --git a/actionpack/test/controller/session/cookie_store_test.rb b/actionpack/test/controller/session/cookie_store_test.rb
index 95d2eb11c4..c94d7b0915 100644
--- a/actionpack/test/controller/session/cookie_store_test.rb
+++ b/actionpack/test/controller/session/cookie_store_test.rb
@@ -30,6 +30,10 @@ class CookieStoreTest < ActionController::IntegrationTest
render :text => "foo: #{session[:foo].inspect}"
end
+ def get_session_id
+ render :text => "foo: #{session[:foo].inspect}; id: #{request.session_options[:id]}"
+ end
+
def call_reset_session
reset_session
head :ok
@@ -92,7 +96,7 @@ class CookieStoreTest < ActionController::IntegrationTest
with_test_route_set do
get '/set_session_value'
assert_response :success
- assert_equal ["_myapp_session=#{response.body}; path=/; httponly"],
+ assert_equal "_myapp_session=#{response.body}; path=/; HttpOnly",
headers['Set-Cookie']
end
end
@@ -106,6 +110,20 @@ class CookieStoreTest < ActionController::IntegrationTest
end
end
+ def test_getting_session_id
+ with_test_route_set do
+ cookies[SessionKey] = SignedBar
+ get '/persistent_session_id'
+ assert_response :success
+ assert_equal response.body.size, 32
+ session_id = response.body
+
+ get '/get_session_id'
+ assert_response :success
+ assert_equal "foo: \"bar\"; id: #{session_id}", response.body
+ end
+ end
+
def test_disregards_tampered_sessions
with_test_route_set do
cookies[SessionKey] = "BAh7BjoIZm9vIghiYXI%3D--123456780"
@@ -127,7 +145,7 @@ class CookieStoreTest < ActionController::IntegrationTest
with_test_route_set do
get '/no_session_access'
assert_response :success
- assert_equal [], headers['Set-Cookie']
+ assert_equal "", headers['Set-Cookie']
end
end
@@ -137,7 +155,7 @@ class CookieStoreTest < ActionController::IntegrationTest
"fef868465920f415f2c0652d6910d3af288a0367"
get '/no_session_access'
assert_response :success
- assert_equal [], headers['Set-Cookie']
+ assert_equal "", headers['Set-Cookie']
end
end
@@ -146,7 +164,7 @@ class CookieStoreTest < ActionController::IntegrationTest
get '/set_session_value'
assert_response :success
session_payload = response.body
- assert_equal ["_myapp_session=#{response.body}; path=/; httponly"],
+ assert_equal "_myapp_session=#{response.body}; path=/; HttpOnly",
headers['Set-Cookie']
get '/call_reset_session'
@@ -191,7 +209,8 @@ class CookieStoreTest < ActionController::IntegrationTest
assert_response :success
cookie_body = response.body
- assert_equal ["_myapp_session=#{cookie_body}; path=/; expires=#{expected_expiry}; httponly"], headers['Set-Cookie']
+ assert_equal "_myapp_session=#{cookie_body}; path=/; expires=#{expected_expiry}; HttpOnly",
+ headers['Set-Cookie']
# Second request does not access the session
time = Time.local(2008, 4, 25)
@@ -201,7 +220,8 @@ class CookieStoreTest < ActionController::IntegrationTest
get '/no_session_access'
assert_response :success
- assert_equal ["_myapp_session=#{cookie_body}; path=/; expires=#{expected_expiry}; httponly"], headers['Set-Cookie']
+ assert_equal "_myapp_session=#{cookie_body}; path=/; expires=#{expected_expiry}; HttpOnly",
+ headers['Set-Cookie']
end
end
diff --git a/actionpack/test/controller/session/mem_cache_store_test.rb b/actionpack/test/controller/session/mem_cache_store_test.rb
index eb896a344c..c3a6c8ce45 100644
--- a/actionpack/test/controller/session/mem_cache_store_test.rb
+++ b/actionpack/test/controller/session/mem_cache_store_test.rb
@@ -16,6 +16,10 @@ class MemCacheStoreTest < ActionController::IntegrationTest
render :text => "foo: #{session[:foo].inspect}"
end
+ def get_session_id
+ render :text => "foo: #{session[:foo].inspect}; id: #{request.session_options[:id]}"
+ end
+
def call_reset_session
reset_session
head :ok
@@ -50,7 +54,20 @@ class MemCacheStoreTest < ActionController::IntegrationTest
with_test_route_set do
get '/get_session_value'
assert_response :success
- assert_equal 'foo: nil', response.body
+ assert_equal 'foo: nil', response.body
+ end
+ end
+
+ def test_getting_session_id
+ with_test_route_set do
+ get '/set_session_value'
+ assert_response :success
+ assert cookies['_session_id']
+ session_id = cookies['_session_id']
+
+ get '/get_session_id'
+ assert_response :success
+ assert_equal "foo: \"bar\"; id: #{session_id}", response.body
end
end
diff --git a/actionpack/test/controller/session/test_session_test.rb b/actionpack/test/controller/session/test_session_test.rb
index 83103be3ec..de6539e1cc 100644
--- a/actionpack/test/controller/session/test_session_test.rb
+++ b/actionpack/test/controller/session/test_session_test.rb
@@ -33,7 +33,7 @@ class ActionController::TestSessionTest < ActiveSupport::TestCase
assert_equal('value', session[:key])
end
- def test_calling_delete_removes item
+ def test_calling_delete_removes_item
session = ActionController::TestSession.new
session[:key] = 'value'
assert_equal('value', session[:key])
diff --git a/actionpack/test/controller/view_paths_test.rb b/actionpack/test/controller/view_paths_test.rb
index ac84e2dfcd..6468283270 100644
--- a/actionpack/test/controller/view_paths_test.rb
+++ b/actionpack/test/controller/view_paths_test.rb
@@ -41,31 +41,35 @@ class ViewLoadPathsTest < ActionController::TestCase
def teardown
ActiveSupport::Deprecation.behavior = @old_behavior
end
+
+ def assert_view_path_strings_are_equal(expected, actual)
+ assert_equal(expected.map {|path| path.sub(/\.\//, '')}, actual)
+ end
def test_template_load_path_was_set_correctly
- assert_equal [FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
+ assert_view_path_strings_are_equal [FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
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_view_path_strings_are_equal [FIXTURE_LOAD_PATH, 'foo'], @controller.view_paths.map(&:to_s)
@controller.append_view_path(%w(bar baz))
- assert_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz'], @controller.view_paths.map(&:to_s)
+ assert_view_path_strings_are_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz'], @controller.view_paths.map(&:to_s)
@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_view_path_strings_are_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
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_view_path_strings_are_equal ['baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
@controller.prepend_view_path(%w(foo bar))
- assert_equal ['foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
+ assert_view_path_strings_are_equal ['foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
@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_view_path_strings_are_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
end
def test_template_appends_view_path_correctly
@@ -73,10 +77,10 @@ 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_view_path_strings_are_equal [FIXTURE_LOAD_PATH, 'foo'], @controller.view_paths.map(&:to_s)
@controller.append_view_path(%w(bar baz))
- assert_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz'], @controller.view_paths.map(&:to_s)
+ assert_view_path_strings_are_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz'], @controller.view_paths.map(&:to_s)
assert_equal class_view_paths, TestController.view_paths
end
@@ -85,10 +89,10 @@ 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_view_path_strings_are_equal ['baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
@controller.prepend_view_path(%w(foo bar))
- assert_equal ['foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
+ assert_view_path_strings_are_equal ['foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
assert_equal class_view_paths, TestController.view_paths
end
diff --git a/actionpack/test/fixtures/test/hello_world.erb~ b/actionpack/test/fixtures/test/hello_world.erb~
new file mode 100644
index 0000000000..21934a1c95
--- /dev/null
+++ b/actionpack/test/fixtures/test/hello_world.erb~
@@ -0,0 +1 @@
+Don't pick me! \ No newline at end of file
diff --git a/actionpack/test/fixtures/test/hello_world.pt-BR.html.erb b/actionpack/test/fixtures/test/hello_world.pt-BR.html.erb
new file mode 100644
index 0000000000..773b3c8c6e
--- /dev/null
+++ b/actionpack/test/fixtures/test/hello_world.pt-BR.html.erb
@@ -0,0 +1 @@
+Ola mundo \ No newline at end of file
diff --git a/actionpack/test/fixtures/test/render_implicit_html_template_from_xhr_request.da.html.erb b/actionpack/test/fixtures/test/render_implicit_html_template_from_xhr_request.da.html.erb
new file mode 100644
index 0000000000..0740b2d07c
--- /dev/null
+++ b/actionpack/test/fixtures/test/render_implicit_html_template_from_xhr_request.da.html.erb
@@ -0,0 +1 @@
+Hey HTML!
diff --git a/actionpack/test/fixtures/test/utf8.html.erb b/actionpack/test/fixtures/test/utf8.html.erb
new file mode 100644
index 0000000000..0b4d19aa0e
--- /dev/null
+++ b/actionpack/test/fixtures/test/utf8.html.erb
@@ -0,0 +1,2 @@
+Русский текст
+日本語のテキスト \ 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 a7ed13cf57..a8f8455a54 100644
--- a/actionpack/test/template/compiled_templates_test.rb
+++ b/actionpack/test/template/compiled_templates_test.rb
@@ -2,74 +2,88 @@ require 'abstract_unit'
require 'controller/fake_models'
class CompiledTemplatesTest < Test::Unit::TestCase
+
def setup
@compiled_templates = ActionView::Base::CompiledTemplates
+
+ # first, if we are running the whole test suite with ReloadableTemplates
+ # try to undef all the methods through ReloadableTemplate's interfaces
+ unless ActionView::Base.cache_template_loading?
+ ActionController::Base.view_paths.each do |view_path|
+ view_path.paths.values.uniq!.each do |reloadable_template|
+ reloadable_template.undef_my_compiled_methods!
+ end
+ end
+ end
+
+ # just purge anything that's left
@compiled_templates.instance_methods.each do |m|
@compiled_templates.send(:remove_method, m) if m =~ /^_run_/
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
+ with_caching(true) do
+ 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
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
+ with_caching(true) do
+ 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
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
+ with_caching(true) do
+ 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
end
- def test_template_changes_are_not_reflected_with_cached_templates
- assert_equal "Hello world!", render(:file => "test/hello_world.erb")
- modify_template "test/hello_world.erb", "Goodbye world!" do
- assert_equal "Hello world!", render(:file => "test/hello_world.erb")
+ def test_template_changes_are_not_reflected_with_cached_template_loading
+ with_caching(true) do
+ with_reloading(false) do
+ assert_equal "Hello world!", render(:file => "test/hello_world.erb")
+ modify_template "test/hello_world.erb", "Goodbye world!" do
+ assert_equal "Hello world!", render(:file => "test/hello_world.erb")
+ end
+ assert_equal "Hello world!", render(:file => "test/hello_world.erb")
+ end
end
- assert_equal "Hello world!", render(:file => "test/hello_world.erb")
end
- def test_template_changes_are_reflected_with_uncached_templates
- assert_equal "Hello world!", render_without_cache(:file => "test/hello_world.erb")
- modify_template "test/hello_world.erb", "Goodbye world!" do
- assert_equal "Goodbye world!", render_without_cache(:file => "test/hello_world.erb")
+ def test_template_changes_are_reflected_without_cached_template_loading
+ with_caching(true) do
+ with_reloading(true) do
+ assert_equal "Hello world!", render(:file => "test/hello_world.erb")
+ modify_template "test/hello_world.erb", "Goodbye world!" do
+ reset_mtime_of('test/hello_world.erb')
+ assert_equal "Goodbye world!", render(:file => "test/hello_world.erb")
+ end
+ reset_mtime_of('test/hello_world.erb')
+ assert_equal "Hello world!", render(:file => "test/hello_world.erb")
+ end
end
- assert_equal "Hello world!", render_without_cache(:file => "test/hello_world.erb")
end
private
def render(*args)
- render_with_cache(*args)
- end
-
- def render_with_cache(*args)
view_paths = ActionController::Base.view_paths
- assert_equal ActionView::Template::EagerPath, view_paths.first.class
ActionView::Base.new(view_paths, {}).render(*args)
end
- def render_without_cache(*args)
- path = ActionView::Template::Path.new(FIXTURE_LOAD_PATH)
- view_paths = ActionView::Base.process_view_paths(path)
- assert_equal ActionView::Template::Path, view_paths.first.class
- ActionView::Base.new(view_paths, {}).render(*args)
+ def reset_mtime_of(template_name)
+ unless ActionView::Base.cache_template_loading?
+ ActionController::Base.view_paths.find_template(template_name).previously_last_modified = 10.seconds.ago
+ end
end
def modify_template(template, content)
@@ -82,4 +96,30 @@ class CompiledTemplatesTest < Test::Unit::TestCase
File.open(filename, "wb+") { |f| f.write(old_content) }
end
end
+
+ def with_caching(perform_caching)
+ old_perform_caching = ActionController::Base.perform_caching
+ begin
+ ActionController::Base.perform_caching = perform_caching
+ yield
+ ensure
+ ActionController::Base.perform_caching = old_perform_caching
+ end
+ end
+
+ def with_reloading(reload_templates)
+ old_view_paths, old_cache_templates = ActionController::Base.view_paths, ActionView::Base.cache_template_loading
+ begin
+ ActionView::Base.cache_template_loading = !reload_templates
+ ActionController::Base.view_paths = view_paths_for(reload_templates)
+ yield
+ ensure
+ ActionController::Base.view_paths, ActionView::Base.cache_template_loading = old_view_paths, old_cache_templates
+ end
+ end
+
+ def view_paths_for(reload_templates)
+ # reloadable paths are cheap to create
+ reload_templates ? ActionView::PathSet.new(CACHED_VIEW_PATHS.map(&:to_s)) : CACHED_VIEW_PATHS
+ end
end
diff --git a/actionpack/test/template/date_helper_test.rb b/actionpack/test/template/date_helper_test.rb
index 59e921f09b..2e4763f446 100644
--- a/actionpack/test/template/date_helper_test.rb
+++ b/actionpack/test/template/date_helper_test.rb
@@ -1820,60 +1820,60 @@ class DateHelperTest < ActionView::TestCase
def test_datetime_select_with_default_prompt
@post = Post.new
- @post.updated_at = Time.local(2004, 6, 15, 16, 35)
+ @post.updated_at = nil
expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}
- expected << %{<option value="">Year</option>\n<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << %{<option value="">Year</option>\n<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
expected << "</select>\n"
expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\n}
- expected << %{<option value="">Month</option>\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << %{<option value="">Month</option>\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
expected << "</select>\n"
expected << %{<select id="post_updated_at_3i" name="post[updated_at(3i)]">\n}
- expected << %{<option value="">Day</option>\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n}
+ expected << %{<option value="">Day</option>\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n}
expected << "</select>\n"
expected << " &mdash; "
expected << %{<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n}
- expected << %{<option value="">Hour</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n}
+ expected << %{<option value="">Hour</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n}
expected << "</select>\n"
expected << " : "
expected << %{<select id="post_updated_at_5i" name="post[updated_at(5i)]">\n}
- expected << %{<option value="">Minute</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n<option value="32">32</option>\n<option value="33">33</option>\n<option value="34">34</option>\n<option value="35" selected="selected">35</option>\n<option value="36">36</option>\n<option value="37">37</option>\n<option value="38">38</option>\n<option value="39">39</option>\n<option value="40">40</option>\n<option value="41">41</option>\n<option value="42">42</option>\n<option value="43">43</option>\n<option value="44">44</option>\n<option value="45">45</option>\n<option value="46">46</option>\n<option value="47">47</option>\n<option value="48">48</option>\n<option value="49">49</option>\n<option value="50">50</option>\n<option value="51">51</option>\n<option value="52">52</option>\n<option value="53">53</option>\n<option value="54">54</option>\n<option value="55">55</option>\n<option value="56">56</option>\n<option value="57">57</option>\n<option value="58">58</option>\n<option value="59">59</option>\n}
+ expected << %{<option value="">Minute</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n<option value="32">32</option>\n<option value="33">33</option>\n<option value="34">34</option>\n<option value="35">35</option>\n<option value="36">36</option>\n<option value="37">37</option>\n<option value="38">38</option>\n<option value="39">39</option>\n<option value="40">40</option>\n<option value="41">41</option>\n<option value="42">42</option>\n<option value="43">43</option>\n<option value="44">44</option>\n<option value="45">45</option>\n<option value="46">46</option>\n<option value="47">47</option>\n<option value="48">48</option>\n<option value="49">49</option>\n<option value="50">50</option>\n<option value="51">51</option>\n<option value="52">52</option>\n<option value="53">53</option>\n<option value="54">54</option>\n<option value="55">55</option>\n<option value="56">56</option>\n<option value="57">57</option>\n<option value="58">58</option>\n<option value="59">59</option>\n}
expected << "</select>\n"
- assert_dom_equal expected, datetime_select("post", "updated_at", :prompt => true)
+ assert_dom_equal expected, datetime_select("post", "updated_at", :start_year=>1999, :end_year=>2009, :prompt => true)
end
def test_datetime_select_with_custom_prompt
@post = Post.new
- @post.updated_at = Time.local(2004, 6, 15, 16, 35)
+ @post.updated_at = nil
expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}
- expected << %{<option value="">Choose year</option>\n<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << %{<option value="">Choose year</option>\n<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
expected << "</select>\n"
expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\n}
- expected << %{<option value="">Choose month</option>\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << %{<option value="">Choose month</option>\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
expected << "</select>\n"
expected << %{<select id="post_updated_at_3i" name="post[updated_at(3i)]">\n}
- expected << %{<option value="">Choose day</option>\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n}
+ expected << %{<option value="">Choose day</option>\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n}
expected << "</select>\n"
expected << " &mdash; "
expected << %{<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n}
- expected << %{<option value="">Choose hour</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n}
+ expected << %{<option value="">Choose hour</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n}
expected << "</select>\n"
expected << " : "
expected << %{<select id="post_updated_at_5i" name="post[updated_at(5i)]">\n}
- expected << %{<option value="">Choose minute</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n<option value="32">32</option>\n<option value="33">33</option>\n<option value="34">34</option>\n<option value="35" selected="selected">35</option>\n<option value="36">36</option>\n<option value="37">37</option>\n<option value="38">38</option>\n<option value="39">39</option>\n<option value="40">40</option>\n<option value="41">41</option>\n<option value="42">42</option>\n<option value="43">43</option>\n<option value="44">44</option>\n<option value="45">45</option>\n<option value="46">46</option>\n<option value="47">47</option>\n<option value="48">48</option>\n<option value="49">49</option>\n<option value="50">50</option>\n<option value="51">51</option>\n<option value="52">52</option>\n<option value="53">53</option>\n<option value="54">54</option>\n<option value="55">55</option>\n<option value="56">56</option>\n<option value="57">57</option>\n<option value="58">58</option>\n<option value="59">59</option>\n}
+ expected << %{<option value="">Choose minute</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n<option value="32">32</option>\n<option value="33">33</option>\n<option value="34">34</option>\n<option value="35">35</option>\n<option value="36">36</option>\n<option value="37">37</option>\n<option value="38">38</option>\n<option value="39">39</option>\n<option value="40">40</option>\n<option value="41">41</option>\n<option value="42">42</option>\n<option value="43">43</option>\n<option value="44">44</option>\n<option value="45">45</option>\n<option value="46">46</option>\n<option value="47">47</option>\n<option value="48">48</option>\n<option value="49">49</option>\n<option value="50">50</option>\n<option value="51">51</option>\n<option value="52">52</option>\n<option value="53">53</option>\n<option value="54">54</option>\n<option value="55">55</option>\n<option value="56">56</option>\n<option value="57">57</option>\n<option value="58">58</option>\n<option value="59">59</option>\n}
expected << "</select>\n"
- assert_dom_equal expected, datetime_select("post", "updated_at", :prompt => {:year => 'Choose year', :month => 'Choose month', :day => 'Choose day', :hour => 'Choose hour', :minute => 'Choose minute'})
+ assert_dom_equal expected, datetime_select("post", "updated_at", :start_year=>1999, :end_year=>2009, :prompt => {:year => 'Choose year', :month => 'Choose month', :day => 'Choose day', :hour => 'Choose hour', :minute => 'Choose minute'})
end
def test_date_select_with_zero_value_and_no_start_year
diff --git a/actionpack/test/template/form_helper_test.rb b/actionpack/test/template/form_helper_test.rb
index b7ea2c0176..5cc81b4afb 100644
--- a/actionpack/test/template/form_helper_test.rb
+++ b/actionpack/test/template/form_helper_test.rb
@@ -170,36 +170,36 @@ class FormHelperTest < ActionView::TestCase
def test_check_box
assert_dom_equal(
- '<input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" /><input name="post[secret]" type="hidden" value="0" />',
+ '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />',
check_box("post", "secret")
)
@post.secret = 0
assert_dom_equal(
- '<input id="post_secret" name="post[secret]" type="checkbox" value="1" /><input name="post[secret]" type="hidden" value="0" />',
+ '<input name="post[secret]" type="hidden" value="0" /><input id="post_secret" name="post[secret]" type="checkbox" value="1" />',
check_box("post", "secret")
)
assert_dom_equal(
- '<input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" /><input name="post[secret]" type="hidden" value="0" />',
+ '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />',
check_box("post", "secret" ,{"checked"=>"checked"})
)
@post.secret = true
assert_dom_equal(
- '<input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" /><input name="post[secret]" type="hidden" value="0" />',
+ '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />',
check_box("post", "secret")
)
assert_dom_equal(
- '<input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" /><input name="post[secret]" type="hidden" value="0" />',
+ '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />',
check_box("post", "secret?")
)
@post.secret = ['0']
assert_dom_equal(
- '<input id="post_secret" name="post[secret]" type="checkbox" value="1" /><input name="post[secret]" type="hidden" value="0" />',
+ '<input name="post[secret]" type="hidden" value="0" /><input id="post_secret" name="post[secret]" type="checkbox" value="1" />',
check_box("post", "secret")
)
@post.secret = ['1']
assert_dom_equal(
- '<input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" /><input name="post[secret]" type="hidden" value="0" />',
+ '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />',
check_box("post", "secret")
)
end
@@ -207,14 +207,14 @@ class FormHelperTest < ActionView::TestCase
def test_check_box_with_explicit_checked_and_unchecked_values
@post.secret = "on"
assert_dom_equal(
- '<input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="on" /><input name="post[secret]" type="hidden" value="off" />',
+ '<input name="post[secret]" type="hidden" value="off" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="on" />',
check_box("post", "secret", {}, "on", "off")
)
end
def test_checkbox_disabled_still_submits_checked_value
assert_dom_equal(
- '<input checked="checked" disabled="disabled" id="post_secret" name="post[secret]" type="checkbox" value="1" /><input name="post[secret]" type="hidden" value="1" />',
+ '<input name="post[secret]" type="hidden" value="1" /><input checked="checked" disabled="disabled" id="post_secret" name="post[secret]" type="checkbox" value="1" />',
check_box("post", "secret", { :disabled => :true })
)
end
@@ -289,7 +289,7 @@ class FormHelperTest < ActionView::TestCase
text_area("post", "body", "name" => "really!")
)
assert_dom_equal(
- '<input checked="checked" id="post_secret" name="i mean it" type="checkbox" value="1" /><input name="i mean it" type="hidden" value="0" />',
+ '<input name="i mean it" type="hidden" value="0" /><input checked="checked" id="post_secret" name="i mean it" type="checkbox" value="1" />',
check_box("post", "secret", "name" => "i mean it")
)
assert_dom_equal text_field("post", "title", "name" => "dont guess"),
@@ -309,7 +309,7 @@ class FormHelperTest < ActionView::TestCase
text_area("post", "body", "id" => "really!")
)
assert_dom_equal(
- '<input checked="checked" id="i mean it" name="post[secret]" type="checkbox" value="1" /><input name="post[secret]" type="hidden" value="0" />',
+ '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="i mean it" name="post[secret]" type="checkbox" value="1" />',
check_box("post", "secret", "id" => "i mean it")
)
assert_dom_equal text_field("post", "title", "id" => "dont guess"),
@@ -334,7 +334,7 @@ class FormHelperTest < ActionView::TestCase
text_area("post[]", "body")
)
assert_dom_equal(
- "<input checked=\"checked\" id=\"post_#{pid}_secret\" name=\"post[#{pid}][secret]\" type=\"checkbox\" value=\"1\" /><input name=\"post[#{pid}][secret]\" type=\"hidden\" value=\"0\" />",
+ "<input name=\"post[#{pid}][secret]\" type=\"hidden\" value=\"0\" /><input checked=\"checked\" id=\"post_#{pid}_secret\" name=\"post[#{pid}][secret]\" type=\"checkbox\" value=\"1\" />",
check_box("post[]", "secret")
)
assert_dom_equal(
@@ -360,8 +360,8 @@ class FormHelperTest < ActionView::TestCase
"<label for='post_title'>Title</label>" +
"<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" +
"<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
- "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" +
"<input name='post[secret]' type='hidden' value='0' />" +
+ "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" +
"<input name='commit' id='post_submit' type='submit' value='Create post' />" +
"</form>"
@@ -380,8 +380,8 @@ class FormHelperTest < ActionView::TestCase
"<div style='margin:0;padding:0'><input name='_method' type='hidden' value='put' /></div>" +
"<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" +
"<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
- "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" +
"<input name='post[secret]' type='hidden' value='0' />" +
+ "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" +
"</form>"
assert_dom_equal expected, output_buffer
@@ -398,8 +398,8 @@ class FormHelperTest < ActionView::TestCase
"<form action='http://www.example.com' id='create-post' method='post'>" +
"<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" +
"<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
- "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" +
"<input name='post[secret]' type='hidden' value='0' />" +
+ "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" +
"</form>"
assert_dom_equal expected, output_buffer
@@ -418,8 +418,8 @@ class FormHelperTest < ActionView::TestCase
"<label for=\"post_123_title\">Title</label>" +
"<input name='post[123][title]' size='30' type='text' id='post_123_title' value='Hello World' />" +
"<textarea name='post[123][body]' id='post_123_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
- "<input name='post[123][secret]' checked='checked' type='checkbox' id='post_123_secret' value='1' />" +
"<input name='post[123][secret]' type='hidden' value='0' />" +
+ "<input name='post[123][secret]' checked='checked' type='checkbox' id='post_123_secret' value='1' />" +
"</form>"
assert_dom_equal expected, output_buffer
@@ -436,8 +436,8 @@ class FormHelperTest < ActionView::TestCase
"<form action='http://www.example.com' method='post'>" +
"<input name='post[][title]' size='30' type='text' id='post__title' value='Hello World' />" +
"<textarea name='post[][body]' id='post__body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
- "<input name='post[][secret]' checked='checked' type='checkbox' id='post__secret' value='1' />" +
"<input name='post[][secret]' type='hidden' value='0' />" +
+ "<input name='post[][secret]' checked='checked' type='checkbox' id='post__secret' value='1' />" +
"</form>"
assert_dom_equal expected, output_buffer
@@ -607,6 +607,7 @@ class FormHelperTest < ActionView::TestCase
expected = '<form action="http://www.example.com" method="post">' +
'<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />' +
'<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="author #321" />' +
'</form>'
@@ -627,8 +628,10 @@ class FormHelperTest < ActionView::TestCase
expected = '<form action="http://www.example.com" method="post">' +
'<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
- '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #1" />' +
- '<input id="post_comments_attributes_2_name" name="post[comments_attributes][2][name]" size="30" type="text" value="comment #2" />' +
+ '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' +
+ '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />' +
+ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" />' +
'</form>'
assert_dom_equal expected, output_buffer
@@ -648,8 +651,8 @@ class FormHelperTest < ActionView::TestCase
expected = '<form action="http://www.example.com" method="post">' +
'<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
- '<input id="post_comments_attributes_new_1_name" name="post[comments_attributes][new_1][name]" size="30" type="text" value="new comment" />' +
- '<input id="post_comments_attributes_new_2_name" name="post[comments_attributes][new_2][name]" size="30" type="text" value="new comment" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="new comment" />' +
+ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="new comment" />' +
'</form>'
assert_dom_equal expected, output_buffer
@@ -669,8 +672,9 @@ class FormHelperTest < ActionView::TestCase
expected = '<form action="http://www.example.com" method="post">' +
'<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
- '<input id="post_comments_attributes_321_name" name="post[comments_attributes][321][name]" size="30" type="text" value="comment #321" />' +
- '<input id="post_comments_attributes_new_1_name" name="post[comments_attributes][new_1][name]" size="30" type="text" value="new comment" />' +
+ '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="321" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #321" />' +
+ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="new comment" />' +
'</form>'
assert_dom_equal expected, output_buffer
@@ -690,14 +694,32 @@ class FormHelperTest < ActionView::TestCase
expected = '<form action="http://www.example.com" method="post">' +
'<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
- '<input id="post_comments_attributes_321_name" name="post[comments_attributes][321][name]" size="30" type="text" value="comment #321" />' +
- '<input id="post_comments_attributes_new_1_name" name="post[comments_attributes][new_1][name]" size="30" type="text" value="new comment" />' +
+ '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="321" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #321" />' +
+ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="new comment" />' +
'</form>'
assert_dom_equal expected, output_buffer
assert_equal yielded_comments, @post.comments
end
+ def test_nested_fields_for_with_child_index_option_override_on_a_nested_attributes_collection_association
+ @post.comments = []
+
+ form_for(:post, @post) do |f|
+ f.fields_for(:comments, Comment.new(321), :child_index => 'abc') do |cf|
+ concat cf.text_field(:name)
+ end
+ end
+
+ expected = '<form action="http://www.example.com" method="post">' +
+ '<input id="post_comments_attributes_abc_id" name="post[comments_attributes][abc][id]" type="hidden" value="321" />' +
+ '<input id="post_comments_attributes_abc_name" name="post[comments_attributes][abc][name]" size="30" type="text" value="comment #321" />' +
+ '</form>'
+
+ assert_dom_equal expected, output_buffer
+ end
+
def test_fields_for
fields_for(:post, @post) do |f|
concat f.text_field(:title)
@@ -708,8 +730,8 @@ class FormHelperTest < ActionView::TestCase
expected =
"<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" +
"<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
- "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" +
- "<input name='post[secret]' type='hidden' value='0' />"
+ "<input name='post[secret]' type='hidden' value='0' />" +
+ "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />"
assert_dom_equal expected, output_buffer
end
@@ -724,8 +746,8 @@ class FormHelperTest < ActionView::TestCase
expected =
"<input name='post[123][title]' size='30' type='text' id='post_123_title' value='Hello World' />" +
"<textarea name='post[123][body]' id='post_123_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
- "<input name='post[123][secret]' checked='checked' type='checkbox' id='post_123_secret' value='1' />" +
- "<input name='post[123][secret]' type='hidden' value='0' />"
+ "<input name='post[123][secret]' type='hidden' value='0' />" +
+ "<input name='post[123][secret]' checked='checked' type='checkbox' id='post_123_secret' value='1' />"
assert_dom_equal expected, output_buffer
end
@@ -740,8 +762,8 @@ class FormHelperTest < ActionView::TestCase
expected =
"<input name='post[][title]' size='30' type='text' id='post__title' value='Hello World' />" +
"<textarea name='post[][body]' id='post__body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
- "<input name='post[][secret]' checked='checked' type='checkbox' id='post__secret' value='1' />" +
- "<input name='post[][secret]' type='hidden' value='0' />"
+ "<input name='post[][secret]' type='hidden' value='0' />" +
+ "<input name='post[][secret]' checked='checked' type='checkbox' id='post__secret' value='1' />"
assert_dom_equal expected, output_buffer
end
@@ -756,8 +778,8 @@ class FormHelperTest < ActionView::TestCase
expected =
"<input name='post[abc][title]' size='30' type='text' id='post_abc_title' value='Hello World' />" +
"<textarea name='post[abc][body]' id='post_abc_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
- "<input name='post[abc][secret]' checked='checked' type='checkbox' id='post_abc_secret' value='1' />" +
- "<input name='post[abc][secret]' type='hidden' value='0' />"
+ "<input name='post[abc][secret]' type='hidden' value='0' />" +
+ "<input name='post[abc][secret]' checked='checked' type='checkbox' id='post_abc_secret' value='1' />"
assert_dom_equal expected, output_buffer
end
@@ -772,8 +794,8 @@ class FormHelperTest < ActionView::TestCase
expected =
"<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" +
"<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
- "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" +
- "<input name='post[secret]' type='hidden' value='0' />"
+ "<input name='post[secret]' type='hidden' value='0' />" +
+ "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />"
assert_dom_equal expected, output_buffer
end
@@ -788,8 +810,8 @@ class FormHelperTest < ActionView::TestCase
expected =
"<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" +
"<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
- "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" +
- "<input name='post[secret]' type='hidden' value='0' />"
+ "<input name='post[secret]' type='hidden' value='0' />" +
+ "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />"
assert_dom_equal expected, output_buffer
end
@@ -834,8 +856,8 @@ class FormHelperTest < ActionView::TestCase
"<form action='http://www.example.com' id='create-post' method='post'>" +
"<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" +
"<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
- "<input name='parent_post[secret]' checked='checked' type='checkbox' id='parent_post_secret' value='1' />" +
"<input name='parent_post[secret]' type='hidden' value='0' />" +
+ "<input name='parent_post[secret]' checked='checked' type='checkbox' id='parent_post_secret' value='1' />" +
"</form>"
assert_dom_equal expected, output_buffer
@@ -883,8 +905,7 @@ class FormHelperTest < ActionView::TestCase
"<form action='http://www.example.com' method='post'>" +
"<label for='title'>Title:</label> <input name='post[title]' size='30' type='text' id='post_title' value='Hello World' /><br/>" +
"<label for='body'>Body:</label> <textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea><br/>" +
- "<label for='secret'>Secret:</label> <input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" +
- "<input name='post[secret]' type='hidden' value='0' /><br/>" +
+ "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' /><br/>" +
"</form>"
assert_dom_equal expected, output_buffer
@@ -904,8 +925,7 @@ class FormHelperTest < ActionView::TestCase
"<form action='http://www.example.com' method='post'>" +
"<label for='title'>Title:</label> <input name='post[title]' size='30' type='text' id='post_title' value='Hello World' /><br/>" +
"<label for='body'>Body:</label> <textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea><br/>" +
- "<label for='secret'>Secret:</label> <input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" +
- "<input name='post[secret]' type='hidden' value='0' /><br/>" +
+ "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' /><br/>" +
"</form>"
assert_dom_equal expected, output_buffer
@@ -960,8 +980,7 @@ class FormHelperTest < ActionView::TestCase
%(<form action="http://www.example.com" onsubmit="new Ajax.Request('http://www.example.com', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;" method="post">) +
"<label for='title'>Title:</label> <input name='post[title]' size='30' type='text' id='post_title' value='Hello World' /><br/>" +
"<label for='body'>Body:</label> <textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea><br/>" +
- "<label for='secret'>Secret:</label> <input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" +
- "<input name='post[secret]' type='hidden' value='0' /><br/>" +
+ "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' /><br/>" +
"</form>"
assert_dom_equal expected, output_buffer
@@ -977,8 +996,7 @@ class FormHelperTest < ActionView::TestCase
expected =
"<label for='title'>Title:</label> <input name='post[title]' size='30' type='text' id='post_title' value='Hello World' /><br/>" +
"<label for='body'>Body:</label> <textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea><br/>" +
- "<label for='secret'>Secret:</label> <input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" +
- "<input name='post[secret]' type='hidden' value='0' /><br/>"
+ "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' /><br/>"
assert_dom_equal expected, output_buffer
end
diff --git a/actionpack/test/template/form_options_helper_test.rb b/actionpack/test/template/form_options_helper_test.rb
index 83c27ac042..78db87971b 100644
--- a/actionpack/test/template/form_options_helper_test.rb
+++ b/actionpack/test/template/form_options_helper_test.rb
@@ -24,45 +24,62 @@ class FormOptionsHelperTest < ActionView::TestCase
end
def test_collection_options
- @posts = [
- Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
- Post.new("Babe went home", "Babe", "To a little house", "shh!"),
- Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
- ]
-
assert_dom_equal(
"<option value=\"&lt;Abe&gt;\">&lt;Abe&gt; went home</option>\n<option value=\"Babe\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>",
- options_from_collection_for_select(@posts, "author_name", "title")
+ options_from_collection_for_select(dummy_posts, "author_name", "title")
)
end
def test_collection_options_with_preselected_value
- @posts = [
- Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
- Post.new("Babe went home", "Babe", "To a little house", "shh!"),
- Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
- ]
-
assert_dom_equal(
"<option value=\"&lt;Abe&gt;\">&lt;Abe&gt; went home</option>\n<option value=\"Babe\" selected=\"selected\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>",
- options_from_collection_for_select(@posts, "author_name", "title", "Babe")
+ options_from_collection_for_select(dummy_posts, "author_name", "title", "Babe")
)
end
def test_collection_options_with_preselected_value_array
- @posts = [
- Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
- Post.new("Babe went home", "Babe", "To a little house", "shh!"),
- Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
- ]
-
assert_dom_equal(
"<option value=\"&lt;Abe&gt;\">&lt;Abe&gt; went home</option>\n<option value=\"Babe\" selected=\"selected\">Babe went home</option>\n<option value=\"Cabe\" selected=\"selected\">Cabe went home</option>",
- options_from_collection_for_select(@posts, "author_name", "title", [ "Babe", "Cabe" ])
+ options_from_collection_for_select(dummy_posts, "author_name", "title", [ "Babe", "Cabe" ])
)
end
+ def test_collection_options_with_proc_for_selected
+ assert_dom_equal(
+ "<option value=\"&lt;Abe&gt;\">&lt;Abe&gt; went home</option>\n<option value=\"Babe\" selected=\"selected\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>",
+ options_from_collection_for_select(dummy_posts, "author_name", "title", lambda{|p| p.author_name == 'Babe' })
+ )
+ end
+
+ def test_collection_options_with_disabled_value
+ assert_dom_equal(
+ "<option value=\"&lt;Abe&gt;\">&lt;Abe&gt; went home</option>\n<option value=\"Babe\" disabled=\"disabled\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>",
+ options_from_collection_for_select(dummy_posts, "author_name", "title", :disabled => "Babe")
+ )
+ end
+
+ def test_collection_options_with_disabled_array
+ assert_dom_equal(
+ "<option value=\"&lt;Abe&gt;\">&lt;Abe&gt; went home</option>\n<option value=\"Babe\" disabled=\"disabled\">Babe went home</option>\n<option value=\"Cabe\" disabled=\"disabled\">Cabe went home</option>",
+ options_from_collection_for_select(dummy_posts, "author_name", "title", :disabled => [ "Babe", "Cabe" ])
+ )
+ end
+
+ def test_collection_options_with_preselected_and_disabled_value
+ assert_dom_equal(
+ "<option value=\"&lt;Abe&gt;\">&lt;Abe&gt; went home</option>\n<option value=\"Babe\" disabled=\"disabled\">Babe went home</option>\n<option value=\"Cabe\" selected=\"selected\">Cabe went home</option>",
+ options_from_collection_for_select(dummy_posts, "author_name", "title", :selected => "Cabe", :disabled => "Babe")
+ )
+ end
+
+ def test_collection_options_with_proc_for_disabled
+ assert_dom_equal(
+ "<option value=\"&lt;Abe&gt;\">&lt;Abe&gt; went home</option>\n<option value=\"Babe\" disabled=\"disabled\">Babe went home</option>\n<option value=\"Cabe\" disabled=\"disabled\">Cabe went home</option>",
+ options_from_collection_for_select(dummy_posts, "author_name", "title", :disabled => lambda{|p| %w(Babe Cabe).include? p.author_name })
+ )
+ end
+
def test_array_options_for_select
assert_dom_equal(
"<option value=\"&lt;Denmark&gt;\">&lt;Denmark&gt;</option>\n<option value=\"USA\">USA</option>\n<option value=\"Sweden\">Sweden</option>",
@@ -84,6 +101,27 @@ class FormOptionsHelperTest < ActionView::TestCase
)
end
+ def test_array_options_for_select_with_disabled_value
+ assert_dom_equal(
+ "<option value=\"Denmark\">Denmark</option>\n<option value=\"&lt;USA&gt;\" disabled=\"disabled\">&lt;USA&gt;</option>\n<option value=\"Sweden\">Sweden</option>",
+ options_for_select([ "Denmark", "<USA>", "Sweden" ], :disabled => "<USA>")
+ )
+ end
+
+ def test_array_options_for_select_with_disabled_array
+ assert_dom_equal(
+ "<option value=\"Denmark\">Denmark</option>\n<option value=\"&lt;USA&gt;\" disabled=\"disabled\">&lt;USA&gt;</option>\n<option value=\"Sweden\" disabled=\"disabled\">Sweden</option>",
+ options_for_select([ "Denmark", "<USA>", "Sweden" ], :disabled => ["<USA>", "Sweden"])
+ )
+ end
+
+ def test_array_options_for_select_with_selection_and_disabled_value
+ assert_dom_equal(
+ "<option value=\"Denmark\" selected=\"selected\">Denmark</option>\n<option value=\"&lt;USA&gt;\" disabled=\"disabled\">&lt;USA&gt;</option>\n<option value=\"Sweden\">Sweden</option>",
+ options_for_select([ "Denmark", "<USA>", "Sweden" ], :selected => "Denmark", :disabled => "<USA>")
+ )
+ end
+
def test_array_options_for_string_include_in_other_string_bug_fix
assert_dom_equal(
"<option value=\"ruby\">ruby</option>\n<option value=\"rubyonrails\" selected=\"selected\">rubyonrails</option>",
@@ -370,34 +408,40 @@ class FormOptionsHelperTest < ActionView::TestCase
)
end
- def test_collection_select
- @posts = [
- Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
- Post.new("Babe went home", "Babe", "To a little house", "shh!"),
- Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
- ]
+ def test_select_with_disabled_value
+ @post = Post.new
+ @post.category = "<mus>"
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"&lt;mus&gt;\" selected=\"selected\">&lt;mus&gt;</option>\n<option value=\"hest\" disabled=\"disabled\">hest</option></select>",
+ select("post", "category", %w( abe <mus> hest ), :disabled => 'hest')
+ )
+ end
+ def test_select_with_disabled_array
+ @post = Post.new
+ @post.category = "<mus>"
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\" disabled=\"disabled\">abe</option>\n<option value=\"&lt;mus&gt;\" selected=\"selected\">&lt;mus&gt;</option>\n<option value=\"hest\" disabled=\"disabled\">hest</option></select>",
+ select("post", "category", %w( abe <mus> hest ), :disabled => ['hest', 'abe'])
+ )
+ end
+
+ def test_collection_select
@post = Post.new
@post.author_name = "Babe"
assert_dom_equal(
"<select id=\"post_author_name\" name=\"post[author_name]\"><option value=\"&lt;Abe&gt;\">&lt;Abe&gt;</option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>",
- collection_select("post", "author_name", @posts, "author_name", "author_name")
+ collection_select("post", "author_name", dummy_posts, "author_name", "author_name")
)
end
def test_collection_select_under_fields_for
- @posts = [
- Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
- Post.new("Babe went home", "Babe", "To a little house", "shh!"),
- Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
- ]
-
@post = Post.new
@post.author_name = "Babe"
fields_for :post, @post do |f|
- concat f.collection_select(:author_name, @posts, :author_name, :author_name)
+ concat f.collection_select(:author_name, dummy_posts, :author_name, :author_name)
end
assert_dom_equal(
@@ -407,17 +451,11 @@ class FormOptionsHelperTest < ActionView::TestCase
end
def test_collection_select_under_fields_for_with_index
- @posts = [
- Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
- Post.new("Babe went home", "Babe", "To a little house", "shh!"),
- Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
- ]
-
@post = Post.new
@post.author_name = "Babe"
fields_for :post, @post, :index => 815 do |f|
- concat f.collection_select(:author_name, @posts, :author_name, :author_name)
+ concat f.collection_select(:author_name, dummy_posts, :author_name, :author_name)
end
assert_dom_equal(
@@ -427,18 +465,12 @@ class FormOptionsHelperTest < ActionView::TestCase
end
def test_collection_select_under_fields_for_with_auto_index
- @posts = [
- Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
- Post.new("Babe went home", "Babe", "To a little house", "shh!"),
- Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
- ]
-
@post = Post.new
@post.author_name = "Babe"
def @post.to_param; 815; end
fields_for "post[]", @post do |f|
- concat f.collection_select(:author_name, @posts, :author_name, :author_name)
+ concat f.collection_select(:author_name, dummy_posts, :author_name, :author_name)
end
assert_dom_equal(
@@ -448,72 +480,58 @@ class FormOptionsHelperTest < ActionView::TestCase
end
def test_collection_select_with_blank_and_style
- @posts = [
- Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
- Post.new("Babe went home", "Babe", "To a little house", "shh!"),
- Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
- ]
-
@post = Post.new
@post.author_name = "Babe"
assert_dom_equal(
"<select id=\"post_author_name\" name=\"post[author_name]\" style=\"width: 200px\"><option value=\"\"></option>\n<option value=\"&lt;Abe&gt;\">&lt;Abe&gt;</option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>",
- collection_select("post", "author_name", @posts, "author_name", "author_name", { :include_blank => true }, "style" => "width: 200px")
+ collection_select("post", "author_name", dummy_posts, "author_name", "author_name", { :include_blank => true }, "style" => "width: 200px")
)
end
def test_collection_select_with_blank_as_string_and_style
- @posts = [
- Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
- Post.new("Babe went home", "Babe", "To a little house", "shh!"),
- Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
- ]
-
@post = Post.new
@post.author_name = "Babe"
assert_dom_equal(
"<select id=\"post_author_name\" name=\"post[author_name]\" style=\"width: 200px\"><option value=\"\">No Selection</option>\n<option value=\"&lt;Abe&gt;\">&lt;Abe&gt;</option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>",
- collection_select("post", "author_name", @posts, "author_name", "author_name", { :include_blank => 'No Selection' }, "style" => "width: 200px")
+ collection_select("post", "author_name", dummy_posts, "author_name", "author_name", { :include_blank => 'No Selection' }, "style" => "width: 200px")
)
end
def test_collection_select_with_multiple_option_appends_array_brackets
- @posts = [
- Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
- Post.new("Babe went home", "Babe", "To a little house", "shh!"),
- Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
- ]
-
@post = Post.new
@post.author_name = "Babe"
expected = "<select id=\"post_author_name\" name=\"post[author_name][]\" multiple=\"multiple\"><option value=\"\"></option>\n<option value=\"&lt;Abe&gt;\">&lt;Abe&gt;</option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>"
# Should suffix default name with [].
- assert_dom_equal expected, collection_select("post", "author_name", @posts, "author_name", "author_name", { :include_blank => true }, :multiple => true)
+ assert_dom_equal expected, collection_select("post", "author_name", dummy_posts, "author_name", "author_name", { :include_blank => true }, :multiple => true)
# Shouldn't suffix custom name with [].
- assert_dom_equal expected, collection_select("post", "author_name", @posts, "author_name", "author_name", { :include_blank => true, :name => 'post[author_name][]' }, :multiple => true)
+ assert_dom_equal expected, collection_select("post", "author_name", dummy_posts, "author_name", "author_name", { :include_blank => true, :name => 'post[author_name][]' }, :multiple => true)
end
def test_collection_select_with_blank_and_selected
- @posts = [
- Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
- Post.new("Babe went home", "Babe", "To a little house", "shh!"),
- Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
- ]
-
@post = Post.new
@post.author_name = "Babe"
assert_dom_equal(
%{<select id="post_author_name" name="post[author_name]"><option value=""></option>\n<option value="&lt;Abe&gt;" selected="selected">&lt;Abe&gt;</option>\n<option value="Babe">Babe</option>\n<option value="Cabe">Cabe</option></select>},
- collection_select("post", "author_name", @posts, "author_name", "author_name", {:include_blank => true, :selected => "<Abe>"})
+ collection_select("post", "author_name", dummy_posts, "author_name", "author_name", {:include_blank => true, :selected => "<Abe>"})
)
end
+ def test_collection_select_with_disabled
+ @post = Post.new
+ @post.author_name = "Babe"
+
+ assert_dom_equal(
+ "<select id=\"post_author_name\" name=\"post[author_name]\"><option value=\"&lt;Abe&gt;\">&lt;Abe&gt;</option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\" disabled=\"disabled\">Cabe</option></select>",
+ collection_select("post", "author_name", dummy_posts, "author_name", "author_name", :disabled => 'Cabe')
+ )
+ end
+
def test_time_zone_select
@firm = Firm.new("D")
html = time_zone_select( "firm", "time_zone" )
@@ -723,4 +741,11 @@ class FormOptionsHelperTest < ActionView::TestCase
html
end
+ private
+
+ def dummy_posts
+ [ Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
+ Post.new("Babe went home", "Babe", "To a little house", "shh!"),
+ Post.new("Cabe went home", "Cabe", "To a little house", "shh!") ]
+ end
end
diff --git a/actionpack/test/template/render_test.rb b/actionpack/test/template/render_test.rb
index c7405d47de..107c625e32 100644
--- a/actionpack/test/template/render_test.rb
+++ b/actionpack/test/template/render_test.rb
@@ -1,3 +1,4 @@
+# encoding: utf-8
require 'abstract_unit'
require 'controller/fake_models'
@@ -9,6 +10,7 @@ module RenderTestCases
# Reload and register danish language for testing
I18n.reload!
I18n.backend.store_translations 'da', {}
+ I18n.backend.store_translations 'pt-BR', {}
# Ensure original are still the same since we are reindexing view paths
assert_equal ORIGINAL_LOCALES, I18n.available_locales.map(&:to_s).sort
@@ -34,6 +36,33 @@ module RenderTestCases
I18n.locale = old_locale
end
+ def test_render_file_with_dashed_locale
+ old_locale = I18n.locale
+ I18n.locale = :"pt-BR"
+ assert_equal "Ola mundo", @view.render(:file => "test/hello_world")
+ ensure
+ I18n.locale = old_locale
+ end
+
+ def test_render_implicit_html_template_from_xhr_request
+ old_format = @view.template_format
+ @view.template_format = :js
+ assert_equal "Hello HTML!", @view.render(:file => "test/render_implicit_html_template_from_xhr_request")
+ ensure
+ @view.template_format = old_format
+ end
+
+ def test_render_implicit_html_template_from_xhr_request_with_localization
+ old_locale = I18n.locale
+ old_format = @view.template_format
+ I18n.locale = :da
+ @view.template_format = :js
+ assert_equal "Hey HTML!\n", @view.render(:file => "test/render_implicit_html_template_from_xhr_request")
+ ensure
+ I18n.locale = old_locale
+ @view.template_format = old_format
+ end
+
def test_render_file_at_top_level
assert_equal 'Elastica', @view.render(:file => '/shared')
end
@@ -204,28 +233,44 @@ module RenderTestCases
assert_equal %(<title>title</title>\n<div id="column">column</div>\n<div id="content">content</div>\n),
@view.render(:file => "test/nested_layout.erb", :layout => "layouts/yield")
end
+
+ if '1.9'.respond_to?(:force_encoding)
+ def test_render_utf8_template
+ result = @view.render(:file => "test/utf8.html.erb", :layouts => "layouts/yield")
+ assert_equal "Русский текст\n日本語のテキスト", result
+ assert_equal Encoding::UTF_8, result.encoding
+ end
+ end
+end
+
+module TemplatesSetupTeardown
+ def setup_view_paths_for(new_cache_template_loading)
+ @previous_cache_template_loading, ActionView::Base.cache_template_loading = ActionView::Base.cache_template_loading, new_cache_template_loading
+ view_paths = new_cache_template_loading ? CACHED_VIEW_PATHS : ActionView::Base.process_view_paths(CACHED_VIEW_PATHS.map(&:to_s))
+ assert_equal(new_cache_template_loading ? ActionView::Template::EagerPath : ActionView::ReloadableTemplate::ReloadablePath, view_paths.first.class)
+ setup_view(view_paths)
+ end
+
+ def teardown
+ ActionView::Base.cache_template_loading = @previous_cache_template_loading
+ end
end
-class CachedViewRenderTest < Test::Unit::TestCase
+class CachedRenderTest < Test::Unit::TestCase
+ include TemplatesSetupTeardown
include RenderTestCases
- # Ensure view path cache is primed
def setup
- view_paths = ActionController::Base.view_paths
- assert_equal ActionView::Template::EagerPath, view_paths.first.class
- setup_view(view_paths)
+ setup_view_paths_for(cache_templates = true)
end
end
-class LazyViewRenderTest < Test::Unit::TestCase
+class ReloadableRenderTest < Test::Unit::TestCase
+ include TemplatesSetupTeardown
include RenderTestCases
- # Test the same thing as above, but make sure the view path
- # is not eager loaded
def setup
- path = ActionView::Template::Path.new(FIXTURE_LOAD_PATH)
- view_paths = ActionView::Base.process_view_paths(path)
- assert_equal ActionView::Template::Path, view_paths.first.class
- setup_view(view_paths)
+ setup_view_paths_for(cache_templates = false)
end
end
+
diff --git a/actionpack/test/template/translation_helper_test.rb b/actionpack/test/template/translation_helper_test.rb
index 6534df6bbd..a20f3c394c 100644
--- a/actionpack/test/template/translation_helper_test.rb
+++ b/actionpack/test/template/translation_helper_test.rb
@@ -23,4 +23,10 @@ class TranslationHelperTest < Test::Unit::TestCase
I18n.expects(:localize).with(@time)
localize @time
end
+
+ def test_scoping_by_partial
+ expects(:template).returns(stub(:path_without_format_and_extension => "people/index"))
+ I18n.expects(:translate).with("people.index.foo", :locale => 'en', :raise => true)
+ translate ".foo", :locale => 'en'
+ end
end
diff --git a/activerecord/Rakefile b/activerecord/Rakefile
index 1c7e2603ee..8b3b97bac4 100644
--- a/activerecord/Rakefile
+++ b/activerecord/Rakefile
@@ -30,7 +30,9 @@ desc 'Run mysql, sqlite, and postgresql tests by default'
task :default => :test
desc 'Run mysql, sqlite, and postgresql tests'
-task :test => %w(test_mysql test_sqlite3 test_postgresql)
+task :test => defined?(JRUBY_VERSION) ?
+ %w(test_jdbcmysql test_jdbcsqlite3 test_jdbcpostgresql) :
+ %w(test_mysql test_sqlite3 test_postgresql)
for adapter in %w( mysql postgresql sqlite sqlite3 firebird db2 oracle sybase openbase frontbase jdbcmysql jdbcpostgresql jdbcsqlite3 jdbcderby jdbch2 jdbchsqldb )
Rake::TestTask.new("test_#{adapter}") { |t|
diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb
index 15350cf1e1..657acd6dc0 100644
--- a/activerecord/lib/active_record/migration.rb
+++ b/activerecord/lib/active_record/migration.rb
@@ -338,6 +338,10 @@ module ActiveRecord
self.verbose = save
end
+ def connection
+ ActiveRecord::Base.connection
+ end
+
def method_missing(method, *arguments, &block)
arg_list = arguments.map(&:inspect) * ', '
@@ -345,7 +349,7 @@ module ActiveRecord
unless arguments.empty? || method == :execute
arguments[0] = Migrator.proper_table_name(arguments.first)
end
- ActiveRecord::Base.connection.send(method, *arguments, &block)
+ connection.send(method, *arguments, &block)
end
end
end
diff --git a/activerecord/lib/active_record/nested_attributes.rb b/activerecord/lib/active_record/nested_attributes.rb
index 5778223c74..e3122d195a 100644
--- a/activerecord/lib/active_record/nested_attributes.rb
+++ b/activerecord/lib/active_record/nested_attributes.rb
@@ -41,15 +41,16 @@ module ActiveRecord
# Enabling nested attributes on a one-to-one association allows you to
# create the member and avatar in one go:
#
- # params = { 'member' => { 'name' => 'Jack', 'avatar_attributes' => { 'icon' => 'smiling' } } }
+ # params = { :member => { :name => 'Jack', :avatar_attributes => { :icon => 'smiling' } } }
# member = Member.create(params)
- # member.avatar.icon #=> 'smiling'
+ # member.avatar.id # => 2
+ # member.avatar.icon # => 'smiling'
#
# It also allows you to update the avatar through the member:
#
- # params = { 'member' => { 'avatar_attributes' => { 'icon' => 'sad' } } }
+ # params = { :member' => { :avatar_attributes => { :id => '2', :icon => 'sad' } } }
# member.update_attributes params['member']
- # member.avatar.icon #=> 'sad'
+ # member.avatar.icon # => 'sad'
#
# By default you will only be able to set and update attributes on the
# associated model. If you want to destroy the associated model through the
@@ -64,7 +65,7 @@ module ActiveRecord
# Now, when you add the <tt>_delete</tt> key to the attributes hash, with a
# value that evaluates to +true+, you will destroy the associated model:
#
- # member.avatar_attributes = { '_delete' => '1' }
+ # member.avatar_attributes = { :id => '2', :_delete => '1' }
# member.avatar.marked_for_destruction? # => true
# member.save
# member.avatar #=> nil
@@ -77,59 +78,80 @@ module ActiveRecord
#
# class Member < ActiveRecord::Base
# has_many :posts
- # accepts_nested_attributes_for :posts, :reject_if => proc { |attributes| attributes['title'].blank? }
+ # accepts_nested_attributes_for :posts
# end
#
# You can now set or update attributes on an associated post model through
# the attribute hash.
#
- # For each key in the hash that starts with the string 'new' a new model
- # will be instantiated. When the proc given with the <tt>:reject_if</tt>
- # option evaluates to +false+ for a certain attribute hash no record will
- # be built for that hash. (Rejecting new records can alternatively be done
- # by utilizing the <tt>'_delete'</tt> key. Scroll down for more info.)
- #
- # params = { 'member' => {
- # 'name' => 'joe', 'posts_attributes' => {
- # 'new_12345' => { 'title' => 'Kari, the awesome Ruby documentation browser!' },
- # 'new_54321' => { 'title' => 'The egalitarian assumption of the modern citizen' },
- # 'new_67890' => { 'title' => '' } # This one matches the :reject_if proc and will not be instantiated.
- # }
+ # For each hash that does _not_ have an <tt>id</tt> key a new record will
+ # be instantiated, unless the hash also contains a <tt>_delete</tt> key
+ # that evaluates to +true+.
+ #
+ # params = { :member => {
+ # :name => 'joe', :posts_attributes => [
+ # { :title => 'Kari, the awesome Ruby documentation browser!' },
+ # { :title => 'The egalitarian assumption of the modern citizen' },
+ # { :title => '', :_delete => '1' } # this will be ignored
+ # ]
# }}
#
# member = Member.create(params['member'])
- # member.posts.length #=> 2
- # member.posts.first.title #=> 'Kari, the awesome Ruby documentation browser!'
- # member.posts.second.title #=> 'The egalitarian assumption of the modern citizen'
+ # member.posts.length # => 2
+ # member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
+ # member.posts.second.title # => 'The egalitarian assumption of the modern citizen'
+ #
+ # You may also set a :reject_if proc to silently ignore any new record
+ # hashes if they fail to pass your criteria. For example, the previous
+ # example could be rewritten as:
+ #
+ # class Member < ActiveRecord::Base
+ # has_many :posts
+ # accepts_nested_attributes_for :posts, :reject_if => proc { |attributes| attributes['title'].blank? }
+ # end
+ #
+ # params = { :member => {
+ # :name => 'joe', :posts_attributes => [
+ # { :title => 'Kari, the awesome Ruby documentation browser!' },
+ # { :title => 'The egalitarian assumption of the modern citizen' },
+ # { :title => '' } # this will be ignored because of the :reject_if proc
+ # ]
+ # }}
+ #
+ # member = Member.create(params['member'])
+ # member.posts.length # => 2
+ # member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
+ # member.posts.second.title # => 'The egalitarian assumption of the modern citizen'
#
- # When the key for post attributes is an integer, the associated post with
- # that ID will be updated:
+ # If the hash contains an <tt>id</tt> key that matches an already
+ # associated record, the matching record will be modified:
#
# member.attributes = {
- # 'name' => 'Joe',
- # 'posts_attributes' => {
- # '1' => { 'title' => '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!' },
- # '2' => { 'title' => '[UPDATED] other post' }
- # }
+ # :name => 'Joe',
+ # :posts_attributes => [
+ # { :id => 1, :title => '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!' },
+ # { :id => 2, :title => '[UPDATED] other post' }
+ # ]
# }
#
- # By default the associated models are protected from being destroyed. If
- # you want to destroy any of the associated models through the attributes
- # hash, you have to enable it first using the <tt>:allow_destroy</tt>
- # option.
+ # member.posts.first.title # => '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!'
+ # member.posts.second.title # => '[UPDATED] other post'
#
- # This will allow you to specify which models to destroy in the attributes
- # hash by setting the '_delete' attribute to a value that evaluates to
- # +true+:
+ # By default the associated records are protected from being destroyed. If
+ # you want to destroy any of the associated records through the attributes
+ # hash, you have to enable it first using the <tt>:allow_destroy</tt>
+ # option. This will allow you to also use the <tt>_delete</tt> key to
+ # destroy existing records:
#
# class Member < ActiveRecord::Base
# has_many :posts
# accepts_nested_attributes_for :posts, :allow_destroy => true
# end
#
- # params = {'member' => { 'name' => 'joe', 'posts_attributes' => {
- # '2' => { '_delete' => '1' }
- # }}}
+ # params = { :member => {
+ # :posts_attributes => [{ :id => '2', :_delete => '1' }]
+ # }}
+ #
# member.attributes = params['member']
# member.posts.detect { |p| p.id == 2 }.marked_for_destruction? # => true
# member.posts.length #=> 2
@@ -143,24 +165,27 @@ module ActiveRecord
# the parent model is saved. This happens inside the transaction initiated
# by the parents save method. See ActiveRecord::AutosaveAssociation.
module ClassMethods
- # Defines an attributes writer for the specified association(s).
+ # Defines an attributes writer for the specified association(s). If you
+ # are using <tt>attr_protected</tt> or <tt>attr_accessible</tt>, then you
+ # will need to add the attribute writer to the allowed list.
#
# Supported options:
# [:allow_destroy]
# If true, destroys any members from the attributes hash with a
- # <tt>_delete</tt> key and a value that converts to +true+
+ # <tt>_delete</tt> key and a value that evaluates to +true+
# (eg. 1, '1', true, or 'true'). This option is off by default.
# [:reject_if]
# Allows you to specify a Proc that checks whether a record should be
# built for a certain attribute hash. The hash is passed to the Proc
# and the Proc should return either +true+ or +false+. When no Proc
- # is specified a record will be built for all attribute hashes.
+ # is specified a record will be built for all attribute hashes that
+ # do not have a <tt>_delete</tt> that evaluates to true.
#
# Examples:
- # accepts_nested_attributes_for :avatar
- # accepts_nested_attributes_for :avatar, :allow_destroy => true
- # accepts_nested_attributes_for :avatar, :reject_if => proc { ... }
- # accepts_nested_attributes_for :avatar, :posts, :allow_destroy => true, :reject_if => proc { ... }
+ # # creates avatar_attributes=
+ # accepts_nested_attributes_for :avatar, :reject_if => proc { |attributes| attributes['name'].blank? }
+ # # creates avatar_attributes= and posts_attributes=
+ # accepts_nested_attributes_for :avatar, :posts, :allow_destroy => true
def accepts_nested_attributes_for(*attr_names)
options = { :allow_destroy => false }
options.update(attr_names.extract_options!)
@@ -193,9 +218,9 @@ module ActiveRecord
end
end
- # Returns ActiveRecord::AutosaveAssociation::marked_for_destruction?
- # It's used in conjunction with fields_for to build a form element
- # for the destruction of this association.
+ # Returns ActiveRecord::AutosaveAssociation::marked_for_destruction? It's
+ # used in conjunction with fields_for to build a form element for the
+ # destruction of this association.
#
# See ActionView::Helpers::FormHelper::fields_for for more info.
def _delete
@@ -204,80 +229,101 @@ module ActiveRecord
private
- # Assigns the given attributes to the association. An association will be
- # build if it doesn't exist yet.
+ # Attribute hash keys that should not be assigned as normal attributes.
+ # These hash keys are nested attributes implementation details.
+ UNASSIGNABLE_KEYS = %w{ id _delete }
+
+ # Assigns the given attributes to the association.
+ #
+ # If the given attributes include an <tt>:id</tt> that matches the existing
+ # record’s id, then the existing record will be modified. Otherwise a new
+ # record will be built.
+ #
+ # If the given attributes include a matching <tt>:id</tt> attribute _and_ a
+ # <tt>:_delete</tt> key set to a truthy value, then the existing record
+ # will be marked for destruction.
def assign_nested_attributes_for_one_to_one_association(association_name, attributes, allow_destroy)
- if should_destroy_nested_attributes_record?(allow_destroy, attributes)
- send(association_name).mark_for_destruction
- else
- (send(association_name) || send("build_#{association_name}")).attributes = attributes
+ attributes = attributes.stringify_keys
+
+ if attributes['id'].blank?
+ unless reject_new_record?(association_name, attributes)
+ send("build_#{association_name}", attributes.except(*UNASSIGNABLE_KEYS))
+ end
+ elsif (existing_record = send(association_name)) && existing_record.id.to_s == attributes['id'].to_s
+ assign_to_or_mark_for_destruction(existing_record, attributes, allow_destroy)
end
end
# Assigns the given attributes to the collection association.
#
- # Keys containing an ID for an associated record will update that record.
- # Keys starting with <tt>new</tt> will instantiate a new record for that
- # association.
+ # Hashes with an <tt>:id</tt> value matching an existing associated record
+ # will update that record. Hashes without an <tt>:id</tt> value will build
+ # a new record for the association. Hashes with a matching <tt>:id</tt>
+ # value and a <tt>:_delete</tt> key set to a truthy value will mark the
+ # matched record for destruction.
#
# For example:
#
# assign_nested_attributes_for_collection_association(:people, {
- # '1' => { 'name' => 'Peter' },
- # 'new_43' => { 'name' => 'John' }
+ # '1' => { :id => '1', :name => 'Peter' },
+ # '2' => { :name => 'John' },
+ # '3' => { :id => '2', :_delete => true }
# })
#
- # Will update the name of the Person with ID 1 and create a new associated
- # person with the name 'John'.
- def assign_nested_attributes_for_collection_association(association_name, attributes, allow_destroy)
- unless attributes.is_a?(Hash)
- raise ArgumentError, "Hash expected, got #{attributes.class.name} (#{attributes.inspect})"
+ # Will update the name of the Person with ID 1, build a new associated
+ # person with the name `John', and mark the associatied Person with ID 2
+ # for destruction.
+ #
+ # Also accepts an Array of attribute hashes:
+ #
+ # assign_nested_attributes_for_collection_association(:people, [
+ # { :id => '1', :name => 'Peter' },
+ # { :name => 'John' },
+ # { :id => '2', :_delete => true }
+ # ])
+ def assign_nested_attributes_for_collection_association(association_name, attributes_collection, allow_destroy)
+ unless attributes_collection.is_a?(Hash) || attributes_collection.is_a?(Array)
+ raise ArgumentError, "Hash or Array expected, got #{attributes_collection.class.name} (#{attributes_collection.inspect})"
end
- # Make sure any new records sorted by their id before they're build.
- sorted_by_id = attributes.sort_by { |id, _| id.is_a?(String) ? id.sub(/^new_/, '').to_i : id }
-
- sorted_by_id.each do |id, record_attributes|
- if id.acts_like?(:string) && id.starts_with?('new_')
- build_new_nested_attributes_record(association_name, record_attributes)
- else
- assign_to_or_destroy_nested_attributes_record(association_name, id, record_attributes, allow_destroy)
- end
+ if attributes_collection.is_a? Hash
+ attributes_collection = attributes_collection.sort_by { |index, _| index.to_i }.map { |_, attributes| attributes }
end
- end
- # Returns +true+ if <tt>allow_destroy</tt> is enabled and the attributes
- # contains a truthy value for the key <tt>'_delete'</tt>.
- #
- # It will _always_ remove the <tt>'_delete'</tt> key, if present.
- def should_destroy_nested_attributes_record?(allow_destroy, attributes)
- ConnectionAdapters::Column.value_to_boolean(attributes.delete('_delete')) && allow_destroy
- end
+ attributes_collection.each do |attributes|
+ attributes = attributes.stringify_keys
- # Builds a new record with the given attributes.
- #
- # If a <tt>:reject_if</tt> proc exists for this association, it will be
- # called with the attributes as its argument. If the proc returns a truthy
- # value, the record is _not_ build.
- #
- # Alternatively, you can specify the <tt>'_delete'</tt> key to _not_ build
- # a record. See should_destroy_nested_attributes_record? for more info.
- def build_new_nested_attributes_record(association_name, attributes)
- if reject_proc = self.class.reject_new_nested_attributes_procs[association_name]
- return if reject_proc.call(attributes)
+ if attributes['id'].blank?
+ unless reject_new_record?(association_name, attributes)
+ send(association_name).build(attributes.except(*UNASSIGNABLE_KEYS))
+ end
+ elsif existing_record = send(association_name).detect { |record| record.id.to_s == attributes['id'].to_s }
+ assign_to_or_mark_for_destruction(existing_record, attributes, allow_destroy)
+ end
end
- send(association_name).build(attributes) unless should_destroy_nested_attributes_record?(true, attributes)
end
- # Assigns the attributes to the record specified by +id+. Or marks it for
- # destruction if #should_destroy_nested_attributes_record? returns +true+.
- def assign_to_or_destroy_nested_attributes_record(association_name, id, attributes, allow_destroy)
- record = send(association_name).detect { |record| record.id == id.to_i }
- if should_destroy_nested_attributes_record?(allow_destroy, attributes)
+ # Updates a record with the +attributes+ or marks it for destruction if
+ # +allow_destroy+ is +true+ and has_delete_flag? returns +true+.
+ def assign_to_or_mark_for_destruction(record, attributes, allow_destroy)
+ if has_delete_flag?(attributes) && allow_destroy
record.mark_for_destruction
else
- record.attributes = attributes
+ record.attributes = attributes.except(*UNASSIGNABLE_KEYS)
end
end
+
+ # Determines if a hash contains a truthy _delete key.
+ def has_delete_flag?(hash)
+ ConnectionAdapters::Column.value_to_boolean hash['_delete']
+ end
+
+ # Determines if a new record should be build by checking for
+ # has_delete_flag? or if a <tt>:reject_if</tt> proc exists for this
+ # association and evaluates to +true+.
+ def reject_new_record?(association_name, attributes)
+ has_delete_flag?(attributes) ||
+ self.class.reject_new_nested_attributes_procs[association_name].try(:call, attributes)
+ end
end
-end \ No newline at end of file
+end
diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb
index 2e531a284e..cd6277c24b 100644
--- a/activerecord/test/cases/nested_attributes_test.rb
+++ b/activerecord/test/cases/nested_attributes_test.rb
@@ -23,7 +23,7 @@ class TestNestedAttributesInGeneral < ActiveRecord::TestCase
include AssertRaiseWithMessage
def teardown
- Pirate.accepts_nested_attributes_for :ship, :allow_destroy => true
+ Pirate.accepts_nested_attributes_for :ship, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
end
def test_base_should_have_an_empty_reject_new_nested_attributes_procs
@@ -71,7 +71,7 @@ class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase
assert_respond_to @pirate, :ship_attributes=
end
- def test_should_automatically_instantiate_an_associated_model_if_there_is_none
+ def test_should_build_a_new_record_if_there_is_no_id
@ship.destroy
@pirate.reload.ship_attributes = { :name => 'Davy Jones Gold Dagger' }
@@ -79,49 +79,106 @@ class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase
assert_equal 'Davy Jones Gold Dagger', @pirate.ship.name
end
- def test_should_take_a_hash_and_assign_the_attributes_to_the_existing_associated_model
- @pirate.ship_attributes = { :name => 'Davy Jones Gold Dagger' }
- assert !@pirate.ship.new_record?
+ def test_should_not_build_a_new_record_if_there_is_no_id_and_delete_is_truthy
+ @ship.destroy
+ @pirate.reload.ship_attributes = { :name => 'Davy Jones Gold Dagger', :_delete => '1' }
+
+ assert_nil @pirate.ship
+ end
+
+ def test_should_not_build_a_new_record_if_a_reject_if_proc_returns_false
+ @ship.destroy
+ @pirate.reload.ship_attributes = {}
+
+ assert_nil @pirate.ship
+ end
+
+ def test_should_replace_an_existing_record_if_there_is_no_id
+ @pirate.reload.ship_attributes = { :name => 'Davy Jones Gold Dagger' }
+
+ assert @pirate.ship.new_record?
assert_equal 'Davy Jones Gold Dagger', @pirate.ship.name
+ assert_equal 'Nights Dirty Lightning', @ship.name
end
- def test_should_also_work_with_a_HashWithIndifferentAccess
- @pirate.ship_attributes = HashWithIndifferentAccess.new(:name => 'Davy Jones Gold Dagger')
- assert !@pirate.ship.new_record?
+ def test_should_not_replace_an_existing_record_if_there_is_no_id_and_delete_is_truthy
+ @pirate.reload.ship_attributes = { :name => 'Davy Jones Gold Dagger', :_delete => '1' }
+
+ assert_equal @ship, @pirate.ship
+ assert_equal 'Nights Dirty Lightning', @pirate.ship.name
+ end
+
+ def test_should_modify_an_existing_record_if_there_is_a_matching_id
+ @pirate.reload.ship_attributes = { :id => @ship.id, :name => 'Davy Jones Gold Dagger' }
+
+ assert_equal @ship, @pirate.ship
assert_equal 'Davy Jones Gold Dagger', @pirate.ship.name
end
- def test_should_work_with_update_attributes_as_well
- @pirate.update_attributes({ :catchphrase => 'Arr', :ship_attributes => { :name => 'Mister Pablo' } })
- @pirate.reload
+ def test_should_take_a_hash_with_string_keys_and_update_the_associated_model
+ @pirate.reload.ship_attributes = { 'id' => @ship.id, 'name' => 'Davy Jones Gold Dagger' }
- assert_equal 'Arr', @pirate.catchphrase
- assert_equal 'Mister Pablo', @pirate.ship.name
+ assert_equal @ship, @pirate.ship
+ assert_equal 'Davy Jones Gold Dagger', @pirate.ship.name
end
- def test_should_be_possible_to_destroy_the_associated_model
+ def test_should_modify_an_existing_record_if_there_is_a_matching_composite_id
+ @ship.stubs(:id).returns('ABC1X')
+ @pirate.ship_attributes = { :id => @ship.id, :name => 'Davy Jones Gold Dagger' }
+
+ assert_equal 'Davy Jones Gold Dagger', @pirate.ship.name
+ end
+
+ def test_should_delete_an_existing_record_if_there_is_a_matching_id_and_delete_is_truthy
@pirate.ship.destroy
- ['1', 1, 'true', true].each do |true_variable|
+ [1, '1', true, 'true'].each do |truth|
@pirate.reload.create_ship(:name => 'Mister Pablo')
assert_difference('Ship.count', -1) do
- @pirate.update_attributes(:ship_attributes => { '_delete' => true_variable })
+ @pirate.update_attribute(:ship_attributes, { :id => @pirate.ship.id, :_delete => truth })
end
end
end
- def test_should_not_destroy_the_associated_model_with_a_non_truthy_argument
- [nil, '0', 0, 'false', false].each do |false_variable|
+ def test_should_not_delete_an_existing_record_if_delete_is_not_truthy
+ [nil, '0', 0, 'false', false].each do |not_truth|
assert_no_difference('Ship.count') do
- @pirate.update_attributes(:ship_attributes => { '_delete' => false_variable })
+ @pirate.update_attribute(:ship_attributes, { :id => @pirate.ship.id, :_delete => not_truth })
end
end
end
+ def test_should_not_delete_an_existing_record_if_allow_destroy_is_false
+ Pirate.accepts_nested_attributes_for :ship, :allow_destroy => false, :reject_if => proc { |attributes| attributes.empty? }
+
+ assert_no_difference('Ship.count') do
+ @pirate.update_attribute(:ship_attributes, { :id => @pirate.ship.id, :_delete => '1' })
+ end
+
+ Pirate.accepts_nested_attributes_for :ship, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
+ end
+
+ def test_should_also_work_with_a_HashWithIndifferentAccess
+ @pirate.ship_attributes = HashWithIndifferentAccess.new(:id => @ship.id, :name => 'Davy Jones Gold Dagger')
+
+ assert !@pirate.ship.new_record?
+ assert_equal 'Davy Jones Gold Dagger', @pirate.ship.name
+ end
+
+ def test_should_work_with_update_attributes_as_well
+ @pirate.update_attributes({ :catchphrase => 'Arr', :ship_attributes => { :id => @ship.id, :name => 'Mister Pablo' } })
+ @pirate.reload
+
+ assert_equal 'Arr', @pirate.catchphrase
+ assert_equal 'Mister Pablo', @pirate.ship.name
+ end
+
def test_should_not_destroy_the_associated_model_until_the_parent_is_saved
assert_no_difference('Ship.count') do
- @pirate.attributes = { :ship_attributes => { '_delete' => true } }
+ @pirate.attributes = { :ship_attributes => { :id => @ship.id, :_delete => '1' } }
+ end
+ assert_difference('Ship.count', -1) do
+ @pirate.save
end
- assert_difference('Ship.count', -1) { @pirate.save }
end
def test_should_automatically_enable_autosave_on_the_association
@@ -131,15 +188,16 @@ end
class TestNestedAttributesOnABelongsToAssociation < ActiveRecord::TestCase
def setup
- @ship = Ship.create!(:name => 'Nights Dirty Lightning')
- @pirate = @ship.create_pirate(:catchphrase => "Don' botharrr talkin' like one, savvy?")
+ @ship = Ship.new(:name => 'Nights Dirty Lightning')
+ @pirate = @ship.build_pirate(:catchphrase => 'Aye')
+ @ship.save!
end
def test_should_define_an_attribute_writer_method_for_the_association
assert_respond_to @ship, :pirate_attributes=
end
- def test_should_automatically_instantiate_an_associated_model_if_there_is_none
+ def test_should_build_a_new_record_if_there_is_no_id
@pirate.destroy
@ship.reload.pirate_attributes = { :catchphrase => 'Arr' }
@@ -147,47 +205,95 @@ class TestNestedAttributesOnABelongsToAssociation < ActiveRecord::TestCase
assert_equal 'Arr', @ship.pirate.catchphrase
end
- def test_should_take_a_hash_and_assign_the_attributes_to_the_existing_associated_model
- @ship.pirate_attributes = { :catchphrase => 'Arr' }
- assert !@ship.pirate.new_record?
+ def test_should_not_build_a_new_record_if_there_is_no_id_and_delete_is_truthy
+ @pirate.destroy
+ @ship.reload.pirate_attributes = { :catchphrase => 'Arr', :_delete => '1' }
+
+ assert_nil @ship.pirate
+ end
+
+ def test_should_not_build_a_new_record_if_a_reject_if_proc_returns_false
+ @pirate.destroy
+ @ship.reload.pirate_attributes = {}
+
+ assert_nil @ship.pirate
+ end
+
+ def test_should_replace_an_existing_record_if_there_is_no_id
+ @ship.reload.pirate_attributes = { :catchphrase => 'Arr' }
+
+ assert @ship.pirate.new_record?
assert_equal 'Arr', @ship.pirate.catchphrase
+ assert_equal 'Aye', @pirate.catchphrase
end
- def test_should_also_work_with_a_HashWithIndifferentAccess
- @ship.pirate_attributes = HashWithIndifferentAccess.new(:catchphrase => 'Arr')
- assert !@ship.pirate.new_record?
+ def test_should_not_replace_an_existing_record_if_there_is_no_id_and_delete_is_truthy
+ @ship.reload.pirate_attributes = { :catchphrase => 'Arr', :_delete => '1' }
+
+ assert_equal @pirate, @ship.pirate
+ assert_equal 'Aye', @ship.pirate.catchphrase
+ end
+
+ def test_should_modify_an_existing_record_if_there_is_a_matching_id
+ @ship.reload.pirate_attributes = { :id => @pirate.id, :catchphrase => 'Arr' }
+
+ assert_equal @pirate, @ship.pirate
assert_equal 'Arr', @ship.pirate.catchphrase
end
- def test_should_work_with_update_attributes_as_well
- @ship.update_attributes({ :name => 'Mister Pablo', :pirate_attributes => { :catchphrase => 'Arr' } })
- @ship.reload
+ def test_should_take_a_hash_with_string_keys_and_update_the_associated_model
+ @ship.reload.pirate_attributes = { 'id' => @pirate.id, 'catchphrase' => 'Arr' }
- assert_equal 'Mister Pablo', @ship.name
+ assert_equal @pirate, @ship.pirate
assert_equal 'Arr', @ship.pirate.catchphrase
end
- def test_should_be_possible_to_destroy_the_associated_model
+ def test_should_modify_an_existing_record_if_there_is_a_matching_composite_id
+ @pirate.stubs(:id).returns('ABC1X')
+ @ship.pirate_attributes = { :id => @pirate.id, :catchphrase => 'Arr' }
+
+ assert_equal 'Arr', @ship.pirate.catchphrase
+ end
+
+ def test_should_delete_an_existing_record_if_there_is_a_matching_id_and_delete_is_truthy
@ship.pirate.destroy
- ['1', 1, 'true', true].each do |true_variable|
+ [1, '1', true, 'true'].each do |truth|
@ship.reload.create_pirate(:catchphrase => 'Arr')
assert_difference('Pirate.count', -1) do
- @ship.update_attributes(:pirate_attributes => { '_delete' => true_variable })
+ @ship.update_attribute(:pirate_attributes, { :id => @ship.pirate.id, :_delete => truth })
end
end
end
- def test_should_not_destroy_the_associated_model_with_a_non_truthy_argument
- [nil, '', '0', 0, 'false', false].each do |false_variable|
+ def test_should_not_delete_an_existing_record_if_delete_is_not_truthy
+ [nil, '0', 0, 'false', false].each do |not_truth|
assert_no_difference('Pirate.count') do
- @ship.update_attributes(:pirate_attributes => { '_delete' => false_variable })
+ @ship.update_attribute(:pirate_attributes, { :id => @ship.pirate.id, :_delete => not_truth })
end
end
end
+ def test_should_not_delete_an_existing_record_if_allow_destroy_is_false
+ Ship.accepts_nested_attributes_for :pirate, :allow_destroy => false, :reject_if => proc { |attributes| attributes.empty? }
+
+ assert_no_difference('Pirate.count') do
+ @ship.update_attribute(:pirate_attributes, { :id => @ship.pirate.id, :_delete => '1' })
+ end
+
+ Ship.accepts_nested_attributes_for :pirate, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
+ end
+
+ def test_should_work_with_update_attributes_as_well
+ @ship.update_attributes({ :name => 'Mister Pablo', :pirate_attributes => { :catchphrase => 'Arr' } })
+ @ship.reload
+
+ assert_equal 'Mister Pablo', @ship.name
+ assert_equal 'Arr', @ship.pirate.catchphrase
+ end
+
def test_should_not_destroy_the_associated_model_until_the_parent_is_saved
assert_no_difference('Pirate.count') do
- @ship.attributes = { :pirate_attributes => { '_delete' => true } }
+ @ship.attributes = { :pirate_attributes => { :id => @ship.pirate.id, '_delete' => true } }
end
assert_difference('Pirate.count', -1) { @ship.save }
end
@@ -210,21 +316,43 @@ module NestedAttributesOnACollectionAssociationTests
assert_equal ['Grace OMalley', 'Privateers Greed'], [@child_1.reload.name, @child_2.reload.name]
end
+ def test_should_take_an_array_and_assign_the_attributes_to_the_associated_models
+ @pirate.send(association_setter, @alternate_params[association_getter].values)
+ @pirate.save
+ assert_equal ['Grace OMalley', 'Privateers Greed'], [@child_1.reload.name, @child_2.reload.name]
+ end
+
def test_should_also_work_with_a_HashWithIndifferentAccess
- @pirate.send(association_setter, HashWithIndifferentAccess.new(@child_1.id => HashWithIndifferentAccess.new(:name => 'Grace OMalley')))
+ @pirate.send(association_setter, HashWithIndifferentAccess.new('foo' => HashWithIndifferentAccess.new(:id => @child_1.id, :name => 'Grace OMalley')))
@pirate.save
assert_equal 'Grace OMalley', @child_1.reload.name
end
- def test_should_take_a_hash_with_integer_keys_and_assign_the_attributes_to_the_associated_models
+ def test_should_take_a_hash_and_assign_the_attributes_to_the_associated_models
@pirate.attributes = @alternate_params
assert_equal 'Grace OMalley', @pirate.send(@association_name).first.name
assert_equal 'Privateers Greed', @pirate.send(@association_name).last.name
end
- def test_should_automatically_build_new_associated_models_for_each_entry_in_a_hash_where_the_id_starts_with_the_string_new_
+ def test_should_take_a_hash_with_composite_id_keys_and_assign_the_attributes_to_the_associated_models
+ @child_1.stubs(:id).returns('ABC1X')
+ @child_2.stubs(:id).returns('ABC2X')
+
+ @pirate.attributes = {
+ association_getter => [
+ { :id => @child_1.id, :name => 'Grace OMalley' },
+ { :id => @child_2.id, :name => 'Privateers Greed' }
+ ]
+ }
+
+ assert_equal ['Grace OMalley', 'Privateers Greed'], [@child_1.name, @child_2.name]
+ end
+
+ def test_should_automatically_build_new_associated_models_for_each_entry_in_a_hash_where_the_id_is_missing
@pirate.send(@association_name).destroy_all
- @pirate.reload.attributes = { association_getter => { 'new_1' => { :name => 'Grace OMalley' }, 'new_2' => { :name => 'Privateers Greed' }}}
+ @pirate.reload.attributes = {
+ association_getter => { 'foo' => { :name => 'Grace OMalley' }, 'bar' => { :name => 'Privateers Greed' }}
+ }
assert @pirate.send(@association_name).first.new_record?
assert_equal 'Grace OMalley', @pirate.send(@association_name).first.name
@@ -233,24 +361,36 @@ module NestedAttributesOnACollectionAssociationTests
assert_equal 'Privateers Greed', @pirate.send(@association_name).last.name
end
- def test_should_remove_delete_key_from_arguments_hash_of_new_records
+ def test_should_not_assign_delete_key_to_a_record
assert_nothing_raised ActiveRecord::UnknownAttributeError do
- @pirate.send(association_setter, { 'new_1' => { '_delete' => '0' }})
+ @pirate.send(association_setter, { 'foo' => { '_delete' => '0' }})
end
end
def test_should_ignore_new_associated_records_with_truthy_delete_attribute
@pirate.send(@association_name).destroy_all
- @pirate.reload.attributes = { association_getter => { 'new_1' => { :name => 'Grace OMalley' }, 'new_2' => { :name => 'Privateers Greed', '_delete' => '1' }}}
+ @pirate.reload.attributes = {
+ association_getter => {
+ 'foo' => { :name => 'Grace OMalley' },
+ 'bar' => { :name => 'Privateers Greed', '_delete' => '1' }
+ }
+ }
assert_equal 1, @pirate.send(@association_name).length
assert_equal 'Grace OMalley', @pirate.send(@association_name).first.name
end
+ def test_should_ignore_new_associated_records_if_a_reject_if_proc_returns_false
+ @alternate_params[association_getter]['baz'] = {}
+ assert_no_difference("@pirate.send(@association_name).length") do
+ @pirate.attributes = @alternate_params
+ end
+ end
+
def test_should_sort_the_hash_by_the_keys_before_building_new_associated_models
attributes = ActiveSupport::OrderedHash.new
- attributes['new_123726353'] = { :name => 'Grace OMalley' }
- attributes['new_2'] = { :name => 'Privateers Greed' } # 2 is lower then 123726353
+ attributes['123726353'] = { :name => 'Grace OMalley' }
+ attributes['2'] = { :name => 'Privateers Greed' } # 2 is lower then 123726353
@pirate.send(association_setter, attributes)
assert_equal ['Posideons Killer', 'Killer bandita Dionne', 'Privateers Greed', 'Grace OMalley'].to_set, @pirate.send(@association_name).map(&:name).to_set
@@ -260,28 +400,20 @@ module NestedAttributesOnACollectionAssociationTests
assert_nothing_raised(ArgumentError) { @pirate.send(association_setter, {}) }
assert_nothing_raised(ArgumentError) { @pirate.send(association_setter, ActiveSupport::OrderedHash.new) }
- assert_raise_with_message ArgumentError, 'Hash expected, got String ("foo")' do
+ assert_raise_with_message ArgumentError, 'Hash or Array expected, got String ("foo")' do
@pirate.send(association_setter, "foo")
end
- assert_raise_with_message ArgumentError, 'Hash expected, got Array ([:foo, :bar])' do
- @pirate.send(association_setter, [:foo, :bar])
- end
end
def test_should_work_with_update_attributes_as_well
- @pirate.update_attributes({ :catchphrase => 'Arr', association_getter => { @child_1.id => { :name => 'Grace OMalley' }}})
- assert_equal 'Grace OMalley', @child_1.reload.name
- end
+ @pirate.update_attributes(:catchphrase => 'Arr',
+ association_getter => { 'foo' => { :id => @child_1.id, :name => 'Grace OMalley' }})
- def test_should_automatically_reject_any_new_record_if_a_reject_if_proc_exists_and_returns_false
- @alternate_params[association_getter]["new_12345"] = {}
- assert_no_difference("@pirate.send(@association_name).length") do
- @pirate.attributes = @alternate_params
- end
+ assert_equal 'Grace OMalley', @child_1.reload.name
end
- def test_should_update_existing_records_and_add_new_ones_that_have_an_id_that_start_with_the_string_new_
- @alternate_params[association_getter]['new_12345'] = { :name => 'Buccaneers Servant' }
+ def test_should_update_existing_records_and_add_new_ones_that_have_no_id
+ @alternate_params[association_getter]['baz'] = { :name => 'Buccaneers Servant' }
assert_difference('@pirate.send(@association_name).count', +1) do
@pirate.update_attributes @alternate_params
end
@@ -292,7 +424,7 @@ module NestedAttributesOnACollectionAssociationTests
['1', 1, 'true', true].each do |true_variable|
record = @pirate.reload.send(@association_name).create!(:name => 'Grace OMalley')
@pirate.send(association_setter,
- @alternate_params[association_getter].merge(record.id => { '_delete' => true_variable })
+ @alternate_params[association_getter].merge('baz' => { :id => record.id, '_delete' => true_variable })
)
assert_difference('@pirate.send(@association_name).count', -1) do
@@ -303,7 +435,7 @@ module NestedAttributesOnACollectionAssociationTests
def test_should_not_destroy_the_associated_model_with_a_non_truthy_argument
[nil, '', '0', 0, 'false', false].each do |false_variable|
- @alternate_params[association_getter][@child_1.id]['_delete'] = false_variable
+ @alternate_params[association_getter]['foo']['_delete'] = false_variable
assert_no_difference('@pirate.send(@association_name).count') do
@pirate.update_attributes(@alternate_params)
end
@@ -312,7 +444,7 @@ module NestedAttributesOnACollectionAssociationTests
def test_should_not_destroy_the_associated_model_until_the_parent_is_saved
assert_no_difference('@pirate.send(@association_name).count') do
- @pirate.send(association_setter, @alternate_params[association_getter].merge(@child_1.id => { '_delete' => true }))
+ @pirate.send(association_setter, @alternate_params[association_getter].merge('baz' => { :id => @child_1.id, '_delete' => true }))
end
assert_difference('@pirate.send(@association_name).count', -1) { @pirate.save }
end
@@ -338,13 +470,15 @@ class TestNestedAttributesOnAHasManyAssociation < ActiveRecord::TestCase
@association_name = :birds
@pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?")
- @child_1 = @pirate.birds.create!(:name => 'Posideons Killer')
- @child_2 = @pirate.birds.create!(:name => 'Killer bandita Dionne')
+ @pirate.birds.create!(:name => 'Posideons Killer')
+ @pirate.birds.create!(:name => 'Killer bandita Dionne')
+
+ @child_1, @child_2 = @pirate.birds
@alternate_params = {
:birds_attributes => {
- @child_1.id => { :name => 'Grace OMalley' },
- @child_2.id => { :name => 'Privateers Greed' }
+ 'foo' => { :id => @child_1.id, :name => 'Grace OMalley' },
+ 'bar' => { :id => @child_2.id, :name => 'Privateers Greed' }
}
}
end
@@ -358,16 +492,18 @@ class TestNestedAttributesOnAHasAndBelongsToManyAssociation < ActiveRecord::Test
@association_name = :parrots
@pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?")
- @child_1 = @pirate.parrots.create!(:name => 'Posideons Killer')
- @child_2 = @pirate.parrots.create!(:name => 'Killer bandita Dionne')
+ @pirate.parrots.create!(:name => 'Posideons Killer')
+ @pirate.parrots.create!(:name => 'Killer bandita Dionne')
+
+ @child_1, @child_2 = @pirate.parrots
@alternate_params = {
:parrots_attributes => {
- @child_1.id => { :name => 'Grace OMalley' },
- @child_2.id => { :name => 'Privateers Greed' }
+ 'foo' => { :id => @child_1.id, :name => 'Grace OMalley' },
+ 'bar' => { :id => @child_2.id, :name => 'Privateers Greed' }
}
}
end
include NestedAttributesOnACollectionAssociationTests
-end \ No newline at end of file
+end
diff --git a/activerecord/test/models/pirate.rb b/activerecord/test/models/pirate.rb
index 6a2416a05c..7bc50e0e7b 100644
--- a/activerecord/test/models/pirate.rb
+++ b/activerecord/test/models/pirate.rb
@@ -10,7 +10,7 @@ class Pirate < ActiveRecord::Base
has_many :birds
accepts_nested_attributes_for :parrots, :birds, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
- accepts_nested_attributes_for :ship, :allow_destroy => true
+ accepts_nested_attributes_for :ship, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
validates_presence_of :catchphrase
end
diff --git a/activerecord/test/models/ship.rb b/activerecord/test/models/ship.rb
index c46e27f3ae..06759d64b8 100644
--- a/activerecord/test/models/ship.rb
+++ b/activerecord/test/models/ship.rb
@@ -4,7 +4,7 @@ class Ship < ActiveRecord::Base
belongs_to :pirate
has_many :parts, :class_name => 'ShipPart', :autosave => true
- accepts_nested_attributes_for :pirate, :allow_destroy => true
+ accepts_nested_attributes_for :pirate, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
validates_presence_of :name
-end \ No newline at end of file
+end
diff --git a/activeresource/Rakefile b/activeresource/Rakefile
index ef99caea67..6af2e6cfba 100644
--- a/activeresource/Rakefile
+++ b/activeresource/Rakefile
@@ -28,6 +28,8 @@ task :default => [ :test ]
# Run the unit tests
Rake::TestTask.new { |t|
+ activesupport_path = "#{File.dirname(__FILE__)}/../activesupport/lib"
+ t.libs << activesupport_path if File.directory?(activesupport_path)
t.libs << "test"
t.pattern = 'test/**/*_test.rb'
t.verbose = true
diff --git a/activeresource/lib/active_resource/base.rb b/activeresource/lib/active_resource/base.rb
index 94418fb559..a8c0da31f2 100644
--- a/activeresource/lib/active_resource/base.rb
+++ b/activeresource/lib/active_resource/base.rb
@@ -462,7 +462,7 @@ module ActiveResource
# that_guy.valid? # => false
# that_guy.new? # => true
def create(attributes = {})
- returning(self.new(attributes)) { |res| res.save }
+ self.new(attributes).tap { |resource| resource.save }
end
# Core method for finding resources. Used similarly to Active Record's +find+ method.
@@ -600,7 +600,7 @@ module ActiveResource
end
def instantiate_record(record, prefix_options = {})
- returning new(record) do |resource|
+ new(record).tap do |resource|
resource.prefix_options = prefix_options
end
end
@@ -747,7 +747,7 @@ module ActiveResource
#
def ==(other)
other.equal?(self) || (other.instance_of?(self.class) && other.id == id && other.prefix_options == prefix_options)
- end
+ end
# Tests for equality (delegates to ==).
def eql?(other)
@@ -773,7 +773,7 @@ module ActiveResource
# my_invoice.customer # => That Company
# next_invoice.customer # => That Company
def dup
- returning self.class.new do |resource|
+ self.class.new.tap do |resource|
resource.attributes = @attributes
resource.prefix_options = @prefix_options
end
@@ -985,14 +985,14 @@ module ActiveResource
# Update the resource on the remote service.
def update
- returning connection.put(element_path(prefix_options), encode, self.class.headers) do |response|
+ connection.put(element_path(prefix_options), encode, self.class.headers).tap do |response|
load_attributes_from_response(response)
end
end
# Create (i.e., \save to the remote service) the \new resource.
def create
- returning connection.post(collection_path, encode, self.class.headers) do |response|
+ connection.post(collection_path, encode, self.class.headers).tap do |response|
self.id = id_from_response(response)
load_attributes_from_response(response)
end
diff --git a/activeresource/lib/active_resource/http_mock.rb b/activeresource/lib/active_resource/http_mock.rb
index 0b4549f759..7d7e378436 100644
--- a/activeresource/lib/active_resource/http_mock.rb
+++ b/activeresource/lib/active_resource/http_mock.rb
@@ -59,7 +59,7 @@ module ActiveResource
# end
module_eval <<-EOE, __FILE__, __LINE__
def #{method}(path, request_headers = {}, body = nil, status = 200, response_headers = {})
- @responses[Request.new(:#{method}, path, nil, request_headers)] = Response.new(body || "", status, response_headers)
+ @responses << [Request.new(:#{method}, path, nil, request_headers), Response.new(body || "", status, response_headers)]
end
EOE
end
@@ -91,21 +91,17 @@ module ActiveResource
@@requests ||= []
end
- # Returns a hash of <tt>request => response</tt> pairs for all all responses this mock has delivered, where +request+
- # is an instance of ActiveResource::Request and the response is, naturally, an instance of
- # ActiveResource::Response.
+ # Returns the list of requests and their mocked responses. Look up a
+ # response for a request using responses.assoc(request).
def responses
- @@responses ||= {}
+ @@responses ||= []
end
# Accepts a block which declares a set of requests and responses for the HttpMock to respond to. See the main
# ActiveResource::HttpMock description for a more detailed explanation.
def respond_to(pairs = {}) #:yields: mock
reset!
- pairs.each do |(path, response)|
- responses[path] = response
- end
-
+ responses.concat pairs.to_a
if block_given?
yield Responder.new(responses)
else
@@ -120,29 +116,23 @@ module ActiveResource
end
end
- for method in [ :post, :put ]
- # def post(path, body, headers)
- # request = ActiveResource::Request.new(:post, path, body, headers)
- # self.class.requests << request
- # self.class.responses[request] || raise(InvalidRequestError.new("No response recorded for #{request}"))
- # end
- module_eval <<-EOE, __FILE__, __LINE__
- def #{method}(path, body, headers)
- request = ActiveResource::Request.new(:#{method}, path, body, headers)
- self.class.requests << request
- self.class.responses[request] || raise(InvalidRequestError.new("No response recorded for \#{request}"))
- end
- EOE
- end
-
- for method in [ :get, :delete, :head ]
- module_eval <<-EOE, __FILE__, __LINE__
- def #{method}(path, headers)
- request = ActiveResource::Request.new(:#{method}, path, nil, headers)
- self.class.requests << request
- self.class.responses[request] || raise(InvalidRequestError.new("No response recorded for \#{request}"))
- end
- EOE
+ # body? methods
+ { true => %w(post put),
+ false => %w(get delete head) }.each do |has_body, methods|
+ methods.each do |method|
+ # def post(path, body, headers)
+ # request = ActiveResource::Request.new(:post, path, body, headers)
+ # self.class.requests << request
+ # self.class.responses.assoc(request).try(:second) || raise(InvalidRequestError.new("No response recorded for #{request}"))
+ # end
+ module_eval <<-EOE, __FILE__, __LINE__
+ def #{method}(path, #{'body, ' if has_body}headers)
+ request = ActiveResource::Request.new(:#{method}, path, #{has_body ? 'body, ' : 'nil, '}headers)
+ self.class.requests << request
+ self.class.responses.assoc(request).try(:second) || raise(InvalidRequestError.new("No response recorded for \#{request}"))
+ end
+ EOE
+ end
end
def initialize(site) #:nodoc:
@@ -157,21 +147,13 @@ module ActiveResource
@method, @path, @body, @headers = method, path, body, headers.merge(ActiveResource::Connection::HTTP_FORMAT_HEADER_NAMES[method] => 'application/xml')
end
- def ==(other_request)
- other_request.hash == hash
- end
-
- def eql?(other_request)
- self == other_request
+ def ==(req)
+ path == req.path && method == req.method && headers == req.headers
end
def to_s
"<#{method.to_s.upcase}: #{path} [#{headers}] (#{body})>"
end
-
- def hash
- "#{path}#{method}#{headers}".hash
- end
end
class Response
diff --git a/activeresource/lib/active_resource/validations.rb b/activeresource/lib/active_resource/validations.rb
index 4bc906d291..de3339935f 100644
--- a/activeresource/lib/active_resource/validations.rb
+++ b/activeresource/lib/active_resource/validations.rb
@@ -203,7 +203,7 @@ module ActiveResource
def from_xml(xml)
clear
humanized_attributes = @base.attributes.keys.inject({}) { |h, attr_name| h.update(attr_name.humanize => attr_name) }
- messages = Hash.from_xml(xml)['errors']['error'] rescue []
+ messages = Array.wrap(Hash.from_xml(xml)['errors']['error']) rescue []
messages.each do |message|
attr_message = humanized_attributes.keys.detect do |attr_name|
if message[0, attr_name.size + 1] == "#{attr_name} "
diff --git a/activeresource/test/setter_trap.rb b/activeresource/test/setter_trap.rb
index 9a899b0fa0..7cfd9ca111 100644
--- a/activeresource/test/setter_trap.rb
+++ b/activeresource/test/setter_trap.rb
@@ -1,9 +1,8 @@
class SetterTrap < ActiveSupport::BasicObject
class << self
def rollback_sets(obj)
- returning yield(setter_trap = new(obj)) do
- setter_trap.rollback_sets
- end
+ trapped = new(obj)
+ yield(trapped).tap { trapped.rollback_sets }
end
end
diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG
index 24e0836bde..b099233698 100644
--- a/activesupport/CHANGELOG
+++ b/activesupport/CHANGELOG
@@ -1,3 +1,12 @@
+*Edge*
+
+* Time#to_s(:rfc822) uses #formatted_offset instead of unreliable and non-standard %z directive #1899 [Zachary Zolton]
+
+* Make TimeWithZone#to_formatted_s an alias to TimeWithZone#to_s #1796 [Levin Alexander]
+
+* Introduce Array.wrap(foo) to wrap the argument in an array unless it's already an array. Wraps nil as an empty array. Use instead of Array(foo) and foo.to_a since they treat String as Enumerable. [Jeremy Kemper]
+
+
*2.3.0 [RC1] (February 1st, 2009)*
* TimeWithZone#xmlschema accepts optional fraction_digits argument [#1725 state:resolved] [Nicholas Dainty]
diff --git a/activesupport/lib/active_support/core_ext/array.rb b/activesupport/lib/active_support/core_ext/array.rb
index cc0a1ebc12..82c6b1243a 100644
--- a/activesupport/lib/active_support/core_ext/array.rb
+++ b/activesupport/lib/active_support/core_ext/array.rb
@@ -3,6 +3,7 @@ require 'active_support/core_ext/array/conversions'
require 'active_support/core_ext/array/extract_options'
require 'active_support/core_ext/array/grouping'
require 'active_support/core_ext/array/random_access'
+require 'active_support/core_ext/array/wrapper'
class Array #:nodoc:
include ActiveSupport::CoreExtensions::Array::Access
@@ -10,4 +11,5 @@ class Array #:nodoc:
include ActiveSupport::CoreExtensions::Array::ExtractOptions
include ActiveSupport::CoreExtensions::Array::Grouping
include ActiveSupport::CoreExtensions::Array::RandomAccess
+ extend ActiveSupport::CoreExtensions::Array::Wrapper
end
diff --git a/activesupport/lib/active_support/core_ext/array/wrapper.rb b/activesupport/lib/active_support/core_ext/array/wrapper.rb
new file mode 100644
index 0000000000..80b8f05531
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/array/wrapper.rb
@@ -0,0 +1,24 @@
+module ActiveSupport #:nodoc:
+ module CoreExtensions #:nodoc:
+ module Array #:nodoc:
+ module Wrapper
+ # Wraps the object in an Array unless it's an Array. Converts the
+ # object to an Array using #to_ary if it implements that.
+ def wrap(object)
+ case object
+ when nil
+ []
+ when self
+ object
+ else
+ if object.respond_to?(:to_ary)
+ object.to_ary
+ else
+ [object]
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/string/inflections.rb b/activesupport/lib/active_support/core_ext/string/inflections.rb
index de99fe5791..15ad3d99cc 100644
--- a/activesupport/lib/active_support/core_ext/string/inflections.rb
+++ b/activesupport/lib/active_support/core_ext/string/inflections.rb
@@ -1,4 +1,4 @@
-require 'active_support/inflector'
+require 'active_support/inflector' unless defined?(ActiveSupport::Inflector)
module ActiveSupport #:nodoc:
module CoreExtensions #:nodoc:
diff --git a/activesupport/lib/active_support/core_ext/time/conversions.rb b/activesupport/lib/active_support/core_ext/time/conversions.rb
index f42be46770..e6f9134661 100644
--- a/activesupport/lib/active_support/core_ext/time/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/time/conversions.rb
@@ -10,7 +10,7 @@ module ActiveSupport #:nodoc:
:short => "%d %b %H:%M",
:long => "%B %d, %Y %H:%M",
:long_ordinal => lambda { |time| time.strftime("%B #{time.day.ordinalize}, %Y %H:%M") },
- :rfc822 => "%a, %d %b %Y %H:%M:%S %z"
+ :rfc822 => lambda { |time| time.strftime("%a, %d %b %Y %H:%M:%S #{time.formatted_offset(false)}") }
}
def self.included(base) #:nodoc:
diff --git a/activesupport/lib/active_support/core_ext/try.rb b/activesupport/lib/active_support/core_ext/try.rb
index 54a38c5189..3de198d198 100644
--- a/activesupport/lib/active_support/core_ext/try.rb
+++ b/activesupport/lib/active_support/core_ext/try.rb
@@ -25,6 +25,7 @@ class Object
def try(method, *args, &block)
send(method, *args, &block)
end
+ remove_method :try
alias_method :try, :__send__
end
diff --git a/activesupport/lib/active_support/inflections.rb b/activesupport/lib/active_support/inflections.rb
index b6d276953a..8fb3fa9aa2 100644
--- a/activesupport/lib/active_support/inflections.rb
+++ b/activesupport/lib/active_support/inflections.rb
@@ -42,6 +42,7 @@ module ActiveSupport
inflect.singular(/(vert|ind)ices$/i, '\1ex')
inflect.singular(/(matr)ices$/i, '\1ix')
inflect.singular(/(quiz)zes$/i, '\1')
+ inflect.singular(/(database)s$/i, '\1')
inflect.irregular('person', 'people')
inflect.irregular('man', 'men')
diff --git a/activesupport/lib/active_support/json/decoding.rb b/activesupport/lib/active_support/json/decoding.rb
index 9da4048272..5eb8c0fd7d 100644
--- a/activesupport/lib/active_support/json/decoding.rb
+++ b/activesupport/lib/active_support/json/decoding.rb
@@ -46,10 +46,11 @@ module ActiveSupport
json.gsub(/\\\//, '/')
else
left_pos = [-1].push(*marks)
- right_pos = marks << json.length
+ right_pos = marks << scanner.pos + scanner.rest_size
output = []
left_pos.each_with_index do |left, i|
- output << json[left.succ..right_pos[i]]
+ scanner.pos = left.succ
+ output << scanner.peek(right_pos[i] - scanner.pos + 1)
end
output = output * " "
diff --git a/activesupport/lib/active_support/json/encoders/hash.rb b/activesupport/lib/active_support/json/encoders/hash.rb
index 16dc8337f5..e38b4f3e16 100644
--- a/activesupport/lib/active_support/json/encoders/hash.rb
+++ b/activesupport/lib/active_support/json/encoders/hash.rb
@@ -31,17 +31,16 @@ class Hash
def to_json(options = {}) #:nodoc:
hash_keys = self.keys
- if options[:except]
- hash_keys = hash_keys - Array(options[:except])
- elsif options[:only]
- hash_keys = hash_keys & Array(options[:only])
+ if except = options[:except]
+ hash_keys = hash_keys - Array.wrap(except)
+ elsif only = options[:only]
+ hash_keys = hash_keys & Array.wrap(only)
end
- returning result = '{' do
- result << hash_keys.map do |key|
- "#{ActiveSupport::JSON.encode(key.to_s)}: #{ActiveSupport::JSON.encode(self[key], options)}"
- end * ', '
- result << '}'
- end
+ result = '{'
+ result << hash_keys.map do |key|
+ "#{ActiveSupport::JSON.encode(key.to_s)}: #{ActiveSupport::JSON.encode(self[key], options)}"
+ end * ', '
+ result << '}'
end
end
diff --git a/activesupport/lib/active_support/testing/assertions.rb b/activesupport/lib/active_support/testing/assertions.rb
index ce2f44efd6..ca51adba1e 100644
--- a/activesupport/lib/active_support/testing/assertions.rb
+++ b/activesupport/lib/active_support/testing/assertions.rb
@@ -31,13 +31,17 @@ module ActiveSupport
# assert_difference 'Article.count', -1, "An Article should be destroyed" do
# post :delete, :id => ...
# end
- def assert_difference(expressions, difference = 1, message = nil, &block)
- expression_evaluations = Array(expressions).collect{ |expression| lambda { eval(expression, block.send(:binding)) } }
+ def assert_difference(expression, difference = 1, message = nil, &block)
+ b = block.send(:binding)
+ exps = Array.wrap(expression)
+ before = exps.map { |e| eval(e, b) }
- original_values = expression_evaluations.inject([]) { |memo, expression| memo << expression.call }
yield
- expression_evaluations.each_with_index do |expression, i|
- assert_equal original_values[i] + difference, expression.call, message
+
+ exps.each_with_index do |e, i|
+ error = "#{e.inspect} didn't change by #{difference}"
+ error = "#{message}.\n#{error}" if message
+ assert_equal(before[i] + difference, eval(e, b), error)
end
end
@@ -53,8 +57,8 @@ module ActiveSupport
# assert_no_difference 'Article.count', "An Article should not be destroyed" do
# post :create, :article => invalid_attributes
# end
- def assert_no_difference(expressions, message = nil, &block)
- assert_difference expressions, 0, message, &block
+ def assert_no_difference(expression, message = nil, &block)
+ assert_difference expression, 0, message, &block
end
end
end
diff --git a/activesupport/lib/active_support/testing/core_ext/test.rb b/activesupport/lib/active_support/testing/core_ext/test.rb
deleted file mode 100644
index d3f38f0bc7..0000000000
--- a/activesupport/lib/active_support/testing/core_ext/test.rb
+++ /dev/null
@@ -1,6 +0,0 @@
-require 'active_support/testing/core_ext/test/unit/assertions'
-require 'active_support/testing/setup_and_teardown'
-
-class Test::Unit::TestCase #:nodoc:
- include ActiveSupport::Testing::SetupAndTeardown
-end \ No newline at end of file
diff --git a/activesupport/lib/active_support/testing/core_ext/test/unit/assertions.rb b/activesupport/lib/active_support/testing/core_ext/test/unit/assertions.rb
deleted file mode 100644
index e5853bf828..0000000000
--- a/activesupport/lib/active_support/testing/core_ext/test/unit/assertions.rb
+++ /dev/null
@@ -1,72 +0,0 @@
-require 'test/unit/assertions'
-module Test
- module Unit
- #--
- # FIXME: no Proc#binding in Ruby 2, must change this API
- #++
- module Assertions
- # Test numeric difference between the return value of an expression as a result of what is evaluated
- # in the yielded block.
- #
- # assert_difference 'Article.count' do
- # post :create, :article => {...}
- # end
- #
- # An arbitrary expression is passed in and evaluated.
- #
- # assert_difference 'assigns(:article).comments(:reload).size' do
- # post :create, :comment => {...}
- # end
- #
- # An arbitrary positive or negative difference can be specified. The default is +1.
- #
- # assert_difference 'Article.count', -1 do
- # post :delete, :id => ...
- # end
- #
- # An array of expressions can also be passed in and evaluated.
- #
- # assert_difference [ 'Article.count', 'Post.count' ], +2 do
- # post :create, :article => {...}
- # end
- #
- # A error message can be specified.
- #
- # assert_difference 'Article.count', -1, "An Article should be destroyed" do
- # post :delete, :id => ...
- # end
- def assert_difference(expressions, difference = 1, message = nil, &block)
- expression_evaluations = Array(expressions).map do |expression|
- [expression, lambda do
- eval(expression, block.__send__(:binding))
- end]
- end
-
- original_values = expression_evaluations.inject([]) { |memo, expression| memo << expression[1].call }
- yield
- expression_evaluations.each_with_index do |expression, i|
- full_message = ""
- full_message << "#{message}.\n" if message
- full_message << "<#{expression[0]}> was the expression that failed"
- assert_equal original_values[i] + difference, expression[1].call, full_message
- end
- end
-
- # Assertion that the numeric result of evaluating an expression is not changed before and after
- # invoking the passed in block.
- #
- # assert_no_difference 'Article.count' do
- # post :create, :article => invalid_attributes
- # end
- #
- # A error message can be specified.
- #
- # assert_no_difference 'Article.count', "An Article should not be destroyed" do
- # post :create, :article => invalid_attributes
- # end
- def assert_no_difference(expressions, message = nil, &block)
- assert_difference expressions, 0, message, &block
- end
- end
- end
-end
diff --git a/activesupport/lib/active_support/testing/setup_and_teardown.rb b/activesupport/lib/active_support/testing/setup_and_teardown.rb
index 245f57a7b0..7edf6fdb32 100644
--- a/activesupport/lib/active_support/testing/setup_and_teardown.rb
+++ b/activesupport/lib/active_support/testing/setup_and_teardown.rb
@@ -8,7 +8,7 @@ module ActiveSupport
include ActiveSupport::Callbacks
define_callbacks :setup, :teardown
- if defined? MiniTest
+ if defined?(MiniTest::Assertions) && TestCase < MiniTest::Assertions
include ForMiniTest
else
include ForClassicTestUnit
diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb
index 1a59b2a08d..518ca7742f 100644
--- a/activesupport/lib/active_support/time_with_zone.rb
+++ b/activesupport/lib/active_support/time_with_zone.rb
@@ -155,6 +155,7 @@ module ActiveSupport
"#{time.strftime("%Y-%m-%d %H:%M:%S")} #{formatted_offset(false, 'UTC')}" # mimicking Ruby 1.9 Time#to_s format
end
end
+ alias_method :to_formatted_s, :to_s
# Replaces <tt>%Z</tt> and <tt>%z</tt> directives with +zone+ and +formatted_offset+, respectively, before passing to
# Time#strftime, so that zone information is correct
@@ -229,7 +230,7 @@ module ActiveSupport
def advance(options)
# If we're advancing a value of variable length (i.e., years, weeks, months, days), advance from #time,
# otherwise advance from #utc, for accuracy when moving across DST boundaries
- if options.detect {|k,v| [:years, :weeks, :months, :days].include? k}
+ if options.values_at(:years, :weeks, :months, :days).any?
method_missing(:advance, options)
else
utc.advance(options).in_time_zone(time_zone)
@@ -327,7 +328,7 @@ module ActiveSupport
end
def duration_of_variable_length?(obj)
- ActiveSupport::Duration === obj && obj.parts.flatten.detect {|p| [:years, :months, :days].include? p }
+ ActiveSupport::Duration === obj && obj.parts.any? {|p| [:years, :months, :days].include? p[0] }
end
end
end
diff --git a/activesupport/lib/active_support/vendor.rb b/activesupport/lib/active_support/vendor.rb
index 3d7d52ca71..cee45cfea1 100644
--- a/activesupport/lib/active_support/vendor.rb
+++ b/activesupport/lib/active_support/vendor.rb
@@ -9,7 +9,7 @@ end
require 'builder'
begin
- gem 'memcache-client', '~> 1.5.0.5'
+ gem 'memcache-client', '>= 1.5.0.5'
rescue Gem::LoadError
$:.unshift "#{File.dirname(__FILE__)}/vendor/memcache-client-1.5.0.5"
end
diff --git a/activesupport/test/core_ext/array_ext_test.rb b/activesupport/test/core_ext/array_ext_test.rb
index 93f4482307..367f0e0027 100644
--- a/activesupport/test/core_ext/array_ext_test.rb
+++ b/activesupport/test/core_ext/array_ext_test.rb
@@ -302,3 +302,37 @@ class ArrayExtRandomTests < Test::Unit::TestCase
assert_equal 2, [1, 2, 3].rand
end
end
+
+class ArrayWrapperTests < Test::Unit::TestCase
+ class FakeCollection
+ def to_ary
+ ["foo", "bar"]
+ end
+ end
+
+ def test_array
+ ary = %w(foo bar)
+ assert_same ary, Array.wrap(ary)
+ end
+
+ def test_nil
+ assert_equal [], Array.wrap(nil)
+ end
+
+ def test_object
+ o = Object.new
+ assert_equal [o], Array.wrap(o)
+ end
+
+ def test_string
+ assert_equal ["foo"], Array.wrap("foo")
+ end
+
+ def test_string_with_newline
+ assert_equal ["foo\nbar"], Array.wrap("foo\nbar")
+ end
+
+ def test_object_with_to_ary
+ assert_equal ["foo", "bar"], Array.wrap(FakeCollection.new)
+ end
+end
diff --git a/activesupport/test/core_ext/date_ext_test.rb b/activesupport/test/core_ext/date_ext_test.rb
index 2cedf65153..1001868c77 100644
--- a/activesupport/test/core_ext/date_ext_test.rb
+++ b/activesupport/test/core_ext/date_ext_test.rb
@@ -240,13 +240,11 @@ class DateExtCalculationsTest < Test::Unit::TestCase
end
def test_current_returns_time_zone_today_when_zone_default_set
- silence_warnings do # silence warnings raised by tzinfo gem
- Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- with_env_tz 'US/Central' do
- Time.stubs(:now).returns Time.local(1999, 12, 31, 23)
- assert_equal Date.new(1999, 12, 31), Date.today
- assert_equal Date.new(2000, 1, 1), Date.current
- end
+ Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ with_env_tz 'US/Central' do
+ Time.stubs(:now).returns Time.local(1999, 12, 31, 23)
+ assert_equal Date.new(1999, 12, 31), Date.today
+ assert_equal Date.new(2000, 1, 1), Date.current
end
ensure
Time.zone_default = nil
diff --git a/activesupport/test/core_ext/duration_test.rb b/activesupport/test/core_ext/duration_test.rb
index 3948006b42..ab5a86668e 100644
--- a/activesupport/test/core_ext/duration_test.rb
+++ b/activesupport/test/core_ext/duration_test.rb
@@ -94,19 +94,17 @@ class DurationTest < ActiveSupport::TestCase
end
def test_since_and_ago_anchored_to_time_zone_now_when_time_zone_default_set
- silence_warnings do # silence warnings raised by tzinfo gem
- Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- with_env_tz 'US/Eastern' do
- Time.stubs(:now).returns Time.local(2000)
- # since
- assert_equal true, 5.seconds.since.is_a?(ActiveSupport::TimeWithZone)
- assert_equal Time.utc(2000,1,1,0,0,5), 5.seconds.since.time
- assert_equal 'Eastern Time (US & Canada)', 5.seconds.since.time_zone.name
- # ago
- assert_equal true, 5.seconds.ago.is_a?(ActiveSupport::TimeWithZone)
- assert_equal Time.utc(1999,12,31,23,59,55), 5.seconds.ago.time
- assert_equal 'Eastern Time (US & Canada)', 5.seconds.ago.time_zone.name
- end
+ Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ with_env_tz 'US/Eastern' do
+ Time.stubs(:now).returns Time.local(2000)
+ # since
+ assert_equal true, 5.seconds.since.is_a?(ActiveSupport::TimeWithZone)
+ assert_equal Time.utc(2000,1,1,0,0,5), 5.seconds.since.time
+ assert_equal 'Eastern Time (US & Canada)', 5.seconds.since.time_zone.name
+ # ago
+ assert_equal true, 5.seconds.ago.is_a?(ActiveSupport::TimeWithZone)
+ assert_equal Time.utc(1999,12,31,23,59,55), 5.seconds.ago.time
+ assert_equal 'Eastern Time (US & Canada)', 5.seconds.ago.time_zone.name
end
ensure
Time.zone_default = nil
diff --git a/activesupport/test/core_ext/time_ext_test.rb b/activesupport/test/core_ext/time_ext_test.rb
index 52d6c18dce..c0855520e8 100644
--- a/activesupport/test/core_ext/time_ext_test.rb
+++ b/activesupport/test/core_ext/time_ext_test.rb
@@ -461,6 +461,10 @@ class TimeExtCalculationsTest < Test::Unit::TestCase
with_env_tz "UTC" do
assert_equal "Mon, 21 Feb 2005 17:44:30 +0000", time.to_s(:rfc822)
end
+ with_env_tz "US/Central" do
+ assert_equal "Thu, 05 Feb 2009 14:30:05 -0600", Time.local(2009, 2, 5, 14, 30, 5).to_s(:rfc822)
+ assert_equal "Mon, 09 Jun 2008 04:05:01 -0500", Time.local(2008, 6, 9, 4, 5, 1).to_s(:rfc822)
+ end
end
def test_custom_date_format
diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb
index 4dc1fec559..1de6a2ac2e 100644
--- a/activesupport/test/core_ext/time_with_zone_test.rb
+++ b/activesupport/test/core_ext/time_with_zone_test.rb
@@ -13,9 +13,7 @@ class TimeWithZoneTest < Test::Unit::TestCase
end
def test_time
- silence_warnings do # silence warnings raised by tzinfo gem
- assert_equal Time.utc(1999, 12, 31, 19), @twz.time
- end
+ assert_equal Time.utc(1999, 12, 31, 19), @twz.time
end
def test_time_zone
@@ -42,30 +40,22 @@ class TimeWithZoneTest < Test::Unit::TestCase
end
def test_formatted_offset
- silence_warnings do # silence warnings raised by tzinfo gem
- assert_equal '-05:00', @twz.formatted_offset
- assert_equal '-04:00', ActiveSupport::TimeWithZone.new(Time.utc(2000, 6), @time_zone).formatted_offset #dst
- end
+ assert_equal '-05:00', @twz.formatted_offset
+ assert_equal '-04:00', ActiveSupport::TimeWithZone.new(Time.utc(2000, 6), @time_zone).formatted_offset #dst
end
def test_dst?
- silence_warnings do # silence warnings raised by tzinfo gem
- assert_equal false, @twz.dst?
- assert_equal true, ActiveSupport::TimeWithZone.new(Time.utc(2000, 6), @time_zone).dst?
- end
+ assert_equal false, @twz.dst?
+ assert_equal true, ActiveSupport::TimeWithZone.new(Time.utc(2000, 6), @time_zone).dst?
end
def test_zone
- silence_warnings do # silence warnings raised by tzinfo gem
- assert_equal 'EST', @twz.zone
- assert_equal 'EDT', ActiveSupport::TimeWithZone.new(Time.utc(2000, 6), @time_zone).zone #dst
- end
+ assert_equal 'EST', @twz.zone
+ assert_equal 'EDT', ActiveSupport::TimeWithZone.new(Time.utc(2000, 6), @time_zone).zone #dst
end
def test_to_json
- silence_warnings do # silence warnings raised by tzinfo gem
- assert_equal "\"1999/12/31 19:00:00 -0500\"", @twz.to_json
- end
+ assert_equal "\"1999/12/31 19:00:00 -0500\"", @twz.to_json
end
def test_to_json_with_use_standard_json_time_format_config_set_to_true
@@ -76,66 +66,50 @@ class TimeWithZoneTest < Test::Unit::TestCase
end
def test_strftime
- silence_warnings do # silence warnings raised by tzinfo gem
- assert_equal '1999-12-31 19:00:00 EST -0500', @twz.strftime('%Y-%m-%d %H:%M:%S %Z %z')
- end
+ assert_equal '1999-12-31 19:00:00 EST -0500', @twz.strftime('%Y-%m-%d %H:%M:%S %Z %z')
end
def test_inspect
- silence_warnings do # silence warnings raised by tzinfo gem
- assert_equal 'Fri, 31 Dec 1999 19:00:00 EST -05:00', @twz.inspect
- end
+ assert_equal 'Fri, 31 Dec 1999 19:00:00 EST -05:00', @twz.inspect
end
def test_to_s
- silence_warnings do # silence warnings raised by tzinfo gem
- assert_equal '1999-12-31 19:00:00 -0500', @twz.to_s
- end
+ assert_equal '1999-12-31 19:00:00 -0500', @twz.to_s
+ end
+
+ def test_to_formatted_s
+ assert_equal '1999-12-31 19:00:00 -0500', @twz.to_formatted_s
end
def test_to_s_db
- silence_warnings do # silence warnings raised by tzinfo gem
- assert_equal '2000-01-01 00:00:00', @twz.to_s(:db)
- end
+ assert_equal '2000-01-01 00:00:00', @twz.to_s(:db)
end
def test_xmlschema
- silence_warnings do # silence warnings raised by tzinfo gem
- assert_equal "1999-12-31T19:00:00-05:00", @twz.xmlschema
- end
+ assert_equal "1999-12-31T19:00:00-05:00", @twz.xmlschema
end
def test_xmlschema_with_fractional_seconds
- silence_warnings do # silence warnings raised by tzinfo gem
- @twz += 0.123456 # advance the time by a fraction of a second
- assert_equal "1999-12-31T19:00:00.123-05:00", @twz.xmlschema(3)
- assert_equal "1999-12-31T19:00:00.123456-05:00", @twz.xmlschema(6)
- assert_equal "1999-12-31T19:00:00.123456-05:00", @twz.xmlschema(12)
- end
+ @twz += 0.123456 # advance the time by a fraction of a second
+ assert_equal "1999-12-31T19:00:00.123-05:00", @twz.xmlschema(3)
+ assert_equal "1999-12-31T19:00:00.123456-05:00", @twz.xmlschema(6)
+ assert_equal "1999-12-31T19:00:00.123456-05:00", @twz.xmlschema(12)
end
def test_to_yaml
- silence_warnings do # silence warnings raised by tzinfo gem
- assert_equal "--- 1999-12-31 19:00:00 -05:00\n", @twz.to_yaml
- end
+ assert_equal "--- 1999-12-31 19:00:00 -05:00\n", @twz.to_yaml
end
def test_ruby_to_yaml
- silence_warnings do
- assert_equal "--- \n:twz: 2000-01-01 00:00:00 Z\n", {:twz => @twz}.to_yaml
- end
+ assert_equal "--- \n:twz: 2000-01-01 00:00:00 Z\n", {:twz => @twz}.to_yaml
end
def test_httpdate
- silence_warnings do # silence warnings raised by tzinfo gem
- assert_equal 'Sat, 01 Jan 2000 00:00:00 GMT', @twz.httpdate
- end
+ assert_equal 'Sat, 01 Jan 2000 00:00:00 GMT', @twz.httpdate
end
def test_rfc2822
- silence_warnings do # silence warnings raised by tzinfo gem
- assert_equal "Fri, 31 Dec 1999 19:00:00 -0500", @twz.rfc2822
- end
+ assert_equal "Fri, 31 Dec 1999 19:00:00 -0500", @twz.rfc2822
end
def test_compare_with_time
@@ -209,50 +183,36 @@ class TimeWithZoneTest < Test::Unit::TestCase
end
def test_plus_with_integer
- silence_warnings do # silence warnings raised by tzinfo gem
- assert_equal Time.utc(1999, 12, 31, 19, 0 ,5), (@twz + 5).time
- end
+ assert_equal Time.utc(1999, 12, 31, 19, 0 ,5), (@twz + 5).time
end
def test_plus_with_integer_when_self_wraps_datetime
- silence_warnings do # silence warnings raised by tzinfo gem
- datetime = DateTime.civil(2000, 1, 1, 0)
- twz = ActiveSupport::TimeWithZone.new(datetime, @time_zone)
- assert_equal DateTime.civil(1999, 12, 31, 19, 0 ,5), (twz + 5).time
- end
+ datetime = DateTime.civil(2000, 1, 1, 0)
+ twz = ActiveSupport::TimeWithZone.new(datetime, @time_zone)
+ assert_equal DateTime.civil(1999, 12, 31, 19, 0 ,5), (twz + 5).time
end
def test_plus_when_crossing_time_class_limit
- silence_warnings do # silence warnings raised by tzinfo gem
- twz = ActiveSupport::TimeWithZone.new(Time.utc(2038, 1, 19), @time_zone)
- assert_equal [0, 0, 19, 19, 1, 2038], (twz + 86_400).to_a[0,6]
- end
+ twz = ActiveSupport::TimeWithZone.new(Time.utc(2038, 1, 19), @time_zone)
+ assert_equal [0, 0, 19, 19, 1, 2038], (twz + 86_400).to_a[0,6]
end
def test_plus_with_duration
- silence_warnings do # silence warnings raised by tzinfo gem
- assert_equal Time.utc(2000, 1, 5, 19, 0 ,0), (@twz + 5.days).time
- end
+ assert_equal Time.utc(2000, 1, 5, 19, 0 ,0), (@twz + 5.days).time
end
def test_minus_with_integer
- silence_warnings do # silence warnings raised by tzinfo gem
- assert_equal Time.utc(1999, 12, 31, 18, 59 ,55), (@twz - 5).time
- end
+ assert_equal Time.utc(1999, 12, 31, 18, 59 ,55), (@twz - 5).time
end
def test_minus_with_integer_when_self_wraps_datetime
- silence_warnings do # silence warnings raised by tzinfo gem
- datetime = DateTime.civil(2000, 1, 1, 0)
- twz = ActiveSupport::TimeWithZone.new(datetime, @time_zone)
- assert_equal DateTime.civil(1999, 12, 31, 18, 59 ,55), (twz - 5).time
- end
+ datetime = DateTime.civil(2000, 1, 1, 0)
+ twz = ActiveSupport::TimeWithZone.new(datetime, @time_zone)
+ assert_equal DateTime.civil(1999, 12, 31, 18, 59 ,55), (twz - 5).time
end
def test_minus_with_duration
- silence_warnings do # silence warnings raised by tzinfo gem
- assert_equal Time.utc(1999, 12, 26, 19, 0 ,0), (@twz - 5.days).time
- end
+ assert_equal Time.utc(1999, 12, 26, 19, 0 ,0), (@twz - 5.days).time
end
def test_minus_with_time
@@ -265,56 +225,50 @@ class TimeWithZoneTest < Test::Unit::TestCase
twz2 = ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2), ActiveSupport::TimeZone['UTC'] )
assert_equal 86_400.0, twz2 - twz1
end
-
+
def test_minus_with_datetime
assert_equal 86_400.0, ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2), ActiveSupport::TimeZone['UTC'] ) - DateTime.civil(2000, 1, 1)
end
-
+
def test_minus_with_wrapped_datetime
assert_equal 86_400.0, ActiveSupport::TimeWithZone.new( DateTime.civil(2000, 1, 2), ActiveSupport::TimeZone['UTC'] ) - Time.utc(2000, 1, 1)
assert_equal 86_400.0, ActiveSupport::TimeWithZone.new( DateTime.civil(2000, 1, 2), ActiveSupport::TimeZone['UTC'] ) - DateTime.civil(2000, 1, 1)
end
def test_plus_and_minus_enforce_spring_dst_rules
- silence_warnings do # silence warnings raised by tzinfo gem
- utc = Time.utc(2006,4,2,6,59,59) # == Apr 2 2006 01:59:59 EST; i.e., 1 second before daylight savings start
- twz = ActiveSupport::TimeWithZone.new(utc, @time_zone)
- assert_equal Time.utc(2006,4,2,1,59,59), twz.time
- assert_equal false, twz.dst?
- assert_equal 'EST', twz.zone
- twz = twz + 1
- assert_equal Time.utc(2006,4,2,3), twz.time # adding 1 sec springs forward to 3:00AM EDT
- assert_equal true, twz.dst?
- assert_equal 'EDT', twz.zone
- twz = twz - 1 # subtracting 1 second takes goes back to 1:59:59AM EST
- assert_equal Time.utc(2006,4,2,1,59,59), twz.time
- assert_equal false, twz.dst?
- assert_equal 'EST', twz.zone
- end
+ utc = Time.utc(2006,4,2,6,59,59) # == Apr 2 2006 01:59:59 EST; i.e., 1 second before daylight savings start
+ twz = ActiveSupport::TimeWithZone.new(utc, @time_zone)
+ assert_equal Time.utc(2006,4,2,1,59,59), twz.time
+ assert_equal false, twz.dst?
+ assert_equal 'EST', twz.zone
+ twz = twz + 1
+ assert_equal Time.utc(2006,4,2,3), twz.time # adding 1 sec springs forward to 3:00AM EDT
+ assert_equal true, twz.dst?
+ assert_equal 'EDT', twz.zone
+ twz = twz - 1 # subtracting 1 second takes goes back to 1:59:59AM EST
+ assert_equal Time.utc(2006,4,2,1,59,59), twz.time
+ assert_equal false, twz.dst?
+ assert_equal 'EST', twz.zone
end
def test_plus_and_minus_enforce_fall_dst_rules
- silence_warnings do # silence warnings raised by tzinfo gem
- utc = Time.utc(2006,10,29,5,59,59) # == Oct 29 2006 01:59:59 EST; i.e., 1 second before daylight savings end
- twz = ActiveSupport::TimeWithZone.new(utc, @time_zone)
- assert_equal Time.utc(2006,10,29,1,59,59), twz.time
- assert_equal true, twz.dst?
- assert_equal 'EDT', twz.zone
- twz = twz + 1
- assert_equal Time.utc(2006,10,29,1), twz.time # adding 1 sec falls back from 1:59:59 EDT to 1:00AM EST
- assert_equal false, twz.dst?
- assert_equal 'EST', twz.zone
- twz = twz - 1
- assert_equal Time.utc(2006,10,29,1,59,59), twz.time # subtracting 1 sec goes back to 1:59:59AM EDT
- assert_equal true, twz.dst?
- assert_equal 'EDT', twz.zone
- end
+ utc = Time.utc(2006,10,29,5,59,59) # == Oct 29 2006 01:59:59 EST; i.e., 1 second before daylight savings end
+ twz = ActiveSupport::TimeWithZone.new(utc, @time_zone)
+ assert_equal Time.utc(2006,10,29,1,59,59), twz.time
+ assert_equal true, twz.dst?
+ assert_equal 'EDT', twz.zone
+ twz = twz + 1
+ assert_equal Time.utc(2006,10,29,1), twz.time # adding 1 sec falls back from 1:59:59 EDT to 1:00AM EST
+ assert_equal false, twz.dst?
+ assert_equal 'EST', twz.zone
+ twz = twz - 1
+ assert_equal Time.utc(2006,10,29,1,59,59), twz.time # subtracting 1 sec goes back to 1:59:59AM EDT
+ assert_equal true, twz.dst?
+ assert_equal 'EDT', twz.zone
end
def test_to_a
- silence_warnings do # silence warnings raised by tzinfo gem
- assert_equal [45, 30, 5, 1, 2, 2000, 2, 32, false, "HST"], ActiveSupport::TimeWithZone.new( Time.utc(2000, 2, 1, 15, 30, 45), ActiveSupport::TimeZone['Hawaii'] ).to_a
- end
+ assert_equal [45, 30, 5, 1, 2, 2000, 2, 32, false, "HST"], ActiveSupport::TimeWithZone.new( Time.utc(2000, 2, 1, 15, 30, 45), ActiveSupport::TimeZone['Hawaii'] ).to_a
end
def test_to_f
@@ -334,22 +288,18 @@ class TimeWithZoneTest < Test::Unit::TestCase
end
def test_to_date
- silence_warnings do # silence warnings raised by tzinfo gem
- # 1 sec before midnight Jan 1 EST
- assert_equal Date.new(1999, 12, 31), ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 4, 59, 59), ActiveSupport::TimeZone['Eastern Time (US & Canada)'] ).to_date
- # midnight Jan 1 EST
- assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 5, 0, 0), ActiveSupport::TimeZone['Eastern Time (US & Canada)'] ).to_date
- # 1 sec before midnight Jan 2 EST
- assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2, 4, 59, 59), ActiveSupport::TimeZone['Eastern Time (US & Canada)'] ).to_date
- # midnight Jan 2 EST
- assert_equal Date.new(2000, 1, 2), ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2, 5, 0, 0), ActiveSupport::TimeZone['Eastern Time (US & Canada)'] ).to_date
- end
+ # 1 sec before midnight Jan 1 EST
+ assert_equal Date.new(1999, 12, 31), ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 4, 59, 59), ActiveSupport::TimeZone['Eastern Time (US & Canada)'] ).to_date
+ # midnight Jan 1 EST
+ assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 5, 0, 0), ActiveSupport::TimeZone['Eastern Time (US & Canada)'] ).to_date
+ # 1 sec before midnight Jan 2 EST
+ assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2, 4, 59, 59), ActiveSupport::TimeZone['Eastern Time (US & Canada)'] ).to_date
+ # midnight Jan 2 EST
+ assert_equal Date.new(2000, 1, 2), ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2, 5, 0, 0), ActiveSupport::TimeZone['Eastern Time (US & Canada)'] ).to_date
end
def test_to_datetime
- silence_warnings do # silence warnings raised by tzinfo gem
- assert_equal DateTime.civil(1999, 12, 31, 19, 0, 0, Rational(-18_000, 86_400)), @twz.to_datetime
- end
+ assert_equal DateTime.civil(1999, 12, 31, 19, 0, 0, Rational(-18_000, 86_400)), @twz.to_datetime
end
def test_acts_like_time
@@ -369,44 +319,38 @@ class TimeWithZoneTest < Test::Unit::TestCase
end
def test_method_missing_with_time_return_value
- silence_warnings do # silence warnings raised by tzinfo gem
- assert_instance_of ActiveSupport::TimeWithZone, @twz.months_since(1)
- assert_equal Time.utc(2000, 1, 31, 19, 0 ,0), @twz.months_since(1).time
- end
+ assert_instance_of ActiveSupport::TimeWithZone, @twz.months_since(1)
+ assert_equal Time.utc(2000, 1, 31, 19, 0 ,0), @twz.months_since(1).time
end
def test_marshal_dump_and_load
- silence_warnings do # silence warnings raised by tzinfo gem
- marshal_str = Marshal.dump(@twz)
- mtime = Marshal.load(marshal_str)
- assert_equal Time.utc(2000, 1, 1, 0), mtime.utc
- assert mtime.utc.utc?
- assert_equal ActiveSupport::TimeZone['Eastern Time (US & Canada)'], mtime.time_zone
- assert_equal Time.utc(1999, 12, 31, 19), mtime.time
- assert mtime.time.utc?
- assert_equal @twz.inspect, mtime.inspect
- end
+ marshal_str = Marshal.dump(@twz)
+ mtime = Marshal.load(marshal_str)
+ assert_equal Time.utc(2000, 1, 1, 0), mtime.utc
+ assert mtime.utc.utc?
+ assert_equal ActiveSupport::TimeZone['Eastern Time (US & Canada)'], mtime.time_zone
+ assert_equal Time.utc(1999, 12, 31, 19), mtime.time
+ assert mtime.time.utc?
+ assert_equal @twz.inspect, mtime.inspect
end
def test_marshal_dump_and_load_with_tzinfo_identifier
- silence_warnings do # silence warnings raised by tzinfo gem
- twz = ActiveSupport::TimeWithZone.new(@utc, TZInfo::Timezone.get('America/New_York'))
- marshal_str = Marshal.dump(twz)
- mtime = Marshal.load(marshal_str)
- assert_equal Time.utc(2000, 1, 1, 0), mtime.utc
- assert mtime.utc.utc?
- assert_equal 'America/New_York', mtime.time_zone.name
- assert_equal Time.utc(1999, 12, 31, 19), mtime.time
- assert mtime.time.utc?
- assert_equal @twz.inspect, mtime.inspect
- end
+ twz = ActiveSupport::TimeWithZone.new(@utc, TZInfo::Timezone.get('America/New_York'))
+ marshal_str = Marshal.dump(twz)
+ mtime = Marshal.load(marshal_str)
+ assert_equal Time.utc(2000, 1, 1, 0), mtime.utc
+ assert mtime.utc.utc?
+ assert_equal 'America/New_York', mtime.time_zone.name
+ assert_equal Time.utc(1999, 12, 31, 19), mtime.time
+ assert mtime.time.utc?
+ assert_equal @twz.inspect, mtime.inspect
end
-
+
def test_freeze
@twz.freeze
assert @twz.frozen?
end
-
+
def test_freeze_preloads_instance_variables
@twz.freeze
assert_nothing_raised do
@@ -416,66 +360,52 @@ class TimeWithZoneTest < Test::Unit::TestCase
end
def test_method_missing_with_non_time_return_value
- silence_warnings do # silence warnings raised by tzinfo gem
- @twz.time.expects(:foo).returns('bar')
- assert_equal 'bar', @twz.foo
- end
+ @twz.time.expects(:foo).returns('bar')
+ assert_equal 'bar', @twz.foo
end
def test_date_part_value_methods
- silence_warnings do # silence warnings raised by tzinfo gem
- twz = ActiveSupport::TimeWithZone.new(Time.utc(1999,12,31,19,18,17,500), @time_zone)
- twz.expects(:method_missing).never
- assert_equal 1999, twz.year
- assert_equal 12, twz.month
- assert_equal 31, twz.day
- assert_equal 14, twz.hour
- assert_equal 18, twz.min
- assert_equal 17, twz.sec
- assert_equal 500, twz.usec
- assert_equal 5, twz.wday
- assert_equal 365, twz.yday
- end
+ twz = ActiveSupport::TimeWithZone.new(Time.utc(1999,12,31,19,18,17,500), @time_zone)
+ twz.expects(:method_missing).never
+ assert_equal 1999, twz.year
+ assert_equal 12, twz.month
+ assert_equal 31, twz.day
+ assert_equal 14, twz.hour
+ assert_equal 18, twz.min
+ assert_equal 17, twz.sec
+ assert_equal 500, twz.usec
+ assert_equal 5, twz.wday
+ assert_equal 365, twz.yday
end
def test_usec_returns_0_when_datetime_is_wrapped
- silence_warnings do # silence warnings raised by tzinfo gem
- twz = ActiveSupport::TimeWithZone.new(DateTime.civil(2000), @time_zone)
- assert_equal 0, twz.usec
- end
+ twz = ActiveSupport::TimeWithZone.new(DateTime.civil(2000), @time_zone)
+ assert_equal 0, twz.usec
end
def test_utc_to_local_conversion_saves_period_in_instance_variable
- silence_warnings do # silence warnings raised by tzinfo gem
- assert_nil @twz.instance_variable_get('@period')
- @twz.time
- assert_kind_of TZInfo::TimezonePeriod, @twz.instance_variable_get('@period')
- end
+ assert_nil @twz.instance_variable_get('@period')
+ @twz.time
+ assert_kind_of TZInfo::TimezonePeriod, @twz.instance_variable_get('@period')
end
def test_instance_created_with_local_time_returns_correct_utc_time
- silence_warnings do # silence warnings raised by tzinfo gem
- twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(1999, 12, 31, 19))
- assert_equal Time.utc(2000), twz.utc
- end
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(1999, 12, 31, 19))
+ assert_equal Time.utc(2000), twz.utc
end
def test_instance_created_with_local_time_enforces_spring_dst_rules
- silence_warnings do # silence warnings raised by tzinfo gem
- twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,4,2,2)) # first second of DST
- assert_equal Time.utc(2006,4,2,3), twz.time # springs forward to 3AM
- assert_equal true, twz.dst?
- assert_equal 'EDT', twz.zone
- end
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,4,2,2)) # first second of DST
+ assert_equal Time.utc(2006,4,2,3), twz.time # springs forward to 3AM
+ assert_equal true, twz.dst?
+ assert_equal 'EDT', twz.zone
end
def test_instance_created_with_local_time_enforces_fall_dst_rules
- silence_warnings do # silence warnings raised by tzinfo gem
- twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,10,29,1)) # 1AM can be either DST or non-DST; we'll pick DST
- assert_equal Time.utc(2006,10,29,1), twz.time
- assert_equal true, twz.dst?
- assert_equal 'EDT', twz.zone
- end
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,10,29,1)) # 1AM can be either DST or non-DST; we'll pick DST
+ assert_equal Time.utc(2006,10,29,1), twz.time
+ assert_equal true, twz.dst?
+ assert_equal 'EDT', twz.zone
end
def test_ruby_19_weekday_name_query_methods
@@ -486,15 +416,11 @@ class TimeWithZoneTest < Test::Unit::TestCase
end
def test_utc_to_local_conversion_with_far_future_datetime
- silence_warnings do # silence warnings raised by tzinfo gem
- assert_equal [0,0,19,31,12,2049], ActiveSupport::TimeWithZone.new(DateTime.civil(2050), @time_zone).to_a[0,6]
- end
+ assert_equal [0,0,19,31,12,2049], ActiveSupport::TimeWithZone.new(DateTime.civil(2050), @time_zone).to_a[0,6]
end
def test_local_to_utc_conversion_with_far_future_datetime
- silence_warnings do # silence warnings raised by tzinfo gem
- assert_equal DateTime.civil(2050).to_f, ActiveSupport::TimeWithZone.new(nil, @time_zone, DateTime.civil(2049,12,31,19)).to_f
- end
+ assert_equal DateTime.civil(2050).to_f, ActiveSupport::TimeWithZone.new(nil, @time_zone, DateTime.civil(2049,12,31,19)).to_f
end
def test_change
@@ -782,42 +708,36 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase
end
def test_in_time_zone
- silence_warnings do # silence warnings raised by tzinfo gem
- Time.use_zone 'Alaska' do
- assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @t.in_time_zone.inspect
- assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @dt.in_time_zone.inspect
- end
- Time.use_zone 'Hawaii' do
- assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @t.in_time_zone.inspect
- assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @dt.in_time_zone.inspect
- end
- Time.use_zone nil do
- assert_equal @t, @t.in_time_zone
- assert_equal @dt, @dt.in_time_zone
- end
+ Time.use_zone 'Alaska' do
+ assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @t.in_time_zone.inspect
+ assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @dt.in_time_zone.inspect
+ end
+ Time.use_zone 'Hawaii' do
+ assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @t.in_time_zone.inspect
+ assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @dt.in_time_zone.inspect
+ end
+ Time.use_zone nil do
+ assert_equal @t, @t.in_time_zone
+ assert_equal @dt, @dt.in_time_zone
end
end
def test_in_time_zone_with_argument
- silence_warnings do # silence warnings raised by tzinfo gem
- Time.use_zone 'Eastern Time (US & Canada)' do # Time.zone will not affect #in_time_zone(zone)
- assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @t.in_time_zone('Alaska').inspect
- assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @dt.in_time_zone('Alaska').inspect
- assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @t.in_time_zone('Hawaii').inspect
- assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @dt.in_time_zone('Hawaii').inspect
- assert_equal 'Sat, 01 Jan 2000 00:00:00 UTC +00:00', @t.in_time_zone('UTC').inspect
- assert_equal 'Sat, 01 Jan 2000 00:00:00 UTC +00:00', @dt.in_time_zone('UTC').inspect
- assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @t.in_time_zone(-9.hours).inspect
- end
+ Time.use_zone 'Eastern Time (US & Canada)' do # Time.zone will not affect #in_time_zone(zone)
+ assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @t.in_time_zone('Alaska').inspect
+ assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @dt.in_time_zone('Alaska').inspect
+ assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @t.in_time_zone('Hawaii').inspect
+ assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @dt.in_time_zone('Hawaii').inspect
+ assert_equal 'Sat, 01 Jan 2000 00:00:00 UTC +00:00', @t.in_time_zone('UTC').inspect
+ assert_equal 'Sat, 01 Jan 2000 00:00:00 UTC +00:00', @dt.in_time_zone('UTC').inspect
+ assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @t.in_time_zone(-9.hours).inspect
end
end
def test_in_time_zone_with_time_local_instance
- silence_warnings do # silence warnings raised by tzinfo gem
- with_env_tz 'US/Eastern' do
- time = Time.local(1999, 12, 31, 19) # == Time.utc(2000)
- assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', time.in_time_zone('Alaska').inspect
- end
+ with_env_tz 'US/Eastern' do
+ time = Time.local(1999, 12, 31, 19) # == Time.utc(2000)
+ assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', time.in_time_zone('Alaska').inspect
end
end
@@ -872,24 +792,20 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase
end
def test_time_zone_setter_with_tzinfo_timezone_object_wraps_in_rails_time_zone
- silence_warnings do # silence warnings raised by tzinfo gem
- tzinfo = TZInfo::Timezone.get('America/New_York')
- Time.zone = tzinfo
- assert_kind_of ActiveSupport::TimeZone, Time.zone
- assert_equal tzinfo, Time.zone.tzinfo
- assert_equal 'America/New_York', Time.zone.name
- assert_equal(-18_000, Time.zone.utc_offset)
- end
+ tzinfo = TZInfo::Timezone.get('America/New_York')
+ Time.zone = tzinfo
+ assert_kind_of ActiveSupport::TimeZone, Time.zone
+ assert_equal tzinfo, Time.zone.tzinfo
+ assert_equal 'America/New_York', Time.zone.name
+ assert_equal(-18_000, Time.zone.utc_offset)
end
def test_time_zone_setter_with_tzinfo_timezone_identifier_does_lookup_and_wraps_in_rails_time_zone
- silence_warnings do # silence warnings raised by tzinfo gem
- Time.zone = 'America/New_York'
- assert_kind_of ActiveSupport::TimeZone, Time.zone
- assert_equal 'America/New_York', Time.zone.tzinfo.name
- assert_equal 'America/New_York', Time.zone.name
- assert_equal(-18_000, Time.zone.utc_offset)
- end
+ Time.zone = 'America/New_York'
+ assert_kind_of ActiveSupport::TimeZone, Time.zone
+ assert_equal 'America/New_York', Time.zone.tzinfo.name
+ assert_equal 'America/New_York', Time.zone.name
+ assert_equal(-18_000, Time.zone.utc_offset)
end
def test_time_zone_setter_with_non_identifying_argument_returns_nil
@@ -908,14 +824,12 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase
end
def test_current_returns_time_zone_now_when_zone_default_set
- silence_warnings do # silence warnings raised by tzinfo gem
- Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- with_env_tz 'US/Eastern' do
- Time.stubs(:now).returns Time.local(2000)
- assert_equal true, Time.current.is_a?(ActiveSupport::TimeWithZone)
- assert_equal 'Eastern Time (US & Canada)', Time.current.time_zone.name
- assert_equal Time.utc(2000), Time.current.time
- end
+ Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ with_env_tz 'US/Eastern' do
+ Time.stubs(:now).returns Time.local(2000)
+ assert_equal true, Time.current.is_a?(ActiveSupport::TimeWithZone)
+ assert_equal 'Eastern Time (US & Canada)', Time.current.time_zone.name
+ assert_equal Time.utc(2000), Time.current.time
end
ensure
Time.zone_default = nil
diff --git a/activesupport/test/inflector_test_cases.rb b/activesupport/test/inflector_test_cases.rb
index 481c3e835c..b7ac467c37 100644
--- a/activesupport/test/inflector_test_cases.rb
+++ b/activesupport/test/inflector_test_cases.rb
@@ -99,7 +99,8 @@ module InflectorTestCases
"prize" => "prizes",
"edge" => "edges",
- "cow" => "kine"
+ "cow" => "kine",
+ "database" => "databases"
}
CamelToUnderscore = {
diff --git a/activesupport/test/json/decoding_test.rb b/activesupport/test/json/decoding_test.rb
index 558b03b90d..ebd46a851e 100644
--- a/activesupport/test/json/decoding_test.rb
+++ b/activesupport/test/json/decoding_test.rb
@@ -1,3 +1,4 @@
+# encoding: UTF-8
require 'abstract_unit'
class TestJSONDecoding < Test::Unit::TestCase
@@ -10,6 +11,8 @@ class TestJSONDecoding < Test::Unit::TestCase
%({"returnTo":[1,"\\"a\\",", "b"]}) => {"returnTo" => [1, "\"a\",", "b"]},
%({a: "'", "b": "5,000"}) => {"a" => "'", "b" => "5,000"},
%({a: "a's, b's and c's", "b": "5,000"}) => {"a" => "a's, b's and c's", "b" => "5,000"},
+ # multibyte
+ %({"matzue": "松江", "asakusa": "浅草"}) => {"matzue" => "松江", "asakusa" => "浅草"},
%({a: "2007-01-01"}) => {'a' => Date.new(2007, 1, 1)},
%({a: "2007-01-01 01:12:34 Z"}) => {'a' => Time.utc(2007, 1, 1, 1, 12, 34)},
# no time zone
diff --git a/activesupport/test/test_test.rb b/activesupport/test/test_test.rb
index 298037e27c..d250b10822 100644
--- a/activesupport/test/test_test.rb
+++ b/activesupport/test/test_test.rb
@@ -66,7 +66,8 @@ class AssertDifferenceTest < ActiveSupport::TestCase
end
fail 'should not get to here'
rescue Exception => e
- assert_equal "<3> expected but was\n<2>.", e.message
+ assert_match(/didn't change by/, e.message)
+ assert_match(/expected but was/, e.message)
end
def test_array_of_expressions_identify_failure_when_message_provided
@@ -75,7 +76,9 @@ class AssertDifferenceTest < ActiveSupport::TestCase
end
fail 'should not get to here'
rescue Exception => e
- assert_equal "something went wrong.\n<3> expected but was\n<2>.", e.message
+ assert_match(/something went wrong/, e.message)
+ assert_match(/didn't change by/, e.message)
+ assert_match(/expected but was/, e.message)
end
else
def default_test; end
diff --git a/activesupport/test/time_zone_test.rb b/activesupport/test/time_zone_test.rb
index f80575cfd4..6dec6a8f34 100644
--- a/activesupport/test/time_zone_test.rb
+++ b/activesupport/test/time_zone_test.rb
@@ -2,34 +2,26 @@ require 'abstract_unit'
class TimeZoneTest < Test::Unit::TestCase
def test_utc_to_local
- silence_warnings do # silence warnings raised by tzinfo gem
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- assert_equal Time.utc(1999, 12, 31, 19), zone.utc_to_local(Time.utc(2000, 1)) # standard offset -0500
- assert_equal Time.utc(2000, 6, 30, 20), zone.utc_to_local(Time.utc(2000, 7)) # dst offset -0400
- end
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ assert_equal Time.utc(1999, 12, 31, 19), zone.utc_to_local(Time.utc(2000, 1)) # standard offset -0500
+ assert_equal Time.utc(2000, 6, 30, 20), zone.utc_to_local(Time.utc(2000, 7)) # dst offset -0400
end
def test_local_to_utc
- silence_warnings do # silence warnings raised by tzinfo gem
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- assert_equal Time.utc(2000, 1, 1, 5), zone.local_to_utc(Time.utc(2000, 1)) # standard offset -0500
- assert_equal Time.utc(2000, 7, 1, 4), zone.local_to_utc(Time.utc(2000, 7)) # dst offset -0400
- end
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ assert_equal Time.utc(2000, 1, 1, 5), zone.local_to_utc(Time.utc(2000, 1)) # standard offset -0500
+ assert_equal Time.utc(2000, 7, 1, 4), zone.local_to_utc(Time.utc(2000, 7)) # dst offset -0400
end
def test_period_for_local
- silence_warnings do # silence warnings raised by tzinfo gem
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- assert_instance_of TZInfo::TimezonePeriod, zone.period_for_local(Time.utc(2000))
- end
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ assert_instance_of TZInfo::TimezonePeriod, zone.period_for_local(Time.utc(2000))
end
ActiveSupport::TimeZone::MAPPING.keys.each do |name|
define_method("test_map_#{name.downcase.gsub(/[^a-z]/, '_')}_to_tzinfo") do
- silence_warnings do # silence warnings raised by tzinfo gem
- zone = ActiveSupport::TimeZone[name]
- assert zone.tzinfo.respond_to?(:period_for_local)
- end
+ zone = ActiveSupport::TimeZone[name]
+ assert zone.tzinfo.respond_to?(:period_for_local)
end
end
@@ -44,16 +36,12 @@ class TimeZoneTest < Test::Unit::TestCase
ActiveSupport::TimeZone.all.each do |zone|
name = zone.name.downcase.gsub(/[^a-z]/, '_')
define_method("test_from_#{name}_to_map") do
- silence_warnings do # silence warnings raised by tzinfo gem
- assert_instance_of ActiveSupport::TimeZone, ActiveSupport::TimeZone[zone.name]
- end
+ assert_instance_of ActiveSupport::TimeZone, ActiveSupport::TimeZone[zone.name]
end
define_method("test_utc_offset_for_#{name}") do
- silence_warnings do # silence warnings raised by tzinfo gem
- period = zone.tzinfo.current_period
- assert_equal period.utc_offset, zone.utc_offset
- end
+ period = zone.tzinfo.current_period
+ assert_equal period.utc_offset, zone.utc_offset
end
end
@@ -98,19 +86,15 @@ class TimeZoneTest < Test::Unit::TestCase
end
def test_local
- silence_warnings do # silence warnings raised by tzinfo gem
- time = ActiveSupport::TimeZone["Hawaii"].local(2007, 2, 5, 15, 30, 45)
- assert_equal Time.utc(2007, 2, 5, 15, 30, 45), time.time
- assert_equal ActiveSupport::TimeZone["Hawaii"], time.time_zone
- end
+ time = ActiveSupport::TimeZone["Hawaii"].local(2007, 2, 5, 15, 30, 45)
+ assert_equal Time.utc(2007, 2, 5, 15, 30, 45), time.time
+ assert_equal ActiveSupport::TimeZone["Hawaii"], time.time_zone
end
def test_local_with_old_date
- silence_warnings do # silence warnings raised by tzinfo gem
- time = ActiveSupport::TimeZone["Hawaii"].local(1850, 2, 5, 15, 30, 45)
- assert_equal [45,30,15,5,2,1850], time.to_a[0,6]
- assert_equal ActiveSupport::TimeZone["Hawaii"], time.time_zone
- end
+ time = ActiveSupport::TimeZone["Hawaii"].local(1850, 2, 5, 15, 30, 45)
+ assert_equal [45,30,15,5,2,1850], time.to_a[0,6]
+ assert_equal ActiveSupport::TimeZone["Hawaii"], time.time_zone
end
def test_local_enforces_spring_dst_rules
@@ -179,29 +163,23 @@ class TimeZoneTest < Test::Unit::TestCase
end
def test_parse_with_old_date
- silence_warnings do # silence warnings raised by tzinfo gem
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- twz = zone.parse('1850-12-31 19:00:00')
- assert_equal [0,0,19,31,12,1850], twz.to_a[0,6]
- assert_equal zone, twz.time_zone
- end
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ twz = zone.parse('1850-12-31 19:00:00')
+ assert_equal [0,0,19,31,12,1850], twz.to_a[0,6]
+ assert_equal zone, twz.time_zone
end
def test_parse_far_future_date_with_time_zone_offset_in_string
- silence_warnings do # silence warnings raised by tzinfo gem
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- twz = zone.parse('2050-12-31 19:00:00 -10:00') # i.e., 2050-01-01 05:00:00 UTC
- assert_equal [0,0,0,1,1,2051], twz.to_a[0,6]
- assert_equal zone, twz.time_zone
- end
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ twz = zone.parse('2050-12-31 19:00:00 -10:00') # i.e., 2050-01-01 05:00:00 UTC
+ assert_equal [0,0,0,1,1,2051], twz.to_a[0,6]
+ assert_equal zone, twz.time_zone
end
def test_parse_returns_nil_when_string_without_date_information_is_passed_in
- silence_warnings do # silence warnings raised by tzinfo gem
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- assert_nil zone.parse('foobar')
- assert_nil zone.parse(' ')
- end
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ assert_nil zone.parse('foobar')
+ assert_nil zone.parse(' ')
end
def test_parse_with_incomplete_date
@@ -212,12 +190,10 @@ class TimeZoneTest < Test::Unit::TestCase
end
def test_utc_offset_lazy_loaded_from_tzinfo_when_not_passed_in_to_initialize
- silence_warnings do # silence warnings raised by tzinfo gem
- tzinfo = TZInfo::Timezone.get('America/New_York')
- zone = ActiveSupport::TimeZone.create(tzinfo.name, nil, tzinfo)
- assert_equal nil, zone.instance_variable_get('@utc_offset')
- assert_equal(-18_000, zone.utc_offset)
- end
+ tzinfo = TZInfo::Timezone.get('America/New_York')
+ zone = ActiveSupport::TimeZone.create(tzinfo.name, nil, tzinfo)
+ assert_equal nil, zone.instance_variable_get('@utc_offset')
+ assert_equal(-18_000, zone.utc_offset)
end
def test_formatted_offset_positive
diff --git a/railties/environments/production.rb b/railties/environments/production.rb
index 1fc9f6b923..27119d2d18 100644
--- a/railties/environments/production.rb
+++ b/railties/environments/production.rb
@@ -7,6 +7,7 @@ config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.action_controller.consider_all_requests_local = false
config.action_controller.perform_caching = true
+config.action_view.cache_template_loading = true
# See everything in the log (default is :info)
# config.log_level = :debug
diff --git a/railties/environments/test.rb b/railties/environments/test.rb
index 496eb9572b..d6f80a4080 100644
--- a/railties/environments/test.rb
+++ b/railties/environments/test.rb
@@ -12,6 +12,7 @@ config.whiny_nils = true
# Show full error reports and disable caching
config.action_controller.consider_all_requests_local = true
config.action_controller.perform_caching = false
+config.action_view.cache_template_loading = true
# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false
diff --git a/railties/html/500.html b/railties/html/500.html
index 74142cb04a..ec3bbf02c4 100644
--- a/railties/html/500.html
+++ b/railties/html/500.html
@@ -25,9 +25,6 @@
<div class="dialog">
<h1>We're sorry, but something went wrong.</h1>
<p>We've been notified about this issue and we'll take a look at it shortly.</p>
- <p><small>(If you're the administrator of this website, then please read
- the log file "<%= "<%s>" % "%=h RAILS_ENV %" %>.log"
- to find out what went wrong.)</small></p>
</div>
</body>
</html>
diff --git a/railties/lib/console_app.rb b/railties/lib/console_app.rb
index 96bf3117c8..a35c96c957 100644
--- a/railties/lib/console_app.rb
+++ b/railties/lib/console_app.rb
@@ -25,7 +25,6 @@ end
def reload!
puts "Reloading..."
dispatcher = ActionController::Dispatcher.new($stdout)
- dispatcher.cleanup_application
dispatcher.reload_application
true
end
diff --git a/railties/lib/fcgi_handler.rb b/railties/lib/fcgi_handler.rb
index 1256ef2286..0cd2dc51c6 100644
--- a/railties/lib/fcgi_handler.rb
+++ b/railties/lib/fcgi_handler.rb
@@ -38,6 +38,8 @@ class RailsFCGIHandler
# Safely install signal handlers.
install_signal_handlers
+ @app = Dispatcher.new
+
# Start error timestamp at 11 seconds ago.
@last_error_on = Time.now - 11
end
@@ -69,36 +71,36 @@ class RailsFCGIHandler
protected
def process_each_request(provider)
- cgi = nil
+ request = nil
catch :exit do
- provider.each_cgi do |cgi|
- process_request(cgi)
+ provider.each do |request|
+ process_request(request)
case when_ready
when :reload
reload!
when :restart
- close_connection(cgi)
+ close_connection(request)
restart!
when :exit
- close_connection(cgi)
+ close_connection(request)
throw :exit
end
end
end
rescue SignalException => signal
raise unless signal.message == 'SIGUSR1'
- close_connection(cgi)
+ close_connection(request)
end
- def process_request(cgi)
+ def process_request(request)
@processing, @when_ready = true, nil
gc_countdown
with_signal_handler 'USR1' do
begin
- ::Rack::Handler::FastCGI.serve(cgi, Dispatcher.new)
+ ::Rack::Handler::FastCGI.serve(request, @app)
rescue SignalException, SystemExit
raise
rescue Exception => error
@@ -231,7 +233,7 @@ class RailsFCGIHandler
end
end
- def close_connection(cgi)
- cgi.instance_variable_get("@request").finish if cgi
+ def close_connection(request)
+ request.finish if request
end
end
diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb
index cfd42544b6..a8b951ae58 100644
--- a/railties/lib/initializer.rb
+++ b/railties/lib/initializer.rb
@@ -369,11 +369,8 @@ Run `rake gems:install` to install the missing gems.
def load_view_paths
if configuration.frameworks.include?(:action_view)
- if configuration.cache_classes
- view_path = ActionView::Template::EagerPath.new(configuration.view_path)
- ActionController::Base.view_paths = view_path if configuration.frameworks.include?(:action_controller)
- ActionMailer::Base.template_root = view_path if configuration.frameworks.include?(:action_mailer)
- end
+ ActionController::Base.view_paths.load! if configuration.frameworks.include?(:action_controller)
+ ActionMailer::Base.view_paths.load! if configuration.frameworks.include?(:action_mailer)
end
end
@@ -481,7 +478,7 @@ Run `rake gems:install` to install the missing gems.
# set to use Configuration#view_path.
def initialize_framework_views
if configuration.frameworks.include?(:action_view)
- view_path = ActionView::Template::Path.new(configuration.view_path)
+ view_path = ActionView::PathSet.type_cast(configuration.view_path)
ActionMailer::Base.template_root ||= view_path if configuration.frameworks.include?(:action_mailer)
ActionController::Base.view_paths = view_path if configuration.frameworks.include?(:action_controller) && ActionController::Base.view_paths.empty?
end
diff --git a/railties/lib/rails/plugin/loader.rb b/railties/lib/rails/plugin/loader.rb
index be81bdf4fa..bc0184c43d 100644
--- a/railties/lib/rails/plugin/loader.rb
+++ b/railties/lib/rails/plugin/loader.rb
@@ -175,7 +175,7 @@ module Rails
def ensure_all_registered_plugins_are_loaded!
if explicit_plugin_loading_order?
if configuration.plugins.detect {|plugin| plugin != :all && !loaded?(plugin) }
- missing_plugins = configuration.plugins - (plugins + [:all])
+ missing_plugins = configuration.plugins - (plugins.map{|p| p.name.to_sym} + [:all])
raise LoadError, "Could not locate the following plugins: #{missing_plugins.to_sentence}"
end
end
diff --git a/railties/lib/rails_generator/generators/applications/app/template_runner.rb b/railties/lib/rails_generator/generators/applications/app/template_runner.rb
index 84e36ecc1b..eeb6b17661 100644
--- a/railties/lib/rails_generator/generators/applications/app/template_runner.rb
+++ b/railties/lib/rails_generator/generators/applications/app/template_runner.rb
@@ -75,7 +75,7 @@ module Rails
end
elsif options[:git] || options[:svn]
in_root do
- run("script/plugin install #{options[:svn] || options[:git]}", false)
+ run_ruby_script("script/plugin install #{options[:svn] || options[:git]}", false)
end
else
log "! no git or svn provided for #{name}. skipping..."
@@ -220,7 +220,7 @@ module Rails
log 'generating', what
argument = args.map(&:to_s).flatten.join(" ")
- in_root { run("script/generate #{what} #{argument}", false) }
+ in_root { run_ruby_script("script/generate #{what} #{argument}", false) }
end
# Executes a command
@@ -236,6 +236,12 @@ module Rails
`#{command}`
end
+ # Executes a ruby script (taking into account WIN32 platform quirks)
+ def run_ruby_script(command, log_action = true)
+ ruby_command = RUBY_PLATFORM=~ /win32/ ? 'ruby ' : ''
+ run("#{ruby_command}#{command}", log_action)
+ end
+
# Runs the supplied rake task
#
# ==== Example
diff --git a/railties/lib/rails_generator/generators/components/scaffold/templates/functional_test.rb b/railties/lib/rails_generator/generators/components/scaffold/templates/functional_test.rb
index 2d9d635944..cd2fc578bf 100644
--- a/railties/lib/rails_generator/generators/components/scaffold/templates/functional_test.rb
+++ b/railties/lib/rails_generator/generators/components/scaffold/templates/functional_test.rb
@@ -21,23 +21,23 @@ class <%= controller_class_name %>ControllerTest < ActionController::TestCase
end
test "should show <%= file_name %>" do
- get :show, :id => <%= table_name %>(:one).id
+ get :show, :id => <%= table_name %>(:one).to_param
assert_response :success
end
test "should get edit" do
- get :edit, :id => <%= table_name %>(:one).id
+ get :edit, :id => <%= table_name %>(:one).to_param
assert_response :success
end
test "should update <%= file_name %>" do
- put :update, :id => <%= table_name %>(:one).id, :<%= file_name %> => { }
+ put :update, :id => <%= table_name %>(:one).to_param, :<%= file_name %> => { }
assert_redirected_to <%= file_name %>_path(assigns(:<%= file_name %>))
end
test "should destroy <%= file_name %>" do
assert_difference('<%= class_name %>.count', -1) do
- delete :destroy, :id => <%= table_name %>(:one).id
+ delete :destroy, :id => <%= table_name %>(:one).to_param
end
assert_redirected_to <%= table_name %>_path
diff --git a/railties/test/abstract_unit.rb b/railties/test/abstract_unit.rb
index 43736ee7ec..a950fc8b7e 100644
--- a/railties/test/abstract_unit.rb
+++ b/railties/test/abstract_unit.rb
@@ -18,3 +18,11 @@ if defined?(RAILS_ROOT)
else
RAILS_ROOT = File.dirname(__FILE__)
end
+
+def uses_gem(gem_name, test_name, version = '> 0')
+ gem gem_name.to_s, version
+ require gem_name.to_s
+ yield
+rescue LoadError
+ $stderr.puts "Skipping #{test_name} tests. `gem install #{gem_name}` and try again."
+end
diff --git a/railties/test/error_page_test.rb b/railties/test/error_page_test.rb
deleted file mode 100644
index f819e468e8..0000000000
--- a/railties/test/error_page_test.rb
+++ /dev/null
@@ -1,40 +0,0 @@
-require 'abstract_unit'
-require 'action_controller'
-require 'action_controller/test_case'
-
-RAILS_ENV = "test"
-CURRENT_DIR = File.expand_path(File.dirname(__FILE__))
-HTML_DIR = File.expand_path(File.join(CURRENT_DIR, "..", "html"))
-
-module Rails
- def self.public_path
- CURRENT_DIR
- end
-end
-
-class ErrorPageController < ActionController::Base
- def crash
- raise StandardError, "crash!"
- end
-end
-
-ActionController::Routing::Routes.draw do |map|
- map.connect ':controller/:action/:id'
-end
-
-class ErrorPageControllerTest < ActionController::TestCase
- def setup
- ActionController::Base.consider_all_requests_local = false
- rescue_action_in_public!
- end
-
- def test_500_error_page_instructs_system_administrator_to_check_log_file
- template = ERB.new(File.read(File.join(HTML_DIR, "500.html")))
- File.open(File.join(CURRENT_DIR, "500.html"), "w") do |f|
- f.write(template.result)
- end
- get :crash
- expected_log_file = "#{RAILS_ENV}.log"
- assert_not_nil @response.body.index(expected_log_file), @response.body
- end
-end
diff --git a/railties/test/fcgi_dispatcher_test.rb b/railties/test/fcgi_dispatcher_test.rb
index c469c5dd01..c7a7f77118 100644
--- a/railties/test/fcgi_dispatcher_test.rb
+++ b/railties/test/fcgi_dispatcher_test.rb
@@ -1,9 +1,12 @@
require 'abstract_unit'
-begin
+uses_gem "fcgi", "0.8.7" do
+
require 'action_controller'
require 'fcgi_handler'
+Dispatcher.middleware.clear
+
class RailsFCGIHandlerTest < Test::Unit::TestCase
def setup
@log = StringIO.new
@@ -11,14 +14,14 @@ class RailsFCGIHandlerTest < Test::Unit::TestCase
end
def test_process_restart
- cgi = mock
- FCGI.stubs(:each_cgi).yields(cgi)
+ request = mock
+ FCGI.stubs(:each).yields(request)
@handler.expects(:process_request).once
@handler.expects(:dispatcher_error).never
@handler.expects(:when_ready).returns(:restart)
- @handler.expects(:close_connection).with(cgi)
+ @handler.expects(:close_connection).with(request)
@handler.expects(:reload!).never
@handler.expects(:restart!)
@@ -26,14 +29,14 @@ class RailsFCGIHandlerTest < Test::Unit::TestCase
end
def test_process_exit
- cgi = mock
- FCGI.stubs(:each_cgi).yields(cgi)
+ request = mock
+ FCGI.stubs(:each).yields(request)
@handler.expects(:process_request).once
@handler.expects(:dispatcher_error).never
@handler.expects(:when_ready).returns(:exit)
- @handler.expects(:close_connection).with(cgi)
+ @handler.expects(:close_connection).with(request)
@handler.expects(:reload!).never
@handler.expects(:restart!).never
@@ -41,8 +44,8 @@ class RailsFCGIHandlerTest < Test::Unit::TestCase
end
def test_process_with_system_exit_exception
- cgi = mock
- FCGI.stubs(:each_cgi).yields(cgi)
+ request = mock
+ FCGI.stubs(:each).yields(request)
@handler.expects(:process_request).once.raises(SystemExit)
@handler.stubs(:dispatcher_log)
@@ -110,9 +113,9 @@ class RailsFCGIHandlerTest < Test::Unit::TestCase
end
def test_uninterrupted_processing
- cgi = mock
- FCGI.expects(:each_cgi).yields(cgi)
- @handler.expects(:process_request).with(cgi)
+ request = mock
+ FCGI.expects(:each).yields(request)
+ @handler.expects(:process_request).with(request)
@handler.process!
@@ -138,8 +141,8 @@ class RailsFCGIHandlerSignalsTest < Test::Unit::TestCase
end
def test_interrupted_via_HUP_when_not_in_request
- cgi = mock
- FCGI.expects(:each_cgi).once.yields(cgi)
+ request = mock
+ FCGI.expects(:each).once.yields(request)
@handler.expects(:signal).times(2).returns('HUP')
@handler.expects(:reload!).once
@@ -151,13 +154,13 @@ class RailsFCGIHandlerSignalsTest < Test::Unit::TestCase
end
def test_interrupted_via_USR1_when_not_in_request
- cgi = mock
- FCGI.expects(:each_cgi).once.yields(cgi)
+ request = mock
+ FCGI.expects(:each).once.yields(request)
@handler.expects(:signal).times(2).returns('USR1')
@handler.expects(:exit_handler).never
@handler.expects(:reload!).never
- @handler.expects(:close_connection).with(cgi).once
+ @handler.expects(:close_connection).with(request).once
@handler.expects(:exit).never
@handler.process!
@@ -165,13 +168,13 @@ class RailsFCGIHandlerSignalsTest < Test::Unit::TestCase
end
def test_restart_via_USR2_when_in_request
- cgi = mock
- FCGI.expects(:each_cgi).once.yields(cgi)
+ request = mock
+ FCGI.expects(:each).once.yields(request)
@handler.expects(:signal).times(2).returns('USR2')
@handler.expects(:exit_handler).never
@handler.expects(:reload!).never
- @handler.expects(:close_connection).with(cgi).once
+ @handler.expects(:close_connection).with(request).once
@handler.expects(:exit).never
@handler.expects(:restart!).once
@@ -180,8 +183,8 @@ class RailsFCGIHandlerSignalsTest < Test::Unit::TestCase
end
def test_interrupted_via_TERM
- cgi = mock
- FCGI.expects(:each_cgi).once.yields(cgi)
+ request = mock
+ FCGI.expects(:each).once.yields(request)
::Rack::Handler::FastCGI.expects(:serve).once.returns('TERM')
@handler.expects(:reload!).never
@@ -193,16 +196,16 @@ class RailsFCGIHandlerSignalsTest < Test::Unit::TestCase
def test_runtime_exception_in_fcgi
error = RuntimeError.new('foo')
- FCGI.expects(:each_cgi).times(2).raises(error)
+ FCGI.expects(:each).times(2).raises(error)
@handler.expects(:dispatcher_error).with(error, regexp_matches(/^retrying/))
@handler.expects(:dispatcher_error).with(error, regexp_matches(/^stopping/))
@handler.process!
end
def test_runtime_error_in_dispatcher
- cgi = mock
+ request = mock
error = RuntimeError.new('foo')
- FCGI.expects(:each_cgi).once.yields(cgi)
+ FCGI.expects(:each).once.yields(request)
::Rack::Handler::FastCGI.expects(:serve).once.raises(error)
@handler.expects(:dispatcher_error).with(error, regexp_matches(/^unhandled/))
@handler.process!
@@ -210,15 +213,15 @@ class RailsFCGIHandlerSignalsTest < Test::Unit::TestCase
def test_signal_exception_in_fcgi
error = SignalException.new('USR2')
- FCGI.expects(:each_cgi).once.raises(error)
+ FCGI.expects(:each).once.raises(error)
@handler.expects(:dispatcher_error).with(error, regexp_matches(/^stopping/))
@handler.process!
end
def test_signal_exception_in_dispatcher
- cgi = mock
+ request = mock
error = SignalException.new('USR2')
- FCGI.expects(:each_cgi).once.yields(cgi)
+ FCGI.expects(:each).once.yields(request)
::Rack::Handler::FastCGI.expects(:serve).once.raises(error)
@handler.expects(:dispatcher_error).with(error, regexp_matches(/^stopping/))
@handler.process!
@@ -247,9 +250,8 @@ class RailsFCGIHandlerPeriodicGCTest < Test::Unit::TestCase
@handler = RailsFCGIHandler.new(@log, 10)
assert_equal 10, @handler.gc_request_period
- cgi = mock
- FCGI.expects(:each_cgi).times(10).yields(cgi)
- Dispatcher.expects(:new).times(10)
+ request = mock
+ FCGI.expects(:each).times(10).yields(request)
@handler.expects(:run_gc!).never
9.times { @handler.process! }
@@ -259,7 +261,4 @@ class RailsFCGIHandlerPeriodicGCTest < Test::Unit::TestCase
assert_nil @handler.when_ready
end
end
-
-rescue LoadError => e
- raise unless e.message =~ /fcgi/
-end
+end # uses_gem "fcgi"
diff --git a/railties/test/generators/rails_template_runner_test.rb b/railties/test/generators/rails_template_runner_test.rb
index fcc020603d..56afc85eba 100644
--- a/railties/test/generators/rails_template_runner_test.rb
+++ b/railties/test/generators/rails_template_runner_test.rb
@@ -53,12 +53,12 @@ class RailsTemplateRunnerTest < GeneratorTestCase
end
def test_plugin_with_git_option_should_run_plugin_install
- expects_run_with_command("script/plugin install #{@git_plugin_uri}")
+ expects_run_ruby_script_with_command("script/plugin install #{@git_plugin_uri}")
run_template_method(:plugin, 'restful-authentication', :git => @git_plugin_uri)
end
def test_plugin_with_svn_option_should_run_plugin_install
- expects_run_with_command("script/plugin install #{@svn_plugin_uri}")
+ expects_run_ruby_script_with_command("script/plugin install #{@svn_plugin_uri}")
run_template_method(:plugin, 'restful-authentication', :svn => @svn_plugin_uri)
end
@@ -127,7 +127,7 @@ class RailsTemplateRunnerTest < GeneratorTestCase
end
def test_generate_should_run_script_generate_with_argument_and_options
- expects_run_with_command('script/generate model MyModel')
+ expects_run_ruby_script_with_command('script/generate model MyModel')
run_template_method(:generate, 'model', 'MyModel')
end
@@ -162,6 +162,12 @@ class RailsTemplateRunnerTest < GeneratorTestCase
assert_generated_file_with_data 'config/routes.rb', route_command
end
+ def test_run_ruby_script_should_add_ruby_to_command_in_win32_environment
+ ruby_command = RUBY_PLATFORM =~ /win32/ ? 'ruby ' : ''
+ expects_run_with_command("#{ruby_command}script/generate model MyModel")
+ run_template_method(:generate, 'model', 'MyModel')
+ end
+
protected
def run_template_method(method_name, *args, &block)
silence_generator do
@@ -174,6 +180,10 @@ class RailsTemplateRunnerTest < GeneratorTestCase
Rails::TemplateRunner.any_instance.stubs(:run).once.with(command, false)
end
+ def expects_run_ruby_script_with_command(command)
+ Rails::TemplateRunner.any_instance.stubs(:run_ruby_script).once.with(command,false)
+ end
+
def assert_rails_initializer_includes(data, message = nil)
message ||= "Rails::Initializer should include #{data}"
assert_generated_file 'config/environment.rb' do |body|
diff --git a/railties/test/initializer_test.rb b/railties/test/initializer_test.rb
index 39372dc5ab..2ab4101eaf 100644
--- a/railties/test/initializer_test.rb
+++ b/railties/test/initializer_test.rb
@@ -238,6 +238,26 @@ class InitializerPluginLoadingTests < Test::Unit::TestCase
end
end
+ def test_load_error_messages_mention_missing_plugins_and_no_others
+ valid_plugin_names = [:stubby, :acts_as_chunky_bacon]
+ invalid_plugin_names = [:non_existant_plugin1, :non_existant_plugin2]
+ only_load_the_following_plugins!( valid_plugin_names + invalid_plugin_names )
+ begin
+ load_plugins!
+ flunk "Expected a LoadError but did not get one"
+ rescue LoadError => e
+ failure_tip = "It's likely someone renamed or deleted plugin fixtures without updating this test"
+ assert_plugins valid_plugin_names, @initializer.loaded_plugins, failure_tip
+ invalid_plugin_names.each do |plugin|
+ assert_match(/#{plugin.to_s}/, e.message, "LoadError message should mention plugin '#{plugin}'")
+ end
+ valid_plugin_names.each do |plugin|
+ assert_no_match(/#{plugin.to_s}/, e.message, "LoadError message should not mention '#{plugin}'")
+ end
+
+ end
+ end
+
def test_should_ensure_all_loaded_plugins_load_paths_are_added_to_the_load_path
only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon]
diff --git a/railties/test/plugin_loader_test.rb b/railties/test/plugin_loader_test.rb
index 23b81ddbf6..59491fe99e 100644
--- a/railties/test/plugin_loader_test.rb
+++ b/railties/test/plugin_loader_test.rb
@@ -130,7 +130,7 @@ class TestPluginLoader < Test::Unit::TestCase
@loader.send :add_engine_view_paths
- assert_equal [ File.join(plugin_fixture_path('engines/engine'), 'app', 'views') ], ActionController::Base.view_paths
+ assert_equal [ File.join(plugin_fixture_path('engines/engine'), 'app', 'views').sub(/\A\.\//, '') ], ActionController::Base.view_paths
end
def test_should_add_plugin_load_paths_to_Dependencies_load_once_paths