Skip to content
Browse files

Merge branch 'master' into sprockets

  • Loading branch information...
2 parents d7b521d + f0e198b commit ed24595647374885cebc1d43badc174c0991e93a @josh josh committed Apr 12, 2011
Showing with 2,597 additions and 1,013 deletions.
  1. +1 −1 README.rdoc
  2. +14 −1 actionmailer/README.rdoc
  3. +0 −2 actionmailer/actionmailer.gemspec
  4. +27 −3 actionmailer/lib/action_mailer/base.rb
  5. +6 −2 actionmailer/lib/action_mailer/railtie.rb
  6. +40 −0 actionmailer/test/base_test.rb
  7. +2 −0 actionpack/CHANGELOG
  8. +2 −2 actionpack/README.rdoc
  9. +1 −3 actionpack/actionpack.gemspec
  10. +2 −0 actionpack/lib/abstract_controller/base.rb
  11. +1 −1 actionpack/lib/abstract_controller/callbacks.rb
  12. +2 −2 actionpack/lib/action_controller/base.rb
  13. +5 −1 actionpack/lib/action_controller/metal.rb
  14. +1 −1 actionpack/lib/action_controller/metal/http_authentication.rb
  15. +2 −2 actionpack/lib/action_controller/metal/implicit_render.rb
  16. +10 −6 actionpack/lib/action_controller/metal/mime_responds.rb
  17. +41 −4 actionpack/lib/action_controller/metal/responder.rb
  18. +1 −0 actionpack/lib/action_dispatch.rb
  19. +7 −0 actionpack/lib/action_dispatch/middleware/closed_error.rb
  20. +22 −6 actionpack/lib/action_dispatch/middleware/cookies.rb
  21. +60 −8 actionpack/lib/action_dispatch/middleware/flash.rb
  22. +3 −2 actionpack/lib/action_dispatch/routing/mapper.rb
  23. +3 −1 actionpack/lib/action_dispatch/testing/assertions/response.rb
  24. +2 −1 actionpack/lib/action_dispatch/testing/assertions/selector.rb
  25. +14 −14 actionpack/lib/action_dispatch/testing/integration.rb
  26. +5 −5 actionpack/lib/action_view/base.rb
  27. +1 −1 actionpack/lib/action_view/helpers/atom_feed_helper.rb
  28. +1 −1 actionpack/lib/action_view/helpers/capture_helper.rb
  29. +6 −4 actionpack/lib/action_view/helpers/csrf_helper.rb
  30. +1 −1 actionpack/lib/action_view/helpers/prototype_helper.rb
  31. +2 −2 actionpack/lib/action_view/helpers/text_helper.rb
  32. +5 −2 actionpack/lib/action_view/helpers/url_helper.rb
  33. +1 −1 actionpack/lib/action_view/template/handlers/erb.rb
  34. +90 −0 actionpack/test/controller/flash_hash_test.rb
  35. +54 −4 actionpack/test/controller/flash_test.rb
  36. +8 −0 actionpack/test/controller/integration_test.rb
  37. +59 −1 actionpack/test/controller/mime_responds_test.rb
  38. +11 −2 actionpack/test/controller/new_base/render_implicit_action_test.rb
  39. +3 −5 actionpack/test/controller/request_forgery_protection_test.rb
  40. +4 −3 actionpack/test/controller/resources_test.rb
  41. +96 −0 actionpack/test/dispatch/cookies_test.rb
  42. +2 −1 actionpack/test/dispatch/routing_test.rb
  43. +1 −0 actionpack/test/fixtures/respond_with/using_invalid_resource_with_template.xml.erb
  44. +1 −0 actionpack/test/fixtures/respond_with/using_options_with_template.xml.erb
  45. +2 −1 actionpack/test/template/erb_util_test.rb
  46. +2 −1 actionpack/test/template/form_helper_test.rb
  47. +2 −1 actionpack/test/template/form_options_helper_test.rb
  48. +2 −1 actionpack/test/template/form_tag_helper_test.rb
  49. +11 −5 actionpack/test/template/text_helper_test.rb
  50. +9 −0 activemodel/CHANGELOG
  51. +0 −2 activemodel/activemodel.gemspec
  52. +1 −1 activemodel/lib/active_model/dirty.rb
  53. +10 −11 activemodel/lib/active_model/errors.rb
  54. +24 −3 activemodel/lib/active_model/validations/exclusion.rb
  55. +35 −11 activemodel/lib/active_model/validations/format.rb
  56. +19 −7 activemodel/lib/active_model/validations/inclusion.rb
  57. +2 −1 activemodel/lib/active_model/validator.rb
  58. +2 −1 activemodel/test/cases/mass_assignment_security/sanitizer_test.rb
  59. 0 activemodel/test/cases/{serializeration → serializers}/json_serialization_test.rb
  60. 0 activemodel/test/cases/{serializeration → serializers}/xml_serialization_test.rb
  61. +12 −0 activemodel/test/cases/validations/exclusion_validation_test.rb
  62. +24 −0 activemodel/test/cases/validations/format_validation_test.rb
  63. +12 −0 activemodel/test/cases/validations/inclusion_validation_test.rb
  64. +52 −0 activerecord/CHANGELOG
  65. +0 −1 activerecord/activerecord.gemspec
  66. +2 −1 activerecord/lib/active_record/associations/association.rb
  67. +3 −1 activerecord/lib/active_record/associations/builder/belongs_to.rb
  68. +3 −1 activerecord/lib/active_record/associations/builder/has_many.rb
  69. +3 −1 activerecord/lib/active_record/associations/builder/has_one.rb
  70. +0 −12 activerecord/lib/active_record/associations/collection_association.rb
  71. +0 −2 activerecord/lib/active_record/associations/collection_proxy.rb
  72. +3 −1 activerecord/lib/active_record/associations/has_one_association.rb
  73. +2 −1 activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
  74. +90 −51 activerecord/lib/active_record/base.rb
  75. +18 −0 activerecord/lib/active_record/callbacks.rb
  76. +4 −0 activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
  77. +25 −2 activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
  78. +70 −3 activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
  79. +84 −117 activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
  80. +6 −1 activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb
  81. +3 −3 activerecord/lib/active_record/fixtures.rb
  82. +8 −1 activerecord/lib/active_record/identity_map.rb
  83. +94 −19 activerecord/lib/active_record/named_scope.rb
  84. +1 −6 activerecord/lib/active_record/nested_attributes.rb
  85. +3 −1 activerecord/lib/active_record/railties/databases.rake
  86. +2 −1 activerecord/lib/active_record/reflection.rb
  87. +18 −11 activerecord/lib/active_record/relation.rb
  88. +11 −2 activerecord/lib/active_record/relation/finder_methods.rb
  89. +10 −4 activerecord/lib/active_record/relation/query_methods.rb
  90. +4 −0 activerecord/lib/active_record/relation/spawn_methods.rb
  91. +2 −2 activerecord/lib/active_record/result.rb
  92. +1 −0 activerecord/lib/active_record/transactions.rb
  93. +12 −26 activerecord/lib/active_record/validations/uniqueness.rb
  94. +2 −1 activerecord/lib/rails/generators/active_record/session_migration/session_migration_generator.rb
  95. +69 −0 activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb
  96. +62 −1 activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb
  97. +0 −229 activerecord/test/cases/adapters/sqlite/sqlite_adapter_test.rb
  98. +229 −0 activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
  99. +7 −7 activerecord/test/cases/associations/has_many_associations_test.rb
  100. +7 −7 activerecord/test/cases/associations/has_one_associations_test.rb
  101. +3 −2 activerecord/test/cases/associations/join_model_test.rb
  102. +3 −2 activerecord/test/cases/attribute_methods/read_test.rb
  103. +2 −1 activerecord/test/cases/attribute_methods_test.rb
  104. +9 −13 activerecord/test/cases/base_test.rb
  105. +2 −1 activerecord/test/cases/defaults_test.rb
  106. +19 −3 activerecord/test/cases/identity_map_test.rb
  107. +3 −0 activerecord/test/cases/log_subscriber_test.rb
  108. +6 −6 activerecord/test/cases/method_scoping_test.rb
  109. +21 −21 activerecord/test/cases/named_scope_test.rb
  110. +8 −0 activerecord/test/cases/nested_attributes_test.rb
  111. +1 −1 activerecord/test/cases/query_cache_test.rb
  112. +171 −69 activerecord/test/cases/relation_scoping_test.rb
  113. +1 −1 activerecord/test/cases/relation_test.rb
  114. +7 −6 activerecord/test/models/bulb.rb
  115. +7 −2 activerecord/test/models/car.rb
  116. +3 −1 activerecord/test/models/categorization.rb
  117. +4 −1 activerecord/test/models/comment.rb
  118. +67 −4 activerecord/test/models/developer.rb
  119. +1 −1 activerecord/test/models/pirate.rb
  120. +23 −14 activerecord/test/models/post.rb
  121. +5 −2 activerecord/test/models/reference.rb
  122. +15 −11 activerecord/test/models/topic.rb
  123. +4 −2 activerecord/test/models/without_table.rb
  124. +0 −1 activeresource/activeresource.gemspec
  125. +2 −1 activeresource/lib/active_resource/connection.rb
  126. +2 −1 activeresource/lib/active_resource/http_mock.rb
  127. +2 −1 activeresource/test/cases/http_mock_test.rb
  128. +2 −0 activesupport/CHANGELOG
  129. +0 −2 activesupport/activesupport.gemspec
  130. +3 −2 activesupport/lib/active_support/cache/file_store.rb
  131. +2 −1 activesupport/lib/active_support/callbacks.rb
  132. +1 −1 activesupport/lib/active_support/core_ext/date_time/zones.rb
  133. +1 −0 activesupport/lib/active_support/core_ext/object.rb
  134. +20 −0 activesupport/lib/active_support/core_ext/object/inclusion.rb
  135. +1 −1 activesupport/lib/active_support/core_ext/string/output_safety.rb
  136. +24 −17 activesupport/lib/active_support/core_ext/time/zones.rb
  137. +1 −1 activesupport/lib/active_support/railtie.rb
  138. +1 −8 activesupport/lib/active_support/test_case.rb
  139. +7 −0 activesupport/lib/active_support/testing/mochaing.rb
  140. +25 −21 activesupport/lib/active_support/testing/pending.rb
  141. +3 −2 activesupport/lib/active_support/time_with_zone.rb
  142. +52 −0 activesupport/test/core_ext/object/inclusion_test.rb
  143. +43 −4 activesupport/test/core_ext/time_with_zone_test.rb
  144. +2 −1 activesupport/test/transliterate_test.rb
  145. +2 −4 bin/rails
  146. +0 −1 rails.gemspec
  147. +18 −0 railties/CHANGELOG
  148. +4 −2 railties/guides/rails_guides/textile_extensions.rb
  149. +1 −1 railties/guides/source/2_3_release_notes.textile
  150. +3 −14 railties/guides/source/action_controller_overview.textile
  151. +1 −1 railties/guides/source/action_view_overview.textile
  152. +1 −1 railties/guides/source/active_record_querying.textile
  153. +22 −0 railties/guides/source/active_support_core_extensions.textile
  154. +1 −1 railties/guides/source/api_documentation_guidelines.textile
  155. +1 −1 railties/guides/source/command_line.textile
  156. +1 −1 railties/guides/source/configuring.textile
  157. +24 −40 railties/guides/source/getting_started.textile
  158. +2 −3 railties/guides/source/initialization.textile
  159. +1 −1 railties/guides/source/layout.html.erb
  160. +10 −9 railties/guides/source/ruby_on_rails_guides_guidelines.textile
  161. +5 −4 railties/guides/source/testing.textile
  162. +3 −1 railties/lib/rails/commands.rb
  163. +2 −1 railties/lib/rails/commands/application.rb
  164. +3 −1 railties/lib/rails/commands/benchmarker.rb
  165. +4 −0 railties/lib/rails/commands/console.rb
  166. +3 −1 railties/lib/rails/commands/destroy.rb
  167. +3 −1 railties/lib/rails/commands/generate.rb
  168. +3 −1 railties/lib/rails/commands/profiler.rb
  169. +12 −0 railties/lib/rails/generators/app_base.rb
  170. +2 −1 railties/lib/rails/generators/base.rb
  171. +1 −1 railties/lib/rails/generators/erb/scaffold/templates/index.html.erb
  172. +2 −1 railties/lib/rails/generators/generated_attribute.rb
  173. +13 −0 railties/lib/rails/generators/named_base.rb
  174. +7 −3 railties/lib/rails/generators/rails/app/templates/Gemfile
  175. +1 −1 railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt
  176. +2 −2 railties/lib/rails/generators/rails/app/templates/db/seeds.rb
  177. +19 −19 railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb
  178. +5 −5 railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb
  179. +2 −2 railties/lib/rails/source_annotation_extractor.rb
  180. +12 −0 railties/lib/rails/test_help.rb
  181. +0 −1 railties/railties.gemspec
  182. +87 −0 railties/test/application/configuration_test.rb
  183. +18 −0 railties/test/generators/app_generator_test.rb
  184. +18 −0 railties/test/generators/scaffold_controller_generator_test.rb
