Skip to content
Browse files

Merge branch 'master' of git@github.com:rails/rails

  • Loading branch information...
2 parents 0a6d75d + 229eedf commit 0aef9d1a2651fa0acd2adcd2de308eeb0ec8cdd2 @technoweenie technoweenie committed
Showing with 3,280 additions and 2,214 deletions.
  1. +1 −0 .gitignore
  2. 0 actionmailer/README
  3. 0 actionmailer/Rakefile
  4. +6 −6 actionmailer/lib/action_mailer.rb
  5. +36 −31 actionmailer/lib/action_mailer/base.rb
  6. +2 −2 actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/address.rb
  7. +1 −1 actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/header.rb
  8. +1 −1 actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/interface.rb
  9. +2 −2 actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mail.rb
  10. +13 −5 actionmailer/test/abstract_unit.rb
  11. 0 actionmailer/test/fixtures/test_mailer/{signed_up.erb → signed_up.html.erb}
  12. +3 −9 actionmailer/test/mail_render_test.rb
  13. +14 −23 actionmailer/test/mail_service_test.rb
  14. +30 −0 actionpack/CHANGELOG
  15. +6 −12 actionpack/README
  16. +6 −9 actionpack/lib/action_controller.rb
  17. +2 −2 actionpack/lib/action_controller/assertions/response_assertions.rb
  18. +22 −22 actionpack/lib/action_controller/assertions/routing_assertions.rb
  19. +18 −14 actionpack/lib/action_controller/assertions/selector_assertions.rb
  20. +62 −43 actionpack/lib/action_controller/base.rb
  21. +2 −4 actionpack/lib/action_controller/caching/fragments.rb
  22. +3 −42 actionpack/lib/action_controller/cgi_process.rb
  23. +10 −0 actionpack/lib/action_controller/cookies.rb
  24. +10 −14 actionpack/lib/action_controller/dispatcher.rb
  25. +16 −3 actionpack/lib/action_controller/filters.rb
  26. +16 −14 actionpack/lib/action_controller/headers.rb
  27. +48 −52 actionpack/lib/action_controller/integration.rb
  28. +11 −5 actionpack/lib/action_controller/polymorphic_routes.rb
  29. +70 −86 actionpack/lib/action_controller/rack_process.rb
  30. +132 −72 actionpack/lib/action_controller/request.rb
  31. +1 −1 actionpack/lib/action_controller/request_forgery_protection.rb
  32. 0 actionpack/lib/action_controller/request_profiler.rb
  33. +17 −13 actionpack/lib/action_controller/rescue.rb
  34. +34 −29 actionpack/lib/action_controller/resources.rb
  35. +128 −23 actionpack/lib/action_controller/response.rb
  36. +28 −30 actionpack/lib/action_controller/routing.rb
  37. +21 −23 actionpack/lib/action_controller/routing/builder.rb
  38. +13 −12 actionpack/lib/action_controller/routing/optimisations.rb
  39. +17 −23 actionpack/lib/action_controller/routing/recognition_optimisation.rb
  40. +162 −147 actionpack/lib/action_controller/routing/route.rb
  41. +4 −3 actionpack/lib/action_controller/routing/route_set.rb
  42. +0 −1 actionpack/lib/action_controller/routing/routing_ext.rb
  43. +22 −15 actionpack/lib/action_controller/routing/segments.rb
  44. +1 −1 actionpack/lib/action_controller/session/cookie_store.rb
  45. +7 −7 actionpack/lib/action_controller/session/drb_server.rb
  46. +15 −8 actionpack/lib/action_controller/streaming.rb
  47. +2 −2 actionpack/lib/action_controller/templates/rescues/diagnostics.erb
  48. +2 −2 actionpack/lib/action_controller/templates/rescues/template_error.erb
  49. +62 −1 actionpack/lib/action_controller/test_case.rb
  50. +52 −39 actionpack/lib/action_controller/test_process.rb
  51. +90 −13 actionpack/lib/action_controller/url_rewriter.rb
  52. +2 −2 actionpack/lib/action_controller/vendor/html-scanner/html/selector.rb
  53. +16 −4 actionpack/lib/action_view.rb
  54. +35 −76 actionpack/lib/action_view/base.rb
  55. +39 −0 actionpack/lib/action_view/helpers.rb
  56. +50 −21 actionpack/lib/action_view/helpers/active_record_helper.rb
  57. +50 −46 actionpack/lib/action_view/helpers/asset_tag_helper.rb
  58. +13 −11 actionpack/lib/action_view/helpers/atom_feed_helper.rb
  59. +1 −1 actionpack/lib/action_view/helpers/cache_helper.rb
  60. +9 −8 actionpack/lib/action_view/helpers/capture_helper.rb
  61. +471 −293 actionpack/lib/action_view/helpers/date_helper.rb
  62. +20 −13 actionpack/lib/action_view/helpers/debug_helper.rb
  63. +92 −0 actionpack/lib/action_view/helpers/form_country_helper.rb
  64. +57 −16 actionpack/lib/action_view/helpers/form_helper.rb
  65. +1 −74 actionpack/lib/action_view/helpers/form_options_helper.rb
  66. +1 −1 actionpack/lib/action_view/helpers/form_tag_helper.rb
  67. +19 −2 actionpack/lib/action_view/helpers/javascript_helper.rb
  68. +150 −154 actionpack/lib/action_view/helpers/javascripts/prototype.js
  69. +179 −74 actionpack/lib/action_view/helpers/number_helper.rb
  70. +217 −199 actionpack/lib/action_view/helpers/prototype_helper.rb
  71. +55 −32 actionpack/lib/action_view/helpers/sanitize_helper.rb
  72. +1 −1 actionpack/lib/action_view/helpers/scriptaculous_helper.rb
  73. +13 −7 actionpack/lib/action_view/helpers/tag_helper.rb
  74. +148 −58 actionpack/lib/action_view/helpers/text_helper.rb
  75. +22 −0 actionpack/lib/action_view/helpers/translation_helper.rb
  76. +53 −46 actionpack/lib/action_view/helpers/url_helper.rb
  77. +91 −0 actionpack/lib/action_view/locale/en-US.yml
  78. +93 −47 actionpack/lib/action_view/partials.rb
  79. +58 −29 actionpack/lib/action_view/paths.rb
  80. +51 −32 actionpack/lib/action_view/renderable.rb
  81. +1 −1 actionpack/lib/action_view/renderable_partial.rb
  82. +16 −3 actionpack/lib/action_view/template.rb
  83. +1 −1 actionpack/lib/action_view/template_error.rb
  84. +8 −19 actionpack/lib/action_view/template_handler.rb
  85. +0 −1 actionpack/lib/action_view/template_handlers.rb
  86. +2 −8 actionpack/lib/action_view/template_handlers/builder.rb
  87. +0 −20 actionpack/lib/action_view/template_handlers/compilable.rb
  88. +4 −7 actionpack/lib/action_view/template_handlers/erb.rb
  89. +0 −11 actionpack/lib/action_view/template_handlers/rjs.rb
  90. +1 −3 actionpack/lib/action_view/test_case.rb
  91. +1 −1 actionpack/test/abstract_unit.rb
  92. +10 −0 actionpack/test/activerecord/render_partial_with_record_identification_test.rb
  93. +8 −25 actionpack/test/controller/assert_select_test.rb