View
2 README.rdoc
@@ -48,7 +48,7 @@ more separate. Each of these packages can be used independently outside of
"Welcome aboard: You're riding Ruby on Rails!"
-5. Follow the guidelines to start developing your application. You can find the following resources handy:
+5. Follow the guidelines to start developing your application. You may find the following resources handy:
* The README file created within your application.
* The {Getting Started with Rails}[http://guides.rubyonrails.org/getting_started.html].
View
15 actionmailer/README.rdoc
@@ -32,7 +32,7 @@ This can be as simple as:
end
The body of the email is created by using an Action View template (regular
-ERb) that has the instance variables that are declared in the mailer action.
+ERB) that has the instance variables that are declared in the mailer action.
So the corresponding body template for the method above could look like this:
@@ -72,6 +72,19 @@ Or you can just chain the methods together like:
Notifier.welcome.deliver # Creates the email and sends it immediately
+== Setting defaults
+
+It is possible to set default values that will be used in every method in your Action Mailer class. To implement this functionality, you just call the public class method <tt>default</tt> which you get for free from ActionMailer::Base. This method accepts a Hash as the parameter. You can use any of the headers e-mail messages has, like <tt>:from</tt> as the key. You can also pass in a string as the key, like "Content-Type", but Action Mailer does this out of the box for you, so you wont need to worry about that. Finally it is also possible to pass in a Proc that will get evaluated when it is needed.
+
+Note that every value you set with this method will get over written if you use the same key in your mailer method.
+
+Example:
+
+ class Authenticationmailer < ActionMailer::Base
+ default :from => "awesome@application.com", :subject => Proc.new { "E-mail was generated at #{Time.now}" }
+ .....
+ end
+
== Receiving emails
To receive emails, you need to implement a public instance method called <tt>receive</tt> that takes an
View
2 actionmailer/actionmailer.gemspec
@@ -17,8 +17,6 @@ Gem::Specification.new do |s|
s.require_path = 'lib'
s.requirements << 'none'
- s.has_rdoc = true
-
s.add_dependency('actionpack', version)
s.add_dependency('mail', '~> 2.2.15')
end
View
30 actionmailer/lib/action_mailer/base.rb
@@ -4,6 +4,7 @@
require 'active_support/core_ext/array/wrap'
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/proc'
+require 'active_support/core_ext/string/inflections'
require 'action_mailer/log_subscriber'
module ActionMailer #:nodoc:
@@ -349,9 +350,6 @@ class Base < AbstractController::Base
helper ActionMailer::MailHelper
include ActionMailer::OldApi
- delegate :register_observer, :to => Mail
- delegate :register_interceptor, :to => Mail
-
private_class_method :new #:nodoc:
class_attribute :default_params
@@ -363,6 +361,32 @@ class Base < AbstractController::Base
}.freeze
class << self
+ # Register one or more Observers which will be notified when mail is delivered.
+ def register_observers(*observers)
+ observers.flatten.compact.each { |observer| register_observer(observer) }
+ end
+
+ # Register one or more Interceptors which will be called before mail is sent.
+ def register_interceptors(*interceptors)
+ interceptors.flatten.compact.each { |interceptor| register_interceptor(interceptor) }
+ end
+
+ # Register an Observer which will be notified when mail is delivered.
+ # Either a class or a string can be passed in as the Observer. If a string is passed in
+ # it will be <tt>constantize</tt>d.
+ def register_observer(observer)
+ delivery_observer = (observer.is_a?(String) ? observer.constantize : observer)
+ Mail.register_observer(delivery_observer)
+ end
+
+ # Register an Inteceptor which will be called before mail is sent.
+ # Either a class or a string can be passed in as the Observer. If a string is passed in
+ # it will be <tt>constantize</tt>d.
+ def register_interceptor(interceptor)
+ delivery_interceptor = (interceptor.is_a?(String) ? interceptor.constantize : interceptor)
+ Mail.register_interceptor(delivery_interceptor)
+ end
+
def mailer_name
@mailer_name ||= name.underscore
end
View
8 actionmailer/lib/action_mailer/railtie.rb
@@ -19,13 +19,17 @@ class Railtie < Rails::Railtie
options.stylesheets_dir ||= paths["public/stylesheets"].first
# make sure readers methods get compiled
- options.asset_path ||= app.config.asset_path
- options.asset_host ||= app.config.asset_host
+ options.asset_path ||= app.config.asset_path
+ options.asset_host ||= app.config.asset_host
ActiveSupport.on_load(:action_mailer) do
include AbstractController::UrlFor
extend ::AbstractController::Railties::RoutesHelpers.with(app.routes)
include app.routes.mounted_helpers
+
+ register_interceptors(options.delete(:interceptors))
+ register_observers(options.delete(:observers))
+
options.each { |k,v| send("#{k}=", v) }
end
end
View
40 actionmailer/test/base_test.rb
@@ -478,25 +478,65 @@ def self.delivered_email(mail)
end
end
+ class MySecondObserver
+ def self.delivered_email(mail)
+ end
+ end
+
test "you can register an observer to the mail object that gets informed on email delivery" do
ActionMailer::Base.register_observer(MyObserver)
mail = BaseMailer.welcome
MyObserver.expects(:delivered_email).with(mail)
mail.deliver
end
+ test "you can register an observer using its stringified name to the mail object that gets informed on email delivery" do
+ ActionMailer::Base.register_observer("BaseTest::MyObserver")
+ mail = BaseMailer.welcome
+ MyObserver.expects(:delivered_email).with(mail)
+ mail.deliver
+ end
+
+ test "you can register multiple observers to the mail object that both get informed on email delivery" do
+ ActionMailer::Base.register_observers("BaseTest::MyObserver", MySecondObserver)
+ mail = BaseMailer.welcome
+ MyObserver.expects(:delivered_email).with(mail)
+ MySecondObserver.expects(:delivered_email).with(mail)
+ mail.deliver
+ end
+
class MyInterceptor
def self.delivering_email(mail)
end
end
+ class MySecondInterceptor
+ def self.delivering_email(mail)
+ end
+ end
+
test "you can register an interceptor to the mail object that gets passed the mail object before delivery" do
ActionMailer::Base.register_interceptor(MyInterceptor)
mail = BaseMailer.welcome
MyInterceptor.expects(:delivering_email).with(mail)
mail.deliver
end
+ test "you can register an interceptor using its stringified name to the mail object that gets passed the mail object before delivery" do
+ ActionMailer::Base.register_interceptor("BaseTest::MyInterceptor")
+ mail = BaseMailer.welcome
+ MyInterceptor.expects(:delivering_email).with(mail)
+ mail.deliver
+ end
+
+ test "you can register multiple interceptors to the mail object that both get passed the mail object before delivery" do
+ ActionMailer::Base.register_interceptors("BaseTest::MyInterceptor", MySecondInterceptor)
+ mail = BaseMailer.welcome
+ MyInterceptor.expects(:delivering_email).with(mail)
+ MySecondInterceptor.expects(:delivering_email).with(mail)
+ mail.deliver
+ end
+
test "being able to put proc's into the defaults hash and they get evaluated on mail sending" do
mail1 = ProcMailer.welcome
yesterday = 1.day.ago
View
2 actionpack/CHANGELOG
@@ -1,5 +1,7 @@
*Rails 3.1.0 (unreleased)*
+* Implicit actions named not_implemented can be rendered [Santiago Pastorino]
+
* Wildcard route will always matching the optional format segment by default. For example if you have this route:
map '*pages' => 'pages#show'
View
4 actionpack/README.rdoc
@@ -19,7 +19,7 @@ It consists of several modules:
* Action View, which handles view template lookup and rendering, and provides
view helpers that assist when building HTML forms, Atom feeds and more.
- Template formats that Action View handles are ERb (embedded Ruby, typically
+ Template formats that Action View handles are ERB (embedded Ruby, typically
used to inline short Ruby snippets inside HTML), XML Builder and RJS
(dynamically generated JavaScript from Ruby code).
@@ -57,7 +57,7 @@ A short rundown of some of the major features:
{Learn more}[link:classes/ActionController/Base.html]
-* ERb templates (static content mixed with dynamic output from ruby)
+* ERB templates (static content mixed with dynamic output from ruby)
<% for post in @posts %>
Title: <%= post.title %>
View
4 actionpack/actionpack.gemspec
@@ -17,8 +17,6 @@ Gem::Specification.new do |s|
s.require_path = 'lib'
s.requirements << 'none'
- s.has_rdoc = true
-
s.add_dependency('activesupport', version)
s.add_dependency('activemodel', version)
s.add_dependency('rack-cache', '~> 1.0.0')
@@ -28,5 +26,5 @@ Gem::Specification.new do |s|
s.add_dependency('rack-test', '~> 0.5.7')
s.add_dependency('rack-mount', '~> 0.7.1')
s.add_dependency('tzinfo', '~> 0.3.23')
- s.add_dependency('erubis', '~> 2.6.6')
+ s.add_dependency('erubis', '~> 2.7.0')
end
View
2 actionpack/lib/abstract_controller/base.rb
@@ -1,3 +1,4 @@
+require 'erubis'
require 'active_support/configurable'
require 'active_support/descendants_tracker'
require 'active_support/core_ext/module/anonymous'
@@ -18,6 +19,7 @@ class Base
include ActiveSupport::Configurable
extend ActiveSupport::DescendantsTracker
+ undef_method :not_implemented
class << self
attr_reader :abstract
alias_method :abstract?, :abstract
View
2 actionpack/lib/abstract_controller/callbacks.rb
@@ -29,7 +29,7 @@ module ClassMethods
#
# ==== Options
# * <tt>only</tt> - The callback should be run only for this action
- # * <tt>except<tt> - The callback should be run for all actions except this action
+ # * <tt>except</tt> - The callback should be run for all actions except this action
def _normalize_callback_options(options)
if only = options[:only]
only = Array(only).map {|o| "action_name == '#{o}'"}.join(" || ")
View
4 actionpack/lib/action_controller/base.rb
@@ -105,7 +105,7 @@ module ActionController
# == Renders
#
# Action Controller sends content to the user by using one of five rendering methods. The most versatile and common is the rendering
- # of a template. Included in the Action Pack is the Action View, which enables rendering of ERb templates. It's automatically configured.
+ # of a template. Included in the Action Pack is the Action View, which enables rendering of ERB templates. It's automatically configured.
# The controller passes objects to the view by assigning instance variables:
#
# def show
@@ -128,7 +128,7 @@ module ActionController
# end
# end
#
- # Read more about writing ERb and Builder templates in ActionView::Base.
+ # Read more about writing ERB and Builder templates in ActionView::Base.
#
# == Redirects
#
View
6 actionpack/lib/action_controller/metal.rb
@@ -201,19 +201,23 @@ def to_a #:nodoc:
class_attribute :middleware_stack
self.middleware_stack = ActionController::MiddlewareStack.new
- def self.inherited(base)
+ def self.inherited(base) #nodoc:
base.middleware_stack = self.middleware_stack.dup
super
end
+ # Adds given middleware class and its args to bottom of middleware_stack
def self.use(*args, &block)
middleware_stack.use(*args, &block)
end
+ # Alias for middleware_stack
def self.middleware
middleware_stack
end
+ # Makes the controller a rack endpoint that points to the action in
+ # the given env's action_dispatch.request.path_parameters key.
def self.call(env)
action(env['action_dispatch.request.path_parameters'][:action]).call(env)
end
View
2 actionpack/lib/action_controller/metal/http_authentication.rb
@@ -67,7 +67,7 @@ module HttpAuthentication
# class PostsController < ApplicationController
# REALM = "SuperSecret"
# USERS = {"dhh" => "secret", #plain text password
- # "dap" => Digest:MD5::hexdigest(["dap",REALM,"secret"].join(":")) #ha1 digest password
+ # "dap" => Digest::MD5.hexdigest(["dap",REALM,"secret"].join(":")) #ha1 digest password
#
# before_filter :authenticate, :except => [:index]
#
View
4 actionpack/lib/action_controller/metal/implicit_render.rb
@@ -10,8 +10,8 @@ def send_action(method, *args)
end
end
- def default_render
- render
+ def default_render(*args)
+ render(*args)
end
def action_method?(action_name)
View
16 actionpack/lib/action_controller/metal/mime_responds.rb
@@ -1,8 +1,9 @@
require 'abstract_controller/collector'
require 'active_support/core_ext/class/attribute'
+require 'active_support/core_ext/object/inclusion'
module ActionController #:nodoc:
- module MimeResponds #:nodoc:
+ module MimeResponds
extend ActiveSupport::Concern
included do
@@ -189,7 +190,7 @@ def respond_to(*mimes, &block)
raise ArgumentError, "respond_to takes either types or a block, never both" if mimes.any? && block_given?
if response = retrieve_response_from_mimes(mimes, &block)
- response.call
+ response.call(nil)
end
end
@@ -222,6 +223,9 @@ def respond_to(*mimes, &block)
# is quite simple (it just needs to respond to call), you can even give
# a proc to it.
#
+ # In order to use respond_with, first you need to declare the formats your
+ # controller responds to in the class level with a call to <tt>respond_to</tt>.
+ #
def respond_with(*resources, &block)
raise "In order to use respond_with, first you need to declare the formats your " <<
"controller responds to in the class level" if self.class.mimes_for_respond_to.empty?
@@ -245,9 +249,9 @@ def collect_mimes_from_class_level #:nodoc:
config = self.class.mimes_for_respond_to[mime]
if config[:except]
- !config[:except].include?(action)
+ !action.in?(config[:except])
elsif config[:only]
- config[:only].include?(action)
+ action.in?(config[:only])
else
true
end
@@ -257,9 +261,9 @@ def collect_mimes_from_class_level #:nodoc:
# Collects mimes and return the response for the negotiated format. Returns
# nil if :not_acceptable was sent to the client.
#
- def retrieve_response_from_mimes(mimes=nil, &block)
+ def retrieve_response_from_mimes(mimes=nil, &block) #:nodoc:
mimes ||= collect_mimes_from_class_level
- collector = Collector.new(mimes) { default_render }
+ collector = Collector.new(mimes) { |options| default_render(options || {}) }
block.call(collector) if block_given?
if format = request.negotiate_mime(collector.order)
View
45 actionpack/lib/action_controller/metal/responder.rb
@@ -77,6 +77,37 @@ module ActionController #:nodoc:
#
# respond_with(@project, :manager, @task)
#
+ # === Custom options
+ #
+ # <code>respond_with</code> also allow you to pass options that are forwarded
+ # to the underlying render call. Those options are only applied success
+ # scenarios. For instance, you can do the following in the create method above:
+ #
+ # def create
+ # @project = Project.find(params[:project_id])
+ # @task = @project.comments.build(params[:task])
+ # flash[:notice] = 'Task was successfully created.' if @task.save
+ # respond_with(@project, @task, :status => 201)
+ # end
+ #
+ # This will return status 201 if the task was saved with success. If not,
+ # it will simply ignore the given options and return status 422 and the
+ # resource errors. To customize the failure scenario, you can pass a
+ # a block to <code>respond_with</code>:
+ #
+ # def create
+ # @project = Project.find(params[:project_id])
+ # @task = @project.comments.build(params[:task])
+ # respond_with(@project, @task, :status => 201) do |format|
+ # if @task.save
+ # flash[:notice] = 'Task was successfully created.'
+ # else
+ # format.html { render "some_special_template" }
+ # end
+ # end
+ # end
+ #
+ # Using <code>respond_with</code> with a block follows the same syntax as <code>respond_to</code>.
class Responder
attr_reader :controller, :request, :format, :resource, :resources, :options
@@ -131,7 +162,11 @@ def to_html
# responds to :to_format and display it.
#
def to_format
- default_render
+ if get? || !has_errors?
+ default_render
+ else
+ display_errors
+ end
rescue ActionView::MissingTemplate => e
api_behavior(e)
end
@@ -155,8 +190,6 @@ def api_behavior(error)
if get?
display resource
- elsif has_errors?
- display resource.errors, :status => :unprocessable_entity
elsif post?
display resource, :status => :created, :location => api_location
elsif has_empty_resource_definition?
@@ -185,7 +218,7 @@ def resource_location
# controller.
#
def default_render
- @default_response.call
+ @default_response.call(options)
end
# Display is just a shortcut to render a resource with the current format.
@@ -209,6 +242,10 @@ def display(resource, given_options={})
controller.render given_options.merge!(options).merge!(format => resource)
end
+ def display_errors
+ controller.render format => resource.errors, :status => :unprocessable_entity
+ end
+
# Check whether the resource has errors.
#
def has_errors?
View
1 actionpack/lib/action_dispatch.rb
@@ -60,6 +60,7 @@ module ActionDispatch
autoload :Static
end
+ autoload :ClosedError, 'action_dispatch/middleware/closed_error'
autoload :MiddlewareStack, 'action_dispatch/middleware/stack'
autoload :Routing
View
7 actionpack/lib/action_dispatch/middleware/closed_error.rb
@@ -0,0 +1,7 @@
+module ActionDispatch
+ class ClosedError < StandardError #:nodoc:
+ def initialize(kind)
+ super "Cannot modify #{kind} because it was closed. This means it was already streamed back to the client or converted to HTTP headers."
+ end
+ end
+end
View
28 actionpack/lib/action_dispatch/middleware/cookies.rb
@@ -83,7 +83,7 @@ class Cookies
# Raised when storing more than 4K of session data.
class CookieOverflow < StandardError; end
- class CookieJar < Hash #:nodoc:
+ class CookieJar #:nodoc:
# This regular expression is used to split the levels of a domain.
# The top level domain can be any string without a period or
@@ -115,13 +115,22 @@ def initialize(secret = nil, host = nil, secure = false)
@delete_cookies = {}
@host = host
@secure = secure
-
- super()
+ @closed = false
+ @cookies = {}
end
+ attr_reader :closed
+ alias :closed? :closed
+ def close!; @closed = true end
+
# Returns the value of the cookie by +name+, or +nil+ if no such cookie exists.
def [](name)
- super(name.to_s)
+ @cookies[name.to_s]
+ end
+
+ def update(other_hash)
+ @cookies.update other_hash
+ self
end
def handle_options(options) #:nodoc:
@@ -145,6 +154,7 @@ def handle_options(options) #:nodoc:
# Sets the cookie named +name+. The second argument may be the very cookie
# value, or a hash of options as documented above.
def []=(key, options)
+ raise ClosedError, :cookies if closed?
if options.is_a?(Hash)
options.symbolize_keys!
value = options[:value]
@@ -153,7 +163,7 @@ def []=(key, options)
options = { :value => value }
end
- value = super(key.to_s, value)
+ value = @cookies[key.to_s] = value
handle_options(options)
@@ -170,7 +180,7 @@ def delete(key, options = {})
handle_options(options)
- value = super(key.to_s)
+ value = @cookies.delete(key.to_s)
@delete_cookies[key] = options
value
end
@@ -225,6 +235,7 @@ def initialize(parent_jar, secret)
end
def []=(key, options)
+ raise ClosedError, :cookies if closed?
if options.is_a?(Hash)
options.symbolize_keys!
else
@@ -263,6 +274,7 @@ def [](name)
end
def []=(key, options)
+ raise ClosedError, :cookies if closed?
if options.is_a?(Hash)
options.symbolize_keys!
options[:value] = @verifier.generate(options[:value])
@@ -305,6 +317,7 @@ def initialize(app)
end
def call(env)
+ cookie_jar = nil
status, headers, body = @app.call(env)
if cookie_jar = env['action_dispatch.cookies']
@@ -315,6 +328,9 @@ def call(env)
end
[status, headers, body]
+ ensure
+ cookie_jar = ActionDispatch::Request.new(env).cookie_jar unless cookie_jar
+ cookie_jar.close!
end
end
end
View
68 actionpack/lib/action_dispatch/middleware/flash.rb
@@ -43,9 +43,15 @@ class Flash
class FlashNow #:nodoc:
def initialize(flash)
@flash = flash
+ @closed = false
end
+ attr_reader :closed
+ alias :closed? :closed
+ def close!; @closed = true end
+
def []=(k, v)
+ raise ClosedError, :flash if closed?
@flash[k] = v
@flash.discard(k)
v
@@ -66,27 +72,70 @@ def notice=(message)
end
end
- class FlashHash < Hash
+ class FlashHash
+ include Enumerable
+
def initialize #:nodoc:
- super
- @used = Set.new
+ @used = Set.new
+ @closed = false
+ @flashes = {}
end
+ attr_reader :closed
+ alias :closed? :closed
+ def close!; @closed = true end
+
def []=(k, v) #:nodoc:
+ raise ClosedError, :flash if closed?
keep(k)
- super
+ @flashes[k] = v
+ end
+
+ def [](k)
+ @flashes[k]
end
def update(h) #:nodoc:
h.keys.each { |k| keep(k) }
- super
+ @flashes.update h
+ self
+ end
+
+ def keys
+ @flashes.keys
+ end
+
+ def key?(name)
+ @flashes.key? name
+ end
+
+ def delete(key)
+ @flashes.delete key
+ self
+ end
+
+ def to_hash
+ @flashes.dup
+ end
+
+ def empty?
+ @flashes.empty?
+ end
+
+ def clear
+ @flashes.clear
+ end
+
+ def each(&block)
+ @flashes.each(&block)
end
alias :merge! :update
def replace(h) #:nodoc:
@used = Set.new
- super
+ @flashes.replace h
+ self
end
# Sets a flash that will not be available to the next action, only to the current.
@@ -100,7 +149,7 @@ def replace(h) #:nodoc:
#
# Entries set via <tt>now</tt> are accessed the same way as standard entries: <tt>flash['my-key']</tt>.
def now
- FlashNow.new(self)
+ @now ||= FlashNow.new(self)
end
# Keeps either the entire current flash or a specific flash entry available for the next action:
@@ -184,8 +233,11 @@ def call(env)
session = env['rack.session'] || {}
flash_hash = env['action_dispatch.request.flash_hash']
- if flash_hash && (!flash_hash.empty? || session.key?('flash'))
+ if flash_hash
+ if !flash_hash.empty? || session.key?('flash')
session["flash"] = flash_hash
+ end
+ flash_hash.close!
end
if session.key?('flash') && session['flash'].empty?
View
5 actionpack/lib/action_dispatch/routing/mapper.rb
@@ -1,6 +1,7 @@
require 'erb'
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/object/blank'
+require 'active_support/core_ext/object/inclusion'
require 'active_support/inflector'
require 'action_dispatch/routing/redirection'
@@ -1345,11 +1346,11 @@ def scope_action_options #:nodoc:
end
def resource_scope? #:nodoc:
- [:resource, :resources].include?(@scope[:scope_level])
+ @scope[:scope_level].among?(:resource, :resources)
end
def resource_method_scope? #:nodoc:
- [:collection, :member, :new].include?(@scope[:scope_level])
+ @scope[:scope_level].among?(:collection, :member, :new)
end
def with_exclusive_scope
View
4 actionpack/lib/action_dispatch/testing/assertions/response.rb
@@ -1,3 +1,5 @@
+require 'active_support/core_ext/object/inclusion'
+
module ActionDispatch
module Assertions
# A small suite of assertions that test responses from \Rails applications.
@@ -33,7 +35,7 @@ module ResponseAssertions
def assert_response(type, message = nil)
validate_request!
- if [ :success, :missing, :redirect, :error ].include?(type) && @response.send("#{type}?")
+ if type.among?(:success, :missing, :redirect, :error) && @response.send("#{type}?")
assert_block("") { true } # to count the assertion
elsif type.is_a?(Fixnum) && @response.response_code == type
assert_block("") { true } # to count the assertion
View
3 actionpack/lib/action_dispatch/testing/assertions/selector.rb
@@ -1,4 +1,5 @@
require 'action_controller/vendor/html-scanner'
+require 'active_support/core_ext/object/inclusion'
#--
# Copyright (c) 2006 Assaf Arkin (http://labnotes.org)
@@ -441,7 +442,7 @@ def assert_select_rjs(*args, &block)
if matches
assert_block("") { true } # to count the assertion
- if block_given? && !([:remove, :show, :hide, :toggle].include? rjs_type)
+ if block_given? && !rjs_type.among?(:remove, :show, :hide, :toggle)
begin
@selected ||= nil
in_scope, @selected = @selected, matches
View
28 actionpack/lib/action_dispatch/testing/integration.rb
@@ -1,6 +1,7 @@
require 'stringio'
require 'uri'
require 'active_support/core_ext/kernel/singleton_class'
+require 'active_support/core_ext/object/inclusion'
require 'active_support/core_ext/object/try'
require 'rack/test'
require 'test/unit/assertions'
@@ -26,31 +27,31 @@ module RequestHelpers
# 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+.
+ # You can also perform POST, PUT, DELETE, and HEAD requests with +#post+,
+ # +#put+, +#delete+, and +#head+.
def get(path, parameters = nil, headers = nil)
process :get, path, parameters, headers
end
- # Performs a POST request with the given parameters. See get() for more
+ # Performs a POST request with the given parameters. See +#get+ for more
# details.
def post(path, parameters = nil, headers = nil)
process :post, path, parameters, headers
end
- # Performs a PUT request with the given parameters. See get() for more
+ # Performs a PUT request with the given parameters. See +#get+ for more
# details.
def put(path, parameters = nil, headers = nil)
process :put, path, parameters, headers
end
- # Performs a DELETE request with the given parameters. See get() for
+ # Performs a DELETE request with the given parameters. See +#get+ for
# more details.
def delete(path, parameters = nil, headers = nil)
process :delete, path, parameters, headers
end
- # Performs a HEAD request with the given parameters. See get() for more
+ # Performs a HEAD request with the given parameters. See +#get+ for more
# details.
def head(path, parameters = nil, headers = nil)
process :head, path, parameters, headers
@@ -59,7 +60,7 @@ def head(path, parameters = nil, headers = nil)
# Performs an XMLHttpRequest request with the given parameters, mirroring
# a request from the Prototype library.
#
- # The request_method is :get, :post, :put, :delete or :head; the
+ # The request_method is +:get+, +:post+, +:put+, +:delete+ or +:head+; the
# parameters are +nil+, a hash, or a url-encoded or multipart string;
# the headers are a hash. Keys are automatically upcased and prefixed
# with 'HTTP_' if not already.
@@ -243,7 +244,8 @@ def _mock_session
end
# Performs the actual request.
- def process(method, path, parameters = nil, rack_environment = nil)
+ def process(method, path, parameters = nil, env = nil)
+ env ||= {}
if path =~ %r{://}
location = URI.parse(path)
https! URI::HTTPS === location if location.scheme
@@ -259,7 +261,7 @@ def process(method, path, parameters = nil, rack_environment = nil)
hostname, port = host.split(':')
- env = {
+ default_env = {
:method => method,
:params => parameters,
@@ -277,9 +279,7 @@ def process(method, path, parameters = nil, rack_environment = nil)
session = Rack::Test::Session.new(_mock_session)
- (rack_environment || {}).each do |key, value|
- env[key] = value
- end
+ env.reverse_merge!(default_env)
# NOTE: rack-test v0.5 doesn't build a default uri correctly
# Make sure requested path is always a full uri
@@ -321,7 +321,7 @@ def reset!
define_method(method) do |*args|
reset! unless integration_session
# reset the html_document variable, but only for new get/post calls
- @html_document = nil unless %w(cookies assigns).include?(method)
+ @html_document = nil unless method.among?("cookies", "assigns")
integration_session.__send__(method, *args).tap do
copy_session_variables!
end
@@ -384,7 +384,7 @@ def integration_session
end
end
- # An test that spans multiple controllers and actions,
+ # An integration test spans multiple controllers and actions,
# tying them all together to ensure they work together as expected. It tests
# more completely than either unit or functional tests do, exercising the
# entire stack, from the dispatcher to the database.
View
10 actionpack/lib/action_view/base.rb
@@ -8,13 +8,13 @@
module ActionView #:nodoc:
# = Action View Base
#
- # Action View templates can be written in three ways. If the template file has a <tt>.erb</tt> (or <tt>.rhtml</tt>) extension then it uses a mixture of ERb
+ # Action View templates can be written in three ways. If the template file has a <tt>.erb</tt> (or <tt>.rhtml</tt>) extension then it uses a mixture of ERB
# (included in Ruby) and HTML. If the template file has a <tt>.builder</tt> (or <tt>.rxml</tt>) extension then Jim Weirich's Builder::XmlMarkup library is used.
# If the template file has a <tt>.rjs</tt> extension then it will use ActionView::Helpers::PrototypeHelper::JavaScriptGenerator.
#
- # == ERb
+ # == ERB
#
- # You trigger ERb by using embeddings such as <% %>, <% -%>, and <%= %>. The <%= %> tag set is used when you want output. Consider the
+ # You trigger ERB by using embeddings such as <% %>, <% -%>, and <%= %>. The <%= %> tag set is used when you want output. Consider the
# following loop for names:
#
# <b>Names of all the people</b>
@@ -23,7 +23,7 @@ module ActionView #:nodoc:
# <% end %>
#
# The loop is setup in regular embedding tags <% %> and the name is written using the output embedding tag <%= %>. Note that this
- # is not just a usage suggestion. Regular output functions like print or puts won't work with ERb templates. So this would be wrong:
+ # is not just a usage suggestion. Regular output functions like print or puts won't work with ERB templates. So this would be wrong:
#
# <%# WRONG %>
# Hi, Mr. <% puts "Frodo" %>
@@ -81,7 +81,7 @@ module ActionView #:nodoc:
#
# == Builder
#
- # Builder templates are a more programmatic alternative to ERb. They are especially useful for generating XML content. An XmlMarkup object
+ # Builder templates are a more programmatic alternative to ERB. They are especially useful for generating XML content. An XmlMarkup object
# named +xml+ is automatically made available to templates with a <tt>.builder</tt> extension.
#
# Here are some basic examples:
View
2 actionpack/lib/action_view/helpers/atom_feed_helper.rb
@@ -4,7 +4,7 @@ module ActionView
# = Action View Atom Feed Helpers
module Helpers #:nodoc:
module AtomFeedHelper
- # Adds easy defaults to writing Atom feeds with the Builder template engine (this does not work on ERb or any other
+ # Adds easy defaults to writing Atom feeds with the Builder template engine (this does not work on ERB or any other
# template languages).
#
# Full usage example:
View
2 actionpack/lib/action_view/helpers/capture_helper.rb
@@ -14,7 +14,7 @@ module CaptureHelper
# variable. You can then use this variable anywhere in your templates or layout.
#
# ==== Examples
- # The capture method can be used in ERb templates...
+ # The capture method can be used in ERB templates...
#
# <% @greeting = capture do %>
# Welcome to my shiny new web page! The date and time is
View
10 actionpack/lib/action_view/helpers/csrf_helper.rb
@@ -17,10 +17,12 @@ module CsrfHelper
# Note that regular forms generate hidden fields, and that Ajax calls are whitelisted,
# so they do not use these tags.
def csrf_meta_tags
- <<-METAS.strip_heredoc.chomp.html_safe if protect_against_forgery?
- <meta name="csrf-param" content="#{Rack::Utils.escape_html(request_forgery_protection_token)}"/>
- <meta name="csrf-token" content="#{Rack::Utils.escape_html(form_authenticity_token)}"/>
- METAS
+ if protect_against_forgery?
+ [
+ tag('meta', :name => 'csrf-param', :content => request_forgery_protection_token),
+ tag('meta', :name => 'csrf-token', :content => form_authenticity_token)
+ ].join("\n").html_safe
+ end
end
# For backwards compatibility.
View
2 actionpack/lib/action_view/helpers/prototype_helper.rb
@@ -584,7 +584,7 @@ def update_page(&block)
# Works like update_page but wraps the generated JavaScript in a
# <tt>\<script></tt> tag. Use this to include generated JavaScript in an
- # ERb template. See JavaScriptGenerator for more information.
+ # ERB template. See JavaScriptGenerator for more information.
#
# +html_options+ may be a hash of <tt>\<script></tt> attributes to be
# passed to ActionView::Helpers::JavaScriptHelper#javascript_tag.
View
4 actionpack/lib/action_view/helpers/text_helper.rb
@@ -303,7 +303,7 @@ def simple_format(text, html_options={}, options={})
# # => "Welcome to my new blog at <a href=\"http://www.myblog.com/\" target=\"_blank\">http://www.myblog.com</a>.
# Please e-mail me at <a href=\"mailto:me@email.com\">me@email.com</a>."
def auto_link(text, *args, &block)#link = :all, html = {}, &block)
- return ''.html_safe if text.blank?
+ return '' if text.blank?
options = args.size == 2 ? {} : args.extract_options! # this is necessary because the old auto_link API has a Hash as its last parameter
unless args.empty?
@@ -507,7 +507,7 @@ def auto_link_urls(text, html_options = {}, options = {})
end
content_tag(:a, link_text, link_attributes.merge('href' => href), !!options[:sanitize]) + punctuation.reverse.join('')
end
- end.html_safe
+ end
end
# Turns all email addresses into clickable links. If a block is given,
View
7 actionpack/lib/action_view/helpers/url_helper.rb
@@ -81,9 +81,12 @@ def url_options
# # => /workshops
#
# <%= url_for(@workshop) %>
- # # calls @workshop.to_s
+ # # calls @workshop.to_param which by default returns the id
# # => /workshops/5
#
+ # # to_param can be re-defined in a model to provide different URL names:
+ # # => /workshops/1-workshop-name
+ #
# <%= url_for("http://www.example.com") %>
# # => http://www.example.com
#
@@ -183,7 +186,7 @@ def url_for(options = {})
# link_to "Profiles", :controller => "profiles"
# # => <a href="/profiles">Profiles</a>
#
- # You can use a block as well if your link target is hard to fit into the name parameter. ERb example:
+ # You can use a block as well if your link target is hard to fit into the name parameter. ERB example:
#
# <%= link_to(@profile) do %>
# <strong><%= @profile.name %></strong> -- <span>Check it out!</span>
View
2 actionpack/lib/action_view/template/handlers/erb.rb
@@ -55,7 +55,7 @@ def add_postamble(src)
class ERB
# Specify trim mode for the ERB compiler. Defaults to '-'.
- # See ERb documentation for suitable values.
+ # See ERB documentation for suitable values.
class_attribute :erb_trim_mode
self.erb_trim_mode = '-'
View
90 actionpack/test/controller/flash_hash_test.rb
@@ -0,0 +1,90 @@
+require 'abstract_unit'
+
+module ActionDispatch
+ class FlashHashTest < ActiveSupport::TestCase
+ def setup
+ @hash = Flash::FlashHash.new
+ end
+
+ def test_set_get
+ @hash[:foo] = 'zomg'
+ assert_equal 'zomg', @hash[:foo]
+ end
+
+ def test_keys
+ assert_equal [], @hash.keys
+
+ @hash['foo'] = 'zomg'
+ assert_equal ['foo'], @hash.keys
+
+ @hash['bar'] = 'zomg'
+ assert_equal ['foo', 'bar'].sort, @hash.keys.sort
+ end
+
+ def test_update
+ @hash['foo'] = 'bar'
+ @hash.update('foo' => 'baz', 'hello' => 'world')
+
+ assert_equal 'baz', @hash['foo']
+ assert_equal 'world', @hash['hello']
+ end
+
+ def test_delete
+ @hash['foo'] = 'bar'
+ @hash.delete 'foo'
+
+ assert !@hash.key?('foo')
+ assert_nil @hash['foo']
+ end
+
+ def test_to_hash
+ @hash['foo'] = 'bar'
+ assert_equal({'foo' => 'bar'}, @hash.to_hash)
+
+ @hash.to_hash['zomg'] = 'aaron'
+ assert !@hash.key?('zomg')
+ assert_equal({'foo' => 'bar'}, @hash.to_hash)
+ end
+
+ def test_empty?
+ assert @hash.empty?
+ @hash['zomg'] = 'bears'
+ assert !@hash.empty?
+ @hash.clear
+ assert @hash.empty?
+ end
+
+ def test_each
+ @hash['hello'] = 'world'
+ @hash['foo'] = 'bar'
+
+ things = []
+ @hash.each do |k,v|
+ things << [k,v]
+ end
+
+ assert_equal([%w{ hello world }, %w{ foo bar }].sort, things.sort)
+ end
+
+ def test_replace
+ @hash['hello'] = 'world'
+ @hash.replace('omg' => 'aaron')
+ assert_equal({'omg' => 'aaron'}, @hash.to_hash)
+ end
+
+ def test_discard_no_args
+ @hash['hello'] = 'world'
+ @hash.discard
+ @hash.sweep
+ assert_equal({}, @hash.to_hash)
+ end
+
+ def test_discard_one_arg
+ @hash['hello'] = 'world'
+ @hash['omg'] = 'world'
+ @hash.discard 'hello'
+ @hash.sweep
+ assert_equal({'omg' => 'world'}, @hash.to_hash)
+ end
+ end
+end
View
58 actionpack/test/controller/flash_test.rb
@@ -174,13 +174,13 @@ def test_keep_and_discard_return_values
assert_equal(:foo_indeed, flash.discard(:foo)) # valid key passed
assert_nil flash.discard(:unknown) # non existant key passed
- assert_equal({:foo => :foo_indeed, :bar => :bar_indeed}, flash.discard()) # nothing passed
- assert_equal({:foo => :foo_indeed, :bar => :bar_indeed}, flash.discard(nil)) # nothing passed
+ assert_equal({:foo => :foo_indeed, :bar => :bar_indeed}, flash.discard().to_hash) # nothing passed
+ assert_equal({:foo => :foo_indeed, :bar => :bar_indeed}, flash.discard(nil).to_hash) # nothing passed
assert_equal(:foo_indeed, flash.keep(:foo)) # valid key passed
assert_nil flash.keep(:unknown) # non existant key passed
- assert_equal({:foo => :foo_indeed, :bar => :bar_indeed}, flash.keep()) # nothing passed
- assert_equal({:foo => :foo_indeed, :bar => :bar_indeed}, flash.keep(nil)) # nothing passed
+ assert_equal({:foo => :foo_indeed, :bar => :bar_indeed}, flash.keep().to_hash) # nothing passed
+ assert_equal({:foo => :foo_indeed, :bar => :bar_indeed}, flash.keep(nil).to_hash) # nothing passed
end
def test_redirect_to_with_alert
@@ -214,11 +214,20 @@ class FlashIntegrationTest < ActionDispatch::IntegrationTest
SessionSecret = 'b3c631c314c0bbca50c1b2843150fe33'
class TestController < ActionController::Base
+ def dont_set_flash
+ head :ok
+ end
+
def set_flash
flash["that"] = "hello"
head :ok
end
+ def set_flash_now
+ flash.now["that"] = "hello"
+ head :ok
+ end
+
def use_flash
render :inline => "flash: #{flash["that"]}"
end
@@ -245,6 +254,47 @@ def test_just_using_flash_does_not_stream_a_cookie_back
end
end
+ def test_setting_flash_raises_after_stream_back_to_client
+ with_test_route_set do
+ env = { 'action_dispatch.request.flash_hash' => ActionDispatch::Flash::FlashHash.new }
+ get '/set_flash', nil, env
+ assert_raise(ActionDispatch::ClosedError) {
+ @request.flash['alert'] = 'alert'
+ }
+ end
+ end
+
+ def test_setting_flash_raises_after_stream_back_to_client_even_with_an_empty_flash
+ with_test_route_set do
+ env = { 'action_dispatch.request.flash_hash' => ActionDispatch::Flash::FlashHash.new }
+ get '/dont_set_flash', nil, env
+ assert_raise(ActionDispatch::ClosedError) {
+ @request.flash['alert'] = 'alert'
+ }
+ end
+ end
+
+ def test_setting_flash_now_raises_after_stream_back_to_client
+ with_test_route_set do
+ env = { 'action_dispatch.request.flash_hash' => ActionDispatch::Flash::FlashHash.new }
+ get '/set_flash_now', nil, env
+ assert_raise(ActionDispatch::ClosedError) {
+ @request.flash.now['alert'] = 'alert'
+ }
+ end
+ end
+
+ def test_setting_flash_now_raises_after_stream_back_to_client_even_with_an_empty_flash
+ with_test_route_set do
+ env = { 'action_dispatch.request.flash_hash' => ActionDispatch::Flash::FlashHash.new }
+ get '/dont_set_flash', nil, env
+ assert_raise(ActionDispatch::ClosedError) {
+ @request.flash.now['alert'] = 'alert'
+ }
+ end
+ end
+
+
private
# Overwrite get to send SessionSecret in env hash
View
8 actionpack/test/controller/integration_test.rb
@@ -521,4 +521,12 @@ def app
get '/foo'
assert_raise(NameError) { missing_path }
end
+
+ test "process reuse the env we pass as argument" do
+ env = { :SERVER_NAME => 'server', 'action_dispatch.custom' => 'custom' }
+ get '/foo', nil, env
+ assert_equal :get, env[:method]
+ assert_equal 'server', env[:SERVER_NAME]
+ assert_equal 'custom', env['action_dispatch.custom']
+ end
end
View
60 actionpack/test/controller/mime_responds_test.rb
@@ -1,6 +1,7 @@
require 'abstract_unit'
require 'controller/fake_models'
require 'active_support/core_ext/hash/conversions'
+require 'active_support/core_ext/object/inclusion'
class StarStarMimeController < ActionController::Base
layout nil
@@ -158,7 +159,7 @@ def rescue_action(e)
protected
def set_layout
- if ["all_types_with_layout", "iphone_with_html_response_type"].include?(action_name)
+ if action_name.among?("all_types_with_layout", "iphone_with_html_response_type")
"respond_to/layouts/standard"
elsif action_name == "iphone_with_html_response_type_without_layout"
"respond_to/layouts/missing"
@@ -558,6 +559,15 @@ def using_resource_with_status_and_location
respond_with(resource, :location => "http://test.host/", :status => :created)
end
+ def using_invalid_resource_with_template
+ respond_with(resource)
+ end
+
+ def using_options_with_template
+ @customer = resource
+ respond_with(@customer, :status => 123, :location => "http://test.host/")
+ end
+
def using_resource_with_responder
responder = proc { |c, r, o| c.render :text => "Resource name is #{r.first.name}" }
respond_with(resource, :responder => responder)
@@ -953,6 +963,54 @@ def test_using_resource_with_status_and_location
assert_equal 201, @response.status
end
+ def test_using_resource_with_status_and_location_with_invalid_resource
+ errors = { :name => :invalid }
+ Customer.any_instance.stubs(:errors).returns(errors)
+
+ @request.accept = "text/xml"
+
+ post :using_resource_with_status_and_location
+ assert_equal errors.to_xml, @response.body
+ assert_equal 422, @response.status
+ assert_equal nil, @response.location
+
+ put :using_resource_with_status_and_location
+ assert_equal errors.to_xml, @response.body
+ assert_equal 422, @response.status
+ assert_equal nil, @response.location
+ end
+
+ def test_using_invalid_resource_with_template
+ errors = { :name => :invalid }
+ Customer.any_instance.stubs(:errors).returns(errors)
+
+ @request.accept = "text/xml"
+
+ post :using_invalid_resource_with_template
+ assert_equal errors.to_xml, @response.body
+ assert_equal 422, @response.status
+ assert_equal nil, @response.location
+
+ put :using_invalid_resource_with_template
+ assert_equal errors.to_xml, @response.body
+ assert_equal 422, @response.status
+ assert_equal nil, @response.location
+ end
+
+ def test_using_options_with_template
+ @request.accept = "text/xml"
+
+ post :using_options_with_template
+ assert_equal "<customer-name>david</customer-name>", @response.body
+ assert_equal 123, @response.status
+ assert_equal "http://test.host/", @response.location
+
+ put :using_options_with_template
+ assert_equal "<customer-name>david</customer-name>", @response.body
+ assert_equal 123, @response.status
+ assert_equal "http://test.host/", @response.location
+ end
+
def test_using_resource_with_responder
get :using_resource_with_responder
assert_equal "Resource name is david", @response.body
View
13 actionpack/test/controller/new_base/render_implicit_action_test.rb
@@ -3,8 +3,9 @@
module RenderImplicitAction
class SimpleController < ::ApplicationController
self.view_paths = [ActionView::FixtureResolver.new(
- "render_implicit_action/simple/hello_world.html.erb" => "Hello world!",
- "render_implicit_action/simple/hyphen-ated.html.erb" => "Hello hyphen-ated!"
+ "render_implicit_action/simple/hello_world.html.erb" => "Hello world!",
+ "render_implicit_action/simple/hyphen-ated.html.erb" => "Hello hyphen-ated!",
+ "render_implicit_action/simple/not_implemented.html.erb" => "Not Implemented"
)]
def hello_world() end
@@ -25,9 +26,17 @@ class RenderImplicitActionTest < Rack::TestCase
assert_status 200
end
+ test "render an action called not_implemented" do
+ get "/render_implicit_action/simple/not_implemented"
+
+ assert_body "Not Implemented"
+ assert_status 200
+ end
+
test "action_method? returns true for implicit actions" do
assert SimpleController.new.action_method?(:hello_world)
assert SimpleController.new.action_method?(:"hyphen-ated")
+ assert SimpleController.new.action_method?(:not_implemented)
end
end
end
View
8 actionpack/test/controller/request_forgery_protection_test.rb
@@ -172,13 +172,11 @@ def assert_not_blocked
class RequestForgeryProtectionControllerTest < ActionController::TestCase
include RequestForgeryProtectionTests
- test 'should emit a csrf-token meta tag' do
+ test 'should emit a csrf-param meta tag and a csrf-token meta tag' do
ActiveSupport::SecureRandom.stubs(:base64).returns(@token + '<=?')
get :meta
- assert_equal <<-METAS.strip_heredoc.chomp, @response.body
- <meta name="csrf-param" content="authenticity_token"/>
- <meta name="csrf-token" content="cf50faa3fe97702ca1ae&lt;=?"/>
- METAS
+ assert_select 'meta[name=?][content=?]', 'csrf-param', 'authenticity_token'
+ assert_select 'meta[name=?][content=?]', 'csrf-token', 'cf50faa3fe97702ca1ae&lt;=?'
end
end
View
7 actionpack/test/controller/resources_test.rb
@@ -1,6 +1,7 @@
require 'abstract_unit'
require 'active_support/core_ext/object/try'
require 'active_support/core_ext/object/with_options'
+require 'active_support/core_ext/object/inclusion'
class ResourcesController < ActionController::Base
def index() render :nothing => true end
@@ -1292,7 +1293,7 @@ def assert_named_route(expected, route, options)
def assert_resource_methods(expected, resource, action_method, method)
assert_equal expected.length, resource.send("#{action_method}_methods")[method].size, "#{resource.send("#{action_method}_methods")[method].inspect}"
expected.each do |action|
- assert resource.send("#{action_method}_methods")[method].include?(action),
+ assert action.in?(resource.send("#{action_method}_methods")[method])
"#{method} not in #{action_method} methods: #{resource.send("#{action_method}_methods")[method].inspect}"
end
end
@@ -1329,9 +1330,9 @@ def assert_whether_allowed(allowed, not_allowed, options, action, path, method)
options = options.merge(:action => action.to_s)
path_options = { :path => path, :method => method }
- if Array(allowed).include?(action)
+ if action.in?(Array(allowed))
assert_recognizes options, path_options
- elsif Array(not_allowed).include?(action)
+ elsif action.in?(Array(not_allowed))
assert_not_recognizes options, path_options
end
end
View
96 actionpack/test/dispatch/cookies_test.rb
@@ -495,3 +495,99 @@ def assert_not_cookie_header(expected)
end
end
end
+
+class CookiesIntegrationTest < ActionDispatch::IntegrationTest
+ SessionKey = '_myapp_session'
+ SessionSecret = 'b3c631c314c0bbca50c1b2843150fe33'
+
+ class TestController < ActionController::Base
+ def dont_set_cookies
+ head :ok
+ end
+
+ def set_cookies
+ cookies["that"] = "hello"
+ head :ok
+ end
+ end
+
+ def test_setting_cookies_raises_after_stream_back_to_client
+ with_test_route_set do
+ get '/set_cookies'
+ assert_raise(ActionDispatch::ClosedError) {
+ request.cookie_jar['alert'] = 'alert'
+ cookies['alert'] = 'alert'
+ }
+ end
+ end
+
+ def test_setting_cookies_raises_after_stream_back_to_client_even_without_cookies
+ with_test_route_set do
+ get '/dont_set_cookies'
+ assert_raise(ActionDispatch::ClosedError) {
+ request.cookie_jar['alert'] = 'alert'
+ }
+ end
+ end
+
+ def test_setting_permanent_cookies_raises_after_stream_back_to_client
+ with_test_route_set do
+ get '/set_cookies'
+ assert_raise(ActionDispatch::ClosedError) {
+ request.cookie_jar.permanent['alert'] = 'alert'
+ cookies['alert'] = 'alert'
+ }
+ end
+ end
+
+ def test_setting_permanent_cookies_raises_after_stream_back_to_client_even_without_cookies
+ with_test_route_set do
+ get '/dont_set_cookies'
+ assert_raise(ActionDispatch::ClosedError) {
+ request.cookie_jar.permanent['alert'] = 'alert'
+ }
+ end
+ end
+
+ def test_setting_signed_cookies_raises_after_stream_back_to_client
+ with_test_route_set do
+ get '/set_cookies'
+ assert_raise(ActionDispatch::ClosedError) {
+ request.cookie_jar.signed['alert'] = 'alert'
+ cookies['alert'] = 'alert'
+ }
+ end
+ end
+
+ def test_setting_signed_cookies_raises_after_stream_back_to_client_even_without_cookies
+ with_test_route_set do
+ get '/dont_set_cookies'
+ assert_raise(ActionDispatch::ClosedError) {
+ request.cookie_jar.signed['alert'] = 'alert'
+ }
+ end
+ end
+
+ private
+
+ # Overwrite get to send SessionSecret in env hash
+ def get(path, parameters = nil, env = {})
+ env["action_dispatch.secret_token"] ||= SessionSecret
+ super
+ end
+
+ def with_test_route_set
+ with_routing do |set|
+ set.draw do
+ match ':action', :to => CookiesIntegrationTest::TestController
+ end
+
+ @app = self.class.build_app(set) do |middleware|
+ middleware.use ActionDispatch::Cookies
+ middleware.delete "ActionDispatch::ShowExceptions"
+ end
+
+ yield
+ end
+ end
+end
View
3 actionpack/test/dispatch/routing_test.rb
@@ -1,6 +1,7 @@
require 'erb'
require 'abstract_unit'
require 'controller/fake_controllers'
+require 'active_support/core_ext/object/inclusion'
class TestRoutingMapper < ActionDispatch::IntegrationTest
SprocketsApp = lambda { |env|
@@ -495,7 +496,7 @@ def self.call(params, request)
resources :todos, :id => /\d+/
end
- scope '/countries/:country', :constraints => lambda { |params, req| %[all France].include?(params[:country]) } do
+ scope '/countries/:country', :constraints => lambda { |params, req| params[:country].among?("all", "France") } do
match '/', :to => 'countries#index'
match '/cities', :to => 'countries#cities'
end
View
1 actionpack/test/fixtures/respond_with/using_invalid_resource_with_template.xml.erb
@@ -0,0 +1 @@
+<content>I should not be displayed</content>
View
1 actionpack/test/fixtures/respond_with/using_options_with_template.xml.erb
@@ -0,0 +1 @@
+<customer-name><%= @customer.name %></customer-name>
View
3 actionpack/test/template/erb_util_test.rb
@@ -1,4 +1,5 @@
require 'abstract_unit'
+require 'active_support/core_ext/object/inclusion'
class ErbUtilTest < Test::Unit::TestCase
include ERB::Util
@@ -29,7 +30,7 @@ def test_html_escape_passes_html_escpe_unmodified
def test_rest_in_ascii
(0..127).to_a.map {|int| int.chr }.each do |chr|
- next if %w(& " < >).include?(chr)
+ next if chr.in?('&"<>')
assert_equal chr, html_escape(chr)
end
end
View
3 actionpack/test/template/form_helper_test.rb
@@ -1,5 +1,6 @@
require 'abstract_unit'
require 'controller/fake_models'
+require 'active_support/core_ext/object/inclusion'
class FormHelperTest < ActionView::TestCase
tests ActionView::Helpers::FormHelper