Sorry, we could not display the entire diff because too many files (408) changed.
View
1 .gitignore
@@ -12,4 +12,5 @@ actionpack/pkg
actionmailer/pkg
activesupport/pkg
railties/pkg
+railties/test/500.html
*.rbc
View
0 actionmailer/README 100755 → 100644
File mode changed.
View
0 actionmailer/Rakefile 100755 → 100644
File mode changed.
View
12 actionmailer/lib/action_mailer.rb 100755 → 100644
@@ -21,13 +21,13 @@
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
-unless defined?(ActionController)
- begin
- $:.unshift "#{File.dirname(__FILE__)}/../../actionpack/lib"
+begin
+ require 'action_controller'
+rescue LoadError
+ actionpack_path = "#{File.dirname(__FILE__)}/../../actionpack/lib"
+ if File.directory?(actionpack_path)
+ $:.unshift actionpack_path
require 'action_controller'
- rescue LoadError
- require 'rubygems'
- gem 'actionpack', '>= 1.12.5'
end
end
View
67 actionmailer/lib/action_mailer/base.rb
@@ -216,7 +216,7 @@ module ActionMailer #:nodoc:
# * <tt>:domain</tt> - If you need to specify a HELO domain, you can do it here.
# * <tt>:user_name</tt> - If your mail server requires authentication, set the username in this setting.
# * <tt>:password</tt> - If your mail server requires authentication, set the password in this setting.
- # * <tt>:authentication</tt> - If your mail server requires authentication, you need to specify the authentication type here.
+ # * <tt>:authentication</tt> - If your mail server requires authentication, you need to specify the authentication type here.
# This is a symbol and one of <tt>:plain</tt>, <tt>:login</tt>, <tt>:cram_md5</tt>.
#
# * <tt>sendmail_settings</tt> - Allows you to override options for the <tt>:sendmail</tt> delivery method.
@@ -233,10 +233,10 @@ module ActionMailer #:nodoc:
# * <tt>deliveries</tt> - Keeps an array of all the emails sent out through the Action Mailer with <tt>delivery_method :test</tt>. Most useful
# for unit and functional testing.
#
- # * <tt>default_charset</tt> - The default charset used for the body and to encode the subject. Defaults to UTF-8. You can also
+ # * <tt>default_charset</tt> - The default charset used for the body and to encode the subject. Defaults to UTF-8. You can also
# pick a different charset from inside a method with +charset+.
# * <tt>default_content_type</tt> - The default content type used for the main part of the message. Defaults to "text/plain". You
- # can also pick a different content type from inside a method with +content_type+.
+ # can also pick a different content type from inside a method with +content_type+.
# * <tt>default_mime_version</tt> - The default mime version used for the message. Defaults to <tt>1.0</tt>. You
# can also pick a different value from inside a method with +mime_version+.
# * <tt>default_implicit_parts_order</tt> - When a message is built implicitly (i.e. multiple parts are assembled from templates
@@ -250,12 +250,9 @@ class Base
private_class_method :new #:nodoc:
- class_inheritable_accessor :template_root
+ class_inheritable_accessor :view_paths
cattr_accessor :logger
- cattr_accessor :template_extensions
- @@template_extensions = ['erb', 'builder', 'rhtml', 'rxml']
-
@@smtp_settings = {
:address => "localhost",
:port => 25,
@@ -414,19 +411,18 @@ def deliver(mail)
new.deliver!(mail)
end
- # Register a template extension so mailer templates written in a
- # templating language other than rhtml or rxml are supported.
- # To use this, include in your template-language plugin's init
- # code or on a per-application basis, this can be invoked from
- # <tt>config/environment.rb</tt>:
- #
- # ActionMailer::Base.register_template_extension('haml')
def register_template_extension(extension)
- template_extensions << extension
+ ActiveSupport::Deprecation.warn(
+ "ActionMailer::Base.register_template_extension has been deprecated." +
+ "Use ActionView::Base.register_template_extension instead", caller)
+ end
+
+ def template_root
+ self.view_paths && self.view_paths.first
end
def template_root=(root)
- write_inheritable_attribute(:template_root, ActionView::PathSet.new(Array(root)))
+ self.view_paths = ActionView::Base.process_view_paths(root)
end
end
@@ -451,16 +447,18 @@ def create!(method_name, *parameters) #:nodoc:
# "the_template_file.text.html.erb", etc.). Only do this if parts
# have not already been specified manually.
if @parts.empty?
- templates = Dir.glob("#{template_path}/#{@template}.*")
- templates.each do |path|
- basename = File.basename(path)
- template_regex = Regexp.new("^([^\\\.]+)\\\.([^\\\.]+\\\.[^\\\.]+)\\\.(" + template_extensions.join('|') + ")$")
- next unless md = template_regex.match(basename)
- template_name = basename
- content_type = md.captures[1].gsub('.', '/')
- @parts << Part.new(:content_type => content_type,
- :disposition => "inline", :charset => charset,
- :body => render_message(template_name, @body))
+ Dir.glob("#{template_path}/#{@template}.*").each do |path|
+ template = template_root["#{mailer_name}/#{File.basename(path)}"]
+
+ # Skip unless template has a multipart format
+ next unless template.multipart?
+
+ @parts << Part.new(
+ :content_type => template.content_type,
+ :disposition => "inline",
+ :charset => charset,
+ :body => render_message(template, @body)
+ )
end
unless @parts.empty?
@content_type = "multipart/alternative"
@@ -473,7 +471,7 @@ def create!(method_name, *parameters) #:nodoc:
# normal template exists (or if there were no implicit parts) we render
# it.
template_exists = @parts.empty?
- template_exists ||= Dir.glob("#{template_path}/#{@template}.*").any? { |i| File.basename(i).split(".").length == 2 }
+ template_exists ||= template_root["#{mailer_name}/#{@template}"]
@body = render_message(@template, @body) if template_exists
# Finally, if there are other message parts and a textual body exists,
@@ -529,24 +527,31 @@ def initialize_defaults(method_name)
end
def render_message(method_name, body)
- render :file => method_name, :body => body, :use_full_path => true
+ render :file => method_name, :body => body
end
def render(opts)
body = opts.delete(:body)
- if opts[:file] && opts[:file] !~ /\//
+ if opts[:file] && (opts[:file] !~ /\// && !opts[:file].respond_to?(:render))
opts[:file] = "#{mailer_name}/#{opts[:file]}"
end
- opts[:use_full_path] = true
initialize_template_class(body).render(opts)
end
+ def template_root
+ self.class.template_root
+ end
+
+ def template_root=(root)
+ self.class.template_root = root
+ end
+
def template_path
"#{template_root}/#{mailer_name}"
end
def initialize_template_class(assigns)
- ActionView::Base.new(template_root, assigns, self)
+ ActionView::Base.new(view_paths, assigns, self)
end
def sort_parts(parts, order = [])
View
4 actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/address.rb
@@ -38,7 +38,7 @@ module TMail
# = Class Address
#
# Provides a complete handling library for email addresses. Can parse a string of an
- # address directly or take in preformatted addresses themseleves. Allows you to add
+ # address directly or take in preformatted addresses themselves. Allows you to add
# and remove phrases from the front of the address and provides a compare function for
# email addresses.
#
@@ -143,7 +143,7 @@ def initialize( local, domain )
# This is to catch an unquoted "@" symbol in the local part of the
# address. Handles addresses like <"@"@me.com> and makes sure they
- # stay like <"@"@me.com> (previously were becomming <@@me.com>)
+ # stay like <"@"@me.com> (previously were becoming <@@me.com>)
if local && (local.join == '@' || local.join =~ /\A[^"].*?@.*?[^"]\Z/)
@local = "\"#{local.join}\""
else
View
2 actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/header.rb
@@ -59,7 +59,7 @@ def new( name, body, conf = DEFAULT_CONFIG )
#
# This is because a mailbox doesn't have the : after the From that designates the
# beginning of the envelope sender (which can be different to the from address of
- # the emial)
+ # the email)
#
# Other fields can be passed as normal, "Reply-To", "Received" etc.
#
View
2 actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/interface.rb
@@ -42,7 +42,7 @@ class Mail
# Allows you to query the mail object with a string to get the contents
# of the field you want.
#
- # Returns a string of the exact contnts of the field
+ # Returns a string of the exact contents of the field
#
# mail.from = "mikel <mikel@lindsaar.net>"
# mail.header_string("From") #=> "mikel <mikel@lindsaar.net>"
View
4 actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mail.rb
@@ -255,7 +255,7 @@ def sub_header(key, param)
alias fetch []
# Allows you to set or delete TMail header objects at will.
- # Eamples:
+ # Examples:
# @mail = TMail::Mail.new
# @mail['to'].to_s # => 'mikel@test.com.au'
# @mail['to'] = 'mikel@elsewhere.org'
@@ -265,7 +265,7 @@ def sub_header(key, param)
# @mail['to'].to_s # => nil
# @mail.encoded # => "\r\n"
#
- # Note: setting mail[] = nil actualy deletes the header field in question from the object,
+ # Note: setting mail[] = nil actually deletes the header field in question from the object,
# it does not just set the value of the hash to nil
def []=( key, val )
dkey = key.downcase
View
18 actionmailer/test/abstract_unit.rb
@@ -30,12 +30,20 @@ def self.start(*args)
end
end
-# Wrap tests that use Mocha and skip if unavailable.
-def uses_mocha(test_name)
- gem 'mocha', ">=0.9.0"
+def uses_gem(gem_name, test_name, version = '> 0')
+ require 'rubygems'
+ gem gem_name.to_s, version
+ require gem_name.to_s
yield
-rescue Gem::LoadError
- $stderr.puts "Skipping #{test_name} tests (Mocha >= 0.5 is required). `gem install mocha` and try again."
+rescue LoadError
+ $stderr.puts "Skipping #{test_name} tests. `gem install #{gem_name}` and try again."
+end
+
+# Wrap tests that use Mocha and skip if unavailable.
+unless defined? uses_mocha
+ def uses_mocha(test_name, &block)
+ uses_gem('mocha', test_name, '>= 0.5.5', &block)
+ end
end
def set_delivery_method(delivery_method)
View
0 ...r/test/fixtures/test_mailer/signed_up.erb → ...t/fixtures/test_mailer/signed_up.html.erb
File renamed without changes.
View
12 actionmailer/test/mail_render_test.rb
@@ -20,13 +20,13 @@ def rxml_template(recipient)
subject "rendering rxml template"
from "tester@example.com"
end
-
+
def included_subtemplate(recipient)
recipients recipient
subject "Including another template in the one being rendered"
from "tester@example.com"
end
-
+
def included_old_subtemplate(recipient)
recipients recipient
subject "Including another template in the one being rendered"
@@ -83,17 +83,11 @@ def test_rxml_template
mail = RenderMailer.deliver_rxml_template(@recipient)
assert_equal "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<test/>", mail.body.strip
end
-
+
def test_included_subtemplate
mail = RenderMailer.deliver_included_subtemplate(@recipient)
assert_equal "Hey Ho, let's go!", mail.body.strip
end
-
- def test_deprecated_old_subtemplate
- assert_raises ActionView::ActionViewError do
- RenderMailer.deliver_included_old_subtemplate(@recipient)
- end
- end
end
class FirstSecondHelperTest < Test::Unit::TestCase
View
37 actionmailer/test/mail_service_test.rb 100755 → 100644
@@ -219,7 +219,7 @@ def nested_multipart(recipient)
end
attachment :content_type => "application/octet-stream",:filename => "test.txt", :body => "test abcdefghijklmnopqstuvwxyz"
end
-
+
def nested_multipart_with_body(recipient)
recipients recipient
subject "nested multipart with body"
@@ -321,7 +321,7 @@ def test_nested_parts
assert_nothing_raised { created = TestMailer.create_nested_multipart(@recipient)}
assert_equal 2,created.parts.size
assert_equal 2,created.parts.first.parts.size
-
+
assert_equal "multipart/mixed", created.content_type
assert_equal "multipart/alternative", created.parts.first.content_type
assert_equal "bar", created.parts.first.header['foo'].to_s
@@ -366,7 +366,7 @@ def test_signed_up
assert_not_nil ActionMailer::Base.deliveries.first
assert_equal expected.encoded, ActionMailer::Base.deliveries.first.encoded
end
-
+
def test_custom_template
expected = new_mail
expected.to = @recipient
@@ -382,7 +382,6 @@ def test_custom_template
end
def test_custom_templating_extension
- #
# N.b., custom_templating_extension.text.plain.haml is expected to be in fixtures/test_mailer directory
expected = new_mail
expected.to = @recipient
@@ -390,18 +389,10 @@ def test_custom_templating_extension
expected.body = "Hello there, \n\nMr. #{@recipient}"
expected.from = "system@loudthinking.com"
expected.date = Time.local(2004, 12, 12)
-
+
# Stub the render method so no alternative renderers need be present.
ActionView::Base.any_instance.stubs(:render).returns("Hello there, \n\nMr. #{@recipient}")
-
- # If the template is not registered, there should be no parts.
- created = nil
- assert_nothing_raised { created = TestMailer.create_custom_templating_extension(@recipient) }
- assert_not_nil created
- assert_equal 0, created.parts.length
-
- ActionMailer::Base.register_template_extension('haml')
-
+
# Now that the template is registered, there should be one part. The text/plain part.
created = nil
assert_nothing_raised { created = TestMailer.create_custom_templating_extension(@recipient) }
@@ -428,7 +419,7 @@ def test_cancelled_account
assert_not_nil ActionMailer::Base.deliveries.first
assert_equal expected.encoded, ActionMailer::Base.deliveries.first.encoded
end
-
+
def test_cc_bcc
expected = new_mail
expected.to = @recipient
@@ -550,7 +541,7 @@ def test_perform_deliveries_flag
TestMailer.deliver_signed_up(@recipient)
assert_equal 1, ActionMailer::Base.deliveries.size
end
-
+
def test_doesnt_raise_errors_when_raise_delivery_errors_is_false
ActionMailer::Base.raise_delivery_errors = false
TestMailer.any_instance.expects(:perform_delivery_test).raises(Exception)
@@ -670,7 +661,7 @@ def test_extended_headers
assert_not_nil ActionMailer::Base.deliveries.first
assert_equal expected.encoded, ActionMailer::Base.deliveries.first.encoded
end
-
+
def test_utf8_body_is_not_quoted
@recipient = "Foo áëô îü <extended@example.net>"
expected = new_mail "utf-8"
@@ -760,7 +751,7 @@ def test_multipart_with_mime_version
mail = TestMailer.create_multipart_with_mime_version(@recipient)
assert_equal "1.1", mail.mime_version
end
-
+
def test_multipart_with_utf8_subject
mail = TestMailer.create_multipart_with_utf8_subject(@recipient)
assert_match(/\nSubject: =\?utf-8\?Q\?Foo_.*?\?=/, mail.encoded)
@@ -825,7 +816,7 @@ def test_implicitly_multipart_messages_with_charset
mail = TestMailer.create_implicitly_multipart_example(@recipient, 'iso-8859-1')
assert_equal "multipart/alternative", mail.header['content-type'].body
-
+
assert_equal 'iso-8859-1', mail.parts[0].sub_header("content-type", "charset")
assert_equal 'iso-8859-1', mail.parts[1].sub_header("content-type", "charset")
assert_equal 'iso-8859-1', mail.parts[2].sub_header("content-type", "charset")
@@ -852,7 +843,7 @@ def test_various_newlines_multipart
assert_equal "line #1\nline #2\nline #3\nline #4\n\n", mail.parts[0].body
assert_equal "<p>line #1</p>\n<p>line #2</p>\n<p>line #3</p>\n<p>line #4</p>\n\n", mail.parts[1].body
end
-
+
def test_headers_removed_on_smtp_delivery
ActionMailer::Base.delivery_method = :smtp
TestMailer.deliver_cc_bcc(@recipient)
@@ -942,13 +933,13 @@ def test_return_path_with_deliver
class InheritableTemplateRootTest < Test::Unit::TestCase
def test_attr
expected = "#{File.dirname(__FILE__)}/fixtures/path.with.dots"
- assert_equal [expected], FunkyPathMailer.template_root.map(&:to_s)
+ assert_equal expected, FunkyPathMailer.template_root
sub = Class.new(FunkyPathMailer)
sub.template_root = 'test/path'
- assert_equal ['test/path'], sub.template_root.map(&:to_s)
- assert_equal [expected], FunkyPathMailer.template_root.map(&:to_s)
+ assert_equal 'test/path', sub.template_root
+ assert_equal expected, FunkyPathMailer.template_root
end
end
View
30 actionpack/CHANGELOG
@@ -1,5 +1,35 @@
*Edge*
+* Allow polymorphic_url helper to take url options. #880 [Tarmo Tänav]
+
+* Switched integration test runner to use Rack processor instead of CGI [Josh Peek]
+
+* Made AbstractRequest.if_modified_sense return nil if the header could not be parsed [Jamis Buck]
+
+* Added back ActionController::Base.allow_concurrency flag [Josh Peek]
+
+* AbstractRequest.relative_url_root is no longer automatically configured by a HTTP header. It can now be set in your configuration environment with config.action_controller.relative_url_root [Josh Peek]
+
+* Update Prototype to 1.6.0.2 #599 [Patrick Joyce]
+
+* Conditional GET utility methods. [Jeremy Kemper]
+ response.last_modified = @post.updated_at
+ response.etag = [:admin, @post, current_user]
+
+ if request.fresh?(response)
+ head :not_modified
+ else
+ # render ...
+ end
+
+* All 2xx requests are considered successful [Josh Peek]
+
+* Fixed that AssetTagHelper#compute_public_path shouldn't cache the asset_host along with the source or per-request proc's won't run [DHH]
+
+* Removed config.action_view.cache_template_loading, use config.cache_classes instead [Josh Peek]
+
+* Get buffer for fragment cache from template's @output_buffer [Josh Peek]
+
* Set config.action_view.warn_cache_misses = true to receive a warning if you perform an action that results in an expensive disk operation that could be cached [Josh Peek]
* Refactor template preloading. New abstractions include Renderable mixins and a refactored Template class [Josh Peek]
View
18 actionpack/README
@@ -31,7 +31,7 @@ http://www.rubyonrails.org.
A short rundown of the major features:
* Actions grouped in controller as methods instead of separate command objects
- and can therefore share helper methods.
+ and can therefore share helper methods
BlogController < ActionController::Base
def show
@@ -168,7 +168,7 @@ A short rundown of the major features:
{Learn more}[link:classes/ActionController/Base.html]
-* Javascript and Ajax integration.
+* Javascript and Ajax integration
link_to_function "Greeting", "alert('Hello world!')"
link_to_remote "Delete this post", :update => "posts",
@@ -177,7 +177,7 @@ A short rundown of the major features:
{Learn more}[link:classes/ActionView/Helpers/JavaScriptHelper.html]
-* Pagination for navigating lists of results.
+* Pagination for navigating lists of results
# controller
def list
@@ -192,15 +192,9 @@ A short rundown of the major features:
{Learn more}[link:classes/ActionController/Pagination.html]
-* Easy testing of both controller and template result through TestRequest/Response
-
- class LoginControllerTest < Test::Unit::TestCase
- def setup
- @controller = LoginController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- end
+* Easy testing of both controller and rendered template through ActionController::TestCase
+ class LoginControllerTest < ActionController::TestCase
def test_failing_authenticate
process :authenticate, :user_name => "nop", :password => ""
assert flash.has_key?(:alert)
@@ -208,7 +202,7 @@ A short rundown of the major features:
end
end
- {Learn more}[link:classes/ActionController/TestRequest.html]
+ {Learn more}[link:classes/ActionController/TestCase.html]
* Automated benchmarking and integrated logging
View
15 actionpack/lib/action_controller.rb 100755 → 100644
@@ -21,16 +21,13 @@
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
-$:.unshift(File.dirname(__FILE__)) unless
- $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))
-
-unless defined?(ActiveSupport)
- begin
- $:.unshift "#{File.dirname(__FILE__)}/../../activesupport/lib"
+begin
+ require 'active_support'
+rescue LoadError
+ activesupport_path = "#{File.dirname(__FILE__)}/../../activesupport/lib"
+ if File.directory?(activesupport_path)
+ $:.unshift activesupport_path
require 'active_support'
- rescue LoadError
- require 'rubygems'
- gem 'activesupport'
end
end
View
4 actionpack/lib/action_controller/assertions/response_assertions.rb
@@ -87,11 +87,11 @@ def assert_redirected_to(options = {}, message=nil)
#
def assert_template(expected = nil, message=nil)
clean_backtrace do
- rendered = @response.rendered_template
+ rendered = @response.rendered_template.to_s
msg = build_message(message, "expecting <?> but rendering with <?>", expected, rendered)
assert_block(msg) do
if expected.nil?
- @response.rendered_template.nil?
+ @response.rendered_template.blank?
else
rendered.to_s.match(expected)
end
View
44 actionpack/lib/action_controller/assertions/routing_assertions.rb
@@ -2,7 +2,7 @@ module ActionController
module Assertions
# Suite of assertions to test routes generated by Rails and the handling of requests made to them.
module RoutingAssertions
- # Asserts that the routing of the given +path+ was handled correctly and that the parsed options (given in the +expected_options+ hash)
+ # Asserts that the routing of the given +path+ was handled correctly and that the parsed options (given in the +expected_options+ hash)
# match +path+. Basically, it asserts that Rails recognizes the route given by +expected_options+.
#
# Pass a hash in the second argument (+path+) to specify the request method. This is useful for routes
@@ -14,16 +14,16 @@ module RoutingAssertions
#
# You can also pass in +extras+ with a hash containing URL parameters that would normally be in the query string. This can be used
# to assert that values in the query string string will end up in the params hash correctly. To test query strings you must use the
- # extras argument, appending the query string on the path directly will not work. For example:
+ # extras argument, appending the query string on the path directly will not work. For example:
#
# # assert that a path of '/items/list/1?view=print' returns the correct options
- # assert_recognizes({:controller => 'items', :action => 'list', :id => '1', :view => 'print'}, 'items/list/1', { :view => "print" })
+ # assert_recognizes({:controller => 'items', :action => 'list', :id => '1', :view => 'print'}, 'items/list/1', { :view => "print" })
#
- # The +message+ parameter allows you to pass in an error message that is displayed upon failure.
+ # The +message+ parameter allows you to pass in an error message that is displayed upon failure.
#
# ==== Examples
# # Check the default route (i.e., the index action)
- # assert_recognizes({:controller => 'items', :action => 'index'}, 'items')
+ # assert_recognizes({:controller => 'items', :action => 'index'}, 'items')
#
# # Test a specific action
# assert_recognizes({:controller => 'items', :action => 'list'}, 'items/list')
@@ -44,16 +44,16 @@ def assert_recognizes(expected_options, path, extras={}, message=nil)
request_method = nil
end
- clean_backtrace do
- ActionController::Routing::Routes.reload if ActionController::Routing::Routes.empty?
+ clean_backtrace do
+ ActionController::Routing::Routes.reload if ActionController::Routing::Routes.empty?
request = recognized_request_for(path, request_method)
-
+
expected_options = expected_options.clone
extras.each_key { |key| expected_options.delete key } unless extras.nil?
-
+
expected_options.stringify_keys!
routing_diff = expected_options.diff(request.path_parameters)
- msg = build_message(message, "The recognized options <?> did not match <?>, difference: <?>",
+ msg = build_message(message, "The recognized options <?> did not match <?>, difference: <?>",
request.path_parameters, expected_options, expected_options.diff(request.path_parameters))
assert_block(msg) { request.path_parameters == expected_options }
end
@@ -64,7 +64,7 @@ def assert_recognizes(expected_options, path, extras={}, message=nil)
# a query string. The +message+ parameter allows you to specify a custom error message for assertion failures.
#
# The +defaults+ parameter is unused.
- #
+ #
# ==== Examples
# # Asserts that the default action is generated for a route with no action
# assert_generates("/items", :controller => "items", :action => "index")
@@ -73,34 +73,34 @@ def assert_recognizes(expected_options, path, extras={}, message=nil)
# assert_generates("/items/list", :controller => "items", :action => "list")
#
# # Tests the generation of a route with a parameter
- # assert_generates("/items/list/1", { :controller => "items", :action => "list", :id => "1" })
+ # assert_generates("/items/list/1", { :controller => "items", :action => "list", :id => "1" })
#
# # Asserts that the generated route gives us our custom route
# assert_generates "changesets/12", { :controller => 'scm', :action => 'show_diff', :revision => "12" }
def assert_generates(expected_path, options, defaults={}, extras = {}, message=nil)
- clean_backtrace do
+ clean_backtrace do
expected_path = "/#{expected_path}" unless expected_path[0] == ?/
# Load routes.rb if it hasn't been loaded.
- ActionController::Routing::Routes.reload if ActionController::Routing::Routes.empty?
-
+ ActionController::Routing::Routes.reload if ActionController::Routing::Routes.empty?
+
generated_path, extra_keys = ActionController::Routing::Routes.generate_extras(options, defaults)
found_extras = options.reject {|k, v| ! extra_keys.include? k}
msg = build_message(message, "found extras <?>, not <?>", found_extras, extras)
assert_block(msg) { found_extras == extras }
-
- msg = build_message(message, "The generated path <?> did not match <?>", generated_path,
+
+ msg = build_message(message, "The generated path <?> did not match <?>", generated_path,
expected_path)
assert_block(msg) { expected_path == generated_path }
end
end
- # Asserts that path and options match both ways; in other words, it verifies that <tt>path</tt> generates
+ # Asserts that path and options match both ways; in other words, it verifies that <tt>path</tt> generates
# <tt>options</tt> and then that <tt>options</tt> generates <tt>path</tt>. This essentially combines +assert_recognizes+
# and +assert_generates+ into one step.
#
# The +extras+ hash allows you to specify options that would normally be provided as a query string to the action. The
- # +message+ parameter allows you to specify a custom error message to display upon failure.
+ # +message+ parameter allows you to specify a custom error message to display upon failure.
#
# ==== Examples
# # Assert a basic route: a controller with the default action (index)
@@ -119,12 +119,12 @@ def assert_generates(expected_path, options, defaults={}, extras = {}, message=n
# assert_routing({ :method => 'put', :path => '/product/321' }, { :controller => "product", :action => "update", :id => "321" })
def assert_routing(path, options, defaults={}, extras={}, message=nil)
assert_recognizes(options, path, extras, message)
-
- controller, default_controller = options[:controller], defaults[:controller]
+
+ controller, default_controller = options[:controller], defaults[:controller]
if controller && controller.include?(?/) && default_controller && default_controller.include?(?/)
options[:controller] = "/#{controller}"
end
-
+
assert_generates(path.is_a?(Hash) ? path[:path] : path, options, defaults, extras, message)
end
View
32 actionpack/lib/action_controller/assertions/selector_assertions.rb
@@ -21,10 +21,8 @@ module Assertions
# from the response HTML or elements selected by the enclosing assertion.
#
# In addition to HTML responses, you can make the following assertions:
- # * +assert_select_rjs+ - Assertions on HTML content of RJS update and
- # insertion operations.
- # * +assert_select_encoded+ - Assertions on HTML encoded inside XML,
- # for example for dealing with feed item descriptions.
+ # * +assert_select_rjs+ - Assertions on HTML content of RJS update and insertion operations.
+ # * +assert_select_encoded+ - Assertions on HTML encoded inside XML, for example for dealing with feed item descriptions.
# * +assert_select_email+ - Assertions on the HTML body of an e-mail.
#
# Also see HTML::Selector to learn how to use selectors.
@@ -409,6 +407,7 @@ def assert_select_rjs(*args, &block)
if rjs_type == :insert
arg = args.shift
+ position = arg
insertion = "insert_#{arg}".to_sym
raise ArgumentError, "Unknown RJS insertion type #{arg}" unless RJS_STATEMENTS[insertion]
statement = "(#{RJS_STATEMENTS[insertion]})"
@@ -420,6 +419,7 @@ def assert_select_rjs(*args, &block)
else
statement = "#{RJS_STATEMENTS[:any]}"
end
+ position ||= Regexp.new(RJS_INSERTIONS.join('|'))
# Next argument we're looking for is the element identifier. If missing, we pick
# any element.
@@ -436,9 +436,14 @@ def assert_select_rjs(*args, &block)
Regexp.new("\\$\\(\"#{id}\"\\)#{statement}\\(#{RJS_PATTERN_HTML}\\)", Regexp::MULTILINE)
when :remove, :show, :hide, :toggle
Regexp.new("#{statement}\\(\"#{id}\"\\)")
- else
- Regexp.new("#{statement}\\(\"#{id}\", #{RJS_PATTERN_HTML}\\)", Regexp::MULTILINE)
- end
+ when :replace, :replace_html
+ Regexp.new("#{statement}\\(\"#{id}\", #{RJS_PATTERN_HTML}\\)")
+ when :insert, :insert_html
+ Regexp.new("Element.insert\\(\\\"#{id}\\\", \\{ #{position}: #{RJS_PATTERN_HTML} \\}\\);")
+ else
+ Regexp.union(Regexp.new("#{statement}\\(\"#{id}\", #{RJS_PATTERN_HTML}\\)"),
+ Regexp.new("Element.insert\\(\\\"#{id}\\\", \\{ #{position}: #{RJS_PATTERN_HTML} \\}\\);"))
+ end
# Duplicate the body since the next step involves destroying it.
matches = nil
@@ -447,7 +452,7 @@ def assert_select_rjs(*args, &block)
matches = @response.body.match(pattern)
else
@response.body.gsub(pattern) do |match|
- html = unescape_rjs($2)
+ html = unescape_rjs(match)
matches ||= []
matches.concat HTML::Document.new(html).root.children.select { |n| n.tag? }
""
@@ -587,17 +592,16 @@ def assert_select_email(&block)
:hide => /Element\.hide/,
:toggle => /Element\.toggle/
}
+ RJS_STATEMENTS[:any] = Regexp.new("(#{RJS_STATEMENTS.values.join('|')})")
+ RJS_PATTERN_HTML = /"((\\"|[^"])*)"/
RJS_INSERTIONS = [:top, :bottom, :before, :after]
RJS_INSERTIONS.each do |insertion|
- RJS_STATEMENTS["insert_#{insertion}".to_sym] = Regexp.new(Regexp.quote("new Insertion.#{insertion.to_s.camelize}"))
+ RJS_STATEMENTS["insert_#{insertion}".to_sym] = /Element.insert\(\"([^\"]*)\", \{ #{insertion.to_s.downcase}: #{RJS_PATTERN_HTML} \}\);/
end
- RJS_STATEMENTS[:any] = Regexp.new("(#{RJS_STATEMENTS.values.join('|')})")
RJS_STATEMENTS[:insert_html] = Regexp.new(RJS_INSERTIONS.collect do |insertion|
- Regexp.quote("new Insertion.#{insertion.to_s.camelize}")
+ /Element.insert\(\"([^\"]*)\", \{ #{insertion.to_s.downcase}: #{RJS_PATTERN_HTML} \}\);/
end.join('|'))
- RJS_PATTERN_HTML = /"((\\"|[^"])*)"/
- RJS_PATTERN_EVERYTHING = Regexp.new("#{RJS_STATEMENTS[:any]}\\(\"([^\"]*)\", #{RJS_PATTERN_HTML}\\)",
- Regexp::MULTILINE)
+ RJS_PATTERN_EVERYTHING = Regexp.new("#{RJS_STATEMENTS[:any]}\\(\"([^\"]*)\", #{RJS_PATTERN_HTML}\\)", Regexp::MULTILINE)
RJS_PATTERN_UNICODE_ESCAPED_CHAR = /\\u([0-9a-zA-Z]{4})/
end
View
105 actionpack/lib/action_controller/base.rb 100755 → 100644
@@ -283,6 +283,14 @@ class Base
@@debug_routes = true
cattr_accessor :debug_routes
+ # Indicates whether to allow concurrent action processing. Your
+ # controller actions and any other code they call must also behave well
+ # when called from concurrent threads. Turned off by default.
+ @@allow_concurrency = false
+ cattr_accessor :allow_concurrency
+
+ @@guard = Monitor.new
+
# Modern REST web services often need to submit complex data to the web application.
# The <tt>@@param_parsers</tt> hash lets you register handlers which will process the HTTP body and add parameters to the
# <tt>params</tt> hash. These handlers are invoked for POST and PUT requests.
@@ -354,6 +362,15 @@ class Base
class_inheritable_accessor :allow_forgery_protection
self.allow_forgery_protection = true
+ # If you are deploying to a subdirectory, you will need to set
+ # <tt>config.action_controller.relative_url_root</tt>
+ # This defaults to ENV['RAILS_RELATIVE_URL_ROOT']
+ cattr_writer :relative_url_root
+
+ def self.relative_url_root
+ @@relative_url_root || ENV['RAILS_RELATIVE_URL_ROOT']
+ end
+
# Holds the request object that's primarily used to get environment variables through access like
# <tt>request.env["REQUEST_URI"]</tt>.
attr_internal :request
@@ -411,11 +428,7 @@ def controller_path
# By default, all methods defined in ActionController::Base and included modules are hidden.
# More methods can be hidden using <tt>hide_actions</tt>.
def hidden_actions
- unless read_inheritable_attribute(:hidden_actions)
- write_inheritable_attribute(:hidden_actions, ActionController::Base.public_instance_methods.map { |m| m.to_s })
- end
-
- read_inheritable_attribute(:hidden_actions)
+ read_inheritable_attribute(:hidden_actions) || write_inheritable_attribute(:hidden_actions, [])
end
# Hide each of the given methods from being callable as actions.
@@ -519,6 +532,8 @@ def exempt_from_layout(*extensions)
public
# Extracts the action_name from the request parameters and performs that action.
def process(request, response, method = :perform_action, *arguments) #:nodoc:
+ response.request = request
+
initialize_template_class(response)
assign_shortcuts(request, response)
initialize_current_url
@@ -526,11 +541,13 @@ def process(request, response, method = :perform_action, *arguments) #:nodoc:
forget_variables_added_to_assigns
log_processing
- send(method, *arguments)
- assign_default_content_type_and_charset
+ if @@allow_concurrency
+ send(method, *arguments)
+ else
+ @@guard.synchronize { send(method, *arguments) }
+ end
- response.request = request
response.prepare! unless component_request?
response
ensure
@@ -763,9 +780,6 @@ def append_view_path(path)
# render :file => "/path/to/some/template.erb", :layout => true, :status => 404
# render :file => "c:/path/to/some/template.erb", :layout => true, :status => 404
#
- # # Renders a template relative to the template root and chooses the proper file extension
- # render :file => "some/template", :use_full_path => true
- #
# === Rendering text
#
# Rendering of text is usually used for tests or for rendering prepared content, such as a cache. By default, text
@@ -896,21 +910,10 @@ def render(options = nil, extra_options = {}, &block) #:doc:
response.content_type ||= Mime::JSON
render_for_text(json, options[:status])
- elsif partial = options[:partial]
- partial = default_template_name if partial == true
+ elsif options[:partial]
+ options[:partial] = default_template_name if options[:partial] == true
add_variables_to_assigns
-
- if collection = options[:collection]
- render_for_text(
- @template.send!(:render_partial_collection, partial, collection,
- options[:spacer_template], options[:locals], options[:as]), options[:status]
- )
- else
- render_for_text(
- @template.send!(:render_partial, partial,
- options[:object], options[:locals]), options[:status]
- )
- end
+ render_for_text(@template.render(options), options[:status])
elsif options[:update]
add_variables_to_assigns
@@ -921,8 +924,7 @@ def render(options = nil, extra_options = {}, &block) #:doc:
render_for_text(generator.to_s, options[:status])
elsif options[:nothing]
- # Safari doesn't pass the headers of the return if the response is zero length
- render_for_text(" ", options[:status])
+ render_for_text(nil, options[:status])
else
render_for_file(default_template_name, options[:status], true)
@@ -968,6 +970,17 @@ def head(*args)
render :nothing => true, :status => status
end
+ # Sets the Last-Modified response header. Returns 304 Not Modified if the
+ # If-Modified-Since request header is <= last modified.
+ def last_modified!(utc_time)
+ head(:not_modified) if response.last_modified!(utc_time)
+ end
+
+ # Sets the ETag response header. Returns 304 Not Modified if the
+ # If-None-Match request header matches.
+ def etag!(etag)
+ head(:not_modified) if response.etag!(etag)
+ end
# Clears the rendered results, allowing for another render to be performed.
def erase_render_results #:nodoc:
@@ -1125,7 +1138,11 @@ def render_for_text(text = nil, status = nil, append_response = false) #:nodoc:
response.body ||= ''
response.body << text.to_s
else
- response.body = text.is_a?(Proc) ? text : text.to_s
+ response.body = case text
+ when Proc then text
+ when nil then " " # Safari doesn't pass the headers of the return if the response is zero length
+ else text.to_s
+ end
end
end
@@ -1155,7 +1172,7 @@ def initialize_current_url
def log_processing
if logger && logger.info?
- logger.info "\n\nProcessing #{controller_class_name}\##{action_name} (for #{request_origin}) [#{request.method.to_s.upcase}]"
+ logger.info "\n\nProcessing #{self.class.name}\##{action_name} (for #{request_origin}) [#{request.method.to_s.upcase}]"
logger.info " Session ID: #{@_session.session_id}" if @_session and @_session.respond_to?(:session_id)
logger.info " Parameters: #{respond_to?(:filter_parameters) ? filter_parameters(params).inspect : params.inspect}"
end
@@ -1166,16 +1183,16 @@ def default_render #:nodoc:
end
def perform_action
- if self.class.action_methods.include?(action_name)
+ if action_methods.include?(action_name)
send(action_name)
default_render unless performed?
elsif respond_to? :method_missing
method_missing action_name
default_render unless performed?
- elsif template_exists? && template_public?
+ elsif template_exists?
default_render
else
- raise UnknownAction, "No action responded to #{action_name}", caller
+ raise UnknownAction, "No action responded to #{action_name}. Actions: #{action_methods.sort.to_sentence}", caller
end
end
@@ -1188,20 +1205,24 @@ def assign_names
end
def assign_default_content_type_and_charset
- response.content_type ||= Mime::HTML
- response.charset ||= self.class.default_charset unless sending_file?
- end
-
- def sending_file?
- response.headers["Content-Transfer-Encoding"] == "binary"
+ response.assign_default_content_type_and_charset!
end
+ deprecate :assign_default_content_type_and_charset => :'response.assign_default_content_type_and_charset!'
def action_methods
self.class.action_methods
end
def self.action_methods
- @action_methods ||= Set.new(public_instance_methods.map { |m| m.to_s }) - hidden_actions
+ @action_methods ||=
+ # All public instance methods of this class, including ancestors
+ public_instance_methods(true).map { |m| m.to_s }.to_set -
+ # Except for public instance methods of Base and its ancestors
+ Base.public_instance_methods(true).map { |m| m.to_s } +
+ # Be sure to include shadowed public instance methods of this class
+ public_instance_methods(false).map { |m| m.to_s } -
+ # And always exclude explicitly hidden actions
+ hidden_actions
end
def add_variables_to_assigns
@@ -1243,13 +1264,11 @@ def template_exists?(template_name = default_template_name)
@template.file_exists?(template_name)
end
- def template_public?(template_name = default_template_name)
- @template.file_public?(template_name)
- end
-
def template_exempt_from_layout?(template_name = default_template_name)
template_name = @template.pick_template(template_name).to_s if @template
@@exempt_from_layout.any? { |ext| template_name =~ ext }
+ rescue ActionView::MissingTemplate
+ false
end
def default_template_name(action_name = self.action_name)
View
6 actionpack/lib/action_controller/caching/fragments.rb
@@ -2,7 +2,7 @@ module ActionController #:nodoc:
module Caching
# Fragment caching is used for caching various blocks within templates without caching the entire action as a whole. This is useful when
# certain elements of an action change frequently or depend on complicated state while other parts rarely change or can be shared amongst multiple
- # parties. The caching is doing using the cache helper available in the Action View. A template with caching might look something like:
+ # parties. The caching is done using the cache helper available in the Action View. A template with caching might look something like:
#
# <b>Hello <%= @name %></b>
# <% cache do %>
@@ -60,10 +60,8 @@ def fragment_cache_key(key)
ActiveSupport::Cache.expand_cache_key(key.is_a?(Hash) ? url_for(key).split("://").last : key, :views)
end
- def fragment_for(block, name = {}, options = nil) #:nodoc:
+ def fragment_for(buffer, name = {}, options = nil, &block) #:nodoc:
if perform_caching
- buffer = yield
-
if cache = read_fragment(name, options)
buffer.concat(cache)
else
View
45 actionpack/lib/action_controller/cgi_process.rb
@@ -43,7 +43,7 @@ class SessionFixationAttempt < StandardError #:nodoc:
:session_path => "/", # available to all paths in app
:session_key => "_session_id",
:cookie_only => true
- } unless const_defined?(:DEFAULT_SESSION_OPTIONS)
+ }
def initialize(cgi, session_options = {})
@cgi = cgi
@@ -61,53 +61,14 @@ def query_string
end
end
- # The request body is an IO input stream. If the RAW_POST_DATA environment
- # variable is already set, wrap it in a StringIO.
- def body
- if raw_post = env['RAW_POST_DATA']
- raw_post.force_encoding(Encoding::BINARY) if raw_post.respond_to?(:force_encoding)
- StringIO.new(raw_post)
- else
- @cgi.stdinput
- end
- end
-
- def query_parameters
- @query_parameters ||= self.class.parse_query_parameters(query_string)
- end
-
- def request_parameters
- @request_parameters ||= parse_formatted_request_parameters
+ def body_stream #:nodoc:
+ @cgi.stdinput
end
def cookies
@cgi.cookies.freeze
end
- def host_with_port_without_standard_port_handling
- if forwarded = env["HTTP_X_FORWARDED_HOST"]
- forwarded.split(/,\s?/).last
- elsif http_host = env['HTTP_HOST']
- http_host
- elsif server_name = env['SERVER_NAME']
- server_name
- else
- "#{env['SERVER_ADDR']}:#{env['SERVER_PORT']}"
- end
- end
-
- def host
- host_with_port_without_standard_port_handling.sub(/:\d+$/, '')
- end
-
- def port
- if host_with_port_without_standard_port_handling =~ /:(\d+)$/
- $1.to_i
- else
- standard_port
- end
- end
-
def session
unless defined?(@session)
if @session_options == false
View
10 actionpack/lib/action_controller/cookies.rb
@@ -22,6 +22,16 @@ module ActionController #:nodoc:
#
# cookies.delete :user_name
#
+ # Please note that if you specify a :domain when setting a cookie, you must also specify the domain when deleting the cookie:
+ #
+ # cookies[:key] = {
+ # :value => 'a yummy cookie',
+ # :expires => 1.year.from_now,
+ # :domain => 'domain.com'
+ # }
+ #
+ # cookies.delete(:key, :domain => 'domain.com')
+ #
# The option symbols for setting cookies are:
#
# * <tt>:value</tt> - The cookie's value or list of values (as an array).
View
24 actionpack/lib/action_controller/dispatcher.rb
@@ -2,8 +2,6 @@ module ActionController
# Dispatches requests to the appropriate controller and takes care of
# reloading the app after each request when Dependencies.load? is true.
class Dispatcher
- @@guard = Mutex.new
-
class << self
def define_dispatcher_callbacks(cache_classes)
unless cache_classes
@@ -26,7 +24,7 @@ def define_dispatcher_callbacks(cache_classes)
to_prepare(:activerecord_instantiate_observers) { ActiveRecord::Base.instantiate_observers }
end
- after_dispatch :flush_logger if defined?(RAILS_DEFAULT_LOGGER) && RAILS_DEFAULT_LOGGER.respond_to?(:flush)
+ after_dispatch :flush_logger if Base.logger && Base.logger.respond_to?(:flush)
end
# Backward-compatible class method takes CGI-specific args. Deprecated
@@ -46,7 +44,7 @@ def dispatch(cgi = nil, session_options = CgiRequest::DEFAULT_SESSION_OPTIONS, o
def to_prepare(identifier = nil, &block)
@prepare_dispatch_callbacks ||= ActiveSupport::Callbacks::CallbackChain.new
callback = ActiveSupport::Callbacks::Callback.new(:prepare_dispatch, block, :identifier => identifier)
- @prepare_dispatch_callbacks | callback
+ @prepare_dispatch_callbacks.replace_or_append!(callback)
end
# If the block raises, send status code as a last-ditch response.
@@ -101,15 +99,13 @@ def initialize(output = $stdout, request = nil, response = nil)
end
def dispatch
- @@guard.synchronize do
- begin
- run_callbacks :before_dispatch
- handle_request
- rescue Exception => exception
- failsafe_rescue exception
- ensure
- run_callbacks :after_dispatch, :enumerator => :reverse_each
- end
+ begin
+ run_callbacks :before_dispatch
+ handle_request
+ rescue Exception => exception
+ failsafe_rescue exception
+ ensure
+ run_callbacks :after_dispatch, :enumerator => :reverse_each
end
end
@@ -146,7 +142,7 @@ def cleanup_application
end
def flush_logger
- RAILS_DEFAULT_LOGGER.flush
+ Base.logger.flush
end
protected
View
19 actionpack/lib/action_controller/filters.rb
@@ -109,16 +109,17 @@ def initialize(kind, method, options = {})
update_options! options
end
+ # override these to return true in appropriate subclass
def before?
- self.class == BeforeFilter
+ false
end
def after?
- self.class == AfterFilter
+ false
end
def around?
- self.class == AroundFilter
+ false
end
# Make sets of strings from :only/:except options
@@ -170,6 +171,10 @@ def type
:around
end
+ def around?
+ true
+ end
+
def call(controller, &block)
if should_run_callback?(controller)
method = filter_responds_to_before_and_after? ? around_proc : self.method
@@ -212,6 +217,10 @@ def type
:before
end
+ def before?
+ true
+ end
+
def call(controller, &block)
super
if controller.send!(:performed?)
@@ -224,6 +233,10 @@ class AfterFilter < Filter #:nodoc:
def type
:after
end
+
+ def after?
+ true
+ end
end
# Filters enable controllers to run shared pre- and post-processing code for its actions. These filters can be used to do
View
30 actionpack/lib/action_controller/headers.rb
@@ -1,31 +1,33 @@
+require 'active_support/memoizable'
+
module ActionController
module Http
class Headers < ::Hash
-
- def initialize(constructor = {})
- if constructor.is_a?(Hash)
+ extend ActiveSupport::Memoizable
+
+ def initialize(*args)
+ if args.size == 1 && args[0].is_a?(Hash)
super()
- update(constructor)
+ update(args[0])
else
- super(constructor)
+ super
end
end
-
+
def [](header_name)
if include?(header_name)
- super
+ super
else
- super(normalize_header(header_name))
+ super(env_name(header_name))
end
end
-
-
+
private
- # Takes an HTTP header name and returns it in the
- # format
- def normalize_header(header_name)
+ # Converts a HTTP header name to an environment variable name.
+ def env_name(header_name)
"HTTP_#{header_name.upcase.gsub(/-/, '_')}"
end
+ memoize :env_name
end
end
-end
+end
View
100 actionpack/lib/action_controller/integration.rb
@@ -101,7 +101,7 @@ def https!(flag=true)
@https = flag
end
- # Return +true+ if the session is mimicing a secure HTTPS request.
+ # Return +true+ if the session is mimicking a secure HTTPS request.
#
# if session.https?
# ...
@@ -165,11 +165,19 @@ def redirect?
status/100 == 3
end
- # Performs a GET request with the given parameters. The parameters may
- # be +nil+, a Hash, or a string that is appropriately encoded
- # (<tt>application/x-www-form-urlencoded</tt> or <tt>multipart/form-data</tt>).
- # The headers should be a hash. The keys will automatically be upcased, with the
- # prefix 'HTTP_' added if needed.
+ # Performs a GET request with the given parameters.
+ #
+ # - +path+: The URI (as a String) on which you want to perform a GET request.
+ # - +parameters+: The HTTP parameters that you want to pass. This may be +nil+,
+ # a Hash, or a String that is appropriately encoded
+ # (<tt>application/x-www-form-urlencoded</tt> or <tt>multipart/form-data</tt>).
+ # - +headers+: Additional HTTP headers to pass, as a Hash. The keys will
+ # automatically be upcased, with the prefix 'HTTP_' added if needed.
+ #
+ # This method returns an AbstractResponse object, which one can use to inspect
+ # the details of the response. Furthermore, if this method was called from an
+ # ActionController::IntegrationTest object, then that object's <tt>@response</tt>
+ # instance variable will point to the same response object.
#
# You can also perform POST, PUT, DELETE, and HEAD requests with +post+,
# +put+, +delete+, and +head+.
@@ -220,21 +228,6 @@ def url_for(options)
end
private
- class StubCGI < CGI #:nodoc:
- attr_accessor :stdinput, :stdoutput, :env_table
-
- def initialize(env, stdinput = nil)
- self.env_table = env
- self.stdoutput = StringIO.new
-
- super
-
- stdinput.set_encoding(Encoding::BINARY) if stdinput.respond_to?(:set_encoding)
- stdinput.force_encoding(Encoding::BINARY) if stdinput.respond_to?(:force_encoding)
- @stdinput = stdinput.is_a?(IO) ? stdinput : StringIO.new(stdinput || '')
- end
- end
-
# Tailors the session based on the given URI, setting the HTTPS value
# and the hostname.
def interpret_uri(path)
@@ -282,9 +275,8 @@ def process(method, path, parameters = nil, headers = nil)
ActionController::Base.clear_last_instantiation!
- cgi = StubCGI.new(env, data)
- ActionController::Dispatcher.dispatch(cgi, ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS, cgi.stdoutput)
- @result = cgi.stdoutput.string
+ env['rack.input'] = data.is_a?(IO) ? data : StringIO.new(data || '')
+ @status, @headers, result_body = ActionController::Dispatcher.new.call(env)
@request_count += 1
@controller = ActionController::Base.last_instantiation
@@ -298,32 +290,34 @@ def process(method, path, parameters = nil, headers = nil)
@html_document = nil
- parse_result
- return status
- rescue MultiPartNeededException
- boundary = "----------XnJLe9ZIbbGUYtzPQJ16u1"
- status = process(method, path, multipart_body(parameters, boundary), (headers || {}).merge({"CONTENT_TYPE" => "multipart/form-data; boundary=#{boundary}"}))
- return status
- end
+ # Inject status back in for backwords compatibility with CGI
+ @headers['Status'] = @status
- # Parses the result of the response and extracts the various values,
- # like cookies, status, headers, etc.
- def parse_result
- response_headers, result_body = @result.split(/\r\n\r\n/, 2)
+ @status, @status_message = @status.split(/ /)
+ @status = @status.to_i
- @headers = Hash.new { |h,k| h[k] = [] }
- response_headers.to_s.each_line do |line|
- key, value = line.strip.split(/:\s*/, 2)
- @headers[key.downcase] << value
+ cgi_headers = Hash.new { |h,k| h[k] = [] }
+ @headers.each do |key, value|
+ cgi_headers[key.downcase] << value
end
+ cgi_headers['set-cookie'] = cgi_headers['set-cookie'].first
+ @headers = cgi_headers
- (@headers['set-cookie'] || [] ).each do |string|
- name, value = string.match(/^([^=]*)=([^;]*);/)[1,2]
+ @response.headers['cookie'] ||= []
+ (@headers['set-cookie'] || []).each do |cookie|
+ name, value = cookie.match(/^([^=]*)=([^;]*);/)[1,2]
@cookies[name] = value
+
+ # Fake CGI cookie header
+ # DEPRECATE: Use response.headers["Set-Cookie"] instead
+ @response.headers['cookie'] << CGI::Cookie::new("name" => name, "value" => value)
end
- @status, @status_message = @headers["status"].first.to_s.split(/ /)
- @status = @status.to_i
+ return status
+ rescue MultiPartNeededException
+ boundary = "----------XnJLe9ZIbbGUYtzPQJ16u1"
+ status = process(method, path, multipart_body(parameters, boundary), (headers || {}).merge({"CONTENT_TYPE" => "multipart/form-data; boundary=#{boundary}"}))
+ return status
end
# Encode the cookies hash in a format suitable for passing to a
@@ -336,13 +330,15 @@ def encode_cookies
# Get a temporary URL writer object
def generic_url_rewriter
- cgi = StubCGI.new('REQUEST_METHOD' => "GET",
- 'QUERY_STRING' => "",
- "REQUEST_URI" => "/",
- "HTTP_HOST" => host,
- "SERVER_PORT" => https? ? "443" : "80",
- "HTTPS" => https? ? "on" : "off")
- ActionController::UrlRewriter.new(ActionController::CgiRequest.new(cgi), {})
+ env = {
+ 'REQUEST_METHOD' => "GET",
+ 'QUERY_STRING' => "",
+ "REQUEST_URI" => "/",
+ "HTTP_HOST" => host,
+ "SERVER_PORT" => https? ? "443" : "80",
+ "HTTPS" => https? ? "on" : "off"
+ }
+ ActionController::UrlRewriter.new(ActionController::RackRequest.new(env), {})
end
def name_with_prefix(prefix, name)
@@ -443,7 +439,7 @@ def reset!
end
%w(get post put head delete cookies assigns
- xml_http_request get_via_redirect post_via_redirect).each do |method|
+ xml_http_request xhr get_via_redirect post_via_redirect).each do |method|
define_method(method) do |*args|
reset! unless @integration_session
# reset the html_document variable, but only for new get/post calls
@@ -499,7 +495,7 @@ def copy_session_variables! #:nodoc:
# Delegate unhandled messages to the current session instance.
def method_missing(sym, *args, &block)
reset! unless @integration_session
- returning @integration_session.send!(sym, *args, &block) do
+ returning @integration_session.__send__(sym, *args, &block) do
copy_session_variables!
end
end
View
16 actionpack/lib/action_controller/polymorphic_routes.rb
@@ -102,6 +102,12 @@ def polymorphic_url(record_or_hash_or_array, options = {})
args << format if format
named_route = build_named_route_call(record_or_hash_or_array, namespace, inflection, options)
+
+ url_options = options.except(:action, :routing_type, :format)
+ unless url_options.empty?
+ args.last.kind_of?(Hash) ? args.last.merge!(url_options) : args << url_options
+ end
+
send!(named_route, *args)
end
@@ -114,19 +120,19 @@ def polymorphic_path(record_or_hash_or_array, options = {})
%w(edit new formatted).each do |action|
module_eval <<-EOT, __FILE__, __LINE__
- def #{action}_polymorphic_url(record_or_hash)
- polymorphic_url(record_or_hash, :action => "#{action}")
+ def #{action}_polymorphic_url(record_or_hash, options = {})
+ polymorphic_url(record_or_hash, options.merge(:action => "#{action}"))
end
- def #{action}_polymorphic_path(record_or_hash)
- polymorphic_url(record_or_hash, :action => "#{action}", :routing_type => :path)
+ def #{action}_polymorphic_path(record_or_hash, options = {})
+ polymorphic_url(record_or_hash, options.merge(:action => "#{action}", :routing_type => :path))
end
EOT
end
private
def action_prefix(options)
- options[:action] ? "#{options[:action]}_" : ""
+ options[:action] ? "#{options[:action]}_" : options[:format] ? "formatted_" : ""
end
def routing_type(options)
View
156 actionpack/lib/action_controller/rack_process.rb
@@ -3,7 +3,7 @@
module ActionController #:nodoc:
class RackRequest < AbstractRequest #:nodoc:
- attr_accessor :env, :session_options
+ attr_accessor :session_options
attr_reader :cgi
class SessionFixationAttempt < StandardError #:nodoc:
@@ -15,7 +15,7 @@ class SessionFixationAttempt < StandardError #:nodoc:
:session_path => "/", # available to all paths in app
:session_key => "_session_id",
:cookie_only => true
- } unless const_defined?(:DEFAULT_SESSION_OPTIONS)
+ }
def initialize(env, session_options = DEFAULT_SESSION_OPTIONS)
@session_options = session_options
@@ -24,39 +24,34 @@ def initialize(env, session_options = DEFAULT_SESSION_OPTIONS)
super()
end
- %w[ AUTH_TYPE CONTENT_TYPE GATEWAY_INTERFACE PATH_INFO
- PATH_TRANSLATED QUERY_STRING REMOTE_HOST
+ %w[ AUTH_TYPE GATEWAY_INTERFACE PATH_INFO
+ PATH_TRANSLATED REMOTE_HOST
REMOTE_IDENT REMOTE_USER SCRIPT_NAME
SERVER_NAME SERVER_PROTOCOL
HTTP_ACCEPT HTTP_ACCEPT_CHARSET HTTP_ACCEPT_ENCODING
- HTTP_ACCEPT_LANGUAGE HTTP_CACHE_CONTROL HTTP_FROM HTTP_HOST
+ HTTP_ACCEPT_LANGUAGE HTTP_CACHE_CONTROL HTTP_FROM
HTTP_NEGOTIATE HTTP_PRAGMA HTTP_REFERER HTTP_USER_AGENT ].each do |env|
define_method(env.sub(/^HTTP_/n, '').downcase) do
@env[env]
end
end
- # The request body is an IO input stream. If the RAW_POST_DATA environment
- # variable is already set, wrap it in a StringIO.
- def body
- if raw_post = env['RAW_POST_DATA']
- StringIO.new(raw_post)
+ def query_string
+ qs = super
+ if !qs.blank?
+ qs
else
- @env['rack.input']
+ @env['QUERY_STRING']
end
end
- def key?(key)
- @env.key?(key)
- end
-
- def query_parameters
- @query_parameters ||= self.class.parse_query_parameters(query_string)
+ def body_stream #:nodoc:
+ @env['rack.input']
end
- def request_parameters
- @request_parameters ||= parse_formatted_request_parameters
+ def key?(key)
+ @env.key?(key)
end
def cookies
@@ -70,38 +65,6 @@ def cookies
@env["rack.request.cookie_hash"]
end
- def host_with_port_without_standard_port_handling
- if forwarded = @env["HTTP_X_FORWARDED_HOST"]
- forwarded.split(/,\s?/).last
- elsif http_host = @env['HTTP_HOST']
- http_host
- elsif server_name = @env['SERVER_NAME']
- server_name
- else
- "#{env['SERVER_ADDR']}:#{env['SERVER_PORT']}"
- end
- end
-
- def host
- host_with_port_without_standard_port_handling.sub(/:\d+$/, '')
- end
-
- def port
- if host_with_port_without_standard_port_handling =~ /:(\d+)$/
- $1.to_i
- else
- standard_port
- end
- end
-
- def remote_addr
- @env['REMOTE_ADDR']
- end
-
- def request_method
- @env['REQUEST_METHOD'].downcase.to_sym
- end
-
def server_port
@env['SERVER_PORT'].to_i
end
@@ -189,23 +152,30 @@ def session_options_with_string_keys
end
class RackResponse < AbstractResponse #:nodoc:
- attr_accessor :status
-
def initialize(request)
- @request = request
+ @cgi = request.cgi
@writer = lambda { |x| @body << x }
@block = nil
super()
end
+ # Retrieve status from instance variable if has already been delete
+ def status
+ @status || super
+ end
+
def out(output = $stdout, &block)
+ # Nasty hack because CGI sessions are closed after the normal
+ # prepare! statement
+ set_cookies!
+
@block = block
- normalize_headers(@headers)
- if [204, 304].include?(@status.to_i)
- @headers.delete "Content-Type"
- [status, @headers.to_hash, []]
+ @status = headers.delete("Status")
+ if [204, 304].include?(status.to_i)
+ headers.delete("Content-Type")
+ [status, headers.to_hash, []]
else
- [status, @headers.to_hash, self]
+ [status, headers.to_hash, self]
end
end
alias to_a out
@@ -237,43 +207,57 @@ def empty?
@block == nil && @body.empty?
end
- private
- def normalize_headers(options = "text/html")
- if options.is_a?(String)
- headers['Content-Type'] = options unless headers['Content-Type']
- else
- headers['Content-Length'] = options.delete('Content-Length').to_s if options['Content-Length']
+ def prepare!
+ super
- headers['Content-Type'] = options.delete('type') || "text/html"
- headers['Content-Type'] += "; charset=" + options.delete('charset') if options['charset']
+ convert_language!
+ convert_expires!
+ set_status!
+ # set_cookies!
+ end
- headers['Content-Language'] = options.delete('language') if options['language']
- headers['Expires'] = options.delete('expires') if options['expires']
+ private
+ def convert_language!
+ headers["Content-Language"] = headers.delete("language") if headers["language"]
+ end
- @status = options['Status'] || "200 OK"
+ def convert_expires!
+ headers["Expires"] = headers.delete("") if headers["expires"]
+ end
- # Convert 'cookie' header to 'Set-Cookie' headers.
- # Because Set-Cookie header can appear more the once in the response body,
- # we store it in a line break seperated string that will be translated to
- # multiple Set-Cookie header by the handler.
- if cookie = options.delete('cookie')
- cookies = []
+ def convert_content_type!
+ super
+ headers['Content-Type'] = headers.delete('type') || "text/html"
+ headers['Content-Type'] += "; charset=" + headers.delete('charset') if headers['charset']
+ end
- case cookie
- when Array then cookie.each { |c| cookies << c.to_s }
- when Hash then cookie.each { |_, c| cookies << c.to_s }
- else cookies << cookie.to_s
- end
+ def set_content_length!
+ super
+ headers["Content-Length"] = headers["Content-Length"].to_s if headers["Content-Length"]
+ end
- @request.cgi.output_cookies.each { |c| cookies << c.to_s } if @request.cgi.output_cookies
+ def set_status!
+ self.status ||= "200 OK"
+ end
- headers['Set-Cookie'] = [headers['Set-Cookie'], cookies].flatten.compact
+ def set_cookies!
+ # Convert 'cookie' header to 'Set-Cookie' headers.
+ # Because Set-Cookie header can appear more the once in the response body,
+ # we store it in a line break separated string that will be translated to
+ # multiple Set-Cookie header by the handler.
+ if cookie = headers.delete('cookie')
+ cookies = []
+
+ case cookie
+ when Array then cookie.each { |c| cookies << c.to_s }
+ when Hash then cookie.each { |_, c| cookies << c.to_s }
+ else cookies << cookie.to_s
end
- options.each { |k,v| headers[k] = v }
- end
+ @cgi.output_cookies.each { |c| cookies << c.to_s } if @cgi.output_cookies
- ""
+ headers['Set-Cookie'] = [headers['Set-Cookie'], cookies].flatten.compact
+ end
end
end
View
204 actionpack/lib/action_controller/request.rb 100755 → 100644
@@ -2,14 +2,21 @@
require 'stringio'
require 'strscan'
-module ActionController
- # HTTP methods which are accepted by default.
- ACCEPTED_HTTP_METHODS = Set.new(%w( get head put post delete options ))
+require 'active_support/memoizable'
+module ActionController
# CgiRequest and TestRequest provide concrete implementations.
class AbstractRequest
- cattr_accessor :relative_url_root
- remove_method :relative_url_root
+ extend ActiveSupport::Memoizable