From 7bbad753e2545a530394f2fe73b7edfef1523ab0 Mon Sep 17 00:00:00 2001 From: John Firebaugh Date: Fri, 24 Sep 2010 18:38:16 -0700 Subject: ActiveSupport::Deprecation.silence no longer needed. --- actionpack/lib/action_view/template/error.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/template/error.rb b/actionpack/lib/action_view/template/error.rb index ff256738a9..3c7380ee19 100644 --- a/actionpack/lib/action_view/template/error.rb +++ b/actionpack/lib/action_view/template/error.rb @@ -62,7 +62,7 @@ module ActionView end def message - ActiveSupport::Deprecation.silence { original_exception.message } + original_exception.message end def sub_template_message -- cgit v1.2.3 From 403b06e98ee88b96b6fbd8692f072fdfa7857639 Mon Sep 17 00:00:00 2001 From: John Firebaugh Date: Fri, 24 Sep 2010 18:42:01 -0700 Subject: Ensure original exception message is present in both Template::Error#message and Template::Error#inspect. Previously, #inspect would produce #, which is not very useful. --- actionpack/lib/action_view/template/error.rb | 5 +---- actionpack/test/template/template_error_test.rb | 13 +++++++++++++ 2 files changed, 14 insertions(+), 4 deletions(-) create mode 100644 actionpack/test/template/template_error_test.rb (limited to 'actionpack') diff --git a/actionpack/lib/action_view/template/error.rb b/actionpack/lib/action_view/template/error.rb index 3c7380ee19..c3d5aca6ac 100644 --- a/actionpack/lib/action_view/template/error.rb +++ b/actionpack/lib/action_view/template/error.rb @@ -52,6 +52,7 @@ module ActionView attr_reader :original_exception, :backtrace def initialize(template, assigns, original_exception) + super(original_exception.message) @template, @assigns, @original_exception = template, assigns.dup, original_exception @sub_templates = nil @backtrace = original_exception.backtrace @@ -61,10 +62,6 @@ module ActionView @template.identifier end - def message - original_exception.message - end - def sub_template_message if @sub_templates "Trace of template inclusion: " + diff --git a/actionpack/test/template/template_error_test.rb b/actionpack/test/template/template_error_test.rb new file mode 100644 index 0000000000..3a874082d9 --- /dev/null +++ b/actionpack/test/template/template_error_test.rb @@ -0,0 +1,13 @@ +require "abstract_unit" + +class TemplateErrorTest < ActiveSupport::TestCase + def test_provides_original_message + error = ActionView::Template::Error.new("test", {}, Exception.new("original")) + assert_equal "original", error.message + end + + def test_provides_useful_inspect + error = ActionView::Template::Error.new("test", {}, Exception.new("original")) + assert_equal "#", error.inspect + end +end -- cgit v1.2.3 From 751733ab963cce8780a71185344d8b31ba93c91d Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Sat, 11 Dec 2010 17:25:28 +1000 Subject: Provide an example for ActionDispatch::Routing::Mapper#scope --- actionpack/lib/action_dispatch/routing/mapper.rb | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 430fcdbe07..45248cf34c 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -458,6 +458,18 @@ module ActionDispatch super end + # Used to scope a set of routes to particular constraints. + # + # Take the following route definition as an example: + # + # scope :path => ":account_id", :as => "account" do + # resources :projects + # end + # + # This generates helpers such as +account_projects_path+, just like +resources+ does. + # The difference here being that the routes generated are like /rails/projects/2, + # rather than /accounts/rails/projects/2. + # # === Supported options # [:module] # If you want to route /posts (without the prefix /admin) to -- cgit v1.2.3 From a6bc1f9be48095e2126a3726b5016fb760a8fdb4 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Mon, 13 Dec 2010 07:02:37 +1000 Subject: Remove nodoc from FormBuilder because the methods inside are public API methods --- actionpack/lib/action_view/helpers/form_helper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb index ef5bbd8ae3..6f0e2c99ba 100644 --- a/actionpack/lib/action_view/helpers/form_helper.rb +++ b/actionpack/lib/action_view/helpers/form_helper.rb @@ -1115,7 +1115,7 @@ module ActionView include InstanceTagMethods end - class FormBuilder #:nodoc: + class FormBuilder # The methods which wrap a form helper call. class_attribute :field_helpers self.field_helpers = (FormHelper.instance_method_names - ['form_for']) -- cgit v1.2.3 From a81f68e879198cb4e01f3cda2671c93f1ef0bc1a Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Mon, 13 Dec 2010 13:03:41 +1000 Subject: Fix indentation on the namespace method's documentation --- actionpack/lib/action_dispatch/routing/mapper.rb | 32 ++++++++++++------------ 1 file changed, 16 insertions(+), 16 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 45248cf34c..f65a294eca 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -570,13 +570,13 @@ module ActionDispatch # # This generates the following routes: # - # admin_posts GET /admin/posts(.:format) {:action=>"index", :controller=>"admin/posts"} - # admin_posts POST /admin/posts(.:format) {:action=>"create", :controller=>"admin/posts"} - # new_admin_post GET /admin/posts/new(.:format) {:action=>"new", :controller=>"admin/posts"} - # edit_admin_post GET /admin/posts/:id/edit(.:format) {:action=>"edit", :controller=>"admin/posts"} - # admin_post GET /admin/posts/:id(.:format) {:action=>"show", :controller=>"admin/posts"} - # admin_post PUT /admin/posts/:id(.:format) {:action=>"update", :controller=>"admin/posts"} - # admin_post DELETE /admin/posts/:id(.:format) {:action=>"destroy", :controller=>"admin/posts"} + # admin_posts GET /admin/posts(.:format) {:action=>"index", :controller=>"admin/posts"} + # admin_posts POST /admin/posts(.:format) {:action=>"create", :controller=>"admin/posts"} + # new_admin_post GET /admin/posts/new(.:format) {:action=>"new", :controller=>"admin/posts"} + # edit_admin_post GET /admin/posts/:id/edit(.:format) {:action=>"edit", :controller=>"admin/posts"} + # admin_post GET /admin/posts/:id(.:format) {:action=>"show", :controller=>"admin/posts"} + # admin_post PUT /admin/posts/:id(.:format) {:action=>"update", :controller=>"admin/posts"} + # admin_post DELETE /admin/posts/:id(.:format) {:action=>"destroy", :controller=>"admin/posts"} # === Supported options # # The +:path+, +:as+, +:module+, +:shallow_path+ and +:shallow_prefix+ options all default to the name of the namespace. @@ -584,24 +584,24 @@ module ActionDispatch # [:path] # The path prefix for the routes. # - # namespace :admin, :path => "sekret" do - # resources :posts - # end + # namespace :admin, :path => "sekret" do + # resources :posts + # end # # All routes for the above +resources+ will be accessible through +/sekret/posts+, rather than +/admin/posts+ # # [:module] # The namespace for the controllers. # - # namespace :admin, :module => "sekret" do - # resources :posts - # end + # namespace :admin, :module => "sekret" do + # resources :posts + # end # # The +PostsController+ here should go in the +Sekret+ namespace and so it should be defined like this: # - # class Sekret::PostsController < ApplicationController - # # code go here - # end + # class Sekret::PostsController < ApplicationController + # # code go here + # end # # [:as] # Changes the name used in routing helpers for this namespace. -- cgit v1.2.3 From 73dafba6ca484e1772fea8cd25ad27ff65c6c66b Mon Sep 17 00:00:00 2001 From: Ben Mills Date: Sun, 12 Dec 2010 23:20:06 -0700 Subject: Added :placeholder option to ActionView::Helpers::FormTagHelper text_field_tag --- actionpack/lib/action_view/helpers/form_tag_helper.rb | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers/form_tag_helper.rb b/actionpack/lib/action_view/helpers/form_tag_helper.rb index 50f065f03d..c41271635d 100644 --- a/actionpack/lib/action_view/helpers/form_tag_helper.rb +++ b/actionpack/lib/action_view/helpers/form_tag_helper.rb @@ -112,6 +112,7 @@ module ActionView # * :disabled - If set to true, the user will not be able to use this input. # * :size - The number of visible characters that will fit in the input. # * :maxlength - The maximum number of characters that the browser will allow the user to enter. + # * :placeholder - The text contained in the field by default which is removed when the field receives focus. # * Any other key creates standard HTML attributes for the tag. # # ==== Examples @@ -121,6 +122,9 @@ module ActionView # text_field_tag 'query', 'Enter your search query here' # # => # + # text_field_tag 'search', nil, :placeholder => 'Enter search term...' + # # => + # # text_field_tag 'request', nil, :class => 'special_input' # # => # -- cgit v1.2.3 From 0e5ee9af48f11201a3b06fb3f5a50144224ec9e8 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Wed, 15 Dec 2010 09:01:18 +0100 Subject: Set proper engine's asset directories when assets are served from engine. When using stylesheet_link_tag(:all) or javascript_include_tag(:all), assets directories are searched for css or js files. When config.serve_static_assets is set to true, those files can be served directly from engine's directories. That's why assets paths should be set individually for controllers inside engine if we want to serve static assets with ActionDispatch::Static --- actionpack/lib/action_controller/railties/paths.rb | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'actionpack') diff --git a/actionpack/lib/action_controller/railties/paths.rb b/actionpack/lib/action_controller/railties/paths.rb index 699c44c62c..dce3c2fe88 100644 --- a/actionpack/lib/action_controller/railties/paths.rb +++ b/actionpack/lib/action_controller/railties/paths.rb @@ -16,6 +16,14 @@ module ActionController if klass.superclass == ActionController::Base && ActionController::Base.include_all_helpers klass.helper :all end + + if app.config.serve_static_assets && namespace + paths = namespace._railtie.config.paths + + klass.config.assets_dir = paths["public"].first + klass.config.javascripts_dir = paths["public/javascripts"].first + klass.config.stylesheets_dir = paths["public/stylesheets"].first + end end end end -- cgit v1.2.3 From 6fc3750471ff9642395c4e0462d5059c2133d9aa Mon Sep 17 00:00:00 2001 From: Aditya Sanghi Date: Wed, 15 Dec 2010 16:13:36 +0530 Subject: eternal confusion! fixed doco to inform correctly --- actionpack/lib/action_view/helpers/form_tag_helper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers/form_tag_helper.rb b/actionpack/lib/action_view/helpers/form_tag_helper.rb index c41271635d..9500e85e8b 100644 --- a/actionpack/lib/action_view/helpers/form_tag_helper.rb +++ b/actionpack/lib/action_view/helpers/form_tag_helper.rb @@ -68,7 +68,7 @@ module ActionView # * Any other key creates standard HTML attributes for the tag. # # ==== Examples - # select_tag "people", options_from_collection_for_select(@people, "name", "id") + # select_tag "people", options_from_collection_for_select(@people, "id", "name") # # # # select_tag "people", "" -- cgit v1.2.3 From 439c23dce33148064c258eaf6e79f9d4563c88a4 Mon Sep 17 00:00:00 2001 From: brainopia Date: Thu, 9 Dec 2010 18:38:52 +0300 Subject: Fix edge cases for domain :all option on cookie store Dont set explicit domain for cookies if host is not a domain name [#6002 state:committed] Signed-off-by: Santiago Pastorino --- .../lib/action_dispatch/middleware/cookies.rb | 7 +++++-- actionpack/test/dispatch/cookies_test.rb | 21 +++++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb index b0a4e3d949..f369d2d3c2 100644 --- a/actionpack/lib/action_dispatch/middleware/cookies.rb +++ b/actionpack/lib/action_dispatch/middleware/cookies.rb @@ -131,8 +131,11 @@ module ActionDispatch options[:path] ||= "/" if options[:domain] == :all - @host =~ DOMAIN_REGEXP - options[:domain] = ".#{$1}.#{$2}" + # if host is not ip and matches domain regexp + # (ip confirms to domain regexp so we explicitly check for ip) + options[:domain] = if (@host !~ /^[\d.]+$/) && (@host =~ DOMAIN_REGEXP) + ".#{$1}.#{$2}" + end end end diff --git a/actionpack/test/dispatch/cookies_test.rb b/actionpack/test/dispatch/cookies_test.rb index 5ec7f12cc1..e2040401c7 100644 --- a/actionpack/test/dispatch/cookies_test.rb +++ b/actionpack/test/dispatch/cookies_test.rb @@ -295,6 +295,27 @@ class CookiesTest < ActionController::TestCase assert_cookie_header "user_name=rizwanreza; domain=.nextangle.local; path=/" end + def test_cookie_with_all_domain_option_using_localhost + @request.host = "localhost" + get :set_cookie_with_domain + assert_response :success + assert_cookie_header "user_name=rizwanreza; path=/" + end + + def test_cookie_with_all_domain_option_using_ipv4_address + @request.host = "192.168.1.1" + get :set_cookie_with_domain + assert_response :success + assert_cookie_header "user_name=rizwanreza; path=/" + end + + def test_cookie_with_all_domain_option_using_ipv6_address + @request.host = "2001:0db8:85a3:0000:0000:8a2e:0370:7334" + get :set_cookie_with_domain + assert_response :success + assert_cookie_header "user_name=rizwanreza; path=/" + end + def test_deleting_cookie_with_all_domain_option get :delete_cookie_with_domain assert_response :success -- cgit v1.2.3 From a462a76bd323ef0087ead0bf0d1792a95655975c Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Wed, 15 Dec 2010 09:01:18 +0100 Subject: Set proper engine's asset directories when assets are served from engine. When using stylesheet_link_tag(:all) or javascript_include_tag(:all), assets directories are searched for css or js files. When config.serve_static_assets is set to true, those files can be served directly from engine's directories. That's why assets paths should be set individually for controllers inside engine if we want to serve static assets with ActionDispatch::Static --- actionpack/lib/action_controller/railties/paths.rb | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'actionpack') diff --git a/actionpack/lib/action_controller/railties/paths.rb b/actionpack/lib/action_controller/railties/paths.rb index 699c44c62c..dce3c2fe88 100644 --- a/actionpack/lib/action_controller/railties/paths.rb +++ b/actionpack/lib/action_controller/railties/paths.rb @@ -16,6 +16,14 @@ module ActionController if klass.superclass == ActionController::Base && ActionController::Base.include_all_helpers klass.helper :all end + + if app.config.serve_static_assets && namespace + paths = namespace._railtie.config.paths + + klass.config.assets_dir = paths["public"].first + klass.config.javascripts_dir = paths["public/javascripts"].first + klass.config.stylesheets_dir = paths["public/stylesheets"].first + end end end end -- cgit v1.2.3 From ebc47465a5865ab91dc7d058d2d8a0cc961510d7 Mon Sep 17 00:00:00 2001 From: brainopia Date: Thu, 9 Dec 2010 18:38:52 +0300 Subject: Fix edge cases for domain :all option on cookie store Dont set explicit domain for cookies if host is not a domain name [#6002 state:committed] Signed-off-by: Santiago Pastorino --- .../lib/action_dispatch/middleware/cookies.rb | 7 +++++-- actionpack/test/dispatch/cookies_test.rb | 21 +++++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb index b0a4e3d949..f369d2d3c2 100644 --- a/actionpack/lib/action_dispatch/middleware/cookies.rb +++ b/actionpack/lib/action_dispatch/middleware/cookies.rb @@ -131,8 +131,11 @@ module ActionDispatch options[:path] ||= "/" if options[:domain] == :all - @host =~ DOMAIN_REGEXP - options[:domain] = ".#{$1}.#{$2}" + # if host is not ip and matches domain regexp + # (ip confirms to domain regexp so we explicitly check for ip) + options[:domain] = if (@host !~ /^[\d.]+$/) && (@host =~ DOMAIN_REGEXP) + ".#{$1}.#{$2}" + end end end diff --git a/actionpack/test/dispatch/cookies_test.rb b/actionpack/test/dispatch/cookies_test.rb index 5ec7f12cc1..e2040401c7 100644 --- a/actionpack/test/dispatch/cookies_test.rb +++ b/actionpack/test/dispatch/cookies_test.rb @@ -295,6 +295,27 @@ class CookiesTest < ActionController::TestCase assert_cookie_header "user_name=rizwanreza; domain=.nextangle.local; path=/" end + def test_cookie_with_all_domain_option_using_localhost + @request.host = "localhost" + get :set_cookie_with_domain + assert_response :success + assert_cookie_header "user_name=rizwanreza; path=/" + end + + def test_cookie_with_all_domain_option_using_ipv4_address + @request.host = "192.168.1.1" + get :set_cookie_with_domain + assert_response :success + assert_cookie_header "user_name=rizwanreza; path=/" + end + + def test_cookie_with_all_domain_option_using_ipv6_address + @request.host = "2001:0db8:85a3:0000:0000:8a2e:0370:7334" + get :set_cookie_with_domain + assert_response :success + assert_cookie_header "user_name=rizwanreza; path=/" + end + def test_deleting_cookie_with_all_domain_option get :delete_cookie_with_domain assert_response :success -- cgit v1.2.3 From 96bae30538951367a82235785e7dba3577b50a5a Mon Sep 17 00:00:00 2001 From: Pavel Gorbokon Date: Wed, 24 Nov 2010 10:17:49 +0200 Subject: Replace rudimentary named_scope with scope. [#6052 state:resolved] * rename method names (actually in tests) * rename instance variable @_named_scopes_cache to @_scopes_cache * rename references in doc comments * don't touch CHANGELOG :) --- .../activerecord/render_partial_with_record_identification_test.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'actionpack') diff --git a/actionpack/test/activerecord/render_partial_with_record_identification_test.rb b/actionpack/test/activerecord/render_partial_with_record_identification_test.rb index 43c534c111..99f09286ff 100644 --- a/actionpack/test/activerecord/render_partial_with_record_identification_test.rb +++ b/actionpack/test/activerecord/render_partial_with_record_identification_test.rb @@ -11,7 +11,7 @@ class RenderPartialWithRecordIdentificationController < ActionController::Base render :partial => @topic.replies end - def render_with_named_scope + def render_with_scope render :partial => Reply.base end @@ -62,8 +62,8 @@ class RenderPartialWithRecordIdentificationTest < ActiveRecordTestCase assert_equal 'Birdman is better!', @response.body end - def test_rendering_partial_with_named_scope - get :render_with_named_scope + def test_rendering_partial_with_scope + get :render_with_scope assert_template 'replies/_reply' assert_equal 'Birdman is better!Nuh uh!', @response.body end -- cgit v1.2.3 From e89fff2f6b815529cf729fc8e900a8275c9514e8 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Thu, 16 Dec 2010 21:37:48 +0100 Subject: Bring back config.action_view.cache_template_loading [#5847 state:resolved] --- actionpack/lib/action_view/base.rb | 8 ++++++++ actionpack/lib/action_view/railtie.rb | 10 +++++++++- actionpack/lib/action_view/template/resolver.rb | 11 ++++++++--- 3 files changed, 25 insertions(+), 4 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb index 15944138f7..92ff3380b0 100644 --- a/actionpack/lib/action_view/base.rb +++ b/actionpack/lib/action_view/base.rb @@ -172,6 +172,14 @@ module ActionView #:nodoc: class << self delegate :erb_trim_mode=, :to => 'ActionView::Template::Handlers::ERB' delegate :logger, :to => 'ActionController::Base', :allow_nil => true + + def cache_template_loading + ActionView::Resolver.caching? + end + + def cache_template_loading=(value) + ActionView::Resolver.caching = value + end end attr_accessor :_template diff --git a/actionpack/lib/action_view/railtie.rb b/actionpack/lib/action_view/railtie.rb index 71cd1a788a..501ec07b09 100644 --- a/actionpack/lib/action_view/railtie.rb +++ b/actionpack/lib/action_view/railtie.rb @@ -35,5 +35,13 @@ module ActionView end end end + + initializer "action_view.caching" do |app| + ActiveSupport.on_load(:action_view) do + if app.config.action_view.cache_template_loading.nil? + ActionView::Resolver.caching = app.config.cache_classes + end + end + end end -end \ No newline at end of file +end diff --git a/actionpack/lib/action_view/template/resolver.rb b/actionpack/lib/action_view/template/resolver.rb index a17454da28..0dccc99d14 100644 --- a/actionpack/lib/action_view/template/resolver.rb +++ b/actionpack/lib/action_view/template/resolver.rb @@ -5,6 +5,13 @@ require "action_view/template" module ActionView # = Action View Resolver class Resolver + cattr_accessor :caching + self.caching = true + + class << self + alias :caching? :caching + end + def initialize @cached = Hash.new { |h1,k1| h1[k1] = Hash.new { |h2,k2| h2[k2] = Hash.new { |h3,k3| h3[k3] = Hash.new { |h4,k4| h4[k4] = {} } } } } @@ -23,9 +30,7 @@ module ActionView private - def caching? - @caching ||= !defined?(Rails.application) || Rails.application.config.cache_classes - end + delegate :caching?, :to => "self.class" # This is what child classes implement. No defaults are needed # because Resolver guarantees that the arguments are present and -- cgit v1.2.3 From f176b2552ecc06634dae53b82a4562d8e80aeed6 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Thu, 16 Dec 2010 22:53:19 +0100 Subject: Changelog and guide entries for config.action_view.cache_template_loading --- actionpack/CHANGELOG | 2 ++ 1 file changed, 2 insertions(+) (limited to 'actionpack') diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG index acd9bd5b63..93b29bcc3a 100644 --- a/actionpack/CHANGELOG +++ b/actionpack/CHANGELOG @@ -1,5 +1,7 @@ *Rails 3.1.0 (unreleased)* +* brought back config.action_view.cache_template_loading, which allows to decide whether templates should be cached or not [Piotr Sarnacki] + * url_for and named url helpers now accept :subdomain and :domain as options [Josh Kalderimis] * The redirect route method now also accepts a hash of options which will only change the parts of the url in question, or an object which responds to call, allowing for redirects to be reused (check the documentation for examples). [Josh Kalderimis] -- cgit v1.2.3 From 006ec77e60163d57d655479602230672d98e0f10 Mon Sep 17 00:00:00 2001 From: Don Wilson Date: Thu, 16 Dec 2010 11:37:11 -0200 Subject: Fixed number_with_precision rounding error [#6182 state:resolved] --- actionpack/lib/action_view/helpers/number_helper.rb | 5 +++-- actionpack/test/template/number_helper_test.rb | 5 +++++ 2 files changed, 8 insertions(+), 2 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers/number_helper.rb b/actionpack/lib/action_view/helpers/number_helper.rb index a9400c347f..650828052f 100644 --- a/actionpack/lib/action_view/helpers/number_helper.rb +++ b/actionpack/lib/action_view/helpers/number_helper.rb @@ -270,12 +270,13 @@ module ActionView digits, rounded_number = 1, 0 else digits = (Math.log10(number.abs) + 1).floor - rounded_number = BigDecimal.new((number / 10 ** (digits - precision)).to_s).round.to_f * 10 ** (digits - precision) + rounded_number = (BigDecimal.new(number.to_s) / 10 ** (digits - precision)).round.to_f * 10 ** (digits - precision) + digits = (Math.log10(rounded_number.abs) + 1).floor # After rounding, the number of digits may have changed end precision -= digits precision = precision > 0 ? precision : 0 #don't let it be negative else - rounded_number = BigDecimal.new((number * (10 ** precision)).to_s).round.to_f / 10 ** precision + rounded_number = BigDecimal.new(number.to_s).round(precision).to_f end formatted_number = number_with_delimiter("%01.#{precision}f" % rounded_number, options) if strip_insignificant_zeros diff --git a/actionpack/test/template/number_helper_test.rb b/actionpack/test/template/number_helper_test.rb index ab127521ad..6b234cfbb9 100644 --- a/actionpack/test/template/number_helper_test.rb +++ b/actionpack/test/template/number_helper_test.rb @@ -100,6 +100,11 @@ class NumberHelperTest < ActionView::TestCase assert_equal("0", number_with_precision(0, :precision => 0)) assert_equal("0.00100", number_with_precision(0.001, :precision => 5)) assert_equal("0.001", number_with_precision(0.00111, :precision => 3)) + assert_equal("10.00", number_with_precision(9.995, :precision => 2)) + assert_equal("11.00", number_with_precision(10.995, :precision => 2)) + assert_equal("10.0", number_with_precision(9.995, :precision => 3, :significant => true)) + assert_equal("9.99", number_with_precision(9.994, :precision => 3, :significant => true)) + assert_equal("11.0", number_with_precision(10.995, :precision => 3, :significant => true)) end def test_number_with_precision_with_custom_delimiter_and_separator -- cgit v1.2.3 From 07567aea5f0c6f14a53f511ab4cc46201b669795 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Fri, 17 Dec 2010 16:11:47 +0100 Subject: Revert "Fixed number_with_precision rounding error [#6182 state:resolved]" This reverts commit 006ec77e60163d57d655479602230672d98e0f10. --- actionpack/lib/action_view/helpers/number_helper.rb | 5 ++--- actionpack/test/template/number_helper_test.rb | 5 ----- 2 files changed, 2 insertions(+), 8 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers/number_helper.rb b/actionpack/lib/action_view/helpers/number_helper.rb index 650828052f..a9400c347f 100644 --- a/actionpack/lib/action_view/helpers/number_helper.rb +++ b/actionpack/lib/action_view/helpers/number_helper.rb @@ -270,13 +270,12 @@ module ActionView digits, rounded_number = 1, 0 else digits = (Math.log10(number.abs) + 1).floor - rounded_number = (BigDecimal.new(number.to_s) / 10 ** (digits - precision)).round.to_f * 10 ** (digits - precision) - digits = (Math.log10(rounded_number.abs) + 1).floor # After rounding, the number of digits may have changed + rounded_number = BigDecimal.new((number / 10 ** (digits - precision)).to_s).round.to_f * 10 ** (digits - precision) end precision -= digits precision = precision > 0 ? precision : 0 #don't let it be negative else - rounded_number = BigDecimal.new(number.to_s).round(precision).to_f + rounded_number = BigDecimal.new((number * (10 ** precision)).to_s).round.to_f / 10 ** precision end formatted_number = number_with_delimiter("%01.#{precision}f" % rounded_number, options) if strip_insignificant_zeros diff --git a/actionpack/test/template/number_helper_test.rb b/actionpack/test/template/number_helper_test.rb index 6b234cfbb9..ab127521ad 100644 --- a/actionpack/test/template/number_helper_test.rb +++ b/actionpack/test/template/number_helper_test.rb @@ -100,11 +100,6 @@ class NumberHelperTest < ActionView::TestCase assert_equal("0", number_with_precision(0, :precision => 0)) assert_equal("0.00100", number_with_precision(0.001, :precision => 5)) assert_equal("0.001", number_with_precision(0.00111, :precision => 3)) - assert_equal("10.00", number_with_precision(9.995, :precision => 2)) - assert_equal("11.00", number_with_precision(10.995, :precision => 2)) - assert_equal("10.0", number_with_precision(9.995, :precision => 3, :significant => true)) - assert_equal("9.99", number_with_precision(9.994, :precision => 3, :significant => true)) - assert_equal("11.0", number_with_precision(10.995, :precision => 3, :significant => true)) end def test_number_with_precision_with_custom_delimiter_and_separator -- cgit v1.2.3 From 5008d33eee4767cd84b1087ceec827f1eaec90d0 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 17 Dec 2010 11:31:08 -0800 Subject: dry up case / when statement --- actionpack/lib/action_dispatch/routing/polymorphic_routes.rb | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb index 49e237f8db..82c4fadb50 100644 --- a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb +++ b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb @@ -99,11 +99,9 @@ module ActionDispatch record = extract_record(record_or_hash_or_array) record = record.to_model if record.respond_to?(:to_model) - args = case record_or_hash_or_array - when Hash; [ record_or_hash_or_array ] - when Array; record_or_hash_or_array.dup - else [ record_or_hash_or_array ] - end + args = Array === record_or_hash_or_array ? + record_or_hash_or_array.dup : + [ record_or_hash_or_array ] inflection = if options[:action] && options[:action].to_s == "new" args.pop -- cgit v1.2.3 From f71809f25761440cbec9463bbc082987c90a471b Mon Sep 17 00:00:00 2001 From: Don Wilson Date: Fri, 17 Dec 2010 09:56:03 -0700 Subject: Fixed number_with_precision rounding error [#6182 state:resolved] --- actionpack/lib/action_view/helpers/number_helper.rb | 5 +++-- actionpack/test/template/number_helper_test.rb | 5 +++++ 2 files changed, 8 insertions(+), 2 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers/number_helper.rb b/actionpack/lib/action_view/helpers/number_helper.rb index a9400c347f..26f8dce3c3 100644 --- a/actionpack/lib/action_view/helpers/number_helper.rb +++ b/actionpack/lib/action_view/helpers/number_helper.rb @@ -270,12 +270,13 @@ module ActionView digits, rounded_number = 1, 0 else digits = (Math.log10(number.abs) + 1).floor - rounded_number = BigDecimal.new((number / 10 ** (digits - precision)).to_s).round.to_f * 10 ** (digits - precision) + rounded_number = (BigDecimal.new(number.to_s) / BigDecimal.new((10 ** (digits - precision)).to_f.to_s)).round.to_f * 10 ** (digits - precision) + digits = (Math.log10(rounded_number.abs) + 1).floor # After rounding, the number of digits may have changed end precision -= digits precision = precision > 0 ? precision : 0 #don't let it be negative else - rounded_number = BigDecimal.new((number * (10 ** precision)).to_s).round.to_f / 10 ** precision + rounded_number = BigDecimal.new(number.to_s).round(precision).to_f end formatted_number = number_with_delimiter("%01.#{precision}f" % rounded_number, options) if strip_insignificant_zeros diff --git a/actionpack/test/template/number_helper_test.rb b/actionpack/test/template/number_helper_test.rb index ab127521ad..156b7cb5ff 100644 --- a/actionpack/test/template/number_helper_test.rb +++ b/actionpack/test/template/number_helper_test.rb @@ -100,6 +100,8 @@ class NumberHelperTest < ActionView::TestCase assert_equal("0", number_with_precision(0, :precision => 0)) assert_equal("0.00100", number_with_precision(0.001, :precision => 5)) assert_equal("0.001", number_with_precision(0.00111, :precision => 3)) + assert_equal("10.00", number_with_precision(9.995, :precision => 2)) + assert_equal("11.00", number_with_precision(10.995, :precision => 2)) end def test_number_with_precision_with_custom_delimiter_and_separator @@ -125,6 +127,9 @@ class NumberHelperTest < ActionView::TestCase assert_equal "0.0001", number_with_precision(0.0001, :precision => 1, :significant => true ) assert_equal "0.000100", number_with_precision(0.0001, :precision => 3, :significant => true ) assert_equal "0.0001", number_with_precision(0.0001111, :precision => 1, :significant => true ) + assert_equal "10.0", number_with_precision(9.995, :precision => 3, :significant => true) + assert_equal "9.99", number_with_precision(9.994, :precision => 3, :significant => true) + assert_equal "11.0", number_with_precision(10.995, :precision => 3, :significant => true) end def test_number_with_precision_with_strip_insignificant_zeros -- cgit v1.2.3 From 1a6c4c86ea55dd8d72807b54d24b92422a7cf329 Mon Sep 17 00:00:00 2001 From: Will Date: Sun, 19 Dec 2010 14:14:02 +1100 Subject: Correct deprecated AR usage in ActionController::MimeResponds documentation --- actionpack/lib/action_controller/metal/mime_responds.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_controller/metal/mime_responds.rb b/actionpack/lib/action_controller/metal/mime_responds.rb index 9ba37134b8..3474f09d33 100644 --- a/actionpack/lib/action_controller/metal/mime_responds.rb +++ b/actionpack/lib/action_controller/metal/mime_responds.rb @@ -63,13 +63,13 @@ module ActionController #:nodoc: # might look something like this: # # def index - # @people = Person.find(:all) + # @people = Person.all # end # # Here's the same action, with web-service support baked in: # # def index - # @people = Person.find(:all) + # @people = Person.all # # respond_to do |format| # format.html @@ -155,7 +155,7 @@ module ActionController #:nodoc: # Respond to also allows you to specify a common block for different formats by using any: # # def index - # @people = Person.find(:all) + # @people = Person.all # # respond_to do |format| # format.html @@ -178,7 +178,7 @@ module ActionController #:nodoc: # respond_to :html, :xml, :json # # def index - # @people = Person.find(:all) + # @people = Person.all # respond_with(@person) # end # end -- cgit v1.2.3 From aebbbc78cceff32282d17068525a76acda71928b Mon Sep 17 00:00:00 2001 From: Will Date: Sun, 19 Dec 2010 14:16:54 +1100 Subject: Fix respond_with example code so it makes sense --- actionpack/lib/action_controller/metal/mime_responds.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_controller/metal/mime_responds.rb b/actionpack/lib/action_controller/metal/mime_responds.rb index 3474f09d33..a2e06fe0a6 100644 --- a/actionpack/lib/action_controller/metal/mime_responds.rb +++ b/actionpack/lib/action_controller/metal/mime_responds.rb @@ -208,8 +208,8 @@ module ActionController #:nodoc: # It also accepts a block to be given. It's used to overwrite a default # response: # - # def destroy - # @user = User.find(params[:id]) + # def create + # @user = User.new(params[:user]) # flash[:notice] = "User was successfully created." if @user.save # # respond_with(@user) do |format| -- cgit v1.2.3 From f249d07c44d2f18e508ac83153c9f9cb8bce340b Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Sun, 19 Dec 2010 13:53:08 -0200 Subject: Add missing require --- actionpack/lib/action_controller/caching/pages.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'actionpack') diff --git a/actionpack/lib/action_controller/caching/pages.rb b/actionpack/lib/action_controller/caching/pages.rb index 3e57d2c236..f305ed30fa 100644 --- a/actionpack/lib/action_controller/caching/pages.rb +++ b/actionpack/lib/action_controller/caching/pages.rb @@ -1,4 +1,5 @@ require 'fileutils' +require 'active_support/concern' require 'active_support/core_ext/class/attribute_accessors' module ActionController #:nodoc: -- cgit v1.2.3 From 4038a6bc0f9006fac32943040733c734cc8afe14 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Mon, 20 Dec 2010 01:07:33 +0530 Subject: minor fixesin READMEs --- actionpack/README.rdoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack') diff --git a/actionpack/README.rdoc b/actionpack/README.rdoc index 0ad33cfe26..a28d78f688 100644 --- a/actionpack/README.rdoc +++ b/actionpack/README.rdoc @@ -262,7 +262,7 @@ methods: layout "weblog/layout" def index - @posts = Post.find(:all) + @posts = Post.all end def show -- cgit v1.2.3 From ab2bde45f8140a3ebf8b478e688ef612fc4181fc Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Sun, 19 Dec 2010 19:15:26 -0200 Subject: Remove require AS::Concern from places where is already in --- actionpack/lib/action_controller/caching/pages.rb | 1 - 1 file changed, 1 deletion(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_controller/caching/pages.rb b/actionpack/lib/action_controller/caching/pages.rb index f305ed30fa..3e57d2c236 100644 --- a/actionpack/lib/action_controller/caching/pages.rb +++ b/actionpack/lib/action_controller/caching/pages.rb @@ -1,5 +1,4 @@ require 'fileutils' -require 'active_support/concern' require 'active_support/core_ext/class/attribute_accessors' module ActionController #:nodoc: -- cgit v1.2.3 From 0f7c970e4f1cf0f3bcc01c22a6a3038cb3e34668 Mon Sep 17 00:00:00 2001 From: John Firebaugh Date: Tue, 23 Nov 2010 18:04:05 -0800 Subject: Introduce ActionDispatch::Reloader MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Based on the implementation on the 2-3-stable branch, patches by Hongli Lai , and helpful suggestions from José Valim. Hongli Lai's patches included locking around the request cycle; this is now handled by Rack::Lock (https://github.com/rack/rack/issues/issue/87/). [#2873] Signed-off-by: José Valim --- actionpack/lib/action_dispatch.rb | 1 + .../lib/action_dispatch/middleware/reloader.rb | 82 ++++++++++++ actionpack/test/dispatch/reloader_test.rb | 139 +++++++++++++++++++++ 3 files changed, 222 insertions(+) create mode 100644 actionpack/lib/action_dispatch/middleware/reloader.rb create mode 100644 actionpack/test/dispatch/reloader_test.rb (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch.rb b/actionpack/lib/action_dispatch.rb index 50faf666e6..50d0d191c1 100644 --- a/actionpack/lib/action_dispatch.rb +++ b/actionpack/lib/action_dispatch.rb @@ -53,6 +53,7 @@ module ActionDispatch autoload :Flash autoload :Head autoload :ParamsParser + autoload :Reloader autoload :RemoteIp autoload :Rescue autoload :ShowExceptions diff --git a/actionpack/lib/action_dispatch/middleware/reloader.rb b/actionpack/lib/action_dispatch/middleware/reloader.rb new file mode 100644 index 0000000000..b84410fc62 --- /dev/null +++ b/actionpack/lib/action_dispatch/middleware/reloader.rb @@ -0,0 +1,82 @@ +module ActionDispatch + # ActionDispatch::Reloader provides to_prepare and to_cleanup callbacks. + # These are analogs of ActionDispatch::Callback's before and after + # callbacks, with the difference that to_cleanup is not called until the + # request is fully complete -- that is, after #close has been called on + # the request body. This is important for streaming responses such as the + # following: + # + # self.response_body = lambda { |response, output| + # # code here which refers to application models + # } + # + # Cleanup callbacks will not be called until after the response_body lambda + # is evaluated, ensuring that it can refer to application models and other + # classes before they are unloaded. + # + # By default, ActionDispatch::Reloader is included in the middleware stack + # only in the development environment. + # + class Reloader + include ActiveSupport::Callbacks + + define_callbacks :prepare, :scope => :name + define_callbacks :cleanup, :scope => :name + + # Add a preparation callback. Preparation callbacks are run before each + # request. + # + # If a symbol with a block is given, the symbol is used as an identifier. + # That allows to_prepare to be called again with the same identifier to + # replace the existing callback. Passing an identifier is a suggested + # practice if the code adding a preparation block may be reloaded. + def self.to_prepare(*args, &block) + first_arg = args.first + if first_arg.is_a?(Symbol) && block_given? + remove_method :"__#{first_arg}" if method_defined?(:"__#{first_arg}") + define_method :"__#{first_arg}", &block + set_callback(:prepare, :"__#{first_arg}") + else + set_callback(:prepare, *args, &block) + end + end + + # Add a cleanup callback. Cleanup callbacks are run after each request is + # complete (after #close is called on the response body). + def self.to_cleanup(&block) + set_callback(:cleanup, &block) + end + + def self.prepare! + new(nil).send(:_run_prepare_callbacks) + end + + def self.cleanup! + new(nil).send(:_run_cleanup_callbacks) + end + + def self.reload! + prepare! + cleanup! + end + + def initialize(app) + @app = app + end + + module CleanupOnClose + def close + super if defined?(super) + ensure + ActionDispatch::Reloader.cleanup! + end + end + + def call(env) + _run_prepare_callbacks + response = @app.call(env) + response[2].extend(CleanupOnClose) + response + end + end +end diff --git a/actionpack/test/dispatch/reloader_test.rb b/actionpack/test/dispatch/reloader_test.rb new file mode 100644 index 0000000000..58ef346b5c --- /dev/null +++ b/actionpack/test/dispatch/reloader_test.rb @@ -0,0 +1,139 @@ +require 'abstract_unit' + +class ReloaderTest < Test::Unit::TestCase + Reloader = ActionDispatch::Reloader + + def test_prepare_callbacks + a = b = c = nil + Reloader.to_prepare { |*args| a = b = c = 1 } + Reloader.to_prepare { |*args| b = c = 2 } + Reloader.to_prepare { |*args| c = 3 } + + # Ensure to_prepare callbacks are not run when defined + assert_nil a || b || c + + # Run callbacks + call_and_return_body + + assert_equal 1, a + assert_equal 2, b + assert_equal 3, c + end + + def test_to_prepare_with_identifier_replaces + a = b = 0 + Reloader.to_prepare(:unique_id) { |*args| a = b = 1 } + Reloader.to_prepare(:unique_id) { |*args| a = 2 } + + call_and_return_body + assert_equal 2, a + assert_equal 0, b + end + + class MyBody < Array + def initialize(&block) + @on_close = block + end + + def foo + "foo" + end + + def bar + "bar" + end + + def close + @on_close.call if @on_close + end + end + + def test_returned_body_object_always_responds_to_close + body = call_and_return_body + assert body.respond_to?(:close) + end + + def test_returned_body_object_behaves_like_underlying_object + body = call_and_return_body do + b = MyBody.new + b << "hello" + b << "world" + [200, { "Content-Type" => "text/html" }, b] + end + assert_equal 2, body.size + assert_equal "hello", body[0] + assert_equal "world", body[1] + assert_equal "foo", body.foo + assert_equal "bar", body.bar + end + + def test_it_calls_close_on_underlying_object_when_close_is_called_on_body + close_called = false + body = call_and_return_body do + b = MyBody.new do + close_called = true + end + [200, { "Content-Type" => "text/html" }, b] + end + body.close + assert close_called + end + + def test_returned_body_object_responds_to_all_methods_supported_by_underlying_object + body = call_and_return_body do + [200, { "Content-Type" => "text/html" }, MyBody.new] + end + assert body.respond_to?(:size) + assert body.respond_to?(:each) + assert body.respond_to?(:foo) + assert body.respond_to?(:bar) + end + + def test_cleanup_callbacks_are_called_when_body_is_closed + cleaned = false + Reloader.to_cleanup { cleaned = true } + + body = call_and_return_body + assert !cleaned + + body.close + assert cleaned + end + + def test_prepare_callbacks_arent_called_when_body_is_closed + prepared = false + Reloader.to_prepare { prepared = true } + + body = call_and_return_body + prepared = false + + body.close + assert !prepared + end + + def test_manual_reloading + prepared = cleaned = false + Reloader.to_prepare { prepared = true } + Reloader.to_cleanup { cleaned = true } + + Reloader.prepare! + assert prepared + assert !cleaned + + prepared = cleaned = false + Reloader.cleanup! + assert !prepared + assert cleaned + + prepared = cleaned = false + Reloader.reload! + assert prepared + assert cleaned + end + + private + def call_and_return_body(&block) + @reloader ||= Reloader.new(block || proc {[200, {}, 'response']}) + @reloader.call({'rack.input' => StringIO.new('')})[2] + end +end -- cgit v1.2.3 From 435bccda930e4dde3d0fafca958e1c8330b4c3ca Mon Sep 17 00:00:00 2001 From: John Firebaugh Date: Sun, 19 Dec 2010 15:58:58 -0800 Subject: Replace AD::Callbacks.to_prepare with AD::Reloader.to_prepare MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- .../lib/action_dispatch/middleware/callbacks.rb | 31 ++-------- actionpack/test/dispatch/callbacks_test.rb | 72 ++++------------------ 2 files changed, 19 insertions(+), 84 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/middleware/callbacks.rb b/actionpack/lib/action_dispatch/middleware/callbacks.rb index 0bb950d1cc..5776a7bb27 100644 --- a/actionpack/lib/action_dispatch/middleware/callbacks.rb +++ b/actionpack/lib/action_dispatch/middleware/callbacks.rb @@ -1,32 +1,14 @@ module ActionDispatch # Provide callbacks to be executed before and after the request dispatch. - # - # It also provides a to_prepare callback, which is performed in all requests - # in development by only once in production and notification callback for async - # operations. - # class Callbacks include ActiveSupport::Callbacks define_callbacks :call, :rescuable => true - define_callbacks :prepare, :scope => :name - # Add a preparation callback. Preparation callbacks are run before every - # request in development mode, and before the first request in production mode. - # - # If a symbol with a block is given, the symbol is used as an identifier. - # That allows to_prepare to be called again with the same identifier to - # replace the existing callback. Passing an identifier is a suggested - # practice if the code adding a preparation block may be reloaded. def self.to_prepare(*args, &block) - first_arg = args.first - if first_arg.is_a?(Symbol) && block_given? - remove_method :"__#{first_arg}" if method_defined?(:"__#{first_arg}") - define_method :"__#{first_arg}", &block - set_callback(:prepare, :"__#{first_arg}") - else - set_callback(:prepare, *args, &block) - end + ActiveSupport::Deprecation.warn "ActionDispatch::Callbacks.to_prepare is deprecated. " << + "Please use ActionDispatch::Reloader.to_prepare instead." + ActionDispatch::Reloader.to_prepare(*args, &block) end def self.before(*args, &block) @@ -37,14 +19,13 @@ module ActionDispatch set_callback(:call, :after, *args, &block) end - def initialize(app, prepare_each_request = false) - @app, @prepare_each_request = app, prepare_each_request - _run_prepare_callbacks + def initialize(app, unused = nil) + ActiveSupport::Deprecation.warn "Passing a second argument to ActionDispatch::Callbacks.new is deprecated." unless unused.nil? + @app = app end def call(env) _run_call_callbacks do - _run_prepare_callbacks if @prepare_each_request @app.call(env) end end diff --git a/actionpack/test/dispatch/callbacks_test.rb b/actionpack/test/dispatch/callbacks_test.rb index d3aa55a1ba..5becb621de 100644 --- a/actionpack/test/dispatch/callbacks_test.rb +++ b/actionpack/test/dispatch/callbacks_test.rb @@ -1,6 +1,6 @@ require 'abstract_unit' -class DispatcherTest < Test::Unit::TestCase +class DispatcherTest < ActiveSupport::TestCase class Foo cattr_accessor :a, :b end @@ -13,65 +13,9 @@ class DispatcherTest < Test::Unit::TestCase def setup Foo.a, Foo.b = 0, 0 - ActionDispatch::Callbacks.reset_callbacks(:prepare) ActionDispatch::Callbacks.reset_callbacks(:call) end - def test_prepare_callbacks_with_cache_classes - a = b = c = nil - ActionDispatch::Callbacks.to_prepare { |*args| a = b = c = 1 } - ActionDispatch::Callbacks.to_prepare { |*args| b = c = 2 } - ActionDispatch::Callbacks.to_prepare { |*args| c = 3 } - - # Ensure to_prepare callbacks are not run when defined - assert_nil a || b || c - - # Run callbacks - dispatch - - assert_equal 1, a - assert_equal 2, b - assert_equal 3, c - - # Make sure they are only run once - a = b = c = nil - dispatch - assert_nil a || b || c - end - - def test_prepare_callbacks_without_cache_classes - a = b = c = nil - ActionDispatch::Callbacks.to_prepare { |*args| a = b = c = 1 } - ActionDispatch::Callbacks.to_prepare { |*args| b = c = 2 } - ActionDispatch::Callbacks.to_prepare { |*args| c = 3 } - - # Ensure to_prepare callbacks are not run when defined - assert_nil a || b || c - - # Run callbacks - dispatch(false) - - assert_equal 1, a - assert_equal 2, b - assert_equal 3, c - - # Make sure they are run again - a = b = c = nil - dispatch(false) - assert_equal 1, a - assert_equal 2, b - assert_equal 3, c - end - - def test_to_prepare_with_identifier_replaces - ActionDispatch::Callbacks.to_prepare(:unique_id) { |*args| Foo.a, Foo.b = 1, 1 } - ActionDispatch::Callbacks.to_prepare(:unique_id) { |*args| Foo.a = 2 } - - dispatch - assert_equal 2, Foo.a - assert_equal 0, Foo.b - end - def test_before_and_after_callbacks ActionDispatch::Callbacks.before { |*args| Foo.a += 1; Foo.b += 1 } ActionDispatch::Callbacks.after { |*args| Foo.a += 1; Foo.b += 1 } @@ -85,10 +29,20 @@ class DispatcherTest < Test::Unit::TestCase assert_equal 4, Foo.b end + def test_to_prepare_deprecation + prepared = false + assert_deprecated do + ActionDispatch::Callbacks.to_prepare { prepared = true } + end + + ActionDispatch::Reloader.prepare! + assert prepared + end + private - def dispatch(cache_classes = true, &block) - @dispatcher ||= ActionDispatch::Callbacks.new(block || DummyApp.new, !cache_classes) + def dispatch(&block) + @dispatcher ||= ActionDispatch::Callbacks.new(block || DummyApp.new) @dispatcher.call({'rack.input' => StringIO.new('')}) end -- cgit v1.2.3 From 0cbfd6c28d327304432f7d0c067662b5c1e41a78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Mon, 20 Dec 2010 12:41:49 +0100 Subject: Small changes on AD::Reloader. --- .../lib/action_dispatch/middleware/reloader.rb | 23 +++----------------- actionpack/test/dispatch/reloader_test.rb | 25 +++++----------------- 2 files changed, 8 insertions(+), 40 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/middleware/reloader.rb b/actionpack/lib/action_dispatch/middleware/reloader.rb index b84410fc62..579b5d8a02 100644 --- a/actionpack/lib/action_dispatch/middleware/reloader.rb +++ b/actionpack/lib/action_dispatch/middleware/reloader.rb @@ -25,26 +25,14 @@ module ActionDispatch # Add a preparation callback. Preparation callbacks are run before each # request. - # - # If a symbol with a block is given, the symbol is used as an identifier. - # That allows to_prepare to be called again with the same identifier to - # replace the existing callback. Passing an identifier is a suggested - # practice if the code adding a preparation block may be reloaded. def self.to_prepare(*args, &block) - first_arg = args.first - if first_arg.is_a?(Symbol) && block_given? - remove_method :"__#{first_arg}" if method_defined?(:"__#{first_arg}") - define_method :"__#{first_arg}", &block - set_callback(:prepare, :"__#{first_arg}") - else - set_callback(:prepare, *args, &block) - end + set_callback(:prepare, *args, &block) end # Add a cleanup callback. Cleanup callbacks are run after each request is # complete (after #close is called on the response body). - def self.to_cleanup(&block) - set_callback(:cleanup, &block) + def self.to_cleanup(*args, &block) + set_callback(:cleanup, *args, &block) end def self.prepare! @@ -55,11 +43,6 @@ module ActionDispatch new(nil).send(:_run_cleanup_callbacks) end - def self.reload! - prepare! - cleanup! - end - def initialize(app) @app = app end diff --git a/actionpack/test/dispatch/reloader_test.rb b/actionpack/test/dispatch/reloader_test.rb index 58ef346b5c..995b19030c 100644 --- a/actionpack/test/dispatch/reloader_test.rb +++ b/actionpack/test/dispatch/reloader_test.rb @@ -20,16 +20,6 @@ class ReloaderTest < Test::Unit::TestCase assert_equal 3, c end - def test_to_prepare_with_identifier_replaces - a = b = 0 - Reloader.to_prepare(:unique_id) { |*args| a = b = 1 } - Reloader.to_prepare(:unique_id) { |*args| a = 2 } - - call_and_return_body - assert_equal 2, a - assert_equal 0, b - end - class MyBody < Array def initialize(&block) @on_close = block @@ -50,7 +40,7 @@ class ReloaderTest < Test::Unit::TestCase def test_returned_body_object_always_responds_to_close body = call_and_return_body - assert body.respond_to?(:close) + assert_respond_to body, :close end def test_returned_body_object_behaves_like_underlying_object @@ -83,10 +73,10 @@ class ReloaderTest < Test::Unit::TestCase body = call_and_return_body do [200, { "Content-Type" => "text/html" }, MyBody.new] end - assert body.respond_to?(:size) - assert body.respond_to?(:each) - assert body.respond_to?(:foo) - assert body.respond_to?(:bar) + assert_respond_to body, :size + assert_respond_to body, :each + assert_respond_to body, :foo + assert_respond_to body, :bar end def test_cleanup_callbacks_are_called_when_body_is_closed @@ -124,11 +114,6 @@ class ReloaderTest < Test::Unit::TestCase Reloader.cleanup! assert !prepared assert cleaned - - prepared = cleaned = false - Reloader.reload! - assert prepared - assert cleaned end private -- cgit v1.2.3 From d4afde9ab025854b35634af51fe2ef4edf1f8549 Mon Sep 17 00:00:00 2001 From: John Firebaugh Date: Mon, 20 Dec 2010 14:55:21 -0800 Subject: Expand ActionDispatch::Reloader docs --- .../lib/action_dispatch/middleware/reloader.rb | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/middleware/reloader.rb b/actionpack/lib/action_dispatch/middleware/reloader.rb index 579b5d8a02..efa0bc7129 100644 --- a/actionpack/lib/action_dispatch/middleware/reloader.rb +++ b/actionpack/lib/action_dispatch/middleware/reloader.rb @@ -1,7 +1,10 @@ module ActionDispatch - # ActionDispatch::Reloader provides to_prepare and to_cleanup callbacks. - # These are analogs of ActionDispatch::Callback's before and after - # callbacks, with the difference that to_cleanup is not called until the + # ActionDispatch::Reloader provides prepare and cleanup callbacks, + # intended to assist with code reloading during development. + # + # Prepare callbacks are run before each request, and cleanup callbacks + # after each request. In this respect they are analogs of ActionDispatch::Callback's + # before and after callbacks. However, cleanup callbacks are not called until the # request is fully complete -- that is, after #close has been called on # the request body. This is important for streaming responses such as the # following: @@ -15,7 +18,10 @@ module ActionDispatch # classes before they are unloaded. # # By default, ActionDispatch::Reloader is included in the middleware stack - # only in the development environment. + # only in the development environment; specifically, when config.cache_classes + # is false. Callbacks may be registered even when it is not included in the + # middleware stack, but are executed only when +ActionDispatch::Reloader.prepare!+ + # or +ActionDispatch::Reloader.cleanup!+ are called manually. # class Reloader include ActiveSupport::Callbacks @@ -23,8 +29,8 @@ module ActionDispatch define_callbacks :prepare, :scope => :name define_callbacks :cleanup, :scope => :name - # Add a preparation callback. Preparation callbacks are run before each - # request. + # Add a prepare callback. Prepare callbacks are run before each request, prior + # to ActionDispatch::Callback's before callbacks. def self.to_prepare(*args, &block) set_callback(:prepare, *args, &block) end @@ -35,10 +41,12 @@ module ActionDispatch set_callback(:cleanup, *args, &block) end + # Execute all prepare callbacks. def self.prepare! new(nil).send(:_run_prepare_callbacks) end + # Execute all cleanup callbacks. def self.cleanup! new(nil).send(:_run_cleanup_callbacks) end -- cgit v1.2.3 From 0b0e6f13c02a425f60bfed9db401392d72f419c6 Mon Sep 17 00:00:00 2001 From: John Firebaugh Date: Tue, 21 Dec 2010 19:32:34 -0800 Subject: Typo (request -> response) --- actionpack/lib/action_dispatch/middleware/reloader.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/middleware/reloader.rb b/actionpack/lib/action_dispatch/middleware/reloader.rb index efa0bc7129..7624a1871a 100644 --- a/actionpack/lib/action_dispatch/middleware/reloader.rb +++ b/actionpack/lib/action_dispatch/middleware/reloader.rb @@ -6,7 +6,7 @@ module ActionDispatch # after each request. In this respect they are analogs of ActionDispatch::Callback's # before and after callbacks. However, cleanup callbacks are not called until the # request is fully complete -- that is, after #close has been called on - # the request body. This is important for streaming responses such as the + # the response body. This is important for streaming responses such as the # following: # # self.response_body = lambda { |response, output| -- cgit v1.2.3 From 09195f10bd3add1be1983a42760113ef2bd31602 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Thu, 16 Dec 2010 08:12:24 +0100 Subject: Do not use the same hash instance for expansions [#6114 state:resolved] Using the same hash instance makes using the same expansions for both javascripts and stylesheets. --- .../action_view/helpers/asset_tag_helpers/asset_include_tag.rb | 4 +++- actionpack/test/template/asset_tag_helper_test.rb | 8 ++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb b/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb index e52797042f..fc0cca28b9 100644 --- a/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb +++ b/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb @@ -11,7 +11,9 @@ module ActionView attr_reader :config, :asset_paths class_attribute :expansions - self.expansions = { } + def self.inherited(base) + base.expansions = { } + end def initialize(config, asset_paths) @config = config diff --git a/actionpack/test/template/asset_tag_helper_test.rb b/actionpack/test/template/asset_tag_helper_test.rb index fbcc99a17a..39ecafd072 100644 --- a/actionpack/test/template/asset_tag_helper_test.rb +++ b/actionpack/test/template/asset_tag_helper_test.rb @@ -273,6 +273,14 @@ class AssetTagHelperTest < ActionView::TestCase assert_raise(ArgumentError) { javascript_include_tag('first', :monkey, 'last') } end + def test_custom_javascript_and_stylesheet_expansion_with_same_name + ENV["RAILS_ASSET_ID"] = "" + ActionView::Helpers::AssetTagHelper::register_javascript_expansion :robbery => ["bank", "robber"] + ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :robbery => ["money", "security"] + assert_dom_equal %(\n\n\n), javascript_include_tag('controls', :robbery, 'effects') + assert_dom_equal %(\n\n\n), stylesheet_link_tag('style', :robbery, 'print') + end + def test_reset_javascript_expansions JavascriptIncludeTag.expansions.clear assert_raise(ArgumentError) { javascript_include_tag(:defaults) } -- cgit v1.2.3 From 5853583f9b810d7186ad36801b3a97ed49f77799 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Wed, 22 Dec 2010 21:36:21 -0200 Subject: Allow registering javascript/stylesheet_expansions to existing symbols --- .../asset_tag_helpers/javascript_tag_helpers.rb | 7 +++++-- .../asset_tag_helpers/stylesheet_tag_helpers.rb | 7 +++++-- actionpack/test/template/asset_tag_helper_test.rb | 19 +++++++++++++++++++ 3 files changed, 29 insertions(+), 4 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb b/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb index 6581e1d6f2..c95808a219 100644 --- a/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb +++ b/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb @@ -59,7 +59,10 @@ module ActionView # # def register_javascript_expansion(expansions) - JavascriptIncludeTag.expansions.merge!(expansions) + js_expansions = JavascriptIncludeTag.expansions + expansions.each do |key, values| + js_expansions[key] = (js_expansions[key] || []) | Array(values) if values + end end end @@ -170,4 +173,4 @@ module ActionView end end -end \ No newline at end of file +end diff --git a/actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb b/actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb index d02b28d7f6..f3e041de95 100644 --- a/actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb +++ b/actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb @@ -44,7 +44,10 @@ module ActionView # # def register_stylesheet_expansion(expansions) - StylesheetIncludeTag.expansions.merge!(expansions) + style_expansions = StylesheetIncludeTag.expansions + expansions.each do |key, values| + style_expansions[key] = (style_expansions[key] || []) | Array(values) if values + end end end @@ -141,4 +144,4 @@ module ActionView end end -end \ No newline at end of file +end diff --git a/actionpack/test/template/asset_tag_helper_test.rb b/actionpack/test/template/asset_tag_helper_test.rb index 39ecafd072..4b4e13e1a7 100644 --- a/actionpack/test/template/asset_tag_helper_test.rb +++ b/actionpack/test/template/asset_tag_helper_test.rb @@ -54,6 +54,9 @@ class AssetTagHelperTest < ActionView::TestCase def teardown config.perform_caching = false ENV.delete('RAILS_ASSET_ID') + + JavascriptIncludeTag.expansions.clear + StylesheetIncludeTag.expansions.clear end AutoDiscoveryToTag = { @@ -268,6 +271,14 @@ class AssetTagHelperTest < ActionView::TestCase assert_dom_equal %(\n\n\n\n\n\n\n\n\n), javascript_include_tag('controls',:defaults, :robbery, 'effects') end + def test_registering_javascript_expansions_merges_with_existing_expansions + ENV["RAILS_ASSET_ID"] = "" + ActionView::Helpers::AssetTagHelper::register_javascript_expansion :can_merge => ['bank'] + ActionView::Helpers::AssetTagHelper::register_javascript_expansion :can_merge => ['robber'] + ActionView::Helpers::AssetTagHelper::register_javascript_expansion :can_merge => ['bank'] + assert_dom_equal %(\n), javascript_include_tag(:can_merge) + end + def test_custom_javascript_expansions_with_undefined_symbol ActionView::Helpers::AssetTagHelper::register_javascript_expansion :monkey => nil assert_raise(ArgumentError) { javascript_include_tag('first', :monkey, 'last') } @@ -327,6 +338,14 @@ class AssetTagHelperTest < ActionView::TestCase assert_raise(ArgumentError) { stylesheet_link_tag('first', :monkey, 'last') } end + def test_registering_stylesheet_expansions_merges_with_existing_expansions + ENV["RAILS_ASSET_ID"] = "" + ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :can_merge => ['bank'] + ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :can_merge => ['robber'] + ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :can_merge => ['bank'] + assert_dom_equal %(\n), stylesheet_link_tag(:can_merge) + end + def test_image_path ImagePathToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) } end -- cgit v1.2.3 From 5fb2f0c07f0e30adc2b3a6d2a1fab896ee9739b8 Mon Sep 17 00:00:00 2001 From: Rizwan Reza Date: Thu, 23 Dec 2010 16:06:53 +0330 Subject: Revised documentation for cache_helper. --- actionpack/lib/action_view/helpers/cache_helper.rb | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers/cache_helper.rb b/actionpack/lib/action_view/helpers/cache_helper.rb index f544a9d147..f41a16a61e 100644 --- a/actionpack/lib/action_view/helpers/cache_helper.rb +++ b/actionpack/lib/action_view/helpers/cache_helper.rb @@ -2,31 +2,29 @@ module ActionView # = Action View Cache Helper module Helpers module CacheHelper - # This helper to exposes a method for caching of view fragments. - # See ActionController::Caching::Fragments for usage instructions. + # This helper exposes a method for caching view fragments caching + # fragments of a view rather than an entire action or page. This + # technique is useful caching pieces like menus, lists of news + # topics, static HTML fragments, and so on. This method takes a + # block that contains the content you wish to cache. # - # A method for caching fragments of a view rather than an entire - # action or page. This technique is useful caching pieces like - # menus, lists of news topics, static HTML fragments, and so on. - # This method takes a block that contains the content you wish - # to cache. See ActionController::Caching::Fragments for more - # information. + # See ActionController::Caching::Fragments for usage instructions. # # ==== Examples - # If you wanted to cache a navigation menu, you could do the - # following. + # If you want to cache a navigation menu, you can do following: # # <% cache do %> # <%= render :partial => "menu" %> # <% end %> # - # You can also cache static content... + # You can also cache static content: # # <% cache do %> #

Hello users! Welcome to our website!

# <% end %> # - # ...and static content mixed with RHTML content. + # Static content with embedded ruby content can be cached as + # well: # # <% cache do %> # Topics: -- cgit v1.2.3 From 0997d5a12dcefe5df4089ddd8b305318abc0a9d4 Mon Sep 17 00:00:00 2001 From: Rizwan Reza Date: Thu, 23 Dec 2010 16:13:36 +0330 Subject: More minor edits. --- actionpack/lib/action_view/helpers/cache_helper.rb | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers/cache_helper.rb b/actionpack/lib/action_view/helpers/cache_helper.rb index f41a16a61e..30e6c078b1 100644 --- a/actionpack/lib/action_view/helpers/cache_helper.rb +++ b/actionpack/lib/action_view/helpers/cache_helper.rb @@ -2,11 +2,11 @@ module ActionView # = Action View Cache Helper module Helpers module CacheHelper - # This helper exposes a method for caching view fragments caching - # fragments of a view rather than an entire action or page. This - # technique is useful caching pieces like menus, lists of news - # topics, static HTML fragments, and so on. This method takes a - # block that contains the content you wish to cache. + # This helper exposes a method for caching fragments of a view + # rather than an entire action or page. This technique is useful + # caching pieces like menus, lists of newstopics, static HTML + # fragments, and so on. This method takes a block that contains + # the content you wish to cache. # # See ActionController::Caching::Fragments for usage instructions. # -- cgit v1.2.3 From 9dfa06acb4414349e6cb70b35f0dbd1b112e4256 Mon Sep 17 00:00:00 2001 From: Rizwan Reza Date: Thu, 23 Dec 2010 16:29:40 +0330 Subject: Edits to caching/fragments. --- .../lib/action_controller/caching/fragments.rb | 56 +++++++++++++++------- 1 file changed, 39 insertions(+), 17 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_controller/caching/fragments.rb b/actionpack/lib/action_controller/caching/fragments.rb index 37c155b9cd..88f973e62d 100644 --- a/actionpack/lib/action_controller/caching/fragments.rb +++ b/actionpack/lib/action_controller/caching/fragments.rb @@ -1,40 +1,59 @@ 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 done using the cache helper available in the Action View. A template with caching might look something like: + # Fragment caching is used for caching various blocks within + # views 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 done using + # the cache helper available in the Action View. A + # template with fragment caching might look like: # # Hello <%= @name %> + # # <% cache do %> # All the topics in the system: # <%= render :partial => "topic", :collection => Topic.find(:all) %> # <% end %> # - # This cache will bind to the name of the action that called it, so if this code was part of the view for the topics/list action, you would - # be able to invalidate it using expire_fragment(:controller => "topics", :action => "list"). + # This cache will bind the name of the action that called it, so if + # this code was part of the view for the topics/list action, you + # would be able to invalidate it using: + # + # expire_fragment(:controller => "topics", :action => "list") # - # This default behavior is of limited use if you need to cache multiple fragments per action or if the action itself is cached using - # caches_action, so we also have the option to qualify the name of the cached fragment with something like: + # This default behavior is limited if you need to cache multiple + # fragments per action or if the action itself is cached using + # caches_action. To remedy this, there is an option to + # qualify the name of the cached fragment by using the + # :action_suffix option: # # <% cache(:action => "list", :action_suffix => "all_topics") do %> # - # That would result in a name such as /topics/list/all_topics, avoiding conflicts with the action cache and with any fragments that use a - # different suffix. Note that the URL doesn't have to really exist or be callable - the url_for system is just used to generate unique - # cache names that we can refer to when we need to expire the cache. + # That would result in a name such as + # /topics/list/all_topics, avoiding conflicts with the + # action cache and with any fragments that use a different suffix. + # Note that the URL doesn't have to really exist or be callable + # - the url_for system is just used to generate unique cache names + # that we can refer to when we need to expire the cache. # # The expiration call for this example is: # - # expire_fragment(:controller => "topics", :action => "list", :action_suffix => "all_topics") + # expire_fragment(:controller => "topics", + # :action => "list", + # :action_suffix => "all_topics") module Fragments - # Given a key (as described in expire_fragment), returns a key suitable for use in reading, - # writing, or expiring a cached fragment. If the key is a hash, the generated key is the return - # value of url_for on that hash (without the protocol). All keys are prefixed with views/ and uses + # Given a key (as described in expire_fragment), returns + # a key suitable for use in reading, writing, or expiring a + # cached fragment. If the key is a hash, the generated key is the + # return value of url_for on that hash (without the protocol). + # All keys are prefixed with views/ and uses # ActiveSupport::Cache.expand_cache_key for the expansion. def fragment_cache_key(key) ActiveSupport::Cache.expand_cache_key(key.is_a?(Hash) ? url_for(key).split("://").last : key, :views) end - # Writes content to the location signified by key (see expire_fragment for acceptable formats) + # Writes content to the location signified by + # key (see expire_fragment for acceptable formats). def write_fragment(key, content, options = nil) return content unless cache_configured? @@ -46,7 +65,8 @@ module ActionController #:nodoc: content end - # Reads a cached fragment from the location signified by key (see expire_fragment for acceptable formats) + # Reads a cached fragment from the location signified by key + # (see expire_fragment for acceptable formats). def read_fragment(key, options = nil) return unless cache_configured? @@ -57,7 +77,8 @@ module ActionController #:nodoc: end end - # Check if a cached fragment from the location signified by key exists (see expire_fragment for acceptable formats) + # Check if a cached fragment from the location signified by + # key exists (see expire_fragment for acceptable formats) def fragment_exist?(key, options = nil) return unless cache_configured? key = fragment_cache_key(key) @@ -70,6 +91,7 @@ module ActionController #:nodoc: # Removes fragments from the cache. # # +key+ can take one of three forms: + # # * String - This would normally take the form of a path, like # pages/45/notes. # * Hash - Treated as an implicit call to +url_for+, like -- cgit v1.2.3 From 819b8cae40623d26ce3c050d482b490539a25b98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Thu, 23 Dec 2010 19:17:02 +0100 Subject: Clean up callbacks should also be called on exceptions. --- actionpack/lib/action_dispatch/middleware/reloader.rb | 3 +++ actionpack/test/dispatch/reloader_test.rb | 14 ++++++++++++++ 2 files changed, 17 insertions(+) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/middleware/reloader.rb b/actionpack/lib/action_dispatch/middleware/reloader.rb index 7624a1871a..f6ab368ad8 100644 --- a/actionpack/lib/action_dispatch/middleware/reloader.rb +++ b/actionpack/lib/action_dispatch/middleware/reloader.rb @@ -68,6 +68,9 @@ module ActionDispatch response = @app.call(env) response[2].extend(CleanupOnClose) response + rescue Exception + _run_cleanup_callbacks + raise end end end diff --git a/actionpack/test/dispatch/reloader_test.rb b/actionpack/test/dispatch/reloader_test.rb index 995b19030c..eaabc1feb3 100644 --- a/actionpack/test/dispatch/reloader_test.rb +++ b/actionpack/test/dispatch/reloader_test.rb @@ -116,6 +116,20 @@ class ReloaderTest < Test::Unit::TestCase assert cleaned end + def test_cleanup_callbacks_are_called_on_exceptions + cleaned = false + Reloader.to_cleanup { cleaned = true } + + begin + call_and_return_body do + raise "error" + end + rescue + end + + assert cleaned + end + private def call_and_return_body(&block) @reloader ||= Reloader.new(block || proc {[200, {}, 'response']}) -- cgit v1.2.3 From d6efd3cfc2c6d6822aeac550852c49135fbe46c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Thu, 23 Dec 2010 19:20:57 +0100 Subject: Don't deprecate to_prepare. --- actionpack/lib/action_dispatch/middleware/callbacks.rb | 8 ++++---- actionpack/test/dispatch/callbacks_test.rb | 12 +++++++----- 2 files changed, 11 insertions(+), 9 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/middleware/callbacks.rb b/actionpack/lib/action_dispatch/middleware/callbacks.rb index 5776a7bb27..4d038c29f2 100644 --- a/actionpack/lib/action_dispatch/middleware/callbacks.rb +++ b/actionpack/lib/action_dispatch/middleware/callbacks.rb @@ -1,3 +1,5 @@ +require 'active_support/core_ext/module/delegation' + module ActionDispatch # Provide callbacks to be executed before and after the request dispatch. class Callbacks @@ -5,10 +7,8 @@ module ActionDispatch define_callbacks :call, :rescuable => true - def self.to_prepare(*args, &block) - ActiveSupport::Deprecation.warn "ActionDispatch::Callbacks.to_prepare is deprecated. " << - "Please use ActionDispatch::Reloader.to_prepare instead." - ActionDispatch::Reloader.to_prepare(*args, &block) + class << self + delegate :to_prepare, :to_cleanup, :to => "ActionDispatch::Reloader" end def self.before(*args, &block) diff --git a/actionpack/test/dispatch/callbacks_test.rb b/actionpack/test/dispatch/callbacks_test.rb index 5becb621de..eed2eca2ab 100644 --- a/actionpack/test/dispatch/callbacks_test.rb +++ b/actionpack/test/dispatch/callbacks_test.rb @@ -29,14 +29,16 @@ class DispatcherTest < ActiveSupport::TestCase assert_equal 4, Foo.b end - def test_to_prepare_deprecation - prepared = false - assert_deprecated do - ActionDispatch::Callbacks.to_prepare { prepared = true } - end + def test_to_prepare_and_cleanup_delegation + prepared = cleaned = false + ActionDispatch::Callbacks.to_prepare { prepared = true } + ActionDispatch::Callbacks.to_prepare { cleaned = true } ActionDispatch::Reloader.prepare! assert prepared + + ActionDispatch::Reloader.cleanup! + assert cleaned end private -- cgit v1.2.3 From 2cbf948f25a1a0eeeea641d14a95480432cbda24 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Fri, 24 Dec 2010 14:38:18 -0200 Subject: Bump up rack-cache --- actionpack/actionpack.gemspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack') diff --git a/actionpack/actionpack.gemspec b/actionpack/actionpack.gemspec index b7d1d8c2af..20becc0bb1 100644 --- a/actionpack/actionpack.gemspec +++ b/actionpack/actionpack.gemspec @@ -21,7 +21,7 @@ Gem::Specification.new do |s| s.add_dependency('activesupport', version) s.add_dependency('activemodel', version) - s.add_dependency('rack-cache', '~> 0.5.3') + s.add_dependency('rack-cache', '~> 1.0.0') s.add_dependency('builder', '~> 3.0.0') s.add_dependency('i18n', '~> 0.5.0') s.add_dependency('rack', '~> 1.2.1') -- cgit v1.2.3 From 0a1f5f751193d2bbb41ae91226ab4567c502f51c Mon Sep 17 00:00:00 2001 From: Akira Matsuda Date: Sat, 25 Dec 2010 04:41:50 +0900 Subject: for ... in => each ... do --- actionpack/lib/action_view/base.rb | 2 +- actionpack/lib/action_view/partials.rb | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb index 92ff3380b0..f1ea14fc29 100644 --- a/actionpack/lib/action_view/base.rb +++ b/actionpack/lib/action_view/base.rb @@ -18,7 +18,7 @@ module ActionView #:nodoc: # following loop for names: # # Names of all the people - # <% for person in @people %> + # <% @people.each do |person| %> # Name: <%= person.name %>
# <% end %> # diff --git a/actionpack/lib/action_view/partials.rb b/actionpack/lib/action_view/partials.rb index cd3f130dc4..b823dbcf6a 100644 --- a/actionpack/lib/action_view/partials.rb +++ b/actionpack/lib/action_view/partials.rb @@ -19,7 +19,7 @@ module ActionView # # <%= render :partial => "account", :locals => { :account => @buyer } %> # - # <% for ad in @advertisements %> + # <% @advertisements.each do |ad| %> # <%= render :partial => "ad", :locals => { :ad => ad } %> # <% end %> # @@ -44,12 +44,12 @@ module ActionView # # The :object option can be used to directly specify which object is rendered into the partial; # useful when the template's object is elsewhere, in a different ivar or in a local variable for instance. - # + # # Revisiting a previous example we could have written this code: - # + # # <%= render :partial => "account", :object => @buyer %> # - # <% for ad in @advertisements %> + # <% @advertisements.each do |ad| %> # <%= render :partial => "ad", :object => ad %> # <% end %> # @@ -69,7 +69,7 @@ module ActionView # +partial_name_counter+. In the case of the example above, the template would be fed +ad_counter+. # # The :as option may be used when rendering partials. - # + # # You can specify a partial to be rendered between elements via the :spacer_template option. # The following example will render advertiser/_ad_divider.html.erb between each ad partial: # -- cgit v1.2.3 From 4e50c6c08aa420456f0e456444a0cb4a277de7a7 Mon Sep 17 00:00:00 2001 From: Akira Matsuda Date: Sat, 25 Dec 2010 04:57:15 +0900 Subject: .erb => .html.erb --- actionpack/lib/action_controller/base.rb | 2 +- actionpack/lib/action_view/partials.rb | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb index 48308cbb60..81c0698fb8 100644 --- a/actionpack/lib/action_controller/base.rb +++ b/actionpack/lib/action_controller/base.rb @@ -24,7 +24,7 @@ module ActionController # # Actions, by default, render a template in the app/views directory corresponding to the name of the controller and action # after executing code in the action. For example, the +index+ action of the PostsController would render the - # template app/views/posts/index.erb by default after populating the @posts instance variable. + # template app/views/posts/index.html.erb by default after populating the @posts instance variable. # # Unlike index, the create action will not render a template. After performing its main purpose (creating a # new post), it initiates a redirect instead. This redirect works by returning an external diff --git a/actionpack/lib/action_view/partials.rb b/actionpack/lib/action_view/partials.rb index b823dbcf6a..56c661c00c 100644 --- a/actionpack/lib/action_view/partials.rb +++ b/actionpack/lib/action_view/partials.rb @@ -12,7 +12,7 @@ module ActionView # # <%= render :partial => "account" %> # - # This would render "advertiser/_account.erb" and pass the instance variable @account in as a local variable + # This would render "advertiser/_account.html.erb" and pass the instance variable @account in as a local variable # +account+ to the template for display. # # In another template for Advertiser#buy, we could have: @@ -23,8 +23,8 @@ module ActionView # <%= render :partial => "ad", :locals => { :ad => ad } %> # <% end %> # - # This would first render "advertiser/_account.erb" with @buyer passed in as the local variable +account+, then - # render "advertiser/_ad.erb" and pass the local variable +ad+ to the template for display. + # This would first render "advertiser/_account.html.erb" with @buyer passed in as the local variable +account+, then + # render "advertiser/_ad.html.erb" and pass the local variable +ad+ to the template for display. # # == The :as and :object options # @@ -64,7 +64,7 @@ module ActionView # # <%= render :partial => "ad", :collection => @advertisements %> # - # This will render "advertiser/_ad.erb" and pass the local variable +ad+ to the template for display. An + # This will render "advertiser/_ad.html.erb" and pass the local variable +ad+ to the template for display. An # iteration counter will automatically be made available to the template with a name of the form # +partial_name_counter+. In the case of the example above, the template would be fed +ad_counter+. # @@ -89,7 +89,7 @@ module ActionView # # <%= render :partial => "advertisement/ad", :locals => { :ad => @advertisement } %> # - # This will render the partial "advertisement/_ad.erb" regardless of which controller this is being called from. + # This will render the partial "advertisement/_ad.html.erb" regardless of which controller this is being called from. # # == Rendering objects with the RecordIdentifier # -- cgit v1.2.3 From ddd85ef9c6a6297a8ff28816d907bbbf2eae5856 Mon Sep 17 00:00:00 2001 From: artemave Date: Fri, 17 Sep 2010 20:39:14 +0000 Subject: #948 template_inheritance --- actionpack/lib/abstract_controller/layouts.rb | 4 +- actionpack/lib/abstract_controller/rendering.rb | 16 ++++++-- .../lib/action_controller/metal/implicit_render.rb | 4 +- actionpack/lib/action_view/lookup_context.rb | 31 ++++++++++------ actionpack/lib/action_view/path_set.rb | 16 +++++--- .../lib/action_view/renderer/partial_renderer.rb | 4 +- .../lib/action_view/renderer/template_renderer.rb | 4 +- actionpack/lib/action_view/testing/resolvers.rb | 6 ++- .../test/abstract/abstract_controller_test.rb | 14 +++---- actionpack/test/abstract/render_test.rb | 4 +- .../controller/new_base/render_partial_test.rb | 25 ++++++++++++- actionpack/test/controller/new_base/render_test.rb | 43 +++++++++++++++++++++- 12 files changed, 129 insertions(+), 42 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/abstract_controller/layouts.rb b/actionpack/lib/abstract_controller/layouts.rb index 606f7eedec..4ee54474cc 100644 --- a/actionpack/lib/abstract_controller/layouts.rb +++ b/actionpack/lib/abstract_controller/layouts.rb @@ -265,11 +265,11 @@ module AbstractController raise ArgumentError, "Layouts must be specified as a String, Symbol, false, or nil" when nil if name - _prefix = "layouts" unless _implied_layout_name =~ /\blayouts/ + _prefixes = _implied_layout_name =~ /\blayouts/ ? [] : ["layouts"] self.class_eval <<-RUBY, __FILE__, __LINE__ + 1 def _layout - if template_exists?("#{_implied_layout_name}", #{_prefix.inspect}) + if template_exists?("#{_implied_layout_name}", #{_prefixes.inspect}) "#{_implied_layout_name}" else super diff --git a/actionpack/lib/abstract_controller/rendering.rb b/actionpack/lib/abstract_controller/rendering.rb index 91b75273fa..06f4441609 100644 --- a/actionpack/lib/abstract_controller/rendering.rb +++ b/actionpack/lib/abstract_controller/rendering.rb @@ -114,9 +114,17 @@ module AbstractController view_context.render(options) end - # The prefix used in render "foo" shortcuts. - def _prefix - controller_path + # The prefixes used in render "foo" shortcuts. + def _prefixes + prefixes = [controller_path] + parent_controller = self.class.superclass + + until parent_controller.abstract? + prefixes << parent_controller.controller_path + parent_controller = parent_controller.superclass + end + + prefixes end private @@ -156,7 +164,7 @@ module AbstractController end if (options.keys & [:partial, :file, :template, :once]).empty? - options[:prefix] ||= _prefix + options[:prefixes] ||= _prefixes end options[:template] ||= (options[:action] || action_name).to_s diff --git a/actionpack/lib/action_controller/metal/implicit_render.rb b/actionpack/lib/action_controller/metal/implicit_render.rb index 282dcf66b3..cfa7004048 100644 --- a/actionpack/lib/action_controller/metal/implicit_render.rb +++ b/actionpack/lib/action_controller/metal/implicit_render.rb @@ -12,10 +12,10 @@ module ActionController def method_for_action(action_name) super || begin - if template_exists?(action_name.to_s, _prefix) + if template_exists?(action_name.to_s, _prefixes) "default_render" end end end end -end \ No newline at end of file +end diff --git a/actionpack/lib/action_view/lookup_context.rb b/actionpack/lib/action_view/lookup_context.rb index d524c68450..14cccd88f0 100644 --- a/actionpack/lib/action_view/lookup_context.rb +++ b/actionpack/lib/action_view/lookup_context.rb @@ -78,17 +78,17 @@ module ActionView @view_paths = ActionView::Base.process_view_paths(paths) end - def find(name, prefix = nil, partial = false, keys = []) - @view_paths.find(*args_for_lookup(name, prefix, partial, keys)) + def find(name, prefixes = [], partial = false, keys = []) + @view_paths.find(*args_for_lookup(name, prefixes, partial, keys)) end alias :find_template :find - def find_all(name, prefix = nil, partial = false, keys = []) - @view_paths.find_all(*args_for_lookup(name, prefix, partial, keys)) + def find_all(name, prefixes = [], partial = false, keys = []) + @view_paths.find_all(*args_for_lookup(name, prefixes, partial, keys)) end - def exists?(name, prefix = nil, partial = false, keys = []) - @view_paths.exists?(*args_for_lookup(name, prefix, partial, keys)) + def exists?(name, prefixes = [], partial = false, keys = []) + @view_paths.exists?(*args_for_lookup(name, prefixes, partial, keys)) end alias :template_exists? :exists? @@ -107,18 +107,25 @@ module ActionView protected - def args_for_lookup(name, prefix, partial, keys) #:nodoc: - name, prefix = normalize_name(name, prefix) - [name, prefix, partial || false, @details, details_key, keys] + def args_for_lookup(name, prefixes, partial, keys) #:nodoc: + name, prefixes = normalize_name(name, prefixes) + [name, prefixes, partial || false, @details, details_key, keys] end # Support legacy foo.erb names even though we now ignore .erb # as well as incorrectly putting part of the path in the template # name instead of the prefix. - def normalize_name(name, prefix) #:nodoc: + def normalize_name(name, prefixes) #:nodoc: name = name.to_s.gsub(handlers_regexp, '') parts = name.split('/') - return parts.pop, [prefix, *parts].compact.join("/") + name = parts.pop + prx = if not prefixes or prefixes.empty? + [parts.compact.join('/')] + else + prefixes.map {|prefix| [prefix, *parts].compact.join('/') } + end + + return name, prx end def default_handlers #:nodoc: @@ -237,4 +244,4 @@ module ActionView include Details include ViewPaths end -end \ No newline at end of file +end diff --git a/actionpack/lib/action_view/path_set.rb b/actionpack/lib/action_view/path_set.rb index fa35120a0d..a7078b8232 100644 --- a/actionpack/lib/action_view/path_set.rb +++ b/actionpack/lib/action_view/path_set.rb @@ -11,15 +11,19 @@ module ActionView #:nodoc: end def find(*args) - find_all(*args).first || raise(MissingTemplate.new(self, "#{args[1]}/#{args[0]}", args[3], args[2])) + template = find_all(*args).first + template or raise MissingTemplate.new(self, "{#{args[1].join(',')},}/#{args[0]}", args[3], args[2]) end - def find_all(*args) - each do |resolver| - templates = resolver.find_all(*args) - return templates unless templates.empty? + def find_all(path, prefixes = [], *args) + templates = [] + prefixes.each do |prefix| + each do |resolver| + templates << resolver.find_all(path, prefix, *args) + end + # return templates unless templates.flatten!.empty? XXX this was original behavior; turns this method into find_some, but probably makes it faster end - [] + templates.flatten end def exists?(*args) diff --git a/actionpack/lib/action_view/renderer/partial_renderer.rb b/actionpack/lib/action_view/renderer/partial_renderer.rb index 317479ad4c..e83f7be610 100644 --- a/actionpack/lib/action_view/renderer/partial_renderer.rb +++ b/actionpack/lib/action_view/renderer/partial_renderer.rb @@ -111,8 +111,8 @@ module ActionView end def find_template(path=@path, locals=@locals.keys) - prefix = @view.controller_prefix unless path.include?(?/) - @lookup_context.find_template(path, prefix, true, locals) + prefixes = path.include?(?/) ? [] : @view.controller._prefixes + @lookup_context.find_template(path, prefixes, true, locals) end def collection_with_template diff --git a/actionpack/lib/action_view/renderer/template_renderer.rb b/actionpack/lib/action_view/renderer/template_renderer.rb index ece3f621b6..4a0bc503d3 100644 --- a/actionpack/lib/action_view/renderer/template_renderer.rb +++ b/actionpack/lib/action_view/renderer/template_renderer.rb @@ -43,13 +43,13 @@ module ActionView if options.key?(:text) Template::Text.new(options[:text], formats.try(:first)) elsif options.key?(:file) - with_fallbacks { find_template(options[:file], options[:prefix], false, keys) } + with_fallbacks { find_template(options[:file], [], false, keys) } elsif options.key?(:inline) handler = Template.handler_for_extension(options[:type] || "erb") Template.new(options[:inline], "inline template", handler, :locals => keys) elsif options.key?(:template) options[:template].respond_to?(:render) ? - options[:template] : find_template(options[:template], options[:prefix], false, keys) + options[:template] : find_template(options[:template], options[:prefixes], false, keys) end end diff --git a/actionpack/lib/action_view/testing/resolvers.rb b/actionpack/lib/action_view/testing/resolvers.rb index 55583096e0..5c5cab7c7d 100644 --- a/actionpack/lib/action_view/testing/resolvers.rb +++ b/actionpack/lib/action_view/testing/resolvers.rb @@ -13,7 +13,11 @@ module ActionView #:nodoc: @hash = hash end - private + def to_s + @hash.keys.join(', ') + end + + private def query(path, exts, formats) query = "" diff --git a/actionpack/test/abstract/abstract_controller_test.rb b/actionpack/test/abstract/abstract_controller_test.rb index 19855490b4..981c023d38 100644 --- a/actionpack/test/abstract/abstract_controller_test.rb +++ b/actionpack/test/abstract/abstract_controller_test.rb @@ -30,14 +30,14 @@ module AbstractController class RenderingController < AbstractController::Base include ::AbstractController::Rendering - def _prefix() end + def _prefixes + [] + end def render(options = {}) if options.is_a?(String) options = {:_template_name => options} end - - options[:_prefix] = _prefix super end @@ -116,8 +116,8 @@ module AbstractController name.underscore end - def _prefix - self.class.prefix + def _prefixes + [self.class.prefix] end end @@ -157,10 +157,10 @@ module AbstractController private def self.layout(formats) begin - find_template(name.underscore, {:formats => formats}, :_prefix => "layouts") + find_template(name.underscore, {:formats => formats}, :_prefixes => ["layouts"]) rescue ActionView::MissingTemplate begin - find_template("application", {:formats => formats}, :_prefix => "layouts") + find_template("application", {:formats => formats}, :_prefixes => ["layouts"]) rescue ActionView::MissingTemplate end end diff --git a/actionpack/test/abstract/render_test.rb b/actionpack/test/abstract/render_test.rb index 25dc8bd804..b9293d1241 100644 --- a/actionpack/test/abstract/render_test.rb +++ b/actionpack/test/abstract/render_test.rb @@ -6,8 +6,8 @@ module AbstractController class ControllerRenderer < AbstractController::Base include AbstractController::Rendering - def _prefix - "renderer" + def _prefixes + %w[renderer] end self.view_paths = [ActionView::FixtureResolver.new( diff --git a/actionpack/test/controller/new_base/render_partial_test.rb b/actionpack/test/controller/new_base/render_partial_test.rb index d800ea264d..83b0d039ad 100644 --- a/actionpack/test/controller/new_base/render_partial_test.rb +++ b/actionpack/test/controller/new_base/render_partial_test.rb @@ -9,7 +9,10 @@ module RenderPartial "render_partial/basic/basic.html.erb" => "<%= @test_unchanged = 'goodbye' %><%= render :partial => 'basic' %><%= @test_unchanged %>", "render_partial/basic/with_json.html.erb" => "<%= render 'with_json.json' %>", "render_partial/basic/_with_json.json.erb" => "<%= render 'final' %>", - "render_partial/basic/_final.json.erb" => "{ final: json }" + "render_partial/basic/_final.json.erb" => "{ final: json }", + "render_partial/basic/overriden.html.erb" => "<%= @test_unchanged = 'goodbye' %><%= render :partial => 'overriden' %><%= @test_unchanged %>", + "render_partial/basic/_overriden.html.erb" => "ParentPartial!", + "render_partial/child/_overriden.html.erb" => "OverridenPartial!" )] def html_with_json_inside_json @@ -20,7 +23,13 @@ module RenderPartial @test_unchanged = 'hello' render :action => "basic" end + + def overriden + @test_unchanged = 'hello' + end end + + class ChildController < BasicController; end class TestPartial < Rack::TestCase testing BasicController @@ -37,4 +46,18 @@ module RenderPartial end end + class TestInheritedPartial < Rack::TestCase + testing ChildController + + test "partial from parent controller gets picked if missing in child one" do + get :changing + assert_response("goodbyeBasicPartial!goodbye") + end + + test "partial from child controller gets picked" do + get :overriden + assert_response("goodbyeOverridenPartial!goodbye") + end + end + end diff --git a/actionpack/test/controller/new_base/render_test.rb b/actionpack/test/controller/new_base/render_test.rb index df97a2725b..a520934c5b 100644 --- a/actionpack/test/controller/new_base/render_test.rb +++ b/actionpack/test/controller/new_base/render_test.rb @@ -6,7 +6,11 @@ module Render "render/blank_render/index.html.erb" => "Hello world!", "render/blank_render/access_request.html.erb" => "The request: <%= request.method.to_s.upcase %>", "render/blank_render/access_action_name.html.erb" => "Action Name: <%= action_name %>", - "render/blank_render/access_controller_name.html.erb" => "Controller Name: <%= controller_name %>" + "render/blank_render/access_controller_name.html.erb" => "Controller Name: <%= controller_name %>", + "render/blank_render/overriden_with_own_view_paths_appended.html.erb" => "parent content", + "render/blank_render/overriden_with_own_view_paths_prepended.html.erb" => "parent content", + "render/blank_render/overriden.html.erb" => "parent content", + "render/child_render/overriden.html.erb" => "child content" )] def index @@ -21,6 +25,15 @@ module Render render :action => "access_action_name" end + def overriden_with_own_view_paths_appended + end + + def overriden_with_own_view_paths_prepended + end + + def overriden + end + private def secretz @@ -35,6 +48,11 @@ module Render end end + class ChildRenderController < BlankRenderController + append_view_path ActionView::FixtureResolver.new("render/child_render/overriden_with_own_view_paths_appended.html.erb" => "child content") + prepend_view_path ActionView::FixtureResolver.new("render/child_render/overriden_with_own_view_paths_prepended.html.erb" => "child content") + end + class RenderTest < Rack::TestCase test "render with blank" do with_routing do |set| @@ -94,4 +112,27 @@ module Render assert_body "Controller Name: blank_render" end end + + class TestViewInheritance < Rack::TestCase + test "Template from child controller gets picked over parent one" do + get "/render/child_render/overriden" + assert_body "child content" + end + + test "Template from child controller with custom view_paths prepended gets picked over parent one" do + get "/render/child_render/overriden_with_own_view_paths_prepended" + assert_body "child content" + end + + test "Template from child controller with custom view_paths appended gets picked over parent one" do + get "/render/child_render/overriden_with_own_view_paths_appended" + assert_body "child content" + end + + test "Template from parent controller gets picked if missing in child controller" do + get "/render/child_render/index" + assert_body "Hello world!" + end + end + end -- cgit v1.2.3 From ce21ea783255a30e330c7218a3043801dfe9ad52 Mon Sep 17 00:00:00 2001 From: artemave Date: Fri, 1 Oct 2010 17:49:30 +0000 Subject: #948 make template inheritance optional --- actionpack/lib/abstract_controller/rendering.rb | 16 ++++++++++++---- actionpack/test/controller/new_base/render_test.rb | 11 +++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/abstract_controller/rendering.rb b/actionpack/lib/abstract_controller/rendering.rb index 06f4441609..01dd4ffeb1 100644 --- a/actionpack/lib/abstract_controller/rendering.rb +++ b/actionpack/lib/abstract_controller/rendering.rb @@ -117,11 +117,14 @@ module AbstractController # The prefixes used in render "foo" shortcuts. def _prefixes prefixes = [controller_path] - parent_controller = self.class.superclass - until parent_controller.abstract? - prefixes << parent_controller.controller_path - parent_controller = parent_controller.superclass + if template_inheritance? + parent_controller = self.class.superclass + + until parent_controller.abstract? + prefixes << parent_controller.controller_path + parent_controller = parent_controller.superclass + end end prefixes @@ -173,5 +176,10 @@ module AbstractController def _process_options(options) end + + def template_inheritance? + # is there a better way to check for config option being set? + config.template_inheritance.nil? ? true : config.template_inheritance + end end end diff --git a/actionpack/test/controller/new_base/render_test.rb b/actionpack/test/controller/new_base/render_test.rb index a520934c5b..f5baa829b6 100644 --- a/actionpack/test/controller/new_base/render_test.rb +++ b/actionpack/test/controller/new_base/render_test.rb @@ -53,6 +53,10 @@ module Render prepend_view_path ActionView::FixtureResolver.new("render/child_render/overriden_with_own_view_paths_prepended.html.erb" => "child content") end + class ChildRenderWithoutInheritanceController < BlankRenderController + config.template_inheritance = false + end + class RenderTest < Rack::TestCase test "render with blank" do with_routing do |set| @@ -135,4 +139,11 @@ module Render end end + class TestNoViewInheritance < Rack::TestCase + test "Template from parent controller does not get picked if config.action_controller.template_inheritance = false" do + assert_raises(ActionView::MissingTemplate) do + get "/render/child_render_without_inheritance/index", {}, "action_dispatch.show_exceptions" => false + end + end + end end -- cgit v1.2.3 From 6c5a3bb3125735760e92f49c3824d757ef87c61e Mon Sep 17 00:00:00 2001 From: artemave Date: Sun, 12 Dec 2010 20:40:40 +0000 Subject: all tests pass --- actionpack/lib/action_view/base.rb | 4 +- actionpack/lib/action_view/lookup_context.rb | 2 +- .../lib/action_view/renderer/partial_renderer.rb | 2 +- .../lib/action_view/renderer/template_renderer.rb | 4 +- actionpack/lib/action_view/template.rb | 2 +- .../test/controller/new_base/render_once_test.rb | 8 ++-- actionpack/test/template/log_subscriber_test.rb | 6 +-- actionpack/test/template/lookup_context_test.rb | 48 +++++++++++----------- actionpack/test/template/template_test.rb | 4 +- 9 files changed, 40 insertions(+), 40 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb index 92ff3380b0..95eb3446da 100644 --- a/actionpack/lib/action_view/base.rb +++ b/actionpack/lib/action_view/base.rb @@ -232,8 +232,8 @@ module ActionView #:nodoc: @controller_path ||= controller && controller.controller_path end - def controller_prefix - @controller_prefix ||= controller && controller._prefix + def controller_prefixes + @controller_prefixes ||= controller && controller._prefixes end ActiveSupport.run_load_hooks(:action_view, self) diff --git a/actionpack/lib/action_view/lookup_context.rb b/actionpack/lib/action_view/lookup_context.rb index 14cccd88f0..0d7f15e564 100644 --- a/actionpack/lib/action_view/lookup_context.rb +++ b/actionpack/lib/action_view/lookup_context.rb @@ -119,7 +119,7 @@ module ActionView name = name.to_s.gsub(handlers_regexp, '') parts = name.split('/') name = parts.pop - prx = if not prefixes or prefixes.empty? + prx = if prefixes.blank? [parts.compact.join('/')] else prefixes.map {|prefix| [prefix, *parts].compact.join('/') } diff --git a/actionpack/lib/action_view/renderer/partial_renderer.rb b/actionpack/lib/action_view/renderer/partial_renderer.rb index e83f7be610..f36b0602b1 100644 --- a/actionpack/lib/action_view/renderer/partial_renderer.rb +++ b/actionpack/lib/action_view/renderer/partial_renderer.rb @@ -152,7 +152,7 @@ module ActionView object = object.to_model if object.respond_to?(:to_model) object.class.model_name.partial_path.dup.tap do |partial| - path = @view.controller_prefix + path = @view.controller_prefixes.first partial.insert(0, "#{File.dirname(path)}/") if partial.include?(?/) && path.include?(?/) end end diff --git a/actionpack/lib/action_view/renderer/template_renderer.rb b/actionpack/lib/action_view/renderer/template_renderer.rb index 4a0bc503d3..938bb2a3f3 100644 --- a/actionpack/lib/action_view/renderer/template_renderer.rb +++ b/actionpack/lib/action_view/renderer/template_renderer.rb @@ -22,14 +22,14 @@ module ActionView def render_once(options) paths, locals = options[:once], options[:locals] || {} layout, keys = options[:layout], locals.keys - prefix = options.fetch(:prefix, @view.controller_prefix) + prefixes = options.fetch(:prefixes, @view.controller_prefixes) raise "render :once expects a String or an Array to be given" unless paths render_with_layout(layout, locals) do contents = [] Array.wrap(paths).each do |path| - template = find_template(path, prefix, false, keys) + template = find_template(path, prefixes, false, keys) contents << render_template(template, nil, locals) if @rendered.add?(template) end contents.join("\n") diff --git a/actionpack/lib/action_view/template.rb b/actionpack/lib/action_view/template.rb index 0d8373ef14..80543a8b77 100644 --- a/actionpack/lib/action_view/template.rb +++ b/actionpack/lib/action_view/template.rb @@ -163,7 +163,7 @@ module ActionView name = pieces.pop partial = !!name.sub!(/^_/, "") lookup.disable_cache do - lookup.find_template(name, pieces.join('/'), partial, @locals) + lookup.find_template(name, [ pieces.join('/') ], partial, @locals) end end diff --git a/actionpack/test/controller/new_base/render_once_test.rb b/actionpack/test/controller/new_base/render_once_test.rb index 3035ed4ff2..175abf8a7e 100644 --- a/actionpack/test/controller/new_base/render_once_test.rb +++ b/actionpack/test/controller/new_base/render_once_test.rb @@ -18,8 +18,8 @@ module RenderTemplate self.view_paths = [RESOLVER] - def _prefix - "test" + def _prefixes + %w(test) end def multiple @@ -39,11 +39,11 @@ module RenderTemplate end def with_prefix - render :once => "result", :prefix => "other" + render :once => "result", :prefixes => %w(other) end def with_nil_prefix - render :once => "test/result", :prefix => nil + render :once => "test/result", :prefixes => [] end end diff --git a/actionpack/test/template/log_subscriber_test.rb b/actionpack/test/template/log_subscriber_test.rb index 435936b19f..8b8b005a1d 100644 --- a/actionpack/test/template/log_subscriber_test.rb +++ b/actionpack/test/template/log_subscriber_test.rb @@ -57,7 +57,7 @@ class AVLogSubscriberTest < ActiveSupport::TestCase end def test_render_partial_with_implicit_path - @view.stubs(:controller_prefix).returns("test") + @view.stubs(:controller_prefixes).returns(%w(test)) @view.render(Customer.new("david"), :greeting => "hi") wait @@ -74,7 +74,7 @@ class AVLogSubscriberTest < ActiveSupport::TestCase end def test_render_collection_with_implicit_path - @view.stubs(:controller_prefix).returns("test") + @view.stubs(:controller_prefixes).returns(%w(test)) @view.render([ Customer.new("david"), Customer.new("mary") ], :greeting => "hi") wait @@ -83,7 +83,7 @@ class AVLogSubscriberTest < ActiveSupport::TestCase end def test_render_collection_template_without_path - @view.stubs(:controller_prefix).returns("test") + @view.stubs(:controller_prefixes).returns(%w(test)) @view.render([ GoodCustomer.new("david"), Customer.new("mary") ], :greeting => "hi") wait diff --git a/actionpack/test/template/lookup_context_test.rb b/actionpack/test/template/lookup_context_test.rb index c9dd27cf2a..a629b3c046 100644 --- a/actionpack/test/template/lookup_context_test.rb +++ b/actionpack/test/template/lookup_context_test.rb @@ -80,18 +80,18 @@ class LookupContextTest < ActiveSupport::TestCase end test "find templates using the given view paths and configured details" do - template = @lookup_context.find("hello_world", "test") + template = @lookup_context.find("hello_world", %w(test)) assert_equal "Hello world!", template.source @lookup_context.locale = :da - template = @lookup_context.find("hello_world", "test") + template = @lookup_context.find("hello_world", %w(test)) assert_equal "Hey verden", template.source end test "found templates respects given formats if one cannot be found from template or handler" do ActionView::Template::Handlers::ERB.expects(:default_format).returns(nil) @lookup_context.formats = [:text] - template = @lookup_context.find("hello_world", "test") + template = @lookup_context.find("hello_world", %w(test)) assert_equal [:text], template.formats end @@ -137,44 +137,44 @@ class LookupContextTest < ActiveSupport::TestCase test "gives the key forward to the resolver, so it can be used as cache key" do @lookup_context.view_paths = ActionView::FixtureResolver.new("test/_foo.erb" => "Foo") - template = @lookup_context.find("foo", "test", true) + template = @lookup_context.find("foo", %w(test), true) assert_equal "Foo", template.source # Now we are going to change the template, but it won't change the returned template # since we will hit the cache. @lookup_context.view_paths.first.hash["test/_foo.erb"] = "Bar" - template = @lookup_context.find("foo", "test", true) + template = @lookup_context.find("foo", %w(test), true) assert_equal "Foo", template.source # This time we will change the locale. The updated template should be picked since # lookup_context generated a new key after we changed the locale. @lookup_context.locale = :da - template = @lookup_context.find("foo", "test", true) + template = @lookup_context.find("foo", %w(test), true) assert_equal "Bar", template.source # Now we will change back the locale and it will still pick the old template. # This is expected because lookup_context will reuse the previous key for :en locale. @lookup_context.locale = :en - template = @lookup_context.find("foo", "test", true) + template = @lookup_context.find("foo", %w(test), true) assert_equal "Foo", template.source # Finally, we can expire the cache. And the expected template will be used. @lookup_context.view_paths.first.clear_cache - template = @lookup_context.find("foo", "test", true) + template = @lookup_context.find("foo", %w(test), true) assert_equal "Bar", template.source end test "can disable the cache on demand" do @lookup_context.view_paths = ActionView::FixtureResolver.new("test/_foo.erb" => "Foo") - old_template = @lookup_context.find("foo", "test", true) + old_template = @lookup_context.find("foo", %w(test), true) - template = @lookup_context.find("foo", "test", true) + template = @lookup_context.find("foo", %w(test), true) assert_equal template, old_template assert @lookup_context.cache template = @lookup_context.disable_cache do assert !@lookup_context.cache - @lookup_context.find("foo", "test", true) + @lookup_context.find("foo", %w(test), true) end assert @lookup_context.cache @@ -182,11 +182,11 @@ class LookupContextTest < ActiveSupport::TestCase end test "data can be stored in cached templates" do - template = @lookup_context.find("hello_world", "test") + template = @lookup_context.find("hello_world", %w(test)) template.data["cached"] = "data" assert_equal "Hello world!", template.source - template = @lookup_context.find("hello_world", "test") + template = @lookup_context.find("hello_world", %w(test)) assert_equal "data", template.data["cached"] assert_equal "Hello world!", template.source end @@ -200,54 +200,54 @@ class LookupContextWithFalseCaching < ActiveSupport::TestCase end test "templates are always found in the resolver but timestamp is checked before being compiled" do - template = @lookup_context.find("foo", "test", true) + template = @lookup_context.find("foo", %w(test), true) assert_equal "Foo", template.source # Now we are going to change the template, but it won't change the returned template # since the timestamp is the same. @resolver.hash["test/_foo.erb"][0] = "Bar" - template = @lookup_context.find("foo", "test", true) + template = @lookup_context.find("foo", %w(test), true) assert_equal "Foo", template.source # Now update the timestamp. @resolver.hash["test/_foo.erb"][1] = Time.now.utc - template = @lookup_context.find("foo", "test", true) + template = @lookup_context.find("foo", %w(test), true) assert_equal "Bar", template.source end test "if no template was found in the second lookup, with no cache, raise error" do - template = @lookup_context.find("foo", "test", true) + template = @lookup_context.find("foo", %w(test), true) assert_equal "Foo", template.source @resolver.hash.clear assert_raise ActionView::MissingTemplate do - @lookup_context.find("foo", "test", true) + @lookup_context.find("foo", %w(test), true) end end test "if no template was cached in the first lookup, retrieval should work in the second call" do @resolver.hash.clear assert_raise ActionView::MissingTemplate do - @lookup_context.find("foo", "test", true) + @lookup_context.find("foo", %w(test), true) end @resolver.hash["test/_foo.erb"] = ["Foo", Time.utc(2000)] - template = @lookup_context.find("foo", "test", true) + template = @lookup_context.find("foo", %w(test), true) assert_equal "Foo", template.source end test "data can be stored as long as template was not updated" do - template = @lookup_context.find("foo", "test", true) + template = @lookup_context.find("foo", %w(test), true) template.data["cached"] = "data" assert_equal "Foo", template.source - template = @lookup_context.find("foo", "test", true) + template = @lookup_context.find("foo", %w(test), true) assert_equal "data", template.data["cached"] assert_equal "Foo", template.source @resolver.hash["test/_foo.erb"][1] = Time.now.utc - template = @lookup_context.find("foo", "test", true) + template = @lookup_context.find("foo", %w(test), true) assert_nil template.data["cached"] assert_equal "Foo", template.source end -end \ No newline at end of file +end diff --git a/actionpack/test/template/template_test.rb b/actionpack/test/template/template_test.rb index 2ec640c84c..3432a02c3c 100644 --- a/actionpack/test/template/template_test.rb +++ b/actionpack/test/template/template_test.rb @@ -95,14 +95,14 @@ class TestERBTemplate < ActiveSupport::TestCase def test_refresh_with_templates @template = new_template("Hello", :virtual_path => "test/foo/bar") @template.locals = [:key] - @context.lookup_context.expects(:find_template).with("bar", "test/foo", false, [:key]).returns("template") + @context.lookup_context.expects(:find_template).with("bar", %w(test/foo), false, [:key]).returns("template") assert_equal "template", @template.refresh(@context) end def test_refresh_with_partials @template = new_template("Hello", :virtual_path => "test/_foo") @template.locals = [:key] - @context.lookup_context.expects(:find_template).with("foo", "test", true, [:key]).returns("partial") + @context.lookup_context.expects(:find_template).with("foo", %w(test), true, [:key]).returns("partial") assert_equal "partial", @template.refresh(@context) end -- cgit v1.2.3 From 7c568fda6ba2d6621a0872e4bc0c71bb2d13e65f Mon Sep 17 00:00:00 2001 From: wycats Date: Sun, 26 Dec 2010 23:44:51 -0800 Subject: A bunch of cleanup on the inherited template patch --- actionpack/lib/action_view/path_set.rb | 32 ++++++++++++++++++------ actionpack/lib/action_view/template/error.rb | 8 ++++-- actionpack/lib/action_view/template/resolver.rb | 2 +- actionpack/test/controller/mime_responds_test.rb | 2 +- 4 files changed, 33 insertions(+), 11 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/path_set.rb b/actionpack/lib/action_view/path_set.rb index a7078b8232..2a54b12f78 100644 --- a/actionpack/lib/action_view/path_set.rb +++ b/actionpack/lib/action_view/path_set.rb @@ -11,23 +11,41 @@ module ActionView #:nodoc: end def find(*args) - template = find_all(*args).first - template or raise MissingTemplate.new(self, "{#{args[1].join(',')},}/#{args[0]}", args[3], args[2]) + if template = find_first(*args) + template + else + raise MissingTemplate.new(self, *args) + end end def find_all(path, prefixes = [], *args) - templates = [] prefixes.each do |prefix| + templates = [] + each do |resolver| - templates << resolver.find_all(path, prefix, *args) + templates.concat resolver.find_all(path, prefix, *args) end - # return templates unless templates.flatten!.empty? XXX this was original behavior; turns this method into find_some, but probably makes it faster + + return templates unless templates.empty? end - templates.flatten + + [] + end + + def find_first(path, prefixes = [], *args) + prefixes.each do |prefix| + each do |resolver| + if template = resolver.find_all(path, prefix, *args).first + return template + end + end + end + + nil end def exists?(*args) - find_all(*args).any? + !!find_first(*args) end protected diff --git a/actionpack/lib/action_view/template/error.rb b/actionpack/lib/action_view/template/error.rb index ff256738a9..d7d98e1dd5 100644 --- a/actionpack/lib/action_view/template/error.rb +++ b/actionpack/lib/action_view/template/error.rb @@ -27,7 +27,7 @@ module ActionView class MissingTemplate < ActionViewError #:nodoc: attr_reader :path - def initialize(paths, path, details, partial) + def initialize(paths, path, prefixes, partial, details, *) @path = path display_paths = paths.compact.map{ |p| p.to_s.inspect }.join(", ") template_type = if partial @@ -38,7 +38,11 @@ module ActionView 'template' end - super("Missing #{template_type} #{path} with #{details.inspect} in view paths #{display_paths}") + searched_paths = prefixes.map { |prefix| [prefix, path].join("/") } + + out = "Missing #{template_type} #{searched_paths.join(", ")} with #{details.inspect}. Searched in:\n" + out += paths.compact.map { |p| " * #{p.to_s.inspect}\n" }.join + super out end end diff --git a/actionpack/lib/action_view/template/resolver.rb b/actionpack/lib/action_view/template/resolver.rb index 0dccc99d14..d23aa5ef85 100644 --- a/actionpack/lib/action_view/template/resolver.rb +++ b/actionpack/lib/action_view/template/resolver.rb @@ -47,7 +47,7 @@ module ActionView path end - # Hnadles templates caching. If a key is given and caching is on + # Handles templates caching. If a key is given and caching is on # always check the cache before hitting the resolver. Otherwise, # it always hits the resolver but check if the resolver is fresher # before returning it. diff --git a/actionpack/test/controller/mime_responds_test.rb b/actionpack/test/controller/mime_responds_test.rb index 98c9d43b93..fe14d24327 100644 --- a/actionpack/test/controller/mime_responds_test.rb +++ b/actionpack/test/controller/mime_responds_test.rb @@ -565,7 +565,7 @@ class RespondWithController < ActionController::Base def using_resource_with_action respond_with(resource, :action => :foo) do |format| - format.html { raise ActionView::MissingTemplate.new([], "foo/bar", {}, false) } + format.html { raise ActionView::MissingTemplate.new([], "bar", ["foo"], {}, false) } end end -- cgit v1.2.3 From e03e1fdbc85bc05536a2770817c31b08d4f6be51 Mon Sep 17 00:00:00 2001 From: wycats Date: Sun, 26 Dec 2010 23:56:09 -0800 Subject: Speed up template inheritance and remove template inheritance option --- actionpack/lib/abstract_controller/rendering.rb | 33 +++++++++++----------- actionpack/test/controller/new_base/render_test.rb | 12 -------- 2 files changed, 17 insertions(+), 28 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/abstract_controller/rendering.rb b/actionpack/lib/abstract_controller/rendering.rb index 01dd4ffeb1..9b912ea988 100644 --- a/actionpack/lib/abstract_controller/rendering.rb +++ b/actionpack/lib/abstract_controller/rendering.rb @@ -60,6 +60,20 @@ module AbstractController end end end + + def parent_prefixes + @parent_prefixes ||= begin + parent_controller = superclass + prefixes = [] + + until parent_controller.abstract? + prefixes << parent_controller.controller_path + parent_controller = parent_controller.superclass + end + + prefixes + end + end end attr_writer :view_context_class @@ -116,18 +130,10 @@ module AbstractController # The prefixes used in render "foo" shortcuts. def _prefixes - prefixes = [controller_path] - - if template_inheritance? - parent_controller = self.class.superclass - - until parent_controller.abstract? - prefixes << parent_controller.controller_path - parent_controller = parent_controller.superclass - end + @_prefixes ||= begin + parent_prefixes = self.class.parent_prefixes + parent_prefixes.dup.unshift(controller_path) end - - prefixes end private @@ -176,10 +182,5 @@ module AbstractController def _process_options(options) end - - def template_inheritance? - # is there a better way to check for config option being set? - config.template_inheritance.nil? ? true : config.template_inheritance - end end end diff --git a/actionpack/test/controller/new_base/render_test.rb b/actionpack/test/controller/new_base/render_test.rb index f5baa829b6..d6062bfa8c 100644 --- a/actionpack/test/controller/new_base/render_test.rb +++ b/actionpack/test/controller/new_base/render_test.rb @@ -53,10 +53,6 @@ module Render prepend_view_path ActionView::FixtureResolver.new("render/child_render/overriden_with_own_view_paths_prepended.html.erb" => "child content") end - class ChildRenderWithoutInheritanceController < BlankRenderController - config.template_inheritance = false - end - class RenderTest < Rack::TestCase test "render with blank" do with_routing do |set| @@ -138,12 +134,4 @@ module Render assert_body "Hello world!" end end - - class TestNoViewInheritance < Rack::TestCase - test "Template from parent controller does not get picked if config.action_controller.template_inheritance = false" do - assert_raises(ActionView::MissingTemplate) do - get "/render/child_render_without_inheritance/index", {}, "action_dispatch.show_exceptions" => false - end - end - end end -- cgit v1.2.3 From 51a7d9acdd4a01fb23e21be7a89e6440e51715e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Mon, 27 Dec 2010 09:14:13 +0100 Subject: Final tidy up on templates inheritance. --- actionpack/CHANGELOG | 6 ++++-- actionpack/lib/action_view/lookup_context.rb | 13 +++++++------ actionpack/lib/action_view/path_set.rb | 9 ++------- actionpack/lib/action_view/renderer/partial_renderer.rb | 2 +- actionpack/lib/action_view/renderer/template_renderer.rb | 2 +- 5 files changed, 15 insertions(+), 17 deletions(-) (limited to 'actionpack') diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG index 93b29bcc3a..20b19909fc 100644 --- a/actionpack/CHANGELOG +++ b/actionpack/CHANGELOG @@ -1,8 +1,10 @@ *Rails 3.1.0 (unreleased)* -* brought back config.action_view.cache_template_loading, which allows to decide whether templates should be cached or not [Piotr Sarnacki] +* Template lookup now searches further up in the inheritance chain. [Artemave] -* url_for and named url helpers now accept :subdomain and :domain as options [Josh Kalderimis] +* Brought back config.action_view.cache_template_loading, which allows to decide whether templates should be cached or not. [Piotr Sarnacki] + +* url_for and named url helpers now accept :subdomain and :domain as options, [Josh Kalderimis] * The redirect route method now also accepts a hash of options which will only change the parts of the url in question, or an object which responds to call, allowing for redirects to be reused (check the documentation for examples). [Josh Kalderimis] diff --git a/actionpack/lib/action_view/lookup_context.rb b/actionpack/lib/action_view/lookup_context.rb index 0d7f15e564..1365048724 100644 --- a/actionpack/lib/action_view/lookup_context.rb +++ b/actionpack/lib/action_view/lookup_context.rb @@ -119,13 +119,14 @@ module ActionView name = name.to_s.gsub(handlers_regexp, '') parts = name.split('/') name = parts.pop - prx = if prefixes.blank? - [parts.compact.join('/')] - else - prefixes.map {|prefix| [prefix, *parts].compact.join('/') } - end - return name, prx + prefixes = if prefixes.blank? + [parts.join('/')] + else + prefixes.map { |prefix| [prefix, *parts].compact.join('/') } + end + + return name, prefixes end def default_handlers #:nodoc: diff --git a/actionpack/lib/action_view/path_set.rb b/actionpack/lib/action_view/path_set.rb index 2a54b12f78..2f662b0739 100644 --- a/actionpack/lib/action_view/path_set.rb +++ b/actionpack/lib/action_view/path_set.rb @@ -21,26 +21,21 @@ module ActionView #:nodoc: def find_all(path, prefixes = [], *args) prefixes.each do |prefix| templates = [] - each do |resolver| templates.concat resolver.find_all(path, prefix, *args) end - return templates unless templates.empty? end - [] end def find_first(path, prefixes = [], *args) prefixes.each do |prefix| each do |resolver| - if template = resolver.find_all(path, prefix, *args).first - return template - end + template = resolver.find_all(path, prefix, *args).first + return template if template end end - nil end diff --git a/actionpack/lib/action_view/renderer/partial_renderer.rb b/actionpack/lib/action_view/renderer/partial_renderer.rb index f36b0602b1..3fdea23a4a 100644 --- a/actionpack/lib/action_view/renderer/partial_renderer.rb +++ b/actionpack/lib/action_view/renderer/partial_renderer.rb @@ -111,7 +111,7 @@ module ActionView end def find_template(path=@path, locals=@locals.keys) - prefixes = path.include?(?/) ? [] : @view.controller._prefixes + prefixes = path.include?(?/) ? [] : @view.controller_prefixes @lookup_context.find_template(path, prefixes, true, locals) end diff --git a/actionpack/lib/action_view/renderer/template_renderer.rb b/actionpack/lib/action_view/renderer/template_renderer.rb index 938bb2a3f3..9ae1636131 100644 --- a/actionpack/lib/action_view/renderer/template_renderer.rb +++ b/actionpack/lib/action_view/renderer/template_renderer.rb @@ -43,7 +43,7 @@ module ActionView if options.key?(:text) Template::Text.new(options[:text], formats.try(:first)) elsif options.key?(:file) - with_fallbacks { find_template(options[:file], [], false, keys) } + with_fallbacks { find_template(options[:file], options[:prefixes], false, keys) } elsif options.key?(:inline) handler = Template.handler_for_extension(options[:type] || "erb") Template.new(options[:inline], "inline template", handler, :locals => keys) -- cgit v1.2.3 From 6b099975fa7e18356b19eca659595713512209e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Mon, 27 Dec 2010 09:30:36 +0100 Subject: No need to symbolize these. --- actionpack/lib/action_controller/metal/responder.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_controller/metal/responder.rb b/actionpack/lib/action_controller/metal/responder.rb index 38d32211cc..cffef29f83 100644 --- a/actionpack/lib/action_controller/metal/responder.rb +++ b/actionpack/lib/action_controller/metal/responder.rb @@ -115,7 +115,7 @@ module ActionController #:nodoc: # Main entry point for responder responsible to dispatch to the proper format. # def respond - method = :"to_#{format}" + method = "to_#{format}" respond_to?(method) ? send(method) : to_format end @@ -171,7 +171,7 @@ module ActionController #:nodoc: # Checks whether the resource responds to the current format or not. # def resourceful? - resource.respond_to?(:"to_#{format}") + resource.respond_to?("to_#{format}") end # Returns the resource location by retrieving it from the options or -- cgit v1.2.3 From ecc83c1e6e36913c60d7107fb549c504b1a1e72c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Mon, 27 Dec 2010 10:15:54 +0100 Subject: Clean up PathSet. --- actionpack/lib/action_view/path_set.rb | 23 ++++------------------- 1 file changed, 4 insertions(+), 19 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/path_set.rb b/actionpack/lib/action_view/path_set.rb index 2f662b0739..e3de3e1eac 100644 --- a/actionpack/lib/action_view/path_set.rb +++ b/actionpack/lib/action_view/path_set.rb @@ -11,36 +11,21 @@ module ActionView #:nodoc: end def find(*args) - if template = find_first(*args) - template - else - raise MissingTemplate.new(self, *args) - end + find_all(*args).first || raise(MissingTemplate.new(self, *args)) end def find_all(path, prefixes = [], *args) prefixes.each do |prefix| - templates = [] each do |resolver| - templates.concat resolver.find_all(path, prefix, *args) + templates = resolver.find_all(path, prefix, *args) + return templates unless templates.empty? end - return templates unless templates.empty? end [] end - def find_first(path, prefixes = [], *args) - prefixes.each do |prefix| - each do |resolver| - template = resolver.find_all(path, prefix, *args).first - return template if template - end - end - nil - end - def exists?(*args) - !!find_first(*args) + find_all(*args).any? end protected -- cgit v1.2.3 From a21a3d1f44b51910f535e30bff4fcb63f111392d Mon Sep 17 00:00:00 2001 From: Cheah Chu Yeow Date: Wed, 29 Dec 2010 19:35:33 +0800 Subject: Remove link to outdated Github tag comparison in ActionPack changelog. --- actionpack/CHANGELOG | 2 -- 1 file changed, 2 deletions(-) (limited to 'actionpack') diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG index 93b29bcc3a..1a7b441b92 100644 --- a/actionpack/CHANGELOG +++ b/actionpack/CHANGELOG @@ -47,8 +47,6 @@ * Add clear_helpers as a way to clean up all helpers added to this controller, maintaing just the helper with the same name as the controller. [José Valim] -* See http://github.com/rails/rails/compare/v3.0.0_RC...v3.0.0_RC2 for gory details - * Support routing constraints in functional tests. [Andrew White] * Add a header that tells Internet Explorer (all versions) to use the best available standards support. [Yehuda Katz] -- cgit v1.2.3 From 6f58b9ad5331d3619fc68a4706d5f85a95510a63 Mon Sep 17 00:00:00 2001 From: Cheah Chu Yeow Date: Wed, 29 Dec 2010 19:36:00 +0800 Subject: Fix typo in ActionPack changelog. --- actionpack/CHANGELOG | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack') diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG index 1a7b441b92..b18d6f7817 100644 --- a/actionpack/CHANGELOG +++ b/actionpack/CHANGELOG @@ -45,7 +45,7 @@ * Symbols and strings in routes should yield the same behavior. Note this may break existing apps that were using symbols with the new routes API. [José Valim] -* Add clear_helpers as a way to clean up all helpers added to this controller, maintaing just the helper with the same name as the controller. [José Valim] +* Add clear_helpers as a way to clean up all helpers added to this controller, maintaining just the helper with the same name as the controller. [José Valim] * Support routing constraints in functional tests. [Andrew White] -- cgit v1.2.3 From db24701abed4858d9b326bbaaf5c08726e4ced75 Mon Sep 17 00:00:00 2001 From: Nick Sutterer Date: Wed, 29 Dec 2010 23:56:58 +0100 Subject: process_action accepts multiple args, even with Callbacks. --- actionpack/lib/abstract_controller/callbacks.rb | 2 +- actionpack/test/abstract/callbacks_test.rb | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) (limited to 'actionpack') diff --git a/actionpack/lib/abstract_controller/callbacks.rb b/actionpack/lib/abstract_controller/callbacks.rb index f169ab7c3a..95992c2698 100644 --- a/actionpack/lib/abstract_controller/callbacks.rb +++ b/actionpack/lib/abstract_controller/callbacks.rb @@ -13,7 +13,7 @@ module AbstractController # Override AbstractController::Base's process_action to run the # process_action callbacks around the normal behavior. - def process_action(method_name) + def process_action(method_name, *args) run_callbacks(:process_action, method_name) do super end diff --git a/actionpack/test/abstract/callbacks_test.rb b/actionpack/test/abstract/callbacks_test.rb index 2d02078020..5308fc849b 100644 --- a/actionpack/test/abstract/callbacks_test.rb +++ b/actionpack/test/abstract/callbacks_test.rb @@ -245,6 +245,27 @@ module AbstractController assert_equal "Success", controller.response_body end end + + class CallbacksWithArgs < ControllerWithCallbacks + set_callback :process_action, :before, :first + + def first + @text = "Hello world" + end + + def index(text) + self.response_body = @text + text + end + end + + class TestCallbacksWithArgs < ActiveSupport::TestCase + test "callbacks still work when invoking process with multiple args" do + controller = CallbacksWithArgs.new + result = controller.process(:index, " Howdy!") + assert_equal "Hello world Howdy!", controller.response_body + end + end + end end -- cgit v1.2.3 From e5b84fd72358deddd29c515aacab7edf2643908e Mon Sep 17 00:00:00 2001 From: "Timothy N. Tsvetkov" Date: Wed, 24 Nov 2010 00:17:05 +0300 Subject: ActionController::Base.helpers.sanitize ignores case in protocol [#6044 state:committed] Signed-off-by: Santiago Pastorino --- .../lib/action_controller/vendor/html-scanner/html/sanitizer.rb | 2 +- actionpack/test/fixtures/layout_tests/layouts/symlinked | 1 - actionpack/test/template/html-scanner/sanitizer_test.rb | 7 +++++++ 3 files changed, 8 insertions(+), 2 deletions(-) delete mode 120000 actionpack/test/fixtures/layout_tests/layouts/symlinked (limited to 'actionpack') diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb b/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb index 3e5d23b5c1..09dd08898c 100644 --- a/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb +++ b/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb @@ -170,7 +170,7 @@ module HTML def contains_bad_protocols?(attr_name, value) uri_attributes.include?(attr_name) && - (value =~ /(^[^\/:]*):|(�*58)|(p)|(%|%)3A/ && !allowed_protocols.include?(value.split(protocol_separator).first)) + (value =~ /(^[^\/:]*):|(�*58)|(p)|(%|%)3A/ && !allowed_protocols.include?(value.split(protocol_separator).first.downcase)) end end end diff --git a/actionpack/test/fixtures/layout_tests/layouts/symlinked b/actionpack/test/fixtures/layout_tests/layouts/symlinked deleted file mode 120000 index 0ddc1154ab..0000000000 --- a/actionpack/test/fixtures/layout_tests/layouts/symlinked +++ /dev/null @@ -1 +0,0 @@ -../../symlink_parent \ No newline at end of file diff --git a/actionpack/test/template/html-scanner/sanitizer_test.rb b/actionpack/test/template/html-scanner/sanitizer_test.rb index 3e80317b30..fcc3782f04 100644 --- a/actionpack/test/template/html-scanner/sanitizer_test.rb +++ b/actionpack/test/template/html-scanner/sanitizer_test.rb @@ -130,6 +130,13 @@ class SanitizerTest < ActionController::TestCase assert sanitizer.send(:contains_bad_protocols?, 'src', "#{proto}://bad") end end + + def test_should_accept_good_protocols_ignoring_case + sanitizer = HTML::WhiteListSanitizer.new + HTML::WhiteListSanitizer.allowed_protocols.each do |proto| + assert !sanitizer.send(:contains_bad_protocols?, 'src', "#{proto.capitalize}://good") + end + end def test_should_accept_good_protocols sanitizer = HTML::WhiteListSanitizer.new -- cgit v1.2.3 From 4c44f0468a0b6d2dd9b67d801da4336ad9a169a0 Mon Sep 17 00:00:00 2001 From: Nick Sutterer Date: Thu, 30 Dec 2010 14:11:14 +0100 Subject: added tests for the MissingTemplate exception message. --- actionpack/test/template/lookup_context_test.rb | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) (limited to 'actionpack') diff --git a/actionpack/test/template/lookup_context_test.rb b/actionpack/test/template/lookup_context_test.rb index a629b3c046..4258f88071 100644 --- a/actionpack/test/template/lookup_context_test.rb +++ b/actionpack/test/template/lookup_context_test.rb @@ -251,3 +251,24 @@ class LookupContextWithFalseCaching < ActiveSupport::TestCase assert_equal "Foo", template.source end end + +class TestMissingTemplate < ActiveSupport::TestCase + def setup + @lookup_context = ActionView::LookupContext.new("/Path/to/views", {}) + @details = "{:handlers=>[:erb, :rjs, :builder], :formats=>[:html, :text, :js, :css, :ics, :csv, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json], :locale=>[:en, :en]}" + end + + test "if no template was found we get a helpful error message including the inheritance chain" do + e = assert_raise ActionView::MissingTemplate do + @lookup_context.find("foo", %w(parent child)) + end + assert_equal "Missing template parent/foo, child/foo with #{@details}. Searched in:\n * \"/Path/to/views\"\n", e.message + end + + test "if no partial was found we get a helpful error message including the inheritance chain" do + e = assert_raise ActionView::MissingTemplate do + @lookup_context.find("foo", %w(parent child), true) + end + assert_equal "Missing partial parent/foo, child/foo with #{@details}. Searched in:\n * \"/Path/to/views\"\n", e.message + end +end -- cgit v1.2.3 From 8e5d91062f25f8c97a3bd8c6dc7dc45e38b54388 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Fri, 31 Dec 2010 11:17:37 +0100 Subject: Don't be so picky on MissingTemplate error details, this fails randomly on 1.8.7 because of not ordered hash --- actionpack/test/template/lookup_context_test.rb | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) (limited to 'actionpack') diff --git a/actionpack/test/template/lookup_context_test.rb b/actionpack/test/template/lookup_context_test.rb index 4258f88071..f7a684779c 100644 --- a/actionpack/test/template/lookup_context_test.rb +++ b/actionpack/test/template/lookup_context_test.rb @@ -255,20 +255,19 @@ end class TestMissingTemplate < ActiveSupport::TestCase def setup @lookup_context = ActionView::LookupContext.new("/Path/to/views", {}) - @details = "{:handlers=>[:erb, :rjs, :builder], :formats=>[:html, :text, :js, :css, :ics, :csv, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json], :locale=>[:en, :en]}" end test "if no template was found we get a helpful error message including the inheritance chain" do e = assert_raise ActionView::MissingTemplate do @lookup_context.find("foo", %w(parent child)) end - assert_equal "Missing template parent/foo, child/foo with #{@details}. Searched in:\n * \"/Path/to/views\"\n", e.message + assert_match %r{Missing template parent/foo, child/foo with .* Searched in:\n \* "/Path/to/views"\n}, e.message end - + test "if no partial was found we get a helpful error message including the inheritance chain" do e = assert_raise ActionView::MissingTemplate do @lookup_context.find("foo", %w(parent child), true) end - assert_equal "Missing partial parent/foo, child/foo with #{@details}. Searched in:\n * \"/Path/to/views\"\n", e.message + assert_match %r{Missing partial parent/foo, child/foo with .* Searched in:\n \* "/Path/to/views"\n}, e.message end end -- cgit v1.2.3 From 27ea0481bb68b2a09ade4f442beea3eac812b72c Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Fri, 31 Dec 2010 14:22:27 +0100 Subject: Recreate symlink in layouts for tests --- actionpack/test/fixtures/layout_tests/layouts/symlinked | 1 + 1 file changed, 1 insertion(+) create mode 120000 actionpack/test/fixtures/layout_tests/layouts/symlinked (limited to 'actionpack') diff --git a/actionpack/test/fixtures/layout_tests/layouts/symlinked b/actionpack/test/fixtures/layout_tests/layouts/symlinked new file mode 120000 index 0000000000..0ddc1154ab --- /dev/null +++ b/actionpack/test/fixtures/layout_tests/layouts/symlinked @@ -0,0 +1 @@ +../../symlink_parent \ No newline at end of file -- cgit v1.2.3 From 9bc879d42a39971f26bda182ca01af30fc70a46e Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Sat, 1 Jan 2011 13:13:48 -0200 Subject: This is not needed anymore --- .../action_dispatch/middleware/templates/rescues/template_error.erb | 3 --- 1 file changed, 3 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.erb index 02fa18211d..303b62c3a7 100644 --- a/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.erb +++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.erb @@ -13,9 +13,6 @@

<%=h @exception.sub_template_message %>

-<% @real_exception = @exception - @exception = @exception.original_exception || @exception %> <%= render :file => "rescues/_trace.erb" %> -<% @exception = @real_exception %> <%= render :file => "rescues/_request_and_response.erb" %> -- cgit v1.2.3 From 171172f324444a9ea9c98e4f3663c6e401fb3ec7 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Sat, 1 Jan 2011 13:44:34 -0200 Subject: render :template is faster than render :file --- .../lib/action_dispatch/middleware/templates/rescues/diagnostics.erb | 4 ++-- .../action_dispatch/middleware/templates/rescues/template_error.erb | 5 ++--- 2 files changed, 4 insertions(+), 5 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb index bd6ffbab5d..50d8ca9484 100644 --- a/actionpack/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb +++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb @@ -6,5 +6,5 @@
<%=h @exception.message %>
-<%= render :file => "rescues/_trace.erb" %> -<%= render :file => "rescues/_request_and_response.erb" %> +<%= render :template => "rescues/_trace" %> +<%= render :template => "rescues/_request_and_response" %> diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.erb index 303b62c3a7..c658559be9 100644 --- a/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.erb +++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.erb @@ -13,6 +13,5 @@

<%=h @exception.sub_template_message %>

-<%= render :file => "rescues/_trace.erb" %> - -<%= render :file => "rescues/_request_and_response.erb" %> +<%= render :template => "rescues/_trace" %> +<%= render :template => "rescues/_request_and_response" %> -- cgit v1.2.3 From a8a704b07c1d2303e8e55777e249a6adf0ec4484 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Tue, 4 Jan 2011 19:30:52 +0000 Subject: Bump rack-test version --- actionpack/actionpack.gemspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack') diff --git a/actionpack/actionpack.gemspec b/actionpack/actionpack.gemspec index 20becc0bb1..f6bc5e0d37 100644 --- a/actionpack/actionpack.gemspec +++ b/actionpack/actionpack.gemspec @@ -25,7 +25,7 @@ Gem::Specification.new do |s| s.add_dependency('builder', '~> 3.0.0') s.add_dependency('i18n', '~> 0.5.0') s.add_dependency('rack', '~> 1.2.1') - s.add_dependency('rack-test', '~> 0.5.6') + s.add_dependency('rack-test', '~> 0.5.7') s.add_dependency('rack-mount', '~> 0.6.13') s.add_dependency('tzinfo', '~> 0.3.23') s.add_dependency('erubis', '~> 2.6.6') -- cgit v1.2.3 From 14198d84a90fdf7122c47367485148c52e45053e Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Sun, 9 Jan 2011 13:35:38 -0200 Subject: Remove InstanceTagMethods module and define the methods inside the InstanceTag class --- actionpack/lib/action_view/helpers/form_helper.rb | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb index 6f0e2c99ba..d7b9e0b4f4 100644 --- a/actionpack/lib/action_view/helpers/form_helper.rb +++ b/actionpack/lib/action_view/helpers/form_helper.rb @@ -858,8 +858,7 @@ module ActionView end end - module InstanceTagMethods #:nodoc: - extend ActiveSupport::Concern + class InstanceTag include Helpers::CaptureHelper, Context, Helpers::TagHelper, Helpers::FormTagHelper attr_reader :object, :method_name, :object_name @@ -1025,7 +1024,7 @@ module ActionView self.class.value_before_type_cast(object, @method_name) end - module ClassMethods + class << self def value(object, method_name) object.send method_name if object end @@ -1111,10 +1110,6 @@ module ActionView end end - class InstanceTag - include InstanceTagMethods - end - class FormBuilder # The methods which wrap a form helper call. class_attribute :field_helpers -- cgit v1.2.3 From 18605adec36f8487374d68cdb031e89e91379c56 Mon Sep 17 00:00:00 2001 From: Rizwan Reza Date: Thu, 23 Dec 2010 22:43:46 +0330 Subject: HTML5 button_tag helper This tag is similar in nature to submit_tag, but allows more control. It also doesn't submit if submit type isn't used, allowing JavaScript to control the flow where required. For more information: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-button-element.html#the-button-element --- actionpack/CHANGELOG | 5 +++ .../lib/action_view/helpers/form_tag_helper.rb | 50 ++++++++++++++++++++++ actionpack/test/template/form_tag_helper_test.rb | 28 ++++++++++++ 3 files changed, 83 insertions(+) (limited to 'actionpack') diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG index 78fadce6cb..0687187904 100644 --- a/actionpack/CHANGELOG +++ b/actionpack/CHANGELOG @@ -1,5 +1,7 @@ *Rails 3.1.0 (unreleased)* +* HTML5 button_tag helper. [Rizwan Reza] + * Template lookup now searches further up in the inheritance chain. [Artemave] * Brought back config.action_view.cache_template_loading, which allows to decide whether templates should be cached or not. [Piotr Sarnacki] @@ -33,14 +35,17 @@ * Add Rack::Cache to the default stack. Create a Rails store that delegates to the Rails cache, so by default, whatever caching layer you are using will be used for HTTP caching. Note that Rack::Cache will be used if you use #expires_in, #fresh_when or #stale with :public => true. Otherwise, the caching rules will apply to the browser only. [Yehuda Katz, Carl Lerche] + *Rails 3.0.2 (unreleased)* * The helper number_to_currency accepts a new :negative_format option to be able to configure how to render negative amounts. [Don Wilson] + *Rails 3.0.1 (October 15, 2010)* * No Changes, just a version bump. + *Rails 3.0.0 (August 29, 2010)* * password_field renders with nil value by default making the use of passwords secure by default, if you want to render you should do for instance f.password_field(:password, :value => @user.password) [Santiago Pastorino] diff --git a/actionpack/lib/action_view/helpers/form_tag_helper.rb b/actionpack/lib/action_view/helpers/form_tag_helper.rb index 9500e85e8b..3daf68d29f 100644 --- a/actionpack/lib/action_view/helpers/form_tag_helper.rb +++ b/actionpack/lib/action_view/helpers/form_tag_helper.rb @@ -401,6 +401,56 @@ module ActionView tag :input, { "type" => "submit", "name" => "commit", "value" => value }.update(options.stringify_keys) end + # Creates a button element that defines a submit button, + # resetbutton or a generic button which can be used in + # JavaScript, for example. You can use the button tag as a regular + # submit tag but it isn't supported in legacy browsers. However, + # button tag allows richer labels such as images and emphasis. + # + # ==== Options + # * :confirm => 'question?' - If present, the + # unobtrusive JavaScript drivers will provide a prompt with + # the question specified. If the user accepts, the form is + # processed normally, otherwise no action is taken. + # * :disabled - If true, the user will not be able to + # use this input. + # * :disable_with - Value of this parameter will be + # used as the value for a disabled version of the submit + # button when the form is submitted. This feature is provided + # by the unobtrusive JavaScript driver. + # * Any other key creates standard HTML options for the tag. + # + # ==== Examples + # button_tag + # # => + # + # button_tag "Ask me!" + # # => + # + # button_tag "Checkout", :disable_with => "Please wait..." + # # => + # + def button_tag(label = "Button", options = {}) + options.stringify_keys! + + if disable_with = options.delete("disable_with") + options["data-disable-with"] = disable_with + end + + if confirm = options.delete("confirm") + options["data-confirm"] = confirm + end + + ["type", "name"].each do |option| + options[option] = "button" unless options[option] + end + + content_tag :button, label.to_s.html_safe, { "type" => options.delete("type") }.update(options) + end + # Displays an image which when clicked will submit the form. # # source is passed to AssetTagHelper#path_to_image diff --git a/actionpack/test/template/form_tag_helper_test.rb b/actionpack/test/template/form_tag_helper_test.rb index f3933a25b9..0d29b962d5 100644 --- a/actionpack/test/template/form_tag_helper_test.rb +++ b/actionpack/test/template/form_tag_helper_test.rb @@ -385,6 +385,34 @@ class FormTagHelperTest < ActionView::TestCase ) end + def test_button_tag + assert_dom_equal( + %(), + button_tag + ) + end + + def test_button_tag_with_submit_type + assert_dom_equal( + %(), + button_tag("Save", :type => "submit") + ) + end + + def test_button_tag_with_reset_type + assert_dom_equal( + %(), + button_tag("Reset", :type => "reset") + ) + end + + def test_button_tag_with_disabled_option + assert_dom_equal( + %(), + button_tag("Reset", :type => "reset", :disabled => true) + ) + end + def test_image_submit_tag_with_confirmation assert_dom_equal( %(), -- cgit v1.2.3 From 5d1d9bfb05dd84305369a8fc5a729d2b8ad912e2 Mon Sep 17 00:00:00 2001 From: John Allison Date: Wed, 5 Jan 2011 14:15:10 -0500 Subject: Improve select helpers by allowing a selected value of false. This is useful when using a select helper with a boolean attribute, and the attribute is false. (e.g. f.select :allow_comments) --- .../lib/action_view/helpers/form_options_helper.rb | 2 +- .../test/template/form_options_helper_test.rb | 32 ++++++++++++++++------ 2 files changed, 25 insertions(+), 9 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers/form_options_helper.rb b/actionpack/lib/action_view/helpers/form_options_helper.rb index 6ac8577785..7698602022 100644 --- a/actionpack/lib/action_view/helpers/form_options_helper.rb +++ b/actionpack/lib/action_view/helpers/form_options_helper.rb @@ -533,7 +533,7 @@ module ActionView else selected = Array.wrap(selected) options = selected.extract_options!.symbolize_keys - [ options[:selected] || selected , options[:disabled] ] + [ options.include?(:selected) ? options[:selected] : selected, options[:disabled] ] end end diff --git a/actionpack/test/template/form_options_helper_test.rb b/actionpack/test/template/form_options_helper_test.rb index bc04398afa..69b1d4ff7b 100644 --- a/actionpack/test/template/form_options_helper_test.rb +++ b/actionpack/test/template/form_options_helper_test.rb @@ -7,7 +7,7 @@ class FormOptionsHelperTest < ActionView::TestCase tests ActionView::Helpers::FormOptionsHelper silence_warnings do - Post = Struct.new('Post', :title, :author_name, :body, :secret, :written_on, :category, :origin) + Post = Struct.new('Post', :title, :author_name, :body, :secret, :written_on, :category, :origin, :allow_comments) Continent = Struct.new('Continent', :continent_name, :countries) Country = Struct.new('Country', :country_id, :country_name) Firm = Struct.new('Firm', :time_zone) @@ -130,6 +130,13 @@ class FormOptionsHelperTest < ActionView::TestCase ) end + def test_boolean_array_options_for_select_with_selection_and_disabled_value + assert_dom_equal( + "\n", + options_for_select([ true, false ], :selected => false, :disabled => nil) + ) + end + def test_array_options_for_string_include_in_other_string_bug_fix assert_dom_equal( "\n", @@ -177,7 +184,7 @@ class FormOptionsHelperTest < ActionView::TestCase end def test_collection_options_with_preselected_value_as_string_and_option_value_is_integer - albums = [ Album.new(1, "first","rap"), Album.new(2, "second","pop")] + albums = [ Album.new(1, "first","rap"), Album.new(2, "second","pop")] assert_dom_equal( %(\n), options_from_collection_for_select(albums, "id", "genre", :selected => "1") @@ -185,7 +192,7 @@ class FormOptionsHelperTest < ActionView::TestCase end def test_collection_options_with_preselected_value_as_integer_and_option_value_is_string - albums = [ Album.new("1", "first","rap"), Album.new("2", "second","pop")] + albums = [ Album.new("1", "first","rap"), Album.new("2", "second","pop")] assert_dom_equal( %(\n), @@ -194,7 +201,7 @@ class FormOptionsHelperTest < ActionView::TestCase end def test_collection_options_with_preselected_value_as_string_and_option_value_is_float - albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")] + albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")] assert_dom_equal( %(\n), @@ -203,7 +210,7 @@ class FormOptionsHelperTest < ActionView::TestCase end def test_collection_options_with_preselected_value_as_nil - albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")] + albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")] assert_dom_equal( %(\n), @@ -212,7 +219,7 @@ class FormOptionsHelperTest < ActionView::TestCase end def test_collection_options_with_disabled_value_as_nil - albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")] + albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")] assert_dom_equal( %(\n), @@ -221,7 +228,7 @@ class FormOptionsHelperTest < ActionView::TestCase end def test_collection_options_with_disabled_value_as_array - albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")] + albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")] assert_dom_equal( %(\n), @@ -230,7 +237,7 @@ class FormOptionsHelperTest < ActionView::TestCase end def test_collection_options_with_preselected_values_as_string_array_and_option_value_is_float - albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop"), Album.new(3.0, "third","country") ] + albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop"), Album.new(3.0, "third","country") ] assert_dom_equal( %(\n\n), @@ -364,6 +371,15 @@ class FormOptionsHelperTest < ActionView::TestCase ) end + def test_select_with_boolean_method + @post = Post.new + @post.allow_comments = false + assert_dom_equal( + "", + select("post", "allow_comments", %w( true false )) + ) + end + def test_select_under_fields_for @post = Post.new @post.category = "" -- cgit v1.2.3 From 5106ce88e44286b88e5c2e2c261deb7e28392994 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ku=C5=BAma?= Date: Mon, 27 Dec 2010 23:31:14 +0100 Subject: authenticity_token option for form_tag [#2988 state:resolved] --- actionpack/CHANGELOG | 2 ++ .../lib/action_view/helpers/form_tag_helper.rb | 22 +++++++++++++++++----- .../controller/request_forgery_protection_test.rb | 18 ++++++++++++++++++ 3 files changed, 37 insertions(+), 5 deletions(-) (limited to 'actionpack') diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG index 0687187904..ee9d30e1fb 100644 --- a/actionpack/CHANGELOG +++ b/actionpack/CHANGELOG @@ -1,5 +1,7 @@ *Rails 3.1.0 (unreleased)* +* Add an :authenticity_token option to form_tag for custom handling or to omit the token (pass :authenticity_token => false). [Jakub Kuźma, Igor Wiedler] + * HTML5 button_tag helper. [Rizwan Reza] * Template lookup now searches further up in the inheritance chain. [Artemave] diff --git a/actionpack/lib/action_view/helpers/form_tag_helper.rb b/actionpack/lib/action_view/helpers/form_tag_helper.rb index 3daf68d29f..159b2a2b8e 100644 --- a/actionpack/lib/action_view/helpers/form_tag_helper.rb +++ b/actionpack/lib/action_view/helpers/form_tag_helper.rb @@ -25,6 +25,9 @@ module ActionView # * :method - The method to use when submitting the form, usually either "get" or "post". # If "put", "delete", or another verb is used, a hidden input with name _method # is added to simulate the verb over post. + # * :authenticity_token - Authenticity token to use in the form. Use only if you need to + # pass custom authenticity token string, or to not add authenticity_token field at all + # (by passing false). # * A list of parameters to feed to the URL the form will be posted to. # * :remote - If set to true, will allow the Unobtrusive JavaScript drivers to control the # submit behaviour. By default this behaviour is an ajax submit. @@ -47,6 +50,12 @@ module ActionView # <%= form_tag('/posts', :remote => true) %> # # =>
# + # form_tag('http://far.away.com/form', :authenticity_token => false) + # # form without authenticity token + # + # form_tag('http://far.away.com/form', :authenticity_token => "cf50faa3fe97702ca1ae") + # # form with custom authenticity token + # def form_tag(url_for_options = {}, options = {}, *parameters_for_url, &block) html_options = html_options_for_form(url_for_options, options, *parameters_for_url) if block_given? @@ -584,6 +593,7 @@ module ActionView html_options["action"] = url_for(url_for_options, *parameters_for_url) html_options["accept-charset"] = "UTF-8" html_options["data-remote"] = true if html_options.delete("remote") + html_options["authenticity_token"] = html_options.delete("authenticity_token") if html_options.has_key?("authenticity_token") end end @@ -591,6 +601,7 @@ module ActionView snowman_tag = tag(:input, :type => "hidden", :name => "utf8", :value => "✓".html_safe) + authenticity_token = html_options.delete("authenticity_token") method = html_options.delete("method").to_s method_tag = case method @@ -599,10 +610,10 @@ module ActionView '' when /^post$/i, "", nil html_options["method"] = "post" - token_tag + token_tag(authenticity_token) else html_options["method"] = "post" - tag(:input, :type => "hidden", :name => "_method", :value => method) + token_tag + tag(:input, :type => "hidden", :name => "_method", :value => method) + token_tag(authenticity_token) end tags = snowman_tag << method_tag @@ -622,11 +633,12 @@ module ActionView output.safe_concat("
") end - def token_tag - unless protect_against_forgery? + def token_tag(token) + if token == false || !protect_against_forgery? '' else - tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => form_authenticity_token) + token = form_authenticity_token if token.nil? + tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => token) end end diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb index 2c9aa6187b..405af2a650 100644 --- a/actionpack/test/controller/request_forgery_protection_test.rb +++ b/actionpack/test/controller/request_forgery_protection_test.rb @@ -12,6 +12,14 @@ module RequestForgeryProtectionActions render :inline => "<%= button_to('New', '/') {} %>" end + def external_form + render :inline => "<%= form_tag('http://farfar.away/form', :authenticity_token => 'external_token') {} %>" + end + + def external_form_without_protection + render :inline => "<%= form_tag('http://farfar.away/form', :authenticity_token => false) {} %>" + end + def unsafe render :text => 'pwn' end @@ -65,6 +73,16 @@ module RequestForgeryProtectionTests assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token end + def test_should_render_external_form_with_external_token + get :external_form + assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', 'external_token' + end + + def test_should_render_external_form_without_token + get :external_form_without_protection + assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token, false + end + def test_should_allow_get get :index assert_response :success -- cgit v1.2.3 From 366e7854ac41699217e8cad1a336ab845c781359 Mon Sep 17 00:00:00 2001 From: Krekoten' Marjan Date: Tue, 19 Oct 2010 00:05:22 +0300 Subject: Refactor to handle the X-Cascade without having to raise an exception --- .../action_dispatch/middleware/show_exceptions.rb | 24 +++++++++++----------- 1 file changed, 12 insertions(+), 12 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb index 71e736ce9f..936fd548b9 100644 --- a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb +++ b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb @@ -43,20 +43,20 @@ module ActionDispatch end def call(env) - status, headers, body = @app.call(env) - - # Only this middleware cares about RoutingError. So, let's just raise - # it here. - # TODO: refactor this middleware to handle the X-Cascade scenario without - # having to raise an exception. - if headers['X-Cascade'] == 'pass' - raise ActionController::RoutingError, "No route matches #{env['PATH_INFO'].inspect}" + begin + status, headers, body = @app.call(env) + exception = nil + + # Only this middleware cares about RoutingError. So, let's just raise + # it here. + if headers['X-Cascade'] == 'pass' + exception = ActionController::RoutingError.new("No route matches #{env['PATH_INFO'].inspect}") + end + rescue Exception => exception end - - [status, headers, body] - rescue Exception => exception raise exception if env['action_dispatch.show_exceptions'] == false - render_exception(env, exception) + + exception ? render_exception(env, exception) : [status, headers, body] end private -- cgit v1.2.3 From a61e3acef25d8fb86275d41a9d0d1ba163d7e0bb Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Tue, 11 Jan 2011 18:45:34 -0200 Subject: html_safe.to_str makes no sense --- actionpack/lib/action_controller/caching/fragments.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_controller/caching/fragments.rb b/actionpack/lib/action_controller/caching/fragments.rb index 88f973e62d..0be04b70a1 100644 --- a/actionpack/lib/action_controller/caching/fragments.rb +++ b/actionpack/lib/action_controller/caching/fragments.rb @@ -59,7 +59,7 @@ module ActionController #:nodoc: key = fragment_cache_key(key) instrument_fragment_cache :write_fragment, key do - content = content.html_safe.to_str if content.respond_to?(:html_safe) + content = content.to_str cache_store.write(key, content, options) end content -- cgit v1.2.3 From 6062d434f174c84a18a121b025dcf4f11d6689f1 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Wed, 12 Jan 2011 12:14:00 -0200 Subject: Allow view in AV::TestCase to access it's controller helpers methods --- actionpack/lib/action_view/test_case.rb | 1 + actionpack/test/template/test_case_test.rb | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/test_case.rb b/actionpack/lib/action_view/test_case.rb index 4026f7a40e..72d17143f5 100644 --- a/actionpack/lib/action_view/test_case.rb +++ b/actionpack/lib/action_view/test_case.rb @@ -157,6 +157,7 @@ module ActionView def view @view ||= begin view = ActionView::Base.new(ActionController::Base.view_paths, {}, @controller) + view.singleton_class.send :include, @controller._helpers view.singleton_class.send :include, _helpers view.singleton_class.send :include, @controller._routes.url_helpers view.singleton_class.send :delegate, :alert, :notice, :to => "request.flash" diff --git a/actionpack/test/template/test_case_test.rb b/actionpack/test/template/test_case_test.rb index a745999622..203515d508 100644 --- a/actionpack/test/template/test_case_test.rb +++ b/actionpack/test/template/test_case_test.rb @@ -116,6 +116,27 @@ module ActionView end end + class ControllerHelperMethod < ActionView::TestCase + module SomeHelper + def some_method + render :partial => 'test/from_helper' + end + end + + helper SomeHelper + + test "can call a helper method defined on the current controller from a helper" do + @controller.singleton_class.class_eval <<-EOF, __FILE__, __LINE__ + 1 + def render_from_helper + 'controller_helper_method' + end + EOF + @controller.class.helper_method :render_from_helper + + assert_equal 'controller_helper_method', some_method + end + end + class AssignsTest < ActionView::TestCase setup do ActiveSupport::Deprecation.stubs(:warn) -- cgit v1.2.3 From daada51d1051948c3e6de963a90c4b5bb5bf142b Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Wed, 12 Jan 2011 16:44:56 -0200 Subject: Reuse the view_context from the controller, this make the test environment more similar to the code applications uses --- actionpack/lib/action_view/test_case.rb | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/test_case.rb b/actionpack/lib/action_view/test_case.rb index 72d17143f5..d4f16d4b36 100644 --- a/actionpack/lib/action_view/test_case.rb +++ b/actionpack/lib/action_view/test_case.rb @@ -156,11 +156,8 @@ module ActionView # The instance of ActionView::Base that is used by +render+. def view @view ||= begin - view = ActionView::Base.new(ActionController::Base.view_paths, {}, @controller) - view.singleton_class.send :include, @controller._helpers + view = @controller.view_context view.singleton_class.send :include, _helpers - view.singleton_class.send :include, @controller._routes.url_helpers - view.singleton_class.send :delegate, :alert, :notice, :to => "request.flash" view.extend(Locals) view.locals = self.locals view.output_buffer = self.output_buffer -- cgit v1.2.3 From 1d9c555297c15b6d5212e65c1afec718e043ce45 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 12 Jan 2011 10:01:31 -0800 Subject: reraising should be in the rescue block --- actionpack/lib/action_dispatch/middleware/show_exceptions.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb index 936fd548b9..11739e08d9 100644 --- a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb +++ b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb @@ -53,8 +53,8 @@ module ActionDispatch exception = ActionController::RoutingError.new("No route matches #{env['PATH_INFO'].inspect}") end rescue Exception => exception + raise exception if env['action_dispatch.show_exceptions'] == false end - raise exception if env['action_dispatch.show_exceptions'] == false exception ? render_exception(env, exception) : [status, headers, body] end -- cgit v1.2.3 From 16ae08fff0f16b3f0eb7757e01aabb02b257bd35 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 12 Jan 2011 10:28:21 -0800 Subject: use raise to create exceptions and to set the backtrace --- actionpack/lib/action_dispatch/middleware/show_exceptions.rb | 2 +- actionpack/lib/action_dispatch/routing/route_set.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb index 11739e08d9..dbe3206808 100644 --- a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb +++ b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb @@ -50,7 +50,7 @@ module ActionDispatch # Only this middleware cares about RoutingError. So, let's just raise # it here. if headers['X-Cascade'] == 'pass' - exception = ActionController::RoutingError.new("No route matches #{env['PATH_INFO'].inspect}") + raise ActionController::RoutingError, "No route matches #{env['PATH_INFO'].inspect}" end rescue Exception => exception raise exception if env['action_dispatch.show_exceptions'] == false diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 03bfe178e5..683fa19380 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -450,7 +450,7 @@ module ActionDispatch end def raise_routing_error - raise ActionController::RoutingError.new("No route matches #{options.inspect}") + raise ActionController::RoutingError, "No route matches #{options.inspect}" end def different_controller? -- cgit v1.2.3 From 1de47a0d56328768dfba0e5f86e1ff9491e62c20 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Wed, 12 Jan 2011 22:05:52 -0200 Subject: button_tag should escape it content --- actionpack/lib/action_view/helpers/form_tag_helper.rb | 2 +- actionpack/test/template/form_tag_helper_test.rb | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers/form_tag_helper.rb b/actionpack/lib/action_view/helpers/form_tag_helper.rb index 159b2a2b8e..d6b74974e9 100644 --- a/actionpack/lib/action_view/helpers/form_tag_helper.rb +++ b/actionpack/lib/action_view/helpers/form_tag_helper.rb @@ -457,7 +457,7 @@ module ActionView options[option] = "button" unless options[option] end - content_tag :button, label.to_s.html_safe, { "type" => options.delete("type") }.update(options) + content_tag :button, label, { "type" => options.delete("type") }.update(options) end # Displays an image which when clicked will submit the form. diff --git a/actionpack/test/template/form_tag_helper_test.rb b/actionpack/test/template/form_tag_helper_test.rb index 0d29b962d5..4a584b8db8 100644 --- a/actionpack/test/template/form_tag_helper_test.rb +++ b/actionpack/test/template/form_tag_helper_test.rb @@ -413,6 +413,13 @@ class FormTagHelperTest < ActionView::TestCase ) end + def test_button_tag_escape_content + assert_dom_equal( + %(), + button_tag("Reset", :type => "reset", :disabled => true) + ) + end + def test_image_submit_tag_with_confirmation assert_dom_equal( %(), -- cgit v1.2.3 From 9702159373a4df8f05d06e79dfa0f57723f8bfc8 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 17 Jan 2011 14:33:34 -0800 Subject: removing more unused variables --- actionpack/lib/action_dispatch/http/cache.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/http/cache.rb b/actionpack/lib/action_dispatch/http/cache.rb index 1d2f7e4f19..4f4cb96a74 100644 --- a/actionpack/lib/action_dispatch/http/cache.rb +++ b/actionpack/lib/action_dispatch/http/cache.rb @@ -43,7 +43,7 @@ module ActionDispatch alias :etag? :etag def initialize(*) - status, header, body = super + super @cache_control = {} @etag = self["ETag"] -- cgit v1.2.3 From 990e6a1b3a7015e7d828371a417084d5a94fa780 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 17 Jan 2011 14:43:29 -0800 Subject: fixing wrong test --- actionpack/test/controller/mime_responds_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack') diff --git a/actionpack/test/controller/mime_responds_test.rb b/actionpack/test/controller/mime_responds_test.rb index fe14d24327..5debf96232 100644 --- a/actionpack/test/controller/mime_responds_test.rb +++ b/actionpack/test/controller/mime_responds_test.rb @@ -658,7 +658,7 @@ class RespondWithControllerTest < ActionController::TestCase @request.accept = "application/json" get :using_hash_resource assert_equal "application/json", @response.content_type - assert_equal %Q[{"result":["david",13]}], @response.body + assert_equal %Q[{"result":{"name":"david","id":13}}], @response.body end def test_using_resource_with_block -- cgit v1.2.3 From 1333020448e8b39cbf98b0292a9be9d3f8a14376 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 17 Jan 2011 14:45:24 -0800 Subject: fixing space errors --- actionpack/test/template/test_case_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack') diff --git a/actionpack/test/template/test_case_test.rb b/actionpack/test/template/test_case_test.rb index 203515d508..11c355dc6d 100644 --- a/actionpack/test/template/test_case_test.rb +++ b/actionpack/test/template/test_case_test.rb @@ -167,7 +167,7 @@ module ActionView end end end - + class HelperExposureTest < ActionView::TestCase helper(Module.new do def render_from_helper -- cgit v1.2.3 From 6a8f7f0e04bce3ade8ff24fce80580cd23fae6d7 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 17 Jan 2011 14:53:44 -0800 Subject: minitest added @__io__, so we should ignore it too --- actionpack/lib/action_view/test_case.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/test_case.rb b/actionpack/lib/action_view/test_case.rb index d4f16d4b36..2ce109ea99 100644 --- a/actionpack/lib/action_view/test_case.rb +++ b/actionpack/lib/action_view/test_case.rb @@ -169,6 +169,7 @@ module ActionView INTERNAL_IVARS = %w{ @__name__ + @__io__ @_assertion_wrapped @_assertions @_result -- cgit v1.2.3 From 7dab186fded971e69f9d8bf5db524c20da326b83 Mon Sep 17 00:00:00 2001 From: Christos Trochalakis Date: Thu, 16 Sep 2010 19:44:18 +0300 Subject: Issue one Cache#read command instead of two in the case of a fragment cache hit --- actionpack/lib/action_view/helpers/cache_helper.rb | 4 ++-- actionpack/test/controller/log_subscriber_test.rb | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers/cache_helper.rb b/actionpack/lib/action_view/helpers/cache_helper.rb index 30e6c078b1..385378ea29 100644 --- a/actionpack/lib/action_view/helpers/cache_helper.rb +++ b/actionpack/lib/action_view/helpers/cache_helper.rb @@ -44,8 +44,8 @@ module ActionView private # TODO: Create an object that has caching read/write on it def fragment_for(name = {}, options = nil, &block) #:nodoc: - if controller.fragment_exist?(name, options) - controller.read_fragment(name, options) + if fragment = controller.read_fragment(name, options) + fragment else # VIEW TODO: Make #capture usable outside of ERB # This dance is needed because Builder can't use capture diff --git a/actionpack/test/controller/log_subscriber_test.rb b/actionpack/test/controller/log_subscriber_test.rb index e6fe0b1f04..cac0881133 100644 --- a/actionpack/test/controller/log_subscriber_test.rb +++ b/actionpack/test/controller/log_subscriber_test.rb @@ -139,20 +139,20 @@ class ACLogSubscriberTest < ActionController::TestCase wait assert_equal 4, logs.size - assert_match(/Exist fragment\? views\/foo/, logs[1]) + assert_match /Read fragment views\/foo/, logs[1] assert_match(/Write fragment views\/foo/, logs[2]) ensure @controller.config.perform_caching = true end - + def test_with_fragment_cache_and_percent_in_key @controller.config.perform_caching = true get :with_fragment_cache_and_percent_in_key wait assert_equal 4, logs.size - assert_match(/Exist fragment\? views\/foo%bar/, logs[1]) - assert_match(/Write fragment views\/foo%bar/, logs[2]) + assert_match /Read fragment views\/foo/, logs[1] + assert_match /Write fragment views\/foo/, logs[2] ensure @controller.config.perform_caching = true end -- cgit v1.2.3 From 36d66786905b3cc2dda6c48345a89bbd760fcb82 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 18 Jan 2011 14:55:20 -0800 Subject: removing usesless variable assignments --- actionpack/test/abstract/callbacks_test.rb | 28 ++++++++++++++-------------- actionpack/test/controller/caching_test.rb | 2 -- 2 files changed, 14 insertions(+), 16 deletions(-) (limited to 'actionpack') diff --git a/actionpack/test/abstract/callbacks_test.rb b/actionpack/test/abstract/callbacks_test.rb index 5308fc849b..3bdde86291 100644 --- a/actionpack/test/abstract/callbacks_test.rb +++ b/actionpack/test/abstract/callbacks_test.rb @@ -22,7 +22,7 @@ module AbstractController class TestCallbacks1 < ActiveSupport::TestCase test "basic callbacks work" do controller = Callback1.new - result = controller.process(:index) + controller.process(:index) assert_equal "Hello world", controller.response_body end end @@ -62,7 +62,7 @@ module AbstractController end test "before_filter works" do - result = @controller.process(:index) + @controller.process(:index) assert_equal "Hello world", @controller.response_body end @@ -78,7 +78,7 @@ module AbstractController test "before_filter with overwritten condition" do @controller = Callback2Overwrite.new - result = @controller.process(:index) + @controller.process(:index) assert_equal "", @controller.response_body end end @@ -103,12 +103,12 @@ module AbstractController end test "before_filter works with procs" do - result = @controller.process(:index) + @controller.process(:index) assert_equal "Hello world", @controller.response_body end test "after_filter works with procs" do - result = @controller.process(:index) + @controller.process(:index) assert_equal "Goodbye", @controller.instance_variable_get("@second") end end @@ -152,7 +152,7 @@ module AbstractController end test "when :except is specified, an after filter is not triggered on that action" do - result = @controller.process(:index) + @controller.process(:index) assert !@controller.instance_variable_defined?("@authenticated") end end @@ -186,17 +186,17 @@ module AbstractController end test "when :only is specified with an array, a before filter is triggered on that action" do - result = @controller.process(:index) + @controller.process(:index) assert_equal "Hello, World", @controller.response_body end test "when :only is specified with an array, a before filter is not triggered on other actions" do - result = @controller.process(:sekrit_data) + @controller.process(:sekrit_data) assert_equal "true", @controller.response_body end test "when :except is specified with an array, an after filter is not triggered on that action" do - result = @controller.process(:index) + @controller.process(:index) assert !@controller.instance_variable_defined?("@authenticated") end end @@ -216,12 +216,12 @@ module AbstractController end test "when a callback is modified in a child with :only, it works for the :only action" do - result = @controller.process(:index) + @controller.process(:index) assert_equal "Hello world", @controller.response_body end test "when a callback is modified in a child with :only, it does not work for other actions" do - result = @controller.process(:not_index) + @controller.process(:not_index) assert_equal "", @controller.response_body end end @@ -245,14 +245,14 @@ module AbstractController assert_equal "Success", controller.response_body end end - + class CallbacksWithArgs < ControllerWithCallbacks set_callback :process_action, :before, :first def first @text = "Hello world" end - + def index(text) self.response_body = @text + text end @@ -261,7 +261,7 @@ module AbstractController class TestCallbacksWithArgs < ActiveSupport::TestCase test "callbacks still work when invoking process with multiple args" do controller = CallbacksWithArgs.new - result = controller.process(:index, " Howdy!") + controller.process(:index, " Howdy!") assert_equal "Hello world Howdy!", controller.response_body end end diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb index c7b54eb0ba..af02c7f9fa 100644 --- a/actionpack/test/controller/caching_test.rb +++ b/actionpack/test/controller/caching_test.rb @@ -257,7 +257,6 @@ class ActionCachingMockController end def request - mocked_path = @mock_path Object.new.instance_eval(<<-EVAL) def path; '#{@mock_path}' end def format; 'all' end @@ -416,7 +415,6 @@ class ActionCacheTest < ActionController::TestCase get :index assert_response :success - new_cached_time = content_to_cache assert_not_equal cached_time, @response.body end -- cgit v1.2.3 From 262b2ea8cda20999ddf8c4bf13b7a70453e996d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Wed, 19 Jan 2011 23:42:10 +0100 Subject: Solve SystemStackError when changing locale inside ActionMailer [#5329 state:resolved] --- actionpack/lib/abstract_controller/rendering.rb | 9 +++++---- actionpack/lib/action_view/lookup_context.rb | 4 ++-- actionpack/test/template/lookup_context_test.rb | 2 +- 3 files changed, 8 insertions(+), 7 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/abstract_controller/rendering.rb b/actionpack/lib/abstract_controller/rendering.rb index 9b912ea988..ec1160c31e 100644 --- a/actionpack/lib/abstract_controller/rendering.rb +++ b/actionpack/lib/abstract_controller/rendering.rb @@ -13,14 +13,15 @@ module AbstractController # This is a class to fix I18n global state. Whenever you provide I18n.locale during a request, # it will trigger the lookup_context and consequently expire the cache. class I18nProxy < ::I18n::Config #:nodoc: - attr_reader :i18n_config, :lookup_context + attr_reader :original_config, :lookup_context - def initialize(i18n_config, lookup_context) - @i18n_config, @lookup_context = i18n_config, lookup_context + def initialize(original_config, lookup_context) + original_config = original_config.original_config if original_config.respond_to?(:original_config) + @original_config, @lookup_context = original_config, lookup_context end def locale - @i18n_config.locale + @original_config.locale end def locale=(value) diff --git a/actionpack/lib/action_view/lookup_context.rb b/actionpack/lib/action_view/lookup_context.rb index 1365048724..e434f3b059 100644 --- a/actionpack/lib/action_view/lookup_context.rb +++ b/actionpack/lib/action_view/lookup_context.rb @@ -186,11 +186,11 @@ module ActionView end # Overload locale= to also set the I18n.locale. If the current I18n.config object responds - # to i18n_config, it means that it's has a copy of the original I18n configuration and it's + # to original_config, it means that it's has a copy of the original I18n configuration and it's # acting as proxy, which we need to skip. def locale=(value) if value - config = I18n.config.respond_to?(:i18n_config) ? I18n.config.i18n_config : I18n.config + config = I18n.config.respond_to?(:original_config) ? I18n.config.original_config : I18n.config config.locale = value end diff --git a/actionpack/test/template/lookup_context_test.rb b/actionpack/test/template/lookup_context_test.rb index f7a684779c..f3b1335000 100644 --- a/actionpack/test/template/lookup_context_test.rb +++ b/actionpack/test/template/lookup_context_test.rb @@ -73,7 +73,7 @@ class LookupContextTest < ActiveSupport::TestCase assert_equal :pt, I18n.locale assert_equal :pt, @lookup_context.locale ensure - I18n.config = I18n.config.i18n_config + I18n.config = I18n.config.original_config end assert_equal :pt, I18n.locale -- cgit v1.2.3 From 91a4193ee002d20e1b9bd637a5f14ac6213c8f39 Mon Sep 17 00:00:00 2001 From: brainopia Date: Fri, 21 Jan 2011 14:58:33 +0300 Subject: Support list of possible domains for cookies MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- .../lib/action_dispatch/middleware/cookies.rb | 3 ++ actionpack/test/dispatch/cookies_test.rb | 45 ++++++++++++++++++++++ 2 files changed, 48 insertions(+) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb index f369d2d3c2..0a230fed2c 100644 --- a/actionpack/lib/action_dispatch/middleware/cookies.rb +++ b/actionpack/lib/action_dispatch/middleware/cookies.rb @@ -136,6 +136,9 @@ module ActionDispatch options[:domain] = if (@host !~ /^[\d.]+$/) && (@host =~ DOMAIN_REGEXP) ".#{$1}.#{$2}" end + elsif options[:domain].is_a? Array + # if host matches one of the supplied domains without a dot in front of it + options[:domain] = options[:domain].find {|domain| @host.include? domain[/^\.?(.*)$/, 1] } end end diff --git a/actionpack/test/dispatch/cookies_test.rb b/actionpack/test/dispatch/cookies_test.rb index e2040401c7..766dbe117d 100644 --- a/actionpack/test/dispatch/cookies_test.rb +++ b/actionpack/test/dispatch/cookies_test.rb @@ -95,6 +95,16 @@ class CookiesTest < ActionController::TestCase head :ok end + def set_cookie_with_domains + cookies[:user_name] = {:value => "rizwanreza", :domain => %w(example1.com example2.com .example3.com)} + head :ok + end + + def delete_cookie_with_domains + cookies.delete(:user_name, :domain => %w(example1.com example2.com .example3.com)) + head :ok + end + def symbol_key cookies[:user_name] = "david" head :ok @@ -322,6 +332,41 @@ class CookiesTest < ActionController::TestCase assert_cookie_header "user_name=; domain=.nextangle.com; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT" end + def test_cookie_with_several_preset_domains_using_one_of_these_domains + @request.host = "example1.com" + get :set_cookie_with_domains + assert_response :success + assert_cookie_header "user_name=rizwanreza; domain=example1.com; path=/" + end + + def test_cookie_with_several_preset_domains_using_other_domain + @request.host = "other-domain.com" + get :set_cookie_with_domains + assert_response :success + assert_cookie_header "user_name=rizwanreza; path=/" + end + + def test_cookie_with_several_preset_domains_using_shared_domain + @request.host = "example3.com" + get :set_cookie_with_domains + assert_response :success + assert_cookie_header "user_name=rizwanreza; domain=.example3.com; path=/" + end + + def test_deletings_cookie_with_several_preset_domains_using_one_of_these_domains + @request.host = "example2.com" + get :delete_cookie_with_domains + assert_response :success + assert_cookie_header "user_name=; domain=example2.com; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT" + end + + def test_deletings_cookie_with_several_preset_domains_using_other_domain + @request.host = "other-domain.com" + get :delete_cookie_with_domains + assert_response :success + assert_cookie_header "user_name=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT" + end + def test_cookies_hash_is_indifferent_access [:symbol_key, :string_key].each do |cookie_key| get cookie_key -- cgit v1.2.3 From 8491f16e128d2d2cfe53676f36c5d4c281712bde Mon Sep 17 00:00:00 2001 From: brainopia Date: Fri, 21 Jan 2011 14:59:49 +0300 Subject: Add tld_length option when using domain :all in cookies MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- .../lib/action_dispatch/middleware/cookies.rb | 18 +++++------ actionpack/test/dispatch/cookies_test.rb | 36 ++++++++++++++++++++++ 2 files changed, 45 insertions(+), 9 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb index 0a230fed2c..7ac608f0a8 100644 --- a/actionpack/lib/action_dispatch/middleware/cookies.rb +++ b/actionpack/lib/action_dispatch/middleware/cookies.rb @@ -90,17 +90,14 @@ module ActionDispatch # **.**, ***.** style TLDs like co.uk or com.au # # www.example.co.uk gives: - # $1 => example - # $2 => co.uk + # $& => example.co.uk # # example.com gives: - # $1 => example - # $2 => com + # $& => example.com # # lots.of.subdomains.example.local gives: - # $1 => example - # $2 => local - DOMAIN_REGEXP = /([^.]*)\.([^.]*|..\...|...\...)$/ + # $& => example.local + DOMAIN_REGEXP = /[^.]*\.([^.]*|..\...|...\...)$/ def self.build(request) secret = request.env[TOKEN_KEY] @@ -131,10 +128,13 @@ module ActionDispatch options[:path] ||= "/" if options[:domain] == :all + # if there is a provided tld length then we use it otherwise default domain regexp + domain_regexp = options[:tld_length] ? /([^.]+\.?){#{options[:tld_length]}}$/ : DOMAIN_REGEXP + # if host is not ip and matches domain regexp # (ip confirms to domain regexp so we explicitly check for ip) - options[:domain] = if (@host !~ /^[\d.]+$/) && (@host =~ DOMAIN_REGEXP) - ".#{$1}.#{$2}" + options[:domain] = if (@host !~ /^[\d.]+$/) && (@host =~ domain_regexp) + ".#{$&}" end elsif options[:domain].is_a? Array # if host matches one of the supplied domains without a dot in front of it diff --git a/actionpack/test/dispatch/cookies_test.rb b/actionpack/test/dispatch/cookies_test.rb index 766dbe117d..1cfea6aa12 100644 --- a/actionpack/test/dispatch/cookies_test.rb +++ b/actionpack/test/dispatch/cookies_test.rb @@ -95,6 +95,16 @@ class CookiesTest < ActionController::TestCase head :ok end + def set_cookie_with_domain_and_tld + cookies[:user_name] = {:value => "rizwanreza", :domain => :all, :tld_length => 2} + head :ok + end + + def delete_cookie_with_domain_and_tld + cookies.delete(:user_name, :domain => :all, :tld_length => 2) + head :ok + end + def set_cookie_with_domains cookies[:user_name] = {:value => "rizwanreza", :domain => %w(example1.com example2.com .example3.com)} head :ok @@ -332,6 +342,32 @@ class CookiesTest < ActionController::TestCase assert_cookie_header "user_name=; domain=.nextangle.com; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT" end + def test_cookie_with_all_domain_option_and_tld_length + get :set_cookie_with_domain_and_tld + assert_response :success + assert_cookie_header "user_name=rizwanreza; domain=.nextangle.com; path=/" + end + + def test_cookie_with_all_domain_option_using_a_non_standard_tld_and_tld_length + @request.host = "two.subdomains.nextangle.local" + get :set_cookie_with_domain_and_tld + assert_response :success + assert_cookie_header "user_name=rizwanreza; domain=.nextangle.local; path=/" + end + + def test_cookie_with_all_domain_option_using_host_with_port_and_tld_length + @request.host = "nextangle.local:3000" + get :set_cookie_with_domain_and_tld + assert_response :success + assert_cookie_header "user_name=rizwanreza; domain=.nextangle.local; path=/" + end + + def test_deleting_cookie_with_all_domain_option_and_tld_length + get :delete_cookie_with_domain_and_tld + assert_response :success + assert_cookie_header "user_name=; domain=.nextangle.com; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT" + end + def test_cookie_with_several_preset_domains_using_one_of_these_domains @request.host = "example1.com" get :set_cookie_with_domains -- cgit v1.2.3 From 3d6e223b8457a0bfae0debbc172cb44575a7858a Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 21 Jan 2011 15:43:34 -0800 Subject: use spec compliant YAML --- actionpack/test/controller/webservice_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack') diff --git a/actionpack/test/controller/webservice_test.rb b/actionpack/test/controller/webservice_test.rb index 6ba4c6c48d..621fb79915 100644 --- a/actionpack/test/controller/webservice_test.rb +++ b/actionpack/test/controller/webservice_test.rb @@ -216,7 +216,7 @@ class WebServiceTest < ActionDispatch::IntegrationTest def test_typecast_as_yaml with_test_route_set do with_params_parsers Mime::YAML => :yaml do - yaml = <<-YAML + yaml = (<<-YAML).strip --- data: a: 15 -- cgit v1.2.3 From 7927fc2ff77543a0ab151ac1cb3d60318e2dfa68 Mon Sep 17 00:00:00 2001 From: Doug Fales Date: Tue, 18 Jan 2011 15:36:08 -0700 Subject: A patch so that http status codes are still included in logs even during an exception [#6333 state:resolved] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- actionpack/lib/action_controller/log_subscriber.rb | 6 +++++- actionpack/test/controller/log_subscriber_test.rb | 15 +++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_controller/log_subscriber.rb b/actionpack/lib/action_controller/log_subscriber.rb index 3b19310a69..3fae697cc3 100644 --- a/actionpack/lib/action_controller/log_subscriber.rb +++ b/actionpack/lib/action_controller/log_subscriber.rb @@ -16,7 +16,11 @@ module ActionController payload = event.payload additions = ActionController::Base.log_process_action(payload) - message = "Completed #{payload[:status]} #{Rack::Utils::HTTP_STATUS_CODES[payload[:status]]} in %.0fms" % event.duration + status = payload[:status] + if status.nil? && payload[:exception].present? + status = Rack::Utils.status_code(ActionDispatch::ShowExceptions.rescue_responses[payload[:exception].first]) rescue nil + end + message = "Completed #{status} #{Rack::Utils::HTTP_STATUS_CODES[status]} in %.0fms" % event.duration message << " (#{additions.join(" | ")})" unless additions.blank? info(message) diff --git a/actionpack/test/controller/log_subscriber_test.rb b/actionpack/test/controller/log_subscriber_test.rb index cac0881133..21bbd83653 100644 --- a/actionpack/test/controller/log_subscriber_test.rb +++ b/actionpack/test/controller/log_subscriber_test.rb @@ -32,6 +32,11 @@ module Another cache_page("Super soaker", "/index.html") render :nothing => true end + + def with_exception + raise Exception + end + end end @@ -168,6 +173,16 @@ class ACLogSubscriberTest < ActionController::TestCase ensure @controller.config.perform_caching = true end + + def test_process_action_with_exception_includes_http_status_code + begin + get :with_exception + wait + rescue Exception => e + end + assert_equal 2, logs.size + assert_match(/Completed 500/, logs.last) + end def logs @logs ||= @logger.logged(:info) -- cgit v1.2.3 From c1145d9281c8deee2a58a96a32f2e3218a7c28be Mon Sep 17 00:00:00 2001 From: Neeraj Singh Date: Fri, 21 Jan 2011 19:10:31 -0500 Subject: If I want to set respond_body to nil then it should be nil and not [nil]. If anything other than nil then wrap it in array MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- actionpack/lib/action_controller/metal.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_controller/metal.rb b/actionpack/lib/action_controller/metal.rb index 329798e84f..3df3c341bb 100644 --- a/actionpack/lib/action_controller/metal.rb +++ b/actionpack/lib/action_controller/metal.rb @@ -133,7 +133,7 @@ module ActionController end def response_body=(val) - body = val.respond_to?(:each) ? val : [val] + body = val.nil? ? nil : (val.respond_to?(:each) ? val : [val]) super body end -- cgit v1.2.3 From 806e6f80dc7e0abc3c8e139b584bbf444b30d612 Mon Sep 17 00:00:00 2001 From: Neeraj Singh Date: Fri, 21 Jan 2011 19:13:58 -0500 Subject: render_to_string must ensure that response_body is nil MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [ #5875 state:resolved] Signed-off-by: José Valim --- actionpack/lib/abstract_controller/rendering.rb | 2 +- actionpack/test/controller/render_json_test.rb | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) (limited to 'actionpack') diff --git a/actionpack/lib/abstract_controller/rendering.rb b/actionpack/lib/abstract_controller/rendering.rb index ec1160c31e..691310d5d2 100644 --- a/actionpack/lib/abstract_controller/rendering.rb +++ b/actionpack/lib/abstract_controller/rendering.rb @@ -113,7 +113,7 @@ module AbstractController def render_to_string(*args, &block) options = _normalize_args(*args, &block) _normalize_options(options) - render_to_body(options) + render_to_body(options).tap { self.response_body = nil } end # Raw rendering of a template to a Rack-compatible body. diff --git a/actionpack/test/controller/render_json_test.rb b/actionpack/test/controller/render_json_test.rb index 6dd2a9f23d..fc604a2db3 100644 --- a/actionpack/test/controller/render_json_test.rb +++ b/actionpack/test/controller/render_json_test.rb @@ -26,6 +26,10 @@ class RenderJsonTest < ActionController::TestCase render :json => nil end + def render_json_render_to_string + render :text => render_to_string(:json => '[]') + end + def render_json_hello_world render :json => ActiveSupport::JSON.encode(:hello => 'world') end @@ -76,6 +80,12 @@ class RenderJsonTest < ActionController::TestCase assert_equal 'application/json', @response.content_type end + def test_render_json_render_to_string + get :render_json_render_to_string + assert_equal '[]', @response.body + end + + def test_render_json get :render_json_hello_world assert_equal '{"hello":"world"}', @response.body -- cgit v1.2.3 From cc9301f459739e3eb3674b1b2e15057e35d25630 Mon Sep 17 00:00:00 2001 From: Matt Jankowski Date: Thu, 27 Jan 2011 12:25:22 -0500 Subject: clarify what the "they" that are is and what the "are" in question is --- actionpack/lib/action_dispatch/routing/mapper.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index f65a294eca..6658af15b0 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -827,7 +827,8 @@ module ActionDispatch alias :member_name :singular - # Checks for uncountable plurals, and appends "_index" if they're. + # Checks for uncountable plurals, and appends "_index" if the plural + # and singular form are the same. def collection_name singular == plural ? "#{plural}_index" : plural end -- cgit v1.2.3 From 49744bdaee899d64f8c70f65b2c1d63ace41cafa Mon Sep 17 00:00:00 2001 From: Jonathan Dance + Gabriel Horner Date: Fri, 28 Jan 2011 16:55:21 -0500 Subject: fix cross-references in HttpHelper methods --- actionpack/lib/action_dispatch/routing/mapper.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 6658af15b0..af7a2c31f4 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -349,7 +349,7 @@ module ActionDispatch module HttpHelpers # Define a route that only recognizes HTTP GET. - # For supported arguments, see +match+. + # For supported arguments, see Base#match. # # Example: # @@ -359,7 +359,7 @@ module ActionDispatch end # Define a route that only recognizes HTTP POST. - # For supported arguments, see +match+. + # For supported arguments, see Base#match. # # Example: # @@ -369,7 +369,7 @@ module ActionDispatch end # Define a route that only recognizes HTTP PUT. - # For supported arguments, see +match+. + # For supported arguments, see Base#match. # # Example: # @@ -379,7 +379,7 @@ module ActionDispatch end # Define a route that only recognizes HTTP PUT. - # For supported arguments, see +match+. + # For supported arguments, see Base#match. # # Example: # -- cgit v1.2.3 From 38d728fb944b08b7faabf19c8ba5ef2e69e29c16 Mon Sep 17 00:00:00 2001 From: Jonathan Dance + Gabriel Horner Date: Fri, 28 Jan 2011 17:01:48 -0500 Subject: add cross-references and documentation for scope --- actionpack/lib/action_dispatch/routing.rb | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/routing.rb b/actionpack/lib/action_dispatch/routing.rb index 8810227a59..43fd93adf6 100644 --- a/actionpack/lib/action_dispatch/routing.rb +++ b/actionpack/lib/action_dispatch/routing.rb @@ -56,6 +56,18 @@ module ActionDispatch # resources :posts, :comments # end # + # Alternately, you can add prefixes to your path without using a separate + # directory by using +scope+. +scope+ takes additional options which + # apply to all enclosed routes. + # + # scope :path => "/cpanel", :as => 'admin' do + # resources :posts, :comments + # end + # + # For more, see Routing::Mapper::Resources#resources, + # Routing::Mapper::Scoping#namespace, and + # Routing::Mapper::Scoping#scope. + # # == Named routes # # Routes can be named by passing an :as option, -- cgit v1.2.3 From ef48408a7bed075089999f588250f9710bca8f40 Mon Sep 17 00:00:00 2001 From: misfo Date: Sat, 29 Jan 2011 16:03:40 -0600 Subject: corrected the location of status code symbols --- actionpack/lib/action_dispatch/testing/assertions/response.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/testing/assertions/response.rb b/actionpack/lib/action_dispatch/testing/assertions/response.rb index 1558c3ae05..77a15f3e97 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/response.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/response.rb @@ -20,7 +20,7 @@ module ActionDispatch # # You can also pass an explicit status number like assert_response(501) # or its symbolic equivalent assert_response(:not_implemented). - # See ActionDispatch::StatusCodes for a full list. + # See Rack::Utils::SYMBOL_TO_STATUS_CODE for a full list. # # ==== Examples # -- cgit v1.2.3 From fab16fded9a68cd327b6cfc5439ff10eed6df40b Mon Sep 17 00:00:00 2001 From: Jonathan Dance + Gabriel Horner Date: Sat, 29 Jan 2011 10:16:45 -0500 Subject: organize and expand on options for routing methods --- actionpack/lib/action_dispatch/routing/mapper.rb | 242 +++++++++++++++-------- 1 file changed, 161 insertions(+), 81 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index af7a2c31f4..ee0fdce9dd 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -265,6 +265,78 @@ module ActionDispatch # controller in your application, and :action maps to the name of an # action within that controller. Anything other than :controller or # :action will be available to the action as part of params. + # + # === Supported options + # + # [:controller] + # The route's controller. + # + # [:action] + # The route's action. + # + # [:path] + # The path prefix for the routes. + # + # [:module] + # The namespace for :controller. + # + # match 'path' => 'c#a', :module => 'sekret', :controller => 'posts' + # #=> Sekret::PostsController + # + # See Scoping#namespace for its scope equivalent. + # + # [:as] + # The name used to generate routing helpers. + # + # [:via] + # Allowed HTTP verb(s) for route. + # + # match 'path' => 'c#a', :via => :get + # match 'path' => 'c#a', :via => [:get, :post] + # + # [:to] + # Shorthand for specifying :controller and :action. + # + # match 'path' => 'c#a', :to => 'controller#action' + # + # [:on] + # Shorthand for wrapping routes in a specific RESTful context. Valid + # values are :member, :collection, and :new. Only use within + # resource(s) block. For example: + # + # resource :bar do + # match 'foo' => 'c#a', :on => :member, :via => [:get, :post] + # end + # + # Is equivalent to: + # + # resource :bar do + # member do + # match 'foo' => 'c#a', :via => [:get, :post] + # end + # end + # + # [:constraints] + # Constrains parameters with a hash of regular expressions or an + # object that responds to #matches? + # + # match 'path/:id', :constraints => { :id => /[A-Z]\d{5}/ } + # + # class Blacklist + # def matches?(request) request.remote_ip == '1.2.3.4' end + # end + # match 'path' => 'c#a', :constraints => Blacklist.new + # + # See Scoping#constraints for more examples with its scope + # equivalent. + # + # [:defaults] + # Sets defaults for parameters + # + # # Sets params[:format] to 'jpg' by default + # match 'path' => 'c#a', :defaults => { :format => 'jpg' } + # + # See Scoping#defaults for its scope equivalent. def match(path, options=nil) mapping = Mapping.new(@set, @scope, path, options || {}).to_route @set.add_route(*mapping) @@ -458,7 +530,7 @@ module ActionDispatch super end - # Used to scope a set of routes to particular constraints. + # Scopes a set of routes to the given default options. # # Take the following route definition as an example: # @@ -471,50 +543,25 @@ module ActionDispatch # rather than /accounts/rails/projects/2. # # === Supported options - # [:module] - # If you want to route /posts (without the prefix /admin) to - # Admin::PostsController, you could use - # - # scope :module => "admin" do - # resources :posts - # end - # - # [:path] - # If you want to prefix the route, you could use - # - # scope :path => "/admin" do - # resources :posts - # end # - # This will prefix all of the +posts+ resource's requests with '/admin' + # Takes same options as Base#match and Resources#resources. # - # [:as] - # Prefixes the routing helpers in this scope with the specified label. - # - # scope :as => "sekret" do - # resources :posts - # end - # - # Helpers such as +posts_path+ will now be +sekret_posts_path+ - # - # [:shallow_path] - # - # Prefixes nested shallow routes with the specified path. + # === Examples # - # scope :shallow_path => "sekret" do - # resources :posts do - # resources :comments, :shallow => true - # end + # # route /posts (without the prefix /admin) to Admin::PostsController + # scope :module => "admin" do + # resources :posts + # end # - # The +comments+ resource here will have the following routes generated for it: + # # prefix the posts resource's requests with '/admin' + # scope :path => "/admin" do + # resources :posts + # end # - # post_comments GET /sekret/posts/:post_id/comments(.:format) - # post_comments POST /sekret/posts/:post_id/comments(.:format) - # new_post_comment GET /sekret/posts/:post_id/comments/new(.:format) - # edit_comment GET /sekret/comments/:id/edit(.:format) - # comment GET /sekret/comments/:id(.:format) - # comment PUT /sekret/comments/:id(.:format) - # comment DELETE /sekret/comments/:id(.:format) + # # prefix the routing helper name: sekret_posts_path instead of posts_path + # scope :as => "sekret" do + # resources :posts + # end def scope(*args) options = args.extract_options! options = options.dup @@ -577,43 +624,31 @@ module ActionDispatch # admin_post GET /admin/posts/:id(.:format) {:action=>"show", :controller=>"admin/posts"} # admin_post PUT /admin/posts/:id(.:format) {:action=>"update", :controller=>"admin/posts"} # admin_post DELETE /admin/posts/:id(.:format) {:action=>"destroy", :controller=>"admin/posts"} - # === Supported options - # - # The +:path+, +:as+, +:module+, +:shallow_path+ and +:shallow_prefix+ options all default to the name of the namespace. - # - # [:path] - # The path prefix for the routes. # - # namespace :admin, :path => "sekret" do - # resources :posts - # end - # - # All routes for the above +resources+ will be accessible through +/sekret/posts+, rather than +/admin/posts+ - # - # [:module] - # The namespace for the controllers. + # === Supported options # - # namespace :admin, :module => "sekret" do - # resources :posts - # end + # The +:path+, +:as+, +:module+, +:shallow_path+ and +:shallow_prefix+ + # options all default to the name of the namespace. # - # The +PostsController+ here should go in the +Sekret+ namespace and so it should be defined like this: + # For options, see Base#match. For +:shallow_path+ option, see + # Resources#resources. # - # class Sekret::PostsController < ApplicationController - # # code go here - # end + # === Examples # - # [:as] - # Changes the name used in routing helpers for this namespace. - # - # namespace :admin, :as => "sekret" do - # resources :posts - # end + # # accessible through /sekret/posts rather than /admin/posts + # namespace :admin, :path => "sekret" do + # resources :posts + # end # - # Routing helpers such as +admin_posts_path+ will now be +sekret_posts_path+. + # # maps to Sekret::PostsController rather than Admin::PostsController + # namespace :admin, :module => "sekret" do + # resources :posts + # end # - # [:shallow_path] - # See the +scope+ method. + # # generates sekret_posts_path rather than admin_posts_path + # namespace :admin, :as => "sekret" do + # resources :posts + # end def namespace(path, options = {}) path = path.to_s options = { :path => path, :as => path, :module => path, @@ -680,9 +715,9 @@ module ActionDispatch end # Allows you to set default parameters for a route, such as this: - # defaults :id => 'home' do - # match 'scoped_pages/(:id)', :to => 'pages#show' - # end + # defaults :id => 'home' do + # match 'scoped_pages/(:id)', :to => 'pages#show' + # end # Using this, the +:id+ parameter here will default to 'home'. def defaults(defaults = {}) scope(:defaults => defaults) { yield } @@ -907,6 +942,9 @@ module ActionDispatch # GET /geocoder/edit # PUT /geocoder # DELETE /geocoder + # + # === Supported options + # Takes same options as +resources+. def resource(*resources, &block) options = resources.extract_options! @@ -969,6 +1007,8 @@ module ActionDispatch # DELETE /photos/:id/comments/:id # # === Supported options + # Takes same options as Base#match as well as: + # # [:path_names] # Allows you to change the paths of the seven default actions. # Paths not specified are not changed. @@ -977,20 +1017,60 @@ module ActionDispatch # # The above example will now change /posts/new to /posts/brand_new # - # [:module] - # Set the module where the controller can be found. Defaults to nothing. + # [:only] + # Only generate routes for the given actions. # - # resources :posts, :module => "admin" + # resources :cows, :only => :show + # resources :cows, :only => [:show, :index] # - # All requests to the posts resources will now go to +Admin::PostsController+. + # [:except] + # Generate all routes except for the given actions. # - # [:path] + # resources :cows, :except => :show + # resources :cows, :except => [:show, :index] + # + # [:shallow] + # Generates shallow routes for nested resource(s). When placed on a parent resource, + # generates shallow routes for all nested resources. + # + # resources :posts, :shallow => true do + # resources :comments + # end + # + # Is the same as: + # + # resources :posts do + # resources :comments + # end + # resources :comments + # + # [:shallow_path] + # Prefixes nested shallow routes with the specified path. + # + # scope :shallow_path => "sekret" do + # resources :posts do + # resources :comments, :shallow => true + # end + # end + # + # The +comments+ resource here will have the following routes generated for it: + # + # post_comments GET /sekret/posts/:post_id/comments(.:format) + # post_comments POST /sekret/posts/:post_id/comments(.:format) + # new_post_comment GET /sekret/posts/:post_id/comments/new(.:format) + # edit_comment GET /sekret/comments/:id/edit(.:format) + # comment GET /sekret/comments/:id(.:format) + # comment PUT /sekret/comments/:id(.:format) + # comment DELETE /sekret/comments/:id(.:format) + # + # === Examples # - # Set a path prefix for this resource. + # # routes call Admin::PostsController + # resources :posts, :module => "admin" # - # resources :posts, :path => "admin" + # # resource actions are at /admin/posts. + # resources :posts, :path => "admin" # - # All actions for this resource will now be at +/admin/posts+. def resources(*resources, &block) options = resources.extract_options! -- cgit v1.2.3 From d1ef543794efdcc1d225055f88cbc88b20e84921 Mon Sep 17 00:00:00 2001 From: Jonathan Dance + Gabriel Horner Date: Sat, 29 Jan 2011 17:24:37 -0500 Subject: explain different ways to use match() --- actionpack/lib/action_dispatch/routing/mapper.rb | 25 +++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index ee0fdce9dd..b28b68ad83 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -256,15 +256,22 @@ module ActionDispatch match '/', options.reverse_merge(:as => :root) end - # When you set up a regular route, you supply a series of symbols that - # Rails maps to parts of an incoming HTTP request. - # - # match ':controller/:action/:id/:user_id' - # - # Two of these symbols are special: :controller maps to the name of a - # controller in your application, and :action maps to the name of an - # action within that controller. Anything other than :controller or - # :action will be available to the action as part of params. + # Matches a pattern to one or more urls. Any symbols in a pattern are + # interpreted as url parameters: + # + # # sets parameters :controller, :action and :id + # match ':controller/:action/:id' + # + # Two of these symbols are special: :controller maps to the + # controller name and :action to the action name within that + # controller. Anything other than :controller or + # :action will be available to the action as part of +params+. + # If a pattern does not have :controller and :action symbols, then they + # must be set in options or shorthand. For example: + # + # match 'photos/:id' => 'photos#show' + # match 'photos/:id', :to => 'photos#show' + # match 'photos/:id', :controller => 'photos', :action => 'show' # # === Supported options # -- cgit v1.2.3 From 57bc25c5f8129f57b08a2dc7c319b86778dd8a40 Mon Sep 17 00:00:00 2001 From: John Firebaugh Date: Sun, 9 Jan 2011 10:15:05 -0800 Subject: Use run_callbacks; the generated _run__callbacks method is not a public interface. Signed-off-by: Santiago Pastorino --- actionpack/lib/action_dispatch/middleware/callbacks.rb | 2 +- actionpack/lib/action_dispatch/middleware/reloader.rb | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/middleware/callbacks.rb b/actionpack/lib/action_dispatch/middleware/callbacks.rb index 4d038c29f2..1bb2ad7f67 100644 --- a/actionpack/lib/action_dispatch/middleware/callbacks.rb +++ b/actionpack/lib/action_dispatch/middleware/callbacks.rb @@ -25,7 +25,7 @@ module ActionDispatch end def call(env) - _run_call_callbacks do + run_callbacks :call do @app.call(env) end end diff --git a/actionpack/lib/action_dispatch/middleware/reloader.rb b/actionpack/lib/action_dispatch/middleware/reloader.rb index f6ab368ad8..29289a76b4 100644 --- a/actionpack/lib/action_dispatch/middleware/reloader.rb +++ b/actionpack/lib/action_dispatch/middleware/reloader.rb @@ -43,12 +43,12 @@ module ActionDispatch # Execute all prepare callbacks. def self.prepare! - new(nil).send(:_run_prepare_callbacks) + new(nil).run_callbacks :prepare end # Execute all cleanup callbacks. def self.cleanup! - new(nil).send(:_run_cleanup_callbacks) + new(nil).run_callbacks :cleanup end def initialize(app) @@ -64,12 +64,12 @@ module ActionDispatch end def call(env) - _run_prepare_callbacks + run_callbacks :prepare response = @app.call(env) response[2].extend(CleanupOnClose) response rescue Exception - _run_cleanup_callbacks + run_callbacks :cleanup raise end end -- cgit v1.2.3 From 5dd803e9b1149f8e6d7de787e0c833c94f48d5a4 Mon Sep 17 00:00:00 2001 From: Akira Matsuda Date: Sat, 25 Dec 2010 23:54:34 +0900 Subject: Accept String value for render_partial :as option [#6222 state:committed] Signed-off-by: Santiago Pastorino --- actionpack/lib/action_view/partials.rb | 2 +- actionpack/lib/action_view/renderer/partial_renderer.rb | 4 ++-- actionpack/test/template/render_test.rb | 7 ++++++- 3 files changed, 9 insertions(+), 4 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/partials.rb b/actionpack/lib/action_view/partials.rb index 56c661c00c..c181689e62 100644 --- a/actionpack/lib/action_view/partials.rb +++ b/actionpack/lib/action_view/partials.rb @@ -40,7 +40,7 @@ module ActionView # With the :as option we can specify a different name for said local variable. For example, if we # wanted it to be +agreement+ instead of +contract+ we'd do: # - # <%= render :partial => "contract", :as => :agreement %> + # <%= render :partial => "contract", :as => 'agreement' %> # # The :object option can be used to directly specify which object is rendered into the partial; # useful when the template's object is elsewhere, in a different ivar or in a local variable for instance. diff --git a/actionpack/lib/action_view/renderer/partial_renderer.rb b/actionpack/lib/action_view/renderer/partial_renderer.rb index 3fdea23a4a..94c0a8a8fb 100644 --- a/actionpack/lib/action_view/renderer/partial_renderer.rb +++ b/actionpack/lib/action_view/renderer/partial_renderer.rb @@ -108,7 +108,7 @@ module ActionView locals << @variable_counter if @collection find_template(path, locals) end - end + end def find_template(path=@path, locals=@locals.keys) prefixes = path.include?(?/) ? [] : @view.controller_prefixes @@ -159,7 +159,7 @@ module ActionView end def retrieve_variable(path) - variable = @options[:as] || path[%r'_?(\w+)(\.\w+)*$', 1].to_sym + variable = @options[:as].try(:to_sym) || path[%r'_?(\w+)(\.\w+)*$', 1].to_sym variable_counter = :"#{variable}_counter" if @collection [variable, variable_counter] end diff --git a/actionpack/test/template/render_test.rb b/actionpack/test/template/render_test.rb index 38bedd2e4e..e02d69231f 100644 --- a/actionpack/test/template/render_test.rb +++ b/actionpack/test/template/render_test.rb @@ -146,7 +146,12 @@ module RenderTestCases assert_equal "Hello: davidHello: mary", @view.render(:partial => "test/customer", :collection => [ Customer.new("david"), Customer.new("mary") ]) end - def test_render_partial_collection_as + def test_render_partial_collection_as_by_string + assert_equal "david david davidmary mary mary", + @view.render(:partial => "test/customer_with_var", :collection => [ Customer.new("david"), Customer.new("mary") ], :as => 'customer') + end + + def test_render_partial_collection_as_by_symbol assert_equal "david david davidmary mary mary", @view.render(:partial => "test/customer_with_var", :collection => [ Customer.new("david"), Customer.new("mary") ], :as => :customer) end -- cgit v1.2.3 From cb9fa5283239e649483ea31ca372e99aaac2ca07 Mon Sep 17 00:00:00 2001 From: Akira Matsuda Date: Tue, 31 Aug 2010 04:58:54 +0900 Subject: auto_link: avoid recognizing full width chars as a part of URI scheme fixes regression by http://github.com/rails/rails/commit/133ada6ab0f0cb7bef2bd40dbc18f2d5bc6b964e [#5503 state:committed] Signed-off-by: Santiago Pastorino --- actionpack/lib/action_view/helpers/text_helper.rb | 2 +- actionpack/test/template/text_helper_test.rb | 8 +++++++- 2 files changed, 8 insertions(+), 2 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb index 3d276000a1..4f7f5c454f 100644 --- a/actionpack/lib/action_view/helpers/text_helper.rb +++ b/actionpack/lib/action_view/helpers/text_helper.rb @@ -459,7 +459,7 @@ module ActionView end AUTO_LINK_RE = %r{ - (?: ([\w+.:-]+:)// | www\. ) + (?: ([0-9A-Za-z+.:-]+:)// | www\. ) [^\s<]+ }x diff --git a/actionpack/test/template/text_helper_test.rb b/actionpack/test/template/text_helper_test.rb index 9e9ed9120d..d0d4286393 100644 --- a/actionpack/test/template/text_helper_test.rb +++ b/actionpack/test/template/text_helper_test.rb @@ -1,4 +1,4 @@ -# encoding: us-ascii +# encoding: utf-8 require 'abstract_unit' require 'testing_sandbox' @@ -415,6 +415,12 @@ class TextHelperTest < ActionView::TestCase link10_raw = 'http://www.mail-archive.com/ruby-talk@ruby-lang.org/' link10_result = generate_result(link10_raw) assert_equal %(

#{link10_result} Link

), auto_link("

#{link10_raw} Link

") + + link11_raw = 'http://asakusa.rubyist.net/' + link11_result = generate_result(link11_raw) + with_kcode 'u' do + assert_equal %(浅草.rbの公式サイトはこちら#{link11_result}), auto_link("浅草.rbの公式サイトはこちら#{link11_raw}") + end end def test_auto_link_should_sanitize_input_when_sanitize_option_is_not_false -- cgit v1.2.3 From 15ad707852159f405e5f6dc61581cb9dbb2864c7 Mon Sep 17 00:00:00 2001 From: Andrei Bocan Date: Fri, 19 Nov 2010 20:25:21 +0200 Subject: Allow customization of form class for button_to Signed-off-by: Santiago Pastorino --- actionpack/lib/action_view/helpers/url_helper.rb | 16 +++++++++++++--- actionpack/test/template/url_helper_test.rb | 4 ++++ 2 files changed, 17 insertions(+), 3 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers/url_helper.rb b/actionpack/lib/action_view/helpers/url_helper.rb index c23315b344..cfa88c91e3 100644 --- a/actionpack/lib/action_view/helpers/url_helper.rb +++ b/actionpack/lib/action_view/helpers/url_helper.rb @@ -253,8 +253,9 @@ module ActionView # using the +link_to+ method with the :method modifier as described in # the +link_to+ documentation. # - # The generated form element has a class name of button_to - # to allow styling of the form itself and its children. You can control + # By default, the generated form element has a class name of button_to + # to allow styling of the form itself and its children. This can be changed + # using the :form_class modifier within +html_options+. You can control # the form submission and input element behavior using +html_options+. # This method accepts the :method and :confirm modifiers # described in the +link_to+ documentation. If no :method modifier @@ -275,6 +276,8 @@ module ActionView # processed normally, otherwise no action is taken. # * :remote - If set to true, will allow the Unobtrusive JavaScript drivers to control the # submit behaviour. By default this behaviour is an ajax submit. + # * :form_class - This controls the class of the form within which the submit button will + # be placed # # ==== Examples # <%= button_to "New", :action => "new" %> @@ -283,6 +286,12 @@ module ActionView # # " # # + # <%= button_to "New", :action => "new", :form_class => "new-thing" %> + # # => "
+ # #
+ # #
" + # + # # <%= button_to "Delete Image", { :action => "delete", :id => @image.id }, # :confirm => "Are you sure?", :method => :delete %> # # => "
@@ -312,6 +321,7 @@ module ActionView end form_method = method.to_s == 'get' ? 'get' : 'post' + form_class = html_options.delete('form_class') || 'button_to' remote = html_options.delete('remote') @@ -327,7 +337,7 @@ module ActionView html_options.merge!("type" => "submit", "value" => name) - ("
" + + ("
" + method_tag + tag("input", html_options) + request_token_tag + "
").html_safe end diff --git a/actionpack/test/template/url_helper_test.rb b/actionpack/test/template/url_helper_test.rb index 4a8cea36d4..42232316e8 100644 --- a/actionpack/test/template/url_helper_test.rb +++ b/actionpack/test/template/url_helper_test.rb @@ -50,6 +50,10 @@ class UrlHelperTest < ActiveSupport::TestCase assert_dom_equal "
", button_to("Hello", "http://www.example.com") end + def test_button_to_with_form_class + assert_dom_equal "
", button_to("Hello", "http://www.example.com", :form_class => 'custom-class') + end + def test_button_to_with_query assert_dom_equal "
", button_to("Hello", "http://www.example.com/q1=v1&q2=v2") end -- cgit v1.2.3 From 86dc5987b23047f8c3345552341c15dd0e5e245d Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Tue, 1 Feb 2011 19:17:13 -0200 Subject: add test to check class is being escaped in form_class --- actionpack/test/template/url_helper_test.rb | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'actionpack') diff --git a/actionpack/test/template/url_helper_test.rb b/actionpack/test/template/url_helper_test.rb index 42232316e8..2e1661a0ac 100644 --- a/actionpack/test/template/url_helper_test.rb +++ b/actionpack/test/template/url_helper_test.rb @@ -54,6 +54,10 @@ class UrlHelperTest < ActiveSupport::TestCase assert_dom_equal "
", button_to("Hello", "http://www.example.com", :form_class => 'custom-class') end + def test_button_to_with_form_class_escapes + assert_dom_equal "
", button_to("Hello", "http://www.example.com", :form_class => '') + end + def test_button_to_with_query assert_dom_equal "
", button_to("Hello", "http://www.example.com/q1=v1&q2=v2") end -- cgit v1.2.3 From 2446b1307ecf4ac13dc9ed3bcaf5a03ef3fcef98 Mon Sep 17 00:00:00 2001 From: Bernerd Schaefer Date: Wed, 2 Feb 2011 16:02:28 +0100 Subject: Provide documentation for ActionController::Metal --- actionpack/lib/action_controller/metal.rb | 60 ++++++++++++++++++++++++++++--- 1 file changed, 55 insertions(+), 5 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_controller/metal.rb b/actionpack/lib/action_controller/metal.rb index 329798e84f..0caf37b8cd 100644 --- a/actionpack/lib/action_controller/metal.rb +++ b/actionpack/lib/action_controller/metal.rb @@ -43,12 +43,62 @@ module ActionController end end - # Provides a way to get a valid Rack application from a controller. + # ActionController::Metal is the simplest possible controller, providing a + # valid Rack interface without the additional niceties provided by + # ActionController::Base. + # + # A sample Metal controller might look like this: + # + # class HelloController < ActionController::Metal + # def index + # self.response_body = "Hello World!" + # end + # end + # + # And then to route requests to your Metal controller, you would add + # something like this to config/routes.rb: + # + # match '/hello', :to => HelloController.action(:index), + # :as => 'hello' + # + # The action method returns a valid Rack application for the \Rails + # router to dispatch to. + # + # == Rendering Helpers + # + # ActionController::Metal by default provides no utilities for rendering + # views, partials, or other responses aside from explicitly calling of + # response_body=, content_type=, and status=. To + # add the render helpers you're used to having in a normal controller, you + # can do the following: + # + # class HelloController < ActionController::Metal + # include ActionController::Rendering + # append_view_path Rails.root + "app/views" + # + # def index + # render "hello/index" + # end + # end + # + # == Redirection Helpers + # + # To add redirection helpers to your Metal controller, do the following: + # + # class HelloController < ActionController::Metal + # include ActionController::Redirecting + # + # def index + # redirect_to root_url + # end + # end + # + # == Other Helpers + # + # You can refer to the modules defined in ActionController to see + # the other features in ActionController::Base that you can bring + # into your Metal controller. # - # In AbstractController, dispatching is triggered directly by calling #process on a new controller. - # ActionController::Metal provides an action method that returns a valid Rack application for a - # given action. Other rack builders, such as Rack::Builder, Rack::URLMap, and the \Rails router, - # can dispatch directly to actions returned by controllers in your application. class Metal < AbstractController::Base abstract! -- cgit v1.2.3 From a0757e00f3ec2925ee6fdd25498725acf66fae98 Mon Sep 17 00:00:00 2001 From: Stephen Celis Date: Sat, 9 Oct 2010 09:13:45 -0500 Subject: Protocol-relative URL support. [#5774 state:committed] Signed-off-by: Santiago Pastorino --- actionpack/lib/action_dispatch/http/url.rb | 7 +++++-- actionpack/test/controller/url_for_test.rb | 15 ++++++++++++++- 2 files changed, 19 insertions(+), 3 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb index 796cd8c09b..535ff42b90 100644 --- a/actionpack/lib/action_dispatch/http/url.rb +++ b/actionpack/lib/action_dispatch/http/url.rb @@ -28,8 +28,11 @@ module ActionDispatch rewritten_url = "" unless options[:only_path] - rewritten_url << (options[:protocol] || "http") - rewritten_url << "://" unless rewritten_url.match("://") + unless options[:protocol] == false + rewritten_url << (options[:protocol] || "http") + rewritten_url << ":" unless rewritten_url.match(%r{:|//}) + end + rewritten_url << "//" unless rewritten_url.match("//") rewritten_url << rewrite_authentication(options) rewritten_url << host_or_subdomain_and_domain(options) rewritten_url << ":#{options.delete(:port)}" if options[:port] diff --git a/actionpack/test/controller/url_for_test.rb b/actionpack/test/controller/url_for_test.rb index 1f62d29e80..1c28da33bd 100644 --- a/actionpack/test/controller/url_for_test.rb +++ b/actionpack/test/controller/url_for_test.rb @@ -95,16 +95,29 @@ module AbstractController ) end - def test_protocol_with_and_without_separator + def test_protocol_with_and_without_separators add_host! assert_equal('https://www.basecamphq.com/c/a/i', W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https') ) + assert_equal('https://www.basecamphq.com/c/a/i', + W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https:') + ) assert_equal('https://www.basecamphq.com/c/a/i', W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https://') ) end + def test_without_protocol + add_host! + assert_equal('//www.basecamphq.com/c/a/i', + W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => '//') + ) + assert_equal('//www.basecamphq.com/c/a/i', + W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => false) + ) + end + def test_trailing_slash add_host! options = {:controller => 'foo', :trailing_slash => true, :action => 'bar', :id => '33'} -- cgit v1.2.3 From 33643bcf53c56bafe072ab6ec959196a6a049947 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Wed, 2 Feb 2011 23:03:17 +0100 Subject: copy-edits 2446b13 --- actionpack/lib/action_controller/metal.rb | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_controller/metal.rb b/actionpack/lib/action_controller/metal.rb index 032769a5c6..ab603e40f2 100644 --- a/actionpack/lib/action_controller/metal.rb +++ b/actionpack/lib/action_controller/metal.rb @@ -43,11 +43,11 @@ module ActionController end end - # ActionController::Metal is the simplest possible controller, providing a + # ActionController::Metal is the simplest possible controller, providing a # valid Rack interface without the additional niceties provided by - # ActionController::Base. + # ActionController::Base. # - # A sample Metal controller might look like this: + # A sample metal controller might look like this: # # class HelloController < ActionController::Metal # def index @@ -55,26 +55,25 @@ module ActionController # end # end # - # And then to route requests to your Metal controller, you would add + # And then to route requests to your metal controller, you would add # something like this to config/routes.rb: # - # match '/hello', :to => HelloController.action(:index), - # :as => 'hello' + # match 'hello', :to => HelloController.action(:index) # - # The action method returns a valid Rack application for the \Rails + # The +action+ method returns a valid Rack application for the \Rails # router to dispatch to. # # == Rendering Helpers # - # ActionController::Metal by default provides no utilities for rendering + # ActionController::Metal by default provides no utilities for rendering # views, partials, or other responses aside from explicitly calling of - # response_body=, content_type=, and status=. To + # response_body=, content_type=, and status=. To # add the render helpers you're used to having in a normal controller, you # can do the following: # # class HelloController < ActionController::Metal # include ActionController::Rendering - # append_view_path Rails.root + "app/views" + # append_view_path "#{Rails.root}/app/views" # # def index # render "hello/index" @@ -83,21 +82,21 @@ module ActionController # # == Redirection Helpers # - # To add redirection helpers to your Metal controller, do the following: + # To add redirection helpers to your metal controller, do the following: # # class HelloController < ActionController::Metal # include ActionController::Redirecting # # def index - # redirect_to root_url + # redirect_to "http://www.example.com" # end # end # # == Other Helpers # # You can refer to the modules defined in ActionController to see - # the other features in ActionController::Base that you can bring - # into your Metal controller. + # the other features in ActionController::Base that you can bring + # into your metal controller. # class Metal < AbstractController::Base abstract! -- cgit v1.2.3 From e99e859a045d9241e7297499beb100c7e59e3820 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Wed, 2 Feb 2011 23:27:27 +0100 Subject: revises a metal example --- actionpack/lib/action_controller/metal.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_controller/metal.rb b/actionpack/lib/action_controller/metal.rb index ab603e40f2..b2c8053584 100644 --- a/actionpack/lib/action_controller/metal.rb +++ b/actionpack/lib/action_controller/metal.rb @@ -86,17 +86,17 @@ module ActionController # # class HelloController < ActionController::Metal # include ActionController::Redirecting + # include Rails.application.routes.url_helpers # # def index - # redirect_to "http://www.example.com" + # redirect_to root_url # end # end # # == Other Helpers # - # You can refer to the modules defined in ActionController to see - # the other features in ActionController::Base that you can bring - # into your metal controller. + # You can refer to the modules included in ActionController::Base to see + # other features you can bring into your metal controller. # class Metal < AbstractController::Base abstract! -- cgit v1.2.3 From c1c6f29214d3c280f5d1d4abb49d0b90424fcbd7 Mon Sep 17 00:00:00 2001 From: Anton Astashov Date: Thu, 3 Feb 2011 19:09:21 +0700 Subject: Add a test for 'render :layout' To make sure it will show block contents if it is placed after 'render :partial' [#5557 state:resolved] Signed-off-by: Santiago Pastorino --- .../test/fixtures/test/_layout_with_partial_and_yield.html.erb | 4 ++++ actionpack/test/template/render_test.rb | 5 +++++ 2 files changed, 9 insertions(+) create mode 100644 actionpack/test/fixtures/test/_layout_with_partial_and_yield.html.erb (limited to 'actionpack') diff --git a/actionpack/test/fixtures/test/_layout_with_partial_and_yield.html.erb b/actionpack/test/fixtures/test/_layout_with_partial_and_yield.html.erb new file mode 100644 index 0000000000..5db0822f07 --- /dev/null +++ b/actionpack/test/fixtures/test/_layout_with_partial_and_yield.html.erb @@ -0,0 +1,4 @@ +Before +<%= render :partial => "test/partial.html.erb" %> +<%= yield %> +After diff --git a/actionpack/test/template/render_test.rb b/actionpack/test/template/render_test.rb index e02d69231f..034fb6c210 100644 --- a/actionpack/test/template/render_test.rb +++ b/actionpack/test/template/render_test.rb @@ -209,6 +209,11 @@ module RenderTestCases @view.formats = nil end + def test_render_layout_with_block_and_other_partial_inside + render = @view.render(:layout => "test/layout_with_partial_and_yield.html.erb") { "Yield!" } + assert_equal "Before\npartial html\nYield!\nAfter\n", render + end + def test_render_inline assert_equal "Hello, World!", @view.render(:inline => "Hello, World!") end -- cgit v1.2.3 From d3cfee118245a8806436bbf904bbad36dd810012 Mon Sep 17 00:00:00 2001 From: Franco Brusatti Date: Thu, 3 Feb 2011 19:14:10 -0300 Subject: removing generation of id in submit helper [#6369 state:committed] Signed-off-by: Santiago Pastorino --- actionpack/lib/action_view/helpers/form_helper.rb | 2 +- actionpack/test/template/form_helper_test.rb | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb index d7b9e0b4f4..d6edef0d34 100644 --- a/actionpack/lib/action_view/helpers/form_helper.rb +++ b/actionpack/lib/action_view/helpers/form_helper.rb @@ -1243,7 +1243,7 @@ module ActionView def submit(value=nil, options={}) value, options = nil, value if value.is_a?(Hash) value ||= submit_default_value - @template.submit_tag(value, options.reverse_merge(:id => "#{object_name}_submit")) + @template.submit_tag(value, options) end def emitted_hidden_id? diff --git a/actionpack/test/template/form_helper_test.rb b/actionpack/test/template/form_helper_test.rb index 2c60096475..e27ed20b81 100644 --- a/actionpack/test/template/form_helper_test.rb +++ b/actionpack/test/template/form_helper_test.rb @@ -630,7 +630,7 @@ class FormHelperTest < ActionView::TestCase "" + "" + "" + - "" + "" end assert_dom_equal expected, output_buffer @@ -709,7 +709,7 @@ class FormHelperTest < ActionView::TestCase "" + "" + "" + - "" + "" end assert_dom_equal expected, output_buffer @@ -843,7 +843,7 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts', 'new_post', 'new_post') do - "" + "" end assert_dom_equal expected, output_buffer @@ -859,7 +859,7 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do - "" + "" end assert_dom_equal expected, output_buffer @@ -875,7 +875,7 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form do - "" + "" end assert_dom_equal expected, output_buffer @@ -891,7 +891,7 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'another_post_edit', 'another_post_edit', :method => 'put') do - "" + "" end assert_dom_equal expected, output_buffer -- cgit v1.2.3 From ac15647bf0e6ed85714dee4e2b14b2e7e6f29320 Mon Sep 17 00:00:00 2001 From: Gabriel Horner Date: Thu, 3 Feb 2011 23:51:06 -0500 Subject: keep options titles consistent to "Options" --- actionpack/lib/action_dispatch/routing/mapper.rb | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index b28b68ad83..b5ff6e0dcb 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -273,7 +273,7 @@ module ActionDispatch # match 'photos/:id', :to => 'photos#show' # match 'photos/:id', :controller => 'photos', :action => 'show' # - # === Supported options + # === Options # # [:controller] # The route's controller. @@ -549,7 +549,7 @@ module ActionDispatch # The difference here being that the routes generated are like /rails/projects/2, # rather than /accounts/rails/projects/2. # - # === Supported options + # === Options # # Takes same options as Base#match and Resources#resources. # @@ -632,7 +632,7 @@ module ActionDispatch # admin_post PUT /admin/posts/:id(.:format) {:action=>"update", :controller=>"admin/posts"} # admin_post DELETE /admin/posts/:id(.:format) {:action=>"destroy", :controller=>"admin/posts"} # - # === Supported options + # === Options # # The +:path+, +:as+, +:module+, +:shallow_path+ and +:shallow_prefix+ # options all default to the name of the namespace. @@ -950,7 +950,7 @@ module ActionDispatch # PUT /geocoder # DELETE /geocoder # - # === Supported options + # === Options # Takes same options as +resources+. def resource(*resources, &block) options = resources.extract_options! @@ -1013,7 +1013,7 @@ module ActionDispatch # PUT /photos/:id/comments/:id # DELETE /photos/:id/comments/:id # - # === Supported options + # === Options # Takes same options as Base#match as well as: # # [:path_names] -- cgit v1.2.3 From adbae9aab8a439a824cf1612febb5918d0f4cf87 Mon Sep 17 00:00:00 2001 From: german Date: Fri, 4 Feb 2011 11:51:34 -0500 Subject: fixed bug with nested resources within shallow scope [#6372 state:committed] Signed-off-by: Santiago Pastorino --- actionpack/lib/action_dispatch/routing/mapper.rb | 2 +- actionpack/test/dispatch/routing_test.rb | 62 ++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index b28b68ad83..c38e9ef2c4 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -1199,7 +1199,7 @@ module ActionDispatch end def shallow - scope(:shallow => true) do + scope(:shallow => true, :shallow_path => @scope[:path]) do yield end end diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb index 4bf7880294..bdd4606720 100644 --- a/actionpack/test/dispatch/routing_test.rb +++ b/actionpack/test/dispatch/routing_test.rb @@ -205,6 +205,14 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest end end + scope '/hello' do + shallow do + resources :notes do + resources :trackbacks + end + end + end + resources :threads, :shallow => true do resource :owner resources :messages do @@ -1676,6 +1684,60 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest end end + def test_shallow_nested_resources_within_scope + with_test_routes do + + get '/hello/notes/1/trackbacks' + assert_equal 'trackbacks#index', @response.body + assert_equal '/hello/notes/1/trackbacks', note_trackbacks_path(:note_id => 1) + + get '/hello/notes/1/edit' + assert_equal 'notes#edit', @response.body + assert_equal '/hello/notes/1/edit', edit_note_path(:id => '1') + + get '/hello/notes/1/trackbacks/new' + assert_equal 'trackbacks#new', @response.body + assert_equal '/hello/notes/1/trackbacks/new', new_note_trackback_path(:note_id => 1) + + get '/hello/trackbacks/1' + assert_equal 'trackbacks#show', @response.body + assert_equal '/hello/trackbacks/1', trackback_path(:id => '1') + + get '/hello/trackbacks/1/edit' + assert_equal 'trackbacks#edit', @response.body + assert_equal '/hello/trackbacks/1/edit', edit_trackback_path(:id => '1') + + put '/hello/trackbacks/1' + assert_equal 'trackbacks#update', @response.body + + post '/hello/notes/1/trackbacks' + assert_equal 'trackbacks#create', @response.body + + delete '/hello/trackbacks/1' + assert_equal 'trackbacks#destroy', @response.body + + get '/hello/notes' + assert_equal 'notes#index', @response.body + + post '/hello/notes' + assert_equal 'notes#create', @response.body + + get '/hello/notes/new' + assert_equal 'notes#new', @response.body + assert_equal '/hello/notes/new', new_note_path + + get '/hello/notes/1' + assert_equal 'notes#show', @response.body + assert_equal '/hello/notes/1', note_path(:id => 1) + + put '/hello/notes/1' + assert_equal 'notes#update', @response.body + + delete '/hello/notes/1' + assert_equal 'notes#destroy', @response.body + end + end + def test_custom_resource_routes_are_scoped with_test_routes do assert_equal '/customers/recent', recent_customers_path -- cgit v1.2.3 From 277327bb7f389a140eb4ae7722d64d6cf45e06cf Mon Sep 17 00:00:00 2001 From: Gabriel Horner Date: Sat, 5 Feb 2011 13:12:09 -0500 Subject: improve routing docs, mostly for #match --- actionpack/lib/action_dispatch/routing/mapper.rb | 46 +++++++++++++++++------- 1 file changed, 34 insertions(+), 12 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index b5ff6e0dcb..a91b2e88fb 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -247,7 +247,7 @@ module ActionDispatch # # root :to => 'pages#main' # - # For options, see the +match+ method's documentation, as +root+ uses it internally. + # For options, see +match+, as +root+ uses it internally. # # You should put the root route at the top of config/routes.rb, # because this means it will be matched first. As this is the most popular route @@ -256,25 +256,42 @@ module ActionDispatch match '/', options.reverse_merge(:as => :root) end - # Matches a pattern to one or more urls. Any symbols in a pattern are - # interpreted as url parameters: + # Matches a url pattern to one or more routes. Any symbols in a pattern + # are interpreted as url query parameters and thus available as +params+ + # in an action: # - # # sets parameters :controller, :action and :id + # # sets :controller, :action and :id in params # match ':controller/:action/:id' # - # Two of these symbols are special: :controller maps to the - # controller name and :action to the action name within that - # controller. Anything other than :controller or - # :action will be available to the action as part of +params+. - # If a pattern does not have :controller and :action symbols, then they - # must be set in options or shorthand. For example: + # Two of these symbols are special, +:controller+ maps to the controller + # and +:action+ to the controller's action. A pattern can also map + # wildcard segments (globs) to params: + # + # match 'songs/*category/:title' => 'songs#show' + # + # # 'songs/rock/classic/stairway-to-heaven' sets + # # params[:category] = 'rock/classic' + # # params[:title] = 'stairway-to-heaven' + # + # When a pattern points to an internal route, the route's +:action+ and + # +:controller+ should be set in options or hash shorthand. Examples: # # match 'photos/:id' => 'photos#show' # match 'photos/:id', :to => 'photos#show' # match 'photos/:id', :controller => 'photos', :action => 'show' # + # A pattern can also point to a +Rack+ endpoint i.e. anything that + # responds to +call+: + # + # match 'photos/:id' => lambda {|hash| [200, {}, "Coming soon" } + # match 'photos/:id' => PhotoRackApp + # # Yes, controller actions are just rack endpoints + # match 'photos/:id' => PhotosController.action(:show) + # # === Options # + # Any options not seen here are passed on as params with the url. + # # [:controller] # The route's controller. # @@ -302,9 +319,12 @@ module ActionDispatch # match 'path' => 'c#a', :via => [:get, :post] # # [:to] - # Shorthand for specifying :controller and :action. + # Points to a +Rack+ endpoint. Can be an object that responds to + # +call+ or a string representing a controller's action. # - # match 'path' => 'c#a', :to => 'controller#action' + # match 'path', :to => 'controller#action' + # match 'path', :to => lambda { [200, {}, "Success!"] } + # match 'path', :to => RackApp # # [:on] # Shorthand for wrapping routes in a specific RESTful context. Valid @@ -358,6 +378,8 @@ module ActionDispatch # # mount(SomeRackApp => "some_route") # + # For options, see +match+, as +mount+ uses it internally. + # # All mounted applications come with routing helpers to access them. # These are named after the class specified, so for the above example # the helper is either +some_rack_app_path+ or +some_rack_app_url+. -- cgit v1.2.3 From b9309b47cda12db34ac3427fbafff2dca0314ed7 Mon Sep 17 00:00:00 2001 From: "Timothy N. Tsvetkov" Date: Sat, 5 Feb 2011 18:37:53 +0300 Subject: Added tests for form_for and an authenticity_token option. Added docs for for_for and authenticity_token option. Added section to form helpers guide about forms for external resources and new authenticity_token option for form_tag and form_for helpers. [#6228 state:committed] Signed-off-by: Santiago Pastorino --- actionpack/lib/action_view/helpers/form_helper.rb | 18 ++++++++++++++++++ .../test/controller/request_forgery_protection_test.rb | 18 ++++++++++++++++++ 2 files changed, 36 insertions(+) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb index d6edef0d34..408a3b6721 100644 --- a/actionpack/lib/action_view/helpers/form_helper.rb +++ b/actionpack/lib/action_view/helpers/form_helper.rb @@ -298,6 +298,24 @@ module ActionView # # If you don't need to attach a form to a model instance, then check out # FormTagHelper#form_tag. + # + # === Form to external resources + # + # When you build forms to external resources sometimes you need to set an authenticity token or just render a form + # without it, for example when you submit data to a payment gateway number and types of fields could be limited. + # + # To set an authenticity token you need to pass an :authenticity_token parameter in the :html + # options section: + # + # <%= form_for @invoice, :url => external_url, :html => { :authenticity_token => 'external_token' } do |f| + # ... + # <% end %> + # + # If you don't want to an authenticity token field be rendered at all just pass false: + # + # <%= form_for @invoice, :url => external_url, :html => { :authenticity_token => false } do |f| + # ... + # <% end %> def form_for(record, options = {}, &proc) raise ArgumentError, "Missing block" unless block_given? diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb index 405af2a650..4f4de0cbee 100644 --- a/actionpack/test/controller/request_forgery_protection_test.rb +++ b/actionpack/test/controller/request_forgery_protection_test.rb @@ -28,6 +28,14 @@ module RequestForgeryProtectionActions render :inline => "<%= csrf_meta_tags %>" end + def external_form_for + render :inline => "<%= form_for(:some_resource, :html => { :authenticity_token => 'external_token' }) {} %>" + end + + def form_for_without_protection + render :inline => "<%= form_for(:some_resource, :html => { :authenticity_token => false }) {} %>" + end + def rescue_action(e) raise e end end @@ -68,6 +76,16 @@ module RequestForgeryProtectionTests assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token end + def test_should_render_external_form_for_with_external_token + get :external_form_for + assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', 'external_token' + end + + def test_should_render_form_for_without_token_tag + get :form_for_without_protection + assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token, false + end + def test_should_render_button_to_with_token_tag get :show_button assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token -- cgit v1.2.3 From 10cab35d3b9e87e4b182162f7783c220cf2a937f Mon Sep 17 00:00:00 2001 From: Andre Arko Date: Sat, 5 Feb 2011 15:52:16 -0800 Subject: Allow page_cache_directory to be set as a Pathname For example, page_cache_directory = Rails.root.join("public/cache") Signed-off-by: Santiago Pastorino --- actionpack/lib/action_controller/caching/pages.rb | 2 +- actionpack/test/controller/caching_test.rb | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_controller/caching/pages.rb b/actionpack/lib/action_controller/caching/pages.rb index 3e57d2c236..8c583c7ce0 100644 --- a/actionpack/lib/action_controller/caching/pages.rb +++ b/actionpack/lib/action_controller/caching/pages.rb @@ -106,7 +106,7 @@ module ActionController #:nodoc: end def page_cache_path(path, extension = nil) - page_cache_directory + page_cache_file(path, extension) + page_cache_directory.to_s + page_cache_file(path, extension) end def instrument_page_cache(name, path) diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb index af02c7f9fa..cc393d3ef4 100644 --- a/actionpack/test/controller/caching_test.rb +++ b/actionpack/test/controller/caching_test.rb @@ -156,6 +156,17 @@ class PageCachingTest < ActionController::TestCase assert_page_not_cached :ok end + def test_page_caching_directory_set_as_pathname + begin + ActionController::Base.page_cache_directory = Pathname.new(FILE_STORE_PATH) + get :ok + assert_response :ok + assert_page_cached :ok + ensure + ActionController::Base.page_cache_directory = FILE_STORE_PATH + end + end + private def assert_page_cached(action, message = "#{action} should have been cached") assert page_cached?(action), message -- cgit v1.2.3 From 3026843dc1ff42a632ebe989e1f6dfadb0cd10a5 Mon Sep 17 00:00:00 2001 From: Dan Pickett Date: Sun, 6 Feb 2011 11:19:02 -0500 Subject: put authenticity_token option in parity w/ remote [#6228 state:committed] Signed-off-by: Santiago Pastorino --- actionpack/lib/action_view/helpers/form_helper.rb | 9 +++++---- actionpack/test/controller/request_forgery_protection_test.rb | 4 ++-- 2 files changed, 7 insertions(+), 6 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb index 408a3b6721..d30fd248c1 100644 --- a/actionpack/lib/action_view/helpers/form_helper.rb +++ b/actionpack/lib/action_view/helpers/form_helper.rb @@ -304,16 +304,15 @@ module ActionView # When you build forms to external resources sometimes you need to set an authenticity token or just render a form # without it, for example when you submit data to a payment gateway number and types of fields could be limited. # - # To set an authenticity token you need to pass an :authenticity_token parameter in the :html - # options section: + # To set an authenticity token you need to pass an :authenticity_token parameter # - # <%= form_for @invoice, :url => external_url, :html => { :authenticity_token => 'external_token' } do |f| + # <%= form_for @invoice, :url => external_url, :authenticity_token => 'external_token' do |f| # ... # <% end %> # # If you don't want to an authenticity token field be rendered at all just pass false: # - # <%= form_for @invoice, :url => external_url, :html => { :authenticity_token => false } do |f| + # <%= form_for @invoice, :url => external_url, :authenticity_token => false do |f| # ... # <% end %> def form_for(record, options = {}, &proc) @@ -332,6 +331,8 @@ module ActionView end options[:html][:remote] = options.delete(:remote) + options[:html][:authenticity_token] = options.delete(:authenticity_token) + builder = options[:parent_builder] = instantiate_builder(object_name, object, options, &proc) fields_for = fields_for(object_name, object, options, &proc) default_options = builder.multipart? ? { :multipart => true } : {} diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb index 4f4de0cbee..68d4c6a57c 100644 --- a/actionpack/test/controller/request_forgery_protection_test.rb +++ b/actionpack/test/controller/request_forgery_protection_test.rb @@ -29,11 +29,11 @@ module RequestForgeryProtectionActions end def external_form_for - render :inline => "<%= form_for(:some_resource, :html => { :authenticity_token => 'external_token' }) {} %>" + render :inline => "<%= form_for(:some_resource, :authenticity_token => 'external_token') {} %>" end def form_for_without_protection - render :inline => "<%= form_for(:some_resource, :html => { :authenticity_token => false }) {} %>" + render :inline => "<%= form_for(:some_resource, :authenticity_token => false ) {} %>" end def rescue_action(e) raise e end -- cgit v1.2.3 From ea25224046679ac0d68f3c987c78ebafa491cee5 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 7 Feb 2011 16:44:27 -0800 Subject: cleaning up some warnings on 1.9.3 --- actionpack/test/controller/filters_test.rb | 10 +++++----- actionpack/test/controller/log_subscriber_test.rb | 20 ++++++++++---------- .../test/controller/new_base/bare_metal_test.rb | 2 +- .../test/controller/request/test_request_test.rb | 3 +-- actionpack/test/controller/routing_test.rb | 4 ++-- actionpack/test/dispatch/request_test.rb | 2 +- actionpack/test/dispatch/response_test.rb | 10 +++++----- .../test/dispatch/session/cookie_store_test.rb | 1 - 8 files changed, 25 insertions(+), 27 deletions(-) (limited to 'actionpack') diff --git a/actionpack/test/controller/filters_test.rb b/actionpack/test/controller/filters_test.rb index 68febf425d..330fa276d0 100644 --- a/actionpack/test/controller/filters_test.rb +++ b/actionpack/test/controller/filters_test.rb @@ -664,7 +664,7 @@ class FilterTest < ActionController::TestCase end def test_prepending_and_appending_around_filter - controller = test_process(MixedFilterController) + test_process(MixedFilterController) assert_equal " before aroundfilter before procfilter before appended aroundfilter " + " after appended aroundfilter after procfilter after aroundfilter ", MixedFilterController.execution_log @@ -677,26 +677,26 @@ class FilterTest < ActionController::TestCase end def test_before_filter_rendering_breaks_filtering_chain_for_after_filter - response = test_process(RenderingController) + test_process(RenderingController) assert_equal %w( before_filter_rendering ), assigns["ran_filter"] assert !assigns["ran_action"] end def test_before_filter_redirects_breaks_filtering_chain_for_after_filter - response = test_process(BeforeFilterRedirectionController) + test_process(BeforeFilterRedirectionController) assert_response :redirect assert_equal "http://test.host/filter_test/before_filter_redirection/target_of_redirection", redirect_to_url assert_equal %w( before_filter_redirects ), assigns["ran_filter"] end def test_before_filter_rendering_breaks_filtering_chain_for_preprend_after_filter - response = test_process(RenderingForPrependAfterFilterController) + test_process(RenderingForPrependAfterFilterController) assert_equal %w( before_filter_rendering ), assigns["ran_filter"] assert !assigns["ran_action"] end def test_before_filter_redirects_breaks_filtering_chain_for_preprend_after_filter - response = test_process(BeforeFilterRedirectionForPrependAfterFilterController) + test_process(BeforeFilterRedirectionForPrependAfterFilterController) assert_response :redirect assert_equal "http://test.host/filter_test/before_filter_redirection_for_prepend_after_filter/target_of_redirection", redirect_to_url assert_equal %w( before_filter_redirects ), assigns["ran_filter"] diff --git a/actionpack/test/controller/log_subscriber_test.rb b/actionpack/test/controller/log_subscriber_test.rb index 21bbd83653..ddfa3df552 100644 --- a/actionpack/test/controller/log_subscriber_test.rb +++ b/actionpack/test/controller/log_subscriber_test.rb @@ -144,7 +144,7 @@ class ACLogSubscriberTest < ActionController::TestCase wait assert_equal 4, logs.size - assert_match /Read fragment views\/foo/, logs[1] + assert_match(/Read fragment views\/foo/, logs[1]) assert_match(/Write fragment views\/foo/, logs[2]) ensure @controller.config.perform_caching = true @@ -156,8 +156,8 @@ class ACLogSubscriberTest < ActionController::TestCase wait assert_equal 4, logs.size - assert_match /Read fragment views\/foo/, logs[1] - assert_match /Write fragment views\/foo/, logs[2] + assert_match(/Read fragment views\/foo/, logs[1]) + assert_match(/Write fragment views\/foo/, logs[2]) ensure @controller.config.perform_caching = true end @@ -173,15 +173,15 @@ class ACLogSubscriberTest < ActionController::TestCase ensure @controller.config.perform_caching = true end - + def test_process_action_with_exception_includes_http_status_code begin - get :with_exception - wait - rescue Exception => e - end - assert_equal 2, logs.size - assert_match(/Completed 500/, logs.last) + get :with_exception + wait + rescue Exception + end + assert_equal 2, logs.size + assert_match(/Completed 500/, logs.last) end def logs diff --git a/actionpack/test/controller/new_base/bare_metal_test.rb b/actionpack/test/controller/new_base/bare_metal_test.rb index 543c02b2c5..3ca29f1bcf 100644 --- a/actionpack/test/controller/new_base/bare_metal_test.rb +++ b/actionpack/test/controller/new_base/bare_metal_test.rb @@ -35,7 +35,7 @@ module BareMetalTest class HeadTest < ActiveSupport::TestCase test "head works on its own" do - status, headers, body = HeadController.action(:index).call(Rack::MockRequest.env_for("/")) + status = HeadController.action(:index).call(Rack::MockRequest.env_for("/")).first assert_equal 404, status end end diff --git a/actionpack/test/controller/request/test_request_test.rb b/actionpack/test/controller/request/test_request_test.rb index 0a39feb7fe..e624f11773 100644 --- a/actionpack/test/controller/request/test_request_test.rb +++ b/actionpack/test/controller/request/test_request_test.rb @@ -29,8 +29,7 @@ class ActionController::TestRequestTest < ActiveSupport::TestCase end def test_session_id_different_on_each_call - prev_id = assert_not_equal(@request.session_options[:id], ActionController::TestRequest.new.session_options[:id]) end -end \ No newline at end of file +end diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb index 89f0d03c56..5f6f1b61c0 100644 --- a/actionpack/test/controller/routing_test.rb +++ b/actionpack/test/controller/routing_test.rb @@ -701,7 +701,7 @@ class RouteSetTest < ActiveSupport::TestCase set.draw do match '/users/index' => 'users#index' end - params = set.recognize_path('/users/index', :method => :get) + set.recognize_path('/users/index', :method => :get) assert_equal 1, set.routes.size end @@ -980,7 +980,7 @@ class RouteSetTest < ActiveSupport::TestCase match '/profile' => 'profile#index' end - params = set.recognize_path("/profile") rescue nil + set.recognize_path("/profile") rescue nil assert !Object.const_defined?("Profiler__"), "Profiler should not be loaded" end diff --git a/actionpack/test/dispatch/request_test.rb b/actionpack/test/dispatch/request_test.rb index 75b674ec1a..dd5bf5ec2d 100644 --- a/actionpack/test/dispatch/request_test.rb +++ b/actionpack/test/dispatch/request_test.rb @@ -427,7 +427,7 @@ class RequestTest < ActiveSupport::TestCase begin request = stub_request(mock_rack_env) request.parameters - rescue TypeError => e + rescue TypeError # rack will raise a TypeError when parsing this query string end assert_equal({}, request.parameters) diff --git a/actionpack/test/dispatch/response_test.rb b/actionpack/test/dispatch/response_test.rb index ab26d1a645..6f38714b2e 100644 --- a/actionpack/test/dispatch/response_test.rb +++ b/actionpack/test/dispatch/response_test.rb @@ -18,7 +18,7 @@ class ResponseTest < ActiveSupport::TestCase body.each { |part| parts << part } assert_equal ["Hello, World!"], parts end - + test "status handled properly in initialize" do assert_equal 200, ActionDispatch::Response.new('200 OK').status end @@ -26,7 +26,7 @@ class ResponseTest < ActiveSupport::TestCase test "utf8 output" do @response.body = [1090, 1077, 1089, 1090].pack("U*") - status, headers, body = @response.to_a + status, headers, _ = @response.to_a assert_equal 200, status assert_equal({ "Content-Type" => "text/html; charset=utf-8" @@ -52,20 +52,20 @@ class ResponseTest < ActiveSupport::TestCase test "content type" do [204, 304].each do |c| @response.status = c.to_s - status, headers, body = @response.to_a + _, headers, _ = @response.to_a assert !headers.has_key?("Content-Type"), "#{c} should not have Content-Type header" end [200, 302, 404, 500].each do |c| @response.status = c.to_s - status, headers, body = @response.to_a + _, headers, _ = @response.to_a assert headers.has_key?("Content-Type"), "#{c} did not have Content-Type header" end end test "does not include Status header" do @response.status = "200 OK" - status, headers, body = @response.to_a + _, headers, _ = @response.to_a assert !headers.has_key?('Status') end diff --git a/actionpack/test/dispatch/session/cookie_store_test.rb b/actionpack/test/dispatch/session/cookie_store_test.rb index 256d0781c7..27f55fd7ab 100644 --- a/actionpack/test/dispatch/session/cookie_store_test.rb +++ b/actionpack/test/dispatch/session/cookie_store_test.rb @@ -194,7 +194,6 @@ class CookieStoreTest < ActionDispatch::IntegrationTest with_test_route_set do get '/set_session_value' assert_response :success - session_payload = response.body assert_equal "_myapp_session=#{response.body}; path=/; HttpOnly", headers['Set-Cookie'] -- cgit v1.2.3 From 631e23ec6c1e482abcc242ae1d772a1831288465 Mon Sep 17 00:00:00 2001 From: Carlos Antonio da Silva Date: Tue, 8 Feb 2011 01:00:59 -0200 Subject: Add tests showing the LH issue #6381: fields_for with inline blocks and nested attributes already persisted Signed-off-by: Santiago Pastorino --- actionpack/test/template/form_helper_test.rb | 86 +++++++++++++++++++++++++++- 1 file changed, 85 insertions(+), 1 deletion(-) (limited to 'actionpack') diff --git a/actionpack/test/template/form_helper_test.rb b/actionpack/test/template/form_helper_test.rb index e27ed20b81..b3220d6aa6 100644 --- a/actionpack/test/template/form_helper_test.rb +++ b/actionpack/test/template/form_helper_test.rb @@ -731,7 +731,7 @@ class FormHelperTest < ActionView::TestCase assert_dom_equal expected, output_buffer end - + def test_form_for_with_search_field # Test case for bug which would emit an "object" attribute # when used with form_for using a search_field form helper @@ -1084,6 +1084,44 @@ class FormHelperTest < ActionView::TestCase assert_dom_equal expected, output_buffer end + def test_nested_fields_for_with_an_existing_record_on_a_nested_attributes_one_to_one_association_using_erb_and_inline_block + @post.author = Author.new(321) + + form_for(@post) do |f| + concat f.text_field(:title) + concat f.fields_for(:author) { |af| + af.text_field(:name) + } + end + + expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do + '' + + '' + + '' + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_for_with_an_existing_record_on_a_nested_attributes_one_to_one_association_using_erb_and_multiline_block + @post.author = Author.new(321) + + form_for(@post) do |f| + concat f.text_field(:title) + concat f.fields_for(:author) { |af| + concat af.text_field(:name) + } + end + + expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do + '' + + '' + + '' + end + + assert_dom_equal expected, output_buffer + end + def test_nested_fields_for_with_existing_records_on_a_nested_attributes_one_to_one_association_with_explicit_hidden_field_placement @post.author = Author.new(321) @@ -1127,6 +1165,52 @@ class FormHelperTest < ActionView::TestCase assert_dom_equal expected, output_buffer end + def test_nested_fields_for_with_existing_records_on_a_nested_attributes_collection_association_using_erb_and_inline_block + @post.comments = Array.new(2) { |id| Comment.new(id + 1) } + + form_for(@post) do |f| + concat f.text_field(:title) + @post.comments.each do |comment| + concat f.fields_for(:comments, comment) { |cf| + cf.text_field(:name) + } + end + end + + expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do + '' + + '' + + '' + + '' + + '' + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_for_with_existing_records_on_a_nested_attributes_collection_association_using_erb_and_multiline_block + @post.comments = Array.new(2) { |id| Comment.new(id + 1) } + + form_for(@post) do |f| + concat f.text_field(:title) + @post.comments.each do |comment| + concat f.fields_for(:comments, comment) { |cf| + concat cf.text_field(:name) + } + end + end + + expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do + '' + + '' + + '' + + '' + + '' + end + + assert_dom_equal expected, output_buffer + end + def test_nested_fields_for_with_existing_records_on_a_nested_attributes_collection_association_with_explicit_hidden_field_placement @post.comments = Array.new(2) { |id| Comment.new(id + 1) } -- cgit v1.2.3 From ee0b92ec7a87967c55fa2992350b12493d3c148b Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Tue, 8 Feb 2011 18:02:16 -0200 Subject: fields_for with inline blocks and nested attributes already persisted does not render properly [#6381 state:committed] --- actionpack/lib/action_view/helpers/form_helper.rb | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb index d30fd248c1..befaa3e8d9 100644 --- a/actionpack/lib/action_view/helpers/form_helper.rb +++ b/actionpack/lib/action_view/helpers/form_helper.rb @@ -549,8 +549,11 @@ module ActionView # <% end %> # ... # <% end %> - def fields_for(record, record_object = nil, options = nil, &block) - capture(instantiate_builder(record, record_object, options, &block), &block) + def fields_for(record, record_object = nil, options = {}, &block) + builder = instantiate_builder(record, record_object, options, &block) + output = capture(builder, &block) + output.concat builder.hidden_field(:id) if output && options[:hidden_field_id] && !builder.emitted_hidden_id? + output end # Returns a label tag tailored for labelling an input field for a specified attribute (identified by +method+) on an object @@ -1323,14 +1326,8 @@ module ActionView def fields_for_nested_model(name, object, options, block) object = convert_to_model(object) - if object.persisted? - @template.fields_for(name, object, options) do |builder| - block.call(builder) - @template.concat builder.hidden_field(:id) unless builder.emitted_hidden_id? - end - else - @template.fields_for(name, object, options, &block) - end + options[:hidden_field_id] = object.persisted? + @template.fields_for(name, object, options, &block) end def nested_child_index(name) -- cgit v1.2.3 From 3ddd7f7ec9b156e4b7de4c23d448c2db98f30504 Mon Sep 17 00:00:00 2001 From: Michael Koziarski Date: Tue, 7 Dec 2010 16:27:55 +1300 Subject: Be sure to javascript_escape the email address to prevent apostrophes inadvertently causing javascript errors. This fixes CVE-2011-0446 --- actionpack/lib/action_view/helpers/url_helper.rb | 11 ++++++----- actionpack/test/template/url_helper_test.rb | 9 +++++---- 2 files changed, 11 insertions(+), 9 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers/url_helper.rb b/actionpack/lib/action_view/helpers/url_helper.rb index cfa88c91e3..2cd2dca711 100644 --- a/actionpack/lib/action_view/helpers/url_helper.rb +++ b/actionpack/lib/action_view/helpers/url_helper.rb @@ -497,13 +497,14 @@ module ActionView email_address_obfuscated = email_address.dup email_address_obfuscated.gsub!(/@/, html_options.delete("replace_at")) if html_options.key?("replace_at") email_address_obfuscated.gsub!(/\./, html_options.delete("replace_dot")) if html_options.key?("replace_dot") - case encode when "javascript" - string = - "document.write('#{content_tag("a", name || email_address_obfuscated.html_safe, html_options.merge("href" => "mailto:#{email_address}#{extras}".html_safe))}');".unpack('C*').map { |c| - sprintf("%%%x", c) - }.join + string = '' + html = content_tag("a", name || email_address_obfuscated.html_safe, html_options.merge("href" => "mailto:#{email_address}#{extras}".html_safe)) + html = escape_javascript(html) + "document.write('#{html}');".each_byte do |c| + string << sprintf("%%%x", c) + end "".html_safe when "hex" email_address_encoded = email_address_obfuscated.unpack('C*').map {|c| diff --git a/actionpack/test/template/url_helper_test.rb b/actionpack/test/template/url_helper_test.rb index 2e1661a0ac..fc330f7a73 100644 --- a/actionpack/test/template/url_helper_test.rb +++ b/actionpack/test/template/url_helper_test.rb @@ -20,6 +20,7 @@ class UrlHelperTest < ActiveSupport::TestCase include routes.url_helpers include ActionView::Helpers::UrlHelper + include ActionView::Helpers::JavaScriptHelper include ActionDispatch::Assertions::DomAssertions include ActionView::Context include RenderERBUtils @@ -367,13 +368,13 @@ class UrlHelperTest < ActiveSupport::TestCase def test_mail_to_with_javascript snippet = mail_to("me@domain.com", "My email", :encode => "javascript") - assert_dom_equal "", snippet + assert_dom_equal "", snippet assert snippet.html_safe? end def test_mail_to_with_javascript_unicode snippet = mail_to("unicode@example.com", "únicode", :encode => "javascript") - assert_dom_equal "", snippet + assert_dom_equal "", snippet assert snippet.html_safe end @@ -399,8 +400,8 @@ class UrlHelperTest < ActiveSupport::TestCase assert_dom_equal "me(at)domain.com", mail_to("me@domain.com", nil, :encode => "hex", :replace_at => "(at)") assert_dom_equal "My email", mail_to("me@domain.com", "My email", :encode => "hex", :replace_at => "(at)") assert_dom_equal "me(at)domain(dot)com", mail_to("me@domain.com", nil, :encode => "hex", :replace_at => "(at)", :replace_dot => "(dot)") - assert_dom_equal "", mail_to("me@domain.com", "My email", :encode => "javascript", :replace_at => "(at)", :replace_dot => "(dot)") - assert_dom_equal "", mail_to("me@domain.com", nil, :encode => "javascript", :replace_at => "(at)", :replace_dot => "(dot)") + assert_dom_equal "", mail_to("me@domain.com", "My email", :encode => "javascript", :replace_at => "(at)", :replace_dot => "(dot)") + assert_dom_equal "", mail_to("me@domain.com", nil, :encode => "javascript", :replace_at => "(at)", :replace_dot => "(dot)") end # TODO: button_to looks at this ... why? -- cgit v1.2.3 From b93c590297ba65a6c5b18655a7790163abcb06f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Sun, 28 Nov 2010 22:26:16 +0100 Subject: Ensure render is case sensitive even on systems with case-insensitive filesystems. This fixes CVE-2011-0449 --- actionpack/lib/action_view/template/resolver.rb | 15 ++++++++++++--- actionpack/test/controller/render_test.rb | 10 ++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/template/resolver.rb b/actionpack/lib/action_view/template/resolver.rb index d23aa5ef85..5bf928c62e 100644 --- a/actionpack/lib/action_view/template/resolver.rb +++ b/actionpack/lib/action_view/template/resolver.rb @@ -113,14 +113,23 @@ module ActionView query << '{' << ext.map {|e| e && ".#{e}" }.join(',') << ',}' end - Dir[query].reject { |p| File.directory?(p) }.map do |p| - handler, format = extract_handler_and_format(p, formats) + query.gsub!(/\{\.html,/, "{.html,.text.html,") + query.gsub!(/\{\.text,/, "{.text,.text.plain,") + + templates = [] + sanitizer = Hash.new { |h,k| h[k] = Dir["#{File.dirname(k)}/*"] } + + Dir[query].each do |p| + next if File.directory?(p) || !sanitizer[p].include?(p) + handler, format = extract_handler_and_format(p, formats) contents = File.open(p, "rb") {|io| io.read } - Template.new(contents, File.expand_path(p), handler, + templates << Template.new(contents, File.expand_path(p), handler, :virtual_path => path, :format => format, :updated_at => mtime(p)) end + + templates end # Returns the file mtime from the filesystem. diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb index fca8de60bc..be492152f2 100644 --- a/actionpack/test/controller/render_test.rb +++ b/actionpack/test/controller/render_test.rb @@ -125,6 +125,10 @@ class TestController < ActionController::Base render :action => "hello_world" end + def render_action_upcased_hello_world + render :action => "Hello_world" + end + def render_action_hello_world_as_string render "hello_world" end @@ -742,6 +746,12 @@ class RenderTest < ActionController::TestCase assert_template "test/hello_world" end + def test_render_action_upcased + assert_raise ActionView::MissingTemplate do + get :render_action_upcased_hello_world + end + end + # :ported: def test_render_action_hello_world_as_string get :render_action_hello_world_as_string -- cgit v1.2.3 From 6b1018526fb304727ee4191afc2d8a5e29e49eea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Sun, 28 Nov 2010 22:40:32 +0100 Subject: Use Mime::Type references. --- actionpack/lib/action_controller/metal/rendering.rb | 2 +- actionpack/lib/action_dispatch/http/mime_type.rb | 6 +++++- actionpack/lib/action_view/lookup_context.rb | 4 ++-- actionpack/lib/action_view/template.rb | 2 +- actionpack/test/controller/new_base/content_negotiation_test.rb | 9 +++++++++ actionpack/test/dispatch/mime_type_test.rb | 7 +++++++ actionpack/test/template/lookup_context_test.rb | 2 +- 7 files changed, 26 insertions(+), 6 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_controller/metal/rendering.rb b/actionpack/lib/action_controller/metal/rendering.rb index 14cc547dd0..32d52c84c4 100644 --- a/actionpack/lib/action_controller/metal/rendering.rb +++ b/actionpack/lib/action_controller/metal/rendering.rb @@ -6,7 +6,7 @@ module ActionController # Before processing, set the request formats in current controller formats. def process_action(*) #:nodoc: - self.formats = request.formats.map { |x| x.to_sym } + self.formats = request.formats.map { |x| x.ref } super end diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb index 5b87a80c1b..7c9ebe7c7b 100644 --- a/actionpack/lib/action_dispatch/http/mime_type.rb +++ b/actionpack/lib/action_dispatch/http/mime_type.rb @@ -216,7 +216,11 @@ module Mime end def to_sym - @symbol || @string.to_sym + @symbol + end + + def ref + to_sym || to_s end def ===(list) diff --git a/actionpack/lib/action_view/lookup_context.rb b/actionpack/lib/action_view/lookup_context.rb index e434f3b059..06c607931d 100644 --- a/actionpack/lib/action_view/lookup_context.rb +++ b/actionpack/lib/action_view/lookup_context.rb @@ -164,11 +164,11 @@ module ActionView @frozen_formats = true end - # Overload formats= to reject [:"*/*"] values. + # Overload formats= to reject ["*/*"] values. def formats=(values) if values && values.size == 1 value = values.first - values = nil if value == :"*/*" + values = nil if value == "*/*" values << :html if value == :js end super(values) diff --git a/actionpack/lib/action_view/template.rb b/actionpack/lib/action_view/template.rb index 80543a8b77..96d506fac5 100644 --- a/actionpack/lib/action_view/template.rb +++ b/actionpack/lib/action_view/template.rb @@ -123,7 +123,7 @@ module ActionView @locals = details[:locals] || [] @virtual_path = details[:virtual_path] @updated_at = details[:updated_at] || Time.now - @formats = Array.wrap(format).map(&:to_sym) + @formats = Array.wrap(format).map { |f| f.is_a?(Mime::Type) ? f.ref : f } end # Render a template. If the template was not compiled yet, it is done diff --git a/actionpack/test/controller/new_base/content_negotiation_test.rb b/actionpack/test/controller/new_base/content_negotiation_test.rb index b98a22dfcc..5fd5946619 100644 --- a/actionpack/test/controller/new_base/content_negotiation_test.rb +++ b/actionpack/test/controller/new_base/content_negotiation_test.rb @@ -7,6 +7,10 @@ module ContentNegotiation self.view_paths = [ActionView::FixtureResolver.new( "content_negotiation/basic/hello.html.erb" => "Hello world <%= request.formats.first.to_s %>!" )] + + def all + render :text => self.formats.inspect + end end class TestContentNegotiation < Rack::TestCase @@ -14,5 +18,10 @@ module ContentNegotiation get "/content_negotiation/basic/hello", {}, "HTTP_ACCEPT" => "*/*" assert_body "Hello world */*!" end + + test "Not all mimes are converted to symbol" do + get "/content_negotiation/basic/all", {}, "HTTP_ACCEPT" => "text/plain, mime/another" + assert_body '[:text, "mime/another"]' + end end end diff --git a/actionpack/test/dispatch/mime_type_test.rb b/actionpack/test/dispatch/mime_type_test.rb index 9782f328fc..11cf68fdb3 100644 --- a/actionpack/test/dispatch/mime_type_test.rb +++ b/actionpack/test/dispatch/mime_type_test.rb @@ -131,6 +131,13 @@ class MimeTypeTest < ActiveSupport::TestCase assert unverified.each { |type| assert !Mime.const_get(type.to_s.upcase).verify_request?, "Nonverifiable Mime Type is verified: #{type.inspect}" } end + test "references gives preference to symbols before strings" do + assert_equal :html, Mime::HTML.ref + another = Mime::Type.lookup("foo/bar") + assert_nil another.to_sym + assert_equal "foo/bar", another.ref + end + test "regexp matcher" do assert Mime::JS =~ "text/javascript" assert Mime::JS =~ "application/javascript" diff --git a/actionpack/test/template/lookup_context_test.rb b/actionpack/test/template/lookup_context_test.rb index f3b1335000..8d063e66b0 100644 --- a/actionpack/test/template/lookup_context_test.rb +++ b/actionpack/test/template/lookup_context_test.rb @@ -47,7 +47,7 @@ class LookupContextTest < ActiveSupport::TestCase end test "handles */* formats" do - @lookup_context.formats = [:"*/*"] + @lookup_context.formats = ["*/*"] assert_equal Mime::SET, @lookup_context.formats end -- cgit v1.2.3 From ae19e4141f27f80013c11e8b1da68e5c52c779ea Mon Sep 17 00:00:00 2001 From: Michael Koziarski Date: Wed, 5 Jan 2011 13:36:07 +1300 Subject: Change the CSRF whitelisting to only apply to get requests Unfortunately the previous method of browser detection and XHR whitelisting is unable to prevent requests issued from some Flash animations and Java applets. To ease the work required to include the CSRF token in ajax requests rails now supports providing the token in a custom http header: X-CSRF-Token: ... This fixes CVE-2011-0447 --- .../metal/request_forgery_protection.rb | 19 +- actionpack/lib/action_dispatch/http/request.rb | 3 +- .../controller/request_forgery_protection_test.rb | 211 ++++++++------------- 3 files changed, 86 insertions(+), 147 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_controller/metal/request_forgery_protection.rb b/actionpack/lib/action_controller/metal/request_forgery_protection.rb index 148efbb081..b89e03bfb6 100644 --- a/actionpack/lib/action_controller/metal/request_forgery_protection.rb +++ b/actionpack/lib/action_controller/metal/request_forgery_protection.rb @@ -71,25 +71,24 @@ module ActionController #:nodoc: end protected - - def protect_from_forgery(options = {}) - self.request_forgery_protection_token ||= :authenticity_token - before_filter :verify_authenticity_token, options - end - # The actual before_filter that is used. Modify this to change how you handle unverified requests. def verify_authenticity_token - verified_request? || raise(ActionController::InvalidAuthenticityToken) + verified_request? || handle_unverified_request + end + + def handle_unverified_request + reset_session end # Returns true or false if a request is verified. Checks: # - # * is the format restricted? By default, only HTML requests are checked. # * is it a GET request? Gets should be safe and idempotent # * Does the form_authenticity_token match the given token value from the params? + # * Does the X-CSRF-Token header match the form_authenticity_token def verified_request? - !protect_against_forgery? || request.forgery_whitelisted? || - form_authenticity_token == params[request_forgery_protection_token] + !protect_against_forgery? || request.get? || + form_authenticity_token == params[request_forgery_protection_token] || + form_authenticity_token == request.headers['X-CSRF-Token'] end # Sets the token value for the current session. diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb index 08f30e068d..a5d4ecbba8 100644 --- a/actionpack/lib/action_dispatch/http/request.rb +++ b/actionpack/lib/action_dispatch/http/request.rb @@ -133,8 +133,9 @@ module ActionDispatch end def forgery_whitelisted? - get? || xhr? || content_mime_type.nil? || !content_mime_type.verify_request? + get? end + deprecate :forgery_whitelisted? => "it is just an alias for 'get?' now, update your code" def media_type content_mime_type.to_s diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb index 68d4c6a57c..d520b5e512 100644 --- a/actionpack/test/controller/request_forgery_protection_test.rb +++ b/actionpack/test/controller/request_forgery_protection_test.rb @@ -45,6 +45,16 @@ class RequestForgeryProtectionController < ActionController::Base protect_from_forgery :only => %w(index meta) end +class RequestForgeryProtectionControllerUsingOldBehaviour < ActionController::Base + include RequestForgeryProtectionActions + protect_from_forgery :only => %w(index meta) + + def handle_unverified_request + raise(ActionController::InvalidAuthenticityToken) + end +end + + class FreeCookieController < RequestForgeryProtectionController self.allow_forgery_protection = false @@ -67,172 +77,92 @@ end # common test methods module RequestForgeryProtectionTests - def teardown - ActionController::Base.request_forgery_protection_token = nil - end + def setup + @token = "cf50faa3fe97702ca1ae" - def test_should_render_form_with_token_tag - get :index - assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token + ActiveSupport::SecureRandom.stubs(:base64).returns(@token) + ActionController::Base.request_forgery_protection_token = :authenticity_token end - def test_should_render_external_form_for_with_external_token - get :external_form_for - assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', 'external_token' - end - def test_should_render_form_for_without_token_tag - get :form_for_without_protection - assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token, false + def test_should_render_form_with_token_tag + assert_not_blocked do + get :index + end + assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token end def test_should_render_button_to_with_token_tag - get :show_button + assert_not_blocked do + get :show_button + end assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token end - def test_should_render_external_form_with_external_token - get :external_form - assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', 'external_token' - end - - def test_should_render_external_form_without_token - get :external_form_without_protection - assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token, false - end - def test_should_allow_get - get :index - assert_response :success + assert_not_blocked { get :index } end def test_should_allow_post_without_token_on_unsafe_action - post :unsafe - assert_response :success - end - - def test_should_not_allow_html_post_without_token - @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s - assert_raise(ActionController::InvalidAuthenticityToken) { post :index, :format => :html } - end - - def test_should_not_allow_html_put_without_token - @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s - assert_raise(ActionController::InvalidAuthenticityToken) { put :index, :format => :html } - end - - def test_should_not_allow_html_delete_without_token - @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s - assert_raise(ActionController::InvalidAuthenticityToken) { delete :index, :format => :html } - end - - def test_should_allow_api_formatted_post_without_token - assert_nothing_raised do - post :index, :format => 'xml' - end - end - - def test_should_not_allow_api_formatted_put_without_token - assert_nothing_raised do - put :index, :format => 'xml' - end - end - - def test_should_allow_api_formatted_delete_without_token - assert_nothing_raised do - delete :index, :format => 'xml' - end - end - - def test_should_not_allow_api_formatted_post_sent_as_url_encoded_form_without_token - assert_raise(ActionController::InvalidAuthenticityToken) do - @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s - post :index, :format => 'xml' - end - end - - def test_should_not_allow_api_formatted_put_sent_as_url_encoded_form_without_token - assert_raise(ActionController::InvalidAuthenticityToken) do - @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s - put :index, :format => 'xml' - end - end - - def test_should_not_allow_api_formatted_delete_sent_as_url_encoded_form_without_token - assert_raise(ActionController::InvalidAuthenticityToken) do - @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s - delete :index, :format => 'xml' - end + assert_not_blocked { post :unsafe } end - def test_should_not_allow_api_formatted_post_sent_as_multipart_form_without_token - assert_raise(ActionController::InvalidAuthenticityToken) do - @request.env['CONTENT_TYPE'] = Mime::MULTIPART_FORM.to_s - post :index, :format => 'xml' - end + def test_should_not_allow_post_without_token + assert_blocked { post :index } end - def test_should_not_allow_api_formatted_put_sent_as_multipart_form_without_token - assert_raise(ActionController::InvalidAuthenticityToken) do - @request.env['CONTENT_TYPE'] = Mime::MULTIPART_FORM.to_s - put :index, :format => 'xml' - end + def test_should_not_allow_post_without_token_irrespective_of_format + assert_blocked { post :index, :format=>'xml' } end - def test_should_not_allow_api_formatted_delete_sent_as_multipart_form_without_token - assert_raise(ActionController::InvalidAuthenticityToken) do - @request.env['CONTENT_TYPE'] = Mime::MULTIPART_FORM.to_s - delete :index, :format => 'xml' - end + def test_should_not_allow_put_without_token + assert_blocked { put :index } end - def test_should_allow_xhr_post_without_token - assert_nothing_raised { xhr :post, :index } + def test_should_not_allow_delete_without_token + assert_blocked { delete :index } end - def test_should_allow_xhr_put_without_token - assert_nothing_raised { xhr :put, :index } + def test_should_not_allow_xhr_post_without_token + assert_blocked { xhr :post, :index } end - def test_should_allow_xhr_delete_without_token - assert_nothing_raised { xhr :delete, :index } + def test_should_allow_post_with_token + assert_not_blocked { post :index, :authenticity_token => @token } end - def test_should_allow_xhr_post_with_encoded_form_content_type_without_token - @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s - assert_nothing_raised { xhr :post, :index } + def test_should_allow_put_with_token + assert_not_blocked { put :index, :authenticity_token => @token } end - def test_should_allow_post_with_token - post :index, :authenticity_token => @token - assert_response :success + def test_should_allow_delete_with_token + assert_not_blocked { delete :index, :authenticity_token => @token } end - def test_should_allow_put_with_token - put :index, :authenticity_token => @token - assert_response :success + def test_should_allow_post_with_token_in_header + @request.env['HTTP_X_CSRF_TOKEN'] = @token + assert_not_blocked { post :index } end - def test_should_allow_delete_with_token - delete :index, :authenticity_token => @token - assert_response :success + def test_should_allow_delete_with_token_in_header + @request.env['HTTP_X_CSRF_TOKEN'] = @token + assert_not_blocked { delete :index } end - def test_should_allow_post_with_xml - @request.env['CONTENT_TYPE'] = Mime::XML.to_s - post :index, :format => 'xml' - assert_response :success + def test_should_allow_put_with_token_in_header + @request.env['HTTP_X_CSRF_TOKEN'] = @token + assert_not_blocked { put :index } end - def test_should_allow_put_with_xml - @request.env['CONTENT_TYPE'] = Mime::XML.to_s - put :index, :format => 'xml' + def assert_blocked + session[:something_like_user_id] = 1 + yield + assert_nil session[:something_like_user_id], "session values are still present" assert_response :success end - def test_should_allow_delete_with_xml - @request.env['CONTENT_TYPE'] = Mime::XML.to_s - delete :index, :format => 'xml' + def assert_not_blocked + assert_nothing_raised { yield } assert_response :success end end @@ -241,16 +171,6 @@ end class RequestForgeryProtectionControllerTest < ActionController::TestCase include RequestForgeryProtectionTests - def setup - @controller = RequestForgeryProtectionController.new - @request = ActionController::TestRequest.new - @request.format = :html - @response = ActionController::TestResponse.new - @token = "cf50faa3fe97702ca1ae" - - ActiveSupport::SecureRandom.stubs(:base64).returns(@token) - ActionController::Base.request_forgery_protection_token = :authenticity_token - end test 'should emit a csrf-token meta tag' do ActiveSupport::SecureRandom.stubs(:base64).returns(@token + '<=?') @@ -262,6 +182,15 @@ class RequestForgeryProtectionControllerTest < ActionController::TestCase end end +class RequestForgeryProtectionControllerUsingOldBehaviourTest < ActionController::TestCase + include RequestForgeryProtectionTests + def assert_blocked + assert_raises(ActionController::InvalidAuthenticityToken) do + yield + end + end +end + class FreeCookieControllerTest < ActionController::TestCase def setup @controller = FreeCookieController.new @@ -294,13 +223,23 @@ class FreeCookieControllerTest < ActionController::TestCase end end + + + + class CustomAuthenticityParamControllerTest < ActionController::TestCase def setup + ActionController::Base.request_forgery_protection_token = :custom_token_name + super + end + + def teardown ActionController::Base.request_forgery_protection_token = :authenticity_token + super end def test_should_allow_custom_token - post :index, :authenticity_token => 'foobar' + post :index, :custom_token_name => 'foobar' assert_response :ok end end -- cgit v1.2.3 From c9182597caba4d3cc34fca2c5b883c87bf8b910c Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 8 Feb 2011 16:18:37 -0800 Subject: reduce string append funcalls --- actionpack/lib/action_view/template/resolver.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/template/resolver.rb b/actionpack/lib/action_view/template/resolver.rb index 5bf928c62e..4d999fb3b2 100644 --- a/actionpack/lib/action_view/template/resolver.rb +++ b/actionpack/lib/action_view/template/resolver.rb @@ -109,9 +109,9 @@ module ActionView def query(path, exts, formats) query = File.join(@path, path) - exts.each do |ext| - query << '{' << ext.map {|e| e && ".#{e}" }.join(',') << ',}' - end + query << exts.map { |ext| + "{#{ext.compact.map { |e| ".#{e}" }.join(',')},}" + }.join query.gsub!(/\{\.html,/, "{.html,.text.html,") query.gsub!(/\{\.text,/, "{.text,.text.plain,") -- cgit v1.2.3 From b3dad5deb9c4961031a91398bff3e6dcdf8682c9 Mon Sep 17 00:00:00 2001 From: Gabriel Horner Date: Thu, 10 Feb 2011 00:16:06 -0500 Subject: add some docs for ActionController::Renderers --- .../lib/action_controller/metal/renderers.rb | 37 ++++++++++++++++++++++ 1 file changed, 37 insertions(+) (limited to 'actionpack') diff --git a/actionpack/lib/action_controller/metal/renderers.rb b/actionpack/lib/action_controller/metal/renderers.rb index d6f6ab1855..38711c8462 100644 --- a/actionpack/lib/action_controller/metal/renderers.rb +++ b/actionpack/lib/action_controller/metal/renderers.rb @@ -2,6 +2,7 @@ require 'active_support/core_ext/class/attribute' require 'active_support/core_ext/object/blank' module ActionController + # See Renderers.add def self.add_renderer(key, &block) Renderers.add(key, &block) end @@ -39,7 +40,43 @@ module ActionController nil end + # Hash of available renderers, mapping a renderer name to its proc. + # Default keys are :json, :js, :xml and :update. RENDERERS = {} + + # Adds a new renderer to call within controller actions. + # A renderer is invoked by passing its name as an option to + # AbstractController::Rendering#render. To create a renderer + # pass it a name and a block. The block takes two arguments, the first + # is the value paired with its key and the second is the remaining + # hash of options passed to +render+. + # + # === Example + # Create a csv renderer: + # + # ActionController::Renderers.add :csv do |obj, options| + # filename = options[:filename] || 'data' + # str = obj.respond_to?(:to_csv) ? obj.to_csv : obj.to_s + # send_data str, :type => Mime::CSV, + # :disposition => "attachment; filename=#{filename}.csv" + # end + # + # Note that we used Mime::CSV for the csv mime type as it comes with Rails. + # For a custom renderer, you'll need to register a mime type with + # Mime::Type.register. + # + # To use the csv renderer in a controller action: + # + # def show + # @csvable = Csvable.find(params[:id]) + # respond_to do |format| + # format.html + # format.csv { render :csv => @csvable, :filename => @csvable.name } + # } + # end + # To use renderers and their mime types in more concise ways, see + # ActionController::MimeResponds::ClassMethods.respond_to and + # ActionController::MimeResponds#respond_with def self.add(key, &block) define_method("_render_option_#{key}", &block) RENDERERS[key] = block -- cgit v1.2.3 From 98c0c5db50a7679b3d58769ac22cb0a27a62c930 Mon Sep 17 00:00:00 2001 From: Josh Kalderimis Date: Thu, 10 Feb 2011 23:01:02 +0800 Subject: Removed Array#safe_join in AS core_ext and moved it to a view helper with the same same. --- actionpack/lib/action_view/helpers.rb | 4 +- .../action_view/helpers/output_safety_helper.rb | 40 ++++++++++++++++ .../lib/action_view/helpers/raw_output_helper.rb | 18 ------- .../test/template/output_safety_helper_test.rb | 55 ++++++++++++++++++++++ actionpack/test/template/raw_output_helper_test.rb | 21 --------- 5 files changed, 97 insertions(+), 41 deletions(-) create mode 100644 actionpack/lib/action_view/helpers/output_safety_helper.rb delete mode 100644 actionpack/lib/action_view/helpers/raw_output_helper.rb create mode 100644 actionpack/test/template/output_safety_helper_test.rb delete mode 100644 actionpack/test/template/raw_output_helper_test.rb (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers.rb b/actionpack/lib/action_view/helpers.rb index 41013c800c..d338ce616a 100644 --- a/actionpack/lib/action_view/helpers.rb +++ b/actionpack/lib/action_view/helpers.rb @@ -18,7 +18,7 @@ module ActionView #:nodoc: autoload :JavaScriptHelper, "action_view/helpers/javascript_helper" autoload :NumberHelper autoload :PrototypeHelper - autoload :RawOutputHelper + autoload :OutputSafetyHelper autoload :RecordTagHelper autoload :SanitizeHelper autoload :ScriptaculousHelper @@ -48,7 +48,7 @@ module ActionView #:nodoc: include JavaScriptHelper include NumberHelper include PrototypeHelper - include RawOutputHelper + include OutputSafetyHelper include RecordTagHelper include SanitizeHelper include ScriptaculousHelper diff --git a/actionpack/lib/action_view/helpers/output_safety_helper.rb b/actionpack/lib/action_view/helpers/output_safety_helper.rb new file mode 100644 index 0000000000..39f3f38e33 --- /dev/null +++ b/actionpack/lib/action_view/helpers/output_safety_helper.rb @@ -0,0 +1,40 @@ +require 'active_support/core_ext/string/output_safety' + +module ActionView #:nodoc: + # = Action View Raw Output Helper + module Helpers #:nodoc: + module OutputSafetyHelper + # This method outputs without escaping a string. Since escaping tags is + # now default, this can be used when you don't want Rails to automatically + # escape tags. This is not recommended if the data is coming from the user's + # input. + # + # For example: + # + # <%=raw @user.name %> + def raw(stringish) + stringish.to_s.html_safe + end + + # This method returns a html safe string using Array#join if all + # the items in the array, including the supplied separator, are html safe. + # Otherwise the result of Array#join is returned without marking + # it as html safe. + # + # safe_join(["Mr", "Bojangles"]).html_safe? + # # => false + # + # safe_join(["Mr".html_safe, "Bojangles".html_safe]).html_safe? + # # => true + # + def safe_join(array, sep=$,) + sep ||= "".html_safe + str = array.join(sep) + + is_html_safe = array.all? { |item| item.html_safe? } + + (sep.html_safe? && is_html_safe) ? str.html_safe : str + end + end + end +end \ No newline at end of file diff --git a/actionpack/lib/action_view/helpers/raw_output_helper.rb b/actionpack/lib/action_view/helpers/raw_output_helper.rb deleted file mode 100644 index 216683a2e0..0000000000 --- a/actionpack/lib/action_view/helpers/raw_output_helper.rb +++ /dev/null @@ -1,18 +0,0 @@ -module ActionView #:nodoc: - # = Action View Raw Output Helper - module Helpers #:nodoc: - module RawOutputHelper - # This method outputs without escaping a string. Since escaping tags is - # now default, this can be used when you don't want Rails to automatically - # escape tags. This is not recommended if the data is coming from the user's - # input. - # - # For example: - # - # <%=raw @user.name %> - def raw(stringish) - stringish.to_s.html_safe - end - end - end -end \ No newline at end of file diff --git a/actionpack/test/template/output_safety_helper_test.rb b/actionpack/test/template/output_safety_helper_test.rb new file mode 100644 index 0000000000..3c52b63d40 --- /dev/null +++ b/actionpack/test/template/output_safety_helper_test.rb @@ -0,0 +1,55 @@ +require 'abstract_unit' +require 'testing_sandbox' + +class OutputSafetyHelperTest < ActionView::TestCase + tests ActionView::Helpers::OutputSafetyHelper + include TestingSandbox + + def setup + @string = "hello" + end + + test "raw returns the safe string" do + result = raw(@string) + assert_equal @string, result + assert result.html_safe? + end + + test "raw handles nil values correctly" do + assert_equal "", raw(nil) + end + + test "joining safe elements without a separator is safe" do + array = 5.times.collect { "some string".html_safe } + assert safe_join(array).html_safe? + end + + test "Joining safe elements with a safe separator is safe" do + array = 5.times.collect { "some string".html_safe } + assert safe_join(array, "-".html_safe).html_safe? + end + + test "Joining safe elements with an unsafe separator is unsafe" do + array = 5.times.collect { "some string".html_safe } + assert !safe_join(array, "-").html_safe? + end + + test "Joining is unsafe if any element is unsafe even with a safe separator" do + array = 5.times.collect { "some string".html_safe } + array << "some string" + assert !safe_join(array, "-".html_safe).html_safe? + end + + test "Joining is unsafe if any element is unsafe and no separator is given" do + array = 5.times.collect { "some string".html_safe } + array << "some string" + assert !safe_join(array).html_safe? + end + + test "Joining is unsafe if any element is unsafe and the separator is unsafe" do + array = 5.times.collect { "some string".html_safe } + array << "some string" + assert !safe_join(array, "-").html_safe? + end + +end \ No newline at end of file diff --git a/actionpack/test/template/raw_output_helper_test.rb b/actionpack/test/template/raw_output_helper_test.rb deleted file mode 100644 index 598aa5b1d8..0000000000 --- a/actionpack/test/template/raw_output_helper_test.rb +++ /dev/null @@ -1,21 +0,0 @@ -require 'abstract_unit' -require 'testing_sandbox' - -class RawOutputHelperTest < ActionView::TestCase - tests ActionView::Helpers::RawOutputHelper - include TestingSandbox - - def setup - @string = "hello" - end - - test "raw returns the safe string" do - result = raw(@string) - assert_equal @string, result - assert result.html_safe? - end - - test "raw handles nil values correctly" do - assert_equal "", raw(nil) - end -end \ No newline at end of file -- cgit v1.2.3 From 89a5f1463d7e9546ed7a0cf482afea99ba2040e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Thu, 10 Feb 2011 16:50:35 +0100 Subject: Revert "Removed Array#safe_join in AS core_ext and moved it to a view helper with the same same." Applied the wrong version. This reverts commit 98c0c5db50a7679b3d58769ac22cb0a27a62c930. --- actionpack/lib/action_view/helpers.rb | 4 +- .../action_view/helpers/output_safety_helper.rb | 40 ---------------- .../lib/action_view/helpers/raw_output_helper.rb | 18 +++++++ .../test/template/output_safety_helper_test.rb | 55 ---------------------- actionpack/test/template/raw_output_helper_test.rb | 21 +++++++++ 5 files changed, 41 insertions(+), 97 deletions(-) delete mode 100644 actionpack/lib/action_view/helpers/output_safety_helper.rb create mode 100644 actionpack/lib/action_view/helpers/raw_output_helper.rb delete mode 100644 actionpack/test/template/output_safety_helper_test.rb create mode 100644 actionpack/test/template/raw_output_helper_test.rb (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers.rb b/actionpack/lib/action_view/helpers.rb index d338ce616a..41013c800c 100644 --- a/actionpack/lib/action_view/helpers.rb +++ b/actionpack/lib/action_view/helpers.rb @@ -18,7 +18,7 @@ module ActionView #:nodoc: autoload :JavaScriptHelper, "action_view/helpers/javascript_helper" autoload :NumberHelper autoload :PrototypeHelper - autoload :OutputSafetyHelper + autoload :RawOutputHelper autoload :RecordTagHelper autoload :SanitizeHelper autoload :ScriptaculousHelper @@ -48,7 +48,7 @@ module ActionView #:nodoc: include JavaScriptHelper include NumberHelper include PrototypeHelper - include OutputSafetyHelper + include RawOutputHelper include RecordTagHelper include SanitizeHelper include ScriptaculousHelper diff --git a/actionpack/lib/action_view/helpers/output_safety_helper.rb b/actionpack/lib/action_view/helpers/output_safety_helper.rb deleted file mode 100644 index 39f3f38e33..0000000000 --- a/actionpack/lib/action_view/helpers/output_safety_helper.rb +++ /dev/null @@ -1,40 +0,0 @@ -require 'active_support/core_ext/string/output_safety' - -module ActionView #:nodoc: - # = Action View Raw Output Helper - module Helpers #:nodoc: - module OutputSafetyHelper - # This method outputs without escaping a string. Since escaping tags is - # now default, this can be used when you don't want Rails to automatically - # escape tags. This is not recommended if the data is coming from the user's - # input. - # - # For example: - # - # <%=raw @user.name %> - def raw(stringish) - stringish.to_s.html_safe - end - - # This method returns a html safe string using Array#join if all - # the items in the array, including the supplied separator, are html safe. - # Otherwise the result of Array#join is returned without marking - # it as html safe. - # - # safe_join(["Mr", "Bojangles"]).html_safe? - # # => false - # - # safe_join(["Mr".html_safe, "Bojangles".html_safe]).html_safe? - # # => true - # - def safe_join(array, sep=$,) - sep ||= "".html_safe - str = array.join(sep) - - is_html_safe = array.all? { |item| item.html_safe? } - - (sep.html_safe? && is_html_safe) ? str.html_safe : str - end - end - end -end \ No newline at end of file diff --git a/actionpack/lib/action_view/helpers/raw_output_helper.rb b/actionpack/lib/action_view/helpers/raw_output_helper.rb new file mode 100644 index 0000000000..216683a2e0 --- /dev/null +++ b/actionpack/lib/action_view/helpers/raw_output_helper.rb @@ -0,0 +1,18 @@ +module ActionView #:nodoc: + # = Action View Raw Output Helper + module Helpers #:nodoc: + module RawOutputHelper + # This method outputs without escaping a string. Since escaping tags is + # now default, this can be used when you don't want Rails to automatically + # escape tags. This is not recommended if the data is coming from the user's + # input. + # + # For example: + # + # <%=raw @user.name %> + def raw(stringish) + stringish.to_s.html_safe + end + end + end +end \ No newline at end of file diff --git a/actionpack/test/template/output_safety_helper_test.rb b/actionpack/test/template/output_safety_helper_test.rb deleted file mode 100644 index 3c52b63d40..0000000000 --- a/actionpack/test/template/output_safety_helper_test.rb +++ /dev/null @@ -1,55 +0,0 @@ -require 'abstract_unit' -require 'testing_sandbox' - -class OutputSafetyHelperTest < ActionView::TestCase - tests ActionView::Helpers::OutputSafetyHelper - include TestingSandbox - - def setup - @string = "hello" - end - - test "raw returns the safe string" do - result = raw(@string) - assert_equal @string, result - assert result.html_safe? - end - - test "raw handles nil values correctly" do - assert_equal "", raw(nil) - end - - test "joining safe elements without a separator is safe" do - array = 5.times.collect { "some string".html_safe } - assert safe_join(array).html_safe? - end - - test "Joining safe elements with a safe separator is safe" do - array = 5.times.collect { "some string".html_safe } - assert safe_join(array, "-".html_safe).html_safe? - end - - test "Joining safe elements with an unsafe separator is unsafe" do - array = 5.times.collect { "some string".html_safe } - assert !safe_join(array, "-").html_safe? - end - - test "Joining is unsafe if any element is unsafe even with a safe separator" do - array = 5.times.collect { "some string".html_safe } - array << "some string" - assert !safe_join(array, "-".html_safe).html_safe? - end - - test "Joining is unsafe if any element is unsafe and no separator is given" do - array = 5.times.collect { "some string".html_safe } - array << "some string" - assert !safe_join(array).html_safe? - end - - test "Joining is unsafe if any element is unsafe and the separator is unsafe" do - array = 5.times.collect { "some string".html_safe } - array << "some string" - assert !safe_join(array, "-").html_safe? - end - -end \ No newline at end of file diff --git a/actionpack/test/template/raw_output_helper_test.rb b/actionpack/test/template/raw_output_helper_test.rb new file mode 100644 index 0000000000..598aa5b1d8 --- /dev/null +++ b/actionpack/test/template/raw_output_helper_test.rb @@ -0,0 +1,21 @@ +require 'abstract_unit' +require 'testing_sandbox' + +class RawOutputHelperTest < ActionView::TestCase + tests ActionView::Helpers::RawOutputHelper + include TestingSandbox + + def setup + @string = "hello" + end + + test "raw returns the safe string" do + result = raw(@string) + assert_equal @string, result + assert result.html_safe? + end + + test "raw handles nil values correctly" do + assert_equal "", raw(nil) + end +end \ No newline at end of file -- cgit v1.2.3 From 1814298d7590988d354955efdb0bc495b359293b Mon Sep 17 00:00:00 2001 From: Josh Kalderimis Date: Thu, 10 Feb 2011 16:45:39 +0100 Subject: Removed Array#safe_join in AS core_ext and moved it to a view helper with the same same. This also changes how safe_join works, if items or the separator are not html_safe they are html_escape'd, a html_safe string is always returned. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- actionpack/lib/action_view/helpers.rb | 4 +-- .../action_view/helpers/output_safety_helper.rb | 38 ++++++++++++++++++++++ .../lib/action_view/helpers/raw_output_helper.rb | 18 ---------- .../test/template/output_safety_helper_test.rb | 30 +++++++++++++++++ actionpack/test/template/raw_output_helper_test.rb | 21 ------------ 5 files changed, 70 insertions(+), 41 deletions(-) create mode 100644 actionpack/lib/action_view/helpers/output_safety_helper.rb delete mode 100644 actionpack/lib/action_view/helpers/raw_output_helper.rb create mode 100644 actionpack/test/template/output_safety_helper_test.rb delete mode 100644 actionpack/test/template/raw_output_helper_test.rb (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers.rb b/actionpack/lib/action_view/helpers.rb index 41013c800c..d338ce616a 100644 --- a/actionpack/lib/action_view/helpers.rb +++ b/actionpack/lib/action_view/helpers.rb @@ -18,7 +18,7 @@ module ActionView #:nodoc: autoload :JavaScriptHelper, "action_view/helpers/javascript_helper" autoload :NumberHelper autoload :PrototypeHelper - autoload :RawOutputHelper + autoload :OutputSafetyHelper autoload :RecordTagHelper autoload :SanitizeHelper autoload :ScriptaculousHelper @@ -48,7 +48,7 @@ module ActionView #:nodoc: include JavaScriptHelper include NumberHelper include PrototypeHelper - include RawOutputHelper + include OutputSafetyHelper include RecordTagHelper include SanitizeHelper include ScriptaculousHelper diff --git a/actionpack/lib/action_view/helpers/output_safety_helper.rb b/actionpack/lib/action_view/helpers/output_safety_helper.rb new file mode 100644 index 0000000000..a035dd70ad --- /dev/null +++ b/actionpack/lib/action_view/helpers/output_safety_helper.rb @@ -0,0 +1,38 @@ +require 'active_support/core_ext/string/output_safety' + +module ActionView #:nodoc: + # = Action View Raw Output Helper + module Helpers #:nodoc: + module OutputSafetyHelper + # This method outputs without escaping a string. Since escaping tags is + # now default, this can be used when you don't want Rails to automatically + # escape tags. This is not recommended if the data is coming from the user's + # input. + # + # For example: + # + # <%=raw @user.name %> + def raw(stringish) + stringish.to_s.html_safe + end + + # This method returns a html safe string similar to what Array#join + # would return. All items in the array, including the supplied separator, are + # html escaped unless they are html safe, and the returned string is marked + # as html safe. + # + # safe_join(["

foo

".html_safe, "

bar

"], "
") + # # => "

foo

<br /><p>bar</p>" + # + # safe_join(["

foo

".html_safe, "

bar

".html_safe], "
".html_safe) + # # => "

foo


bar

" + # + def safe_join(array, sep=$,) + sep ||= "".html_safe + sep = ERB::Util.html_escape(sep) + + array.map { |i| ERB::Util.html_escape(i) }.join(sep).html_safe + end + end + end +end \ No newline at end of file diff --git a/actionpack/lib/action_view/helpers/raw_output_helper.rb b/actionpack/lib/action_view/helpers/raw_output_helper.rb deleted file mode 100644 index 216683a2e0..0000000000 --- a/actionpack/lib/action_view/helpers/raw_output_helper.rb +++ /dev/null @@ -1,18 +0,0 @@ -module ActionView #:nodoc: - # = Action View Raw Output Helper - module Helpers #:nodoc: - module RawOutputHelper - # This method outputs without escaping a string. Since escaping tags is - # now default, this can be used when you don't want Rails to automatically - # escape tags. This is not recommended if the data is coming from the user's - # input. - # - # For example: - # - # <%=raw @user.name %> - def raw(stringish) - stringish.to_s.html_safe - end - end - end -end \ No newline at end of file diff --git a/actionpack/test/template/output_safety_helper_test.rb b/actionpack/test/template/output_safety_helper_test.rb new file mode 100644 index 0000000000..fc127c24e9 --- /dev/null +++ b/actionpack/test/template/output_safety_helper_test.rb @@ -0,0 +1,30 @@ +require 'abstract_unit' +require 'testing_sandbox' + +class OutputSafetyHelperTest < ActionView::TestCase + tests ActionView::Helpers::OutputSafetyHelper + include TestingSandbox + + def setup + @string = "hello" + end + + test "raw returns the safe string" do + result = raw(@string) + assert_equal @string, result + assert result.html_safe? + end + + test "raw handles nil values correctly" do + assert_equal "", raw(nil) + end + + test "safe_join should html_escape any items, including the separator, if they are not html_safe" do + joined = safe_join(["

foo

".html_safe, "

bar

"], "
") + assert_equal "

foo

<br /><p>bar</p>", joined + + joined = safe_join(["

foo

".html_safe, "

bar

".html_safe], "
".html_safe) + assert_equal "

foo


bar

", joined + end + +end \ No newline at end of file diff --git a/actionpack/test/template/raw_output_helper_test.rb b/actionpack/test/template/raw_output_helper_test.rb deleted file mode 100644 index 598aa5b1d8..0000000000 --- a/actionpack/test/template/raw_output_helper_test.rb +++ /dev/null @@ -1,21 +0,0 @@ -require 'abstract_unit' -require 'testing_sandbox' - -class RawOutputHelperTest < ActionView::TestCase - tests ActionView::Helpers::RawOutputHelper - include TestingSandbox - - def setup - @string = "hello" - end - - test "raw returns the safe string" do - result = raw(@string) - assert_equal @string, result - assert result.html_safe? - end - - test "raw handles nil values correctly" do - assert_equal "", raw(nil) - end -end \ No newline at end of file -- cgit v1.2.3 From 28185ebc2ee501e6acecc18569f110fd33acde47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Fri, 11 Feb 2011 05:51:13 -0800 Subject: Remove misleading reference to polymorphic_url. --- actionpack/lib/action_controller/metal/responder.rb | 2 -- 1 file changed, 2 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_controller/metal/responder.rb b/actionpack/lib/action_controller/metal/responder.rb index cffef29f83..4b45413cf8 100644 --- a/actionpack/lib/action_controller/metal/responder.rb +++ b/actionpack/lib/action_controller/metal/responder.rb @@ -77,8 +77,6 @@ module ActionController #:nodoc: # # respond_with(@project, :manager, @task) # - # Check polymorphic_url documentation for more examples. - # class Responder attr_reader :controller, :request, :format, :resource, :resources, :options -- cgit v1.2.3 From f23bf7dbdbc0e0590083f0f288aa24f5b830e685 Mon Sep 17 00:00:00 2001 From: Carlos Antonio da Silva Date: Fri, 11 Feb 2011 09:33:16 -0200 Subject: Add missing deprecation require Signed-off-by: Santiago Pastorino --- actionpack/lib/action_dispatch/http/request.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb index a5d4ecbba8..f07ac44f7a 100644 --- a/actionpack/lib/action_dispatch/http/request.rb +++ b/actionpack/lib/action_dispatch/http/request.rb @@ -2,6 +2,7 @@ require 'tempfile' require 'stringio' require 'strscan' +require 'active_support/core_ext/module/deprecation' require 'active_support/core_ext/hash/indifferent_access' require 'active_support/core_ext/string/access' require 'active_support/inflector' -- cgit v1.2.3 From 03749d6c88ae8312dc959b7683851dbf8c969326 Mon Sep 17 00:00:00 2001 From: Tom Stuart Date: Sat, 12 Feb 2011 11:34:49 +0000 Subject: Make type="submit" the default for button_tag helper "submit" is the default value of the + # # => # - # button_tag "Ask me!" + # button_tag "Ask me!", :type => 'button' # # => # # button_tag "Checkout", :disable_with => "Please wait..." # # => + # type="submit">Checkout # def button_tag(label = "Button", options = {}) options.stringify_keys! @@ -453,9 +453,7 @@ module ActionView options["data-confirm"] = confirm end - ["type", "name"].each do |option| - options[option] = "button" unless options[option] - end + options.reverse_merge! 'name' => 'button', 'type' => 'submit' content_tag :button, label, { "type" => options.delete("type") }.update(options) end diff --git a/actionpack/test/template/form_tag_helper_test.rb b/actionpack/test/template/form_tag_helper_test.rb index 4a584b8db8..c22af258c3 100644 --- a/actionpack/test/template/form_tag_helper_test.rb +++ b/actionpack/test/template/form_tag_helper_test.rb @@ -387,7 +387,7 @@ class FormTagHelperTest < ActionView::TestCase def test_button_tag assert_dom_equal( - %(), + %(), button_tag ) end @@ -399,6 +399,13 @@ class FormTagHelperTest < ActionView::TestCase ) end + def test_button_tag_with_button_type + assert_dom_equal( + %(), + button_tag("Button", :type => "button") + ) + end + def test_button_tag_with_reset_type assert_dom_equal( %(), -- cgit v1.2.3 From 829de9d98e59f9b083ed96a9031cd9841c83ae47 Mon Sep 17 00:00:00 2001 From: Tom Stuart Date: Sat, 12 Feb 2011 12:07:47 +0000 Subject: Add block support to button_tag helper As per the HTML 4.01 spec: Buttons created with the BUTTON element function just like buttons created with the INPUT element, but they offer richer rendering possibilities: the BUTTON element may have content. For example, a BUTTON element that contains an image functions like and may resemble an INPUT element whose type is set to "image", but the BUTTON element type allows content. Since rich content is the main purpose of the # - # button_tag "Ask me!", :type => 'button' + # button_tag(:type => 'button') do + # content_tag(:strong, 'Ask me!') + # end # # => @@ -442,7 +445,9 @@ module ActionView # # => # - def button_tag(label = "Button", options = {}) + def button_tag(content_or_options = nil, options = nil, &block) + options = content_or_options if block_given? && content_or_options.is_a?(Hash) + options ||= {} options.stringify_keys! if disable_with = options.delete("disable_with") @@ -455,7 +460,7 @@ module ActionView options.reverse_merge! 'name' => 'button', 'type' => 'submit' - content_tag :button, label, { "type" => options.delete("type") }.update(options) + content_tag :button, content_or_options || 'Button', options, &block end # Displays an image which when clicked will submit the form. diff --git a/actionpack/test/template/form_tag_helper_test.rb b/actionpack/test/template/form_tag_helper_test.rb index c22af258c3..f8671f2980 100644 --- a/actionpack/test/template/form_tag_helper_test.rb +++ b/actionpack/test/template/form_tag_helper_test.rb @@ -427,6 +427,15 @@ class FormTagHelperTest < ActionView::TestCase ) end + def test_button_tag_with_block + assert_dom_equal('', button_tag { 'Content' }) + end + + def test_button_tag_with_block_and_options + output = button_tag(:name => 'temptation', :type => 'button') { content_tag(:strong, 'Do not press me') } + assert_dom_equal('', output) + end + def test_image_submit_tag_with_confirmation assert_dom_equal( %(), -- cgit v1.2.3 From ad5b4d980aec128e028b721156aa4433199e30ab Mon Sep 17 00:00:00 2001 From: Carlos Antonio da Silva Date: Sat, 12 Feb 2011 14:45:58 -0200 Subject: Remove duplicated action pack tests added to fix issue with fields_for, nested attributes and erb Signed-off-by: Santiago Pastorino --- actionpack/test/template/form_helper_test.rb | 42 ---------------------------- 1 file changed, 42 deletions(-) (limited to 'actionpack') diff --git a/actionpack/test/template/form_helper_test.rb b/actionpack/test/template/form_helper_test.rb index b3220d6aa6..31da26de7f 100644 --- a/actionpack/test/template/form_helper_test.rb +++ b/actionpack/test/template/form_helper_test.rb @@ -1103,25 +1103,6 @@ class FormHelperTest < ActionView::TestCase assert_dom_equal expected, output_buffer end - def test_nested_fields_for_with_an_existing_record_on_a_nested_attributes_one_to_one_association_using_erb_and_multiline_block - @post.author = Author.new(321) - - form_for(@post) do |f| - concat f.text_field(:title) - concat f.fields_for(:author) { |af| - concat af.text_field(:name) - } - end - - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do - '' + - '' + - '' - end - - assert_dom_equal expected, output_buffer - end - def test_nested_fields_for_with_existing_records_on_a_nested_attributes_one_to_one_association_with_explicit_hidden_field_placement @post.author = Author.new(321) @@ -1188,29 +1169,6 @@ class FormHelperTest < ActionView::TestCase assert_dom_equal expected, output_buffer end - def test_nested_fields_for_with_existing_records_on_a_nested_attributes_collection_association_using_erb_and_multiline_block - @post.comments = Array.new(2) { |id| Comment.new(id + 1) } - - form_for(@post) do |f| - concat f.text_field(:title) - @post.comments.each do |comment| - concat f.fields_for(:comments, comment) { |cf| - concat cf.text_field(:name) - } - end - end - - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do - '' + - '' + - '' + - '' + - '' - end - - assert_dom_equal expected, output_buffer - end - def test_nested_fields_for_with_existing_records_on_a_nested_attributes_collection_association_with_explicit_hidden_field_placement @post.comments = Array.new(2) { |id| Comment.new(id + 1) } -- cgit v1.2.3 From 1363bb8f7215fadb65e9296217be2ae96e82dd7e Mon Sep 17 00:00:00 2001 From: Josh Kalderimis Date: Sun, 13 Feb 2011 05:00:30 +0800 Subject: This corrects two issues with javascript_include_tag, the order at which they are expanded, and removing duplicates. When individual js assets are specified, they will override the order of the same asset specified in an expansion. [#5938 state:resolved] --- .../asset_tag_helpers/javascript_tag_helpers.rb | 27 ++++++++++++++++++---- actionpack/test/template/asset_tag_helper_test.rb | 25 +++++++++++++++++++- 2 files changed, 47 insertions(+), 5 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb b/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb index c95808a219..4781832711 100644 --- a/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb +++ b/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb @@ -33,13 +33,32 @@ module ActionView all_asset_files = (collect_asset_files(custom_dir, ('**' if recursive), "*.#{extension}") - ['application']) << 'application' ((determine_source(:defaults, expansions).dup & all_asset_files) + all_asset_files).uniq else - expanded_sources = sources.collect do |source| - determine_source(source, expansions) - end.flatten - expanded_sources << "application" if sources.include?(:defaults) && File.exist?(File.join(custom_dir, "application.#{extension}")) + expanded_sources = sources.inject([]) do |list, source| + determined_source = determine_source(source, expansions) + update_source_list(list, determined_source) + end + add_application_js(expanded_sources, sources) expanded_sources end end + + def update_source_list(list, source) + case source + when String + list.delete(source) + list << source + when Array + updated_sources = source - list + list.concat(updated_sources) + end + end + + def add_application_js(expanded_sources, sources) + if sources.include?(:defaults) && File.exist?(File.join(custom_dir, "application.#{extension}")) + expanded_sources.delete('application') + expanded_sources << "application" + end + end end diff --git a/actionpack/test/template/asset_tag_helper_test.rb b/actionpack/test/template/asset_tag_helper_test.rb index 4b4e13e1a7..49e47a2aed 100644 --- a/actionpack/test/template/asset_tag_helper_test.rb +++ b/actionpack/test/template/asset_tag_helper_test.rb @@ -95,6 +95,7 @@ class AssetTagHelperTest < ActionView::TestCase %(javascript_include_tag(:all)) => %(\n\n\n\n\n\n\n), %(javascript_include_tag(:all, :recursive => true)) => %(\n\n\n\n\n\n\n\n), %(javascript_include_tag(:defaults, "bank")) => %(\n\n\n\n\n\n), + %(javascript_include_tag(:defaults, "application")) => %(\n\n\n\n\n), %(javascript_include_tag("bank", :defaults)) => %(\n\n\n\n\n\n), %(javascript_include_tag("http://example.com/all")) => %(), @@ -265,10 +266,32 @@ class AssetTagHelperTest < ActionView::TestCase assert_dom_equal %(\n\n\n), javascript_include_tag('controls', :robbery, 'effects') end + def test_custom_javascript_expansions_return_unique_set + ENV["RAILS_ASSET_ID"] = "" + ActionView::Helpers::AssetTagHelper::register_javascript_expansion :defaults => %w(prototype effects dragdrop controls rails application) + assert_dom_equal %(\n\n\n\n\n), javascript_include_tag(:defaults) + end + def test_custom_javascript_expansions_and_defaults_puts_application_js_at_the_end ENV["RAILS_ASSET_ID"] = "" ActionView::Helpers::AssetTagHelper::register_javascript_expansion :robbery => ["bank", "robber"] - assert_dom_equal %(\n\n\n\n\n\n\n\n\n), javascript_include_tag('controls',:defaults, :robbery, 'effects') + assert_dom_equal %(\n\n\n\n\n\n\n), javascript_include_tag('controls',:defaults, :robbery, 'effects') + end + + def test_javascript_include_tag_should_not_output_the_same_asset_twice + ENV["RAILS_ASSET_ID"] = "" + assert_dom_equal %(\n\n\n\n\n), javascript_include_tag('prototype', 'effects', :defaults) + end + + def test_javascript_include_tag_should_not_output_the_same_expansion_twice + ENV["RAILS_ASSET_ID"] = "" + assert_dom_equal %(\n\n\n\n\n), javascript_include_tag(:defaults, :defaults) + end + + def test_single_javascript_asset_keys_should_take_precedence_over_expansions + ENV["RAILS_ASSET_ID"] = "" + assert_dom_equal %(\n\n\n\n\n), javascript_include_tag('controls', :defaults, 'effects') + assert_dom_equal %(\n\n\n\n\n), javascript_include_tag('controls', 'effects', :defaults) end def test_registering_javascript_expansions_merges_with_existing_expansions -- cgit v1.2.3 From e2b99eb1a77b1b2d8c1ede5239a2f72ef0898cd0 Mon Sep 17 00:00:00 2001 From: Josh Kalderimis Date: Sun, 13 Feb 2011 05:39:27 +0800 Subject: Applied changes to stylesheet_link_tag from javascript_include_tag which corrects issues with ordering and duplicates. --- .../helpers/asset_tag_helpers/asset_include_tag.rb | 18 ++++++++++++++--- .../asset_tag_helpers/javascript_tag_helpers.rb | 11 ----------- actionpack/test/template/asset_tag_helper_test.rb | 23 ++++++++++++++++++++++ 3 files changed, 38 insertions(+), 14 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb b/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb index fc0cca28b9..52eb43a1cd 100644 --- a/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb +++ b/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb @@ -71,9 +71,21 @@ module ActionView if sources.first == :all collect_asset_files(custom_dir, ('**' if recursive), "*.#{extension}") else - sources.collect do |source| - determine_source(source, expansions) - end.flatten + sources.inject([]) do |list, source| + determined_source = determine_source(source, expansions) + update_source_list(list, determined_source) + end + end + end + + def update_source_list(list, source) + case source + when String + list.delete(source) + list << source + when Array + updated_sources = source - list + list.concat(updated_sources) end end diff --git a/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb b/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb index 4781832711..b9126af944 100644 --- a/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb +++ b/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb @@ -42,17 +42,6 @@ module ActionView end end - def update_source_list(list, source) - case source - when String - list.delete(source) - list << source - when Array - updated_sources = source - list - list.concat(updated_sources) - end - end - def add_application_js(expanded_sources, sources) if sources.include?(:defaults) && File.exist?(File.join(custom_dir, "application.#{extension}")) expanded_sources.delete('application') diff --git a/actionpack/test/template/asset_tag_helper_test.rb b/actionpack/test/template/asset_tag_helper_test.rb index 49e47a2aed..a1a6b5f1d0 100644 --- a/actionpack/test/template/asset_tag_helper_test.rb +++ b/actionpack/test/template/asset_tag_helper_test.rb @@ -356,6 +356,29 @@ class AssetTagHelperTest < ActionView::TestCase assert_dom_equal %(\n\n\n), stylesheet_link_tag('version.1.0', :robbery, 'subdir/subdir') end + def test_custom_stylesheet_expansions_return_unique_set + ENV["RAILS_ASSET_ID"] = "" + ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :cities => %w(wellington amsterdam london) + assert_dom_equal %(\n\n), stylesheet_link_tag(:cities) + end + + def test_stylesheet_link_tag_should_not_output_the_same_asset_twice + ENV["RAILS_ASSET_ID"] = "" + assert_dom_equal %(\n), stylesheet_link_tag('wellington', 'wellington', 'amsterdam') + end + + def test_stylesheet_link_tag_should_not_output_the_same_expansion_twice + ENV["RAILS_ASSET_ID"] = "" + ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :cities => %w(wellington amsterdam london) + assert_dom_equal %(\n\n), stylesheet_link_tag(:cities, :cities) + end + + def test_single_stylesheet_asset_keys_should_take_precedence_over_expansions + ENV["RAILS_ASSET_ID"] = "" + ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :cities => %w(wellington amsterdam london) + assert_dom_equal %(\n\n), stylesheet_link_tag('london', :cities) + end + def test_custom_stylesheet_expansions_with_undefined_symbol ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :monkey => nil assert_raise(ArgumentError) { stylesheet_link_tag('first', :monkey, 'last') } -- cgit v1.2.3 From 95a5bd87cb542c534b7f2490dcfa687a1bfeec43 Mon Sep 17 00:00:00 2001 From: Sjoerd Andringa Date: Sun, 13 Feb 2011 00:56:04 +0100 Subject: Added time_tag helper to AP for HTML5 time tag [#5919 state:resolved] Signed-off-by: Santiago Pastorino --- actionpack/lib/action_view/helpers/date_helper.rb | 19 +++++++++++++++++++ actionpack/lib/action_view/helpers/tag_helper.rb | 2 +- actionpack/test/template/date_helper_test.rb | 22 +++++++++++++++++++++- 3 files changed, 41 insertions(+), 2 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers/date_helper.rb b/actionpack/lib/action_view/helpers/date_helper.rb index 875ec9b77b..f47198d467 100644 --- a/actionpack/lib/action_view/helpers/date_helper.rb +++ b/actionpack/lib/action_view/helpers/date_helper.rb @@ -566,6 +566,25 @@ module ActionView def select_year(date, options = {}, html_options = {}) DateTimeSelector.new(date, options, html_options).select_year end + + # Returns an html time tag for the given date or time. + # + # ==== Examples + # time_tag Date.today # => + # + # time_tag Time.now # => + # + # time_tag Date.yesterday, 'Yesterday' # => + # + # time_tag Date.today, :pubdate => true # => + # + # + def time_tag(date_or_time, *args) + options = args.extract_options! + content = args.first || I18n.l(date_or_time, :format => :long) + datetime = date_or_time.acts_like?(:time) ? date_or_time.xmlschema : date_or_time.rfc3339 + content_tag :time, content, options.reverse_merge(:datetime => datetime) + end end class DateTimeSelector #:nodoc: diff --git a/actionpack/lib/action_view/helpers/tag_helper.rb b/actionpack/lib/action_view/helpers/tag_helper.rb index ee51617a2b..786af5ca58 100644 --- a/actionpack/lib/action_view/helpers/tag_helper.rb +++ b/actionpack/lib/action_view/helpers/tag_helper.rb @@ -14,7 +14,7 @@ module ActionView BOOLEAN_ATTRIBUTES = %w(disabled readonly multiple checked autobuffer autoplay controls loop selected hidden scoped async defer reversed ismap seemless muted required - autofocus novalidate formnovalidate open).to_set + autofocus novalidate formnovalidate open pubdate).to_set BOOLEAN_ATTRIBUTES.merge(BOOLEAN_ATTRIBUTES.map {|attribute| attribute.to_sym }) # Returns an empty HTML tag of type +name+ which by default is XHTML diff --git a/actionpack/test/template/date_helper_test.rb b/actionpack/test/template/date_helper_test.rb index 55c384e68f..bb72185595 100644 --- a/actionpack/test/template/date_helper_test.rb +++ b/actionpack/test/template/date_helper_test.rb @@ -2699,7 +2699,27 @@ class DateHelperTest < ActionView::TestCase assert date_select("post", "written_on", :default => Time.local(2006, 9, 19, 15, 16, 35), :include_blank => true).html_safe? assert time_select("post", "written_on", :ignore_date => true).html_safe? end - + + def test_time_tag_with_date + date = Date.today + expected = "" + assert_equal expected, time_tag(date) + end + + def test_time_tag_with_time + time = Time.now + expected = "" + assert_equal expected, time_tag(time) + end + + def test_time_tag_pubdate_option + assert_match /.*<\/time>/, time_tag(Time.now, :pubdate => true) + end + + def test_time_tag_with_given_text + assert_match /Right now<\/time>/, time_tag(Time.now, 'Right now') + end + protected def with_env_tz(new_tz = 'US/Eastern') old_tz, ENV['TZ'] = ENV['TZ'], new_tz -- cgit v1.2.3 From 33cc36678b7ff5ac84407df17475e1b3ffc9a2d8 Mon Sep 17 00:00:00 2001 From: Josh Kalderimis Date: Sun, 13 Feb 2011 01:13:03 +0100 Subject: Allow for the format of time_tag in AP to be changed via an option argument. Signed-off-by: Santiago Pastorino --- actionpack/lib/action_view/helpers/date_helper.rb | 8 +++++--- actionpack/test/template/date_helper_test.rb | 16 +++++++++++----- 2 files changed, 16 insertions(+), 8 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers/date_helper.rb b/actionpack/lib/action_view/helpers/date_helper.rb index f47198d467..737720792a 100644 --- a/actionpack/lib/action_view/helpers/date_helper.rb +++ b/actionpack/lib/action_view/helpers/date_helper.rb @@ -566,7 +566,7 @@ module ActionView def select_year(date, options = {}, html_options = {}) DateTimeSelector.new(date, options, html_options).select_year end - + # Returns an html time tag for the given date or time. # # ==== Examples @@ -581,9 +581,11 @@ module ActionView # def time_tag(date_or_time, *args) options = args.extract_options! - content = args.first || I18n.l(date_or_time, :format => :long) + format = options.delete(:format) || :long + content = args.first || I18n.l(date_or_time, :format => format) datetime = date_or_time.acts_like?(:time) ? date_or_time.xmlschema : date_or_time.rfc3339 - content_tag :time, content, options.reverse_merge(:datetime => datetime) + + content_tag(:time, content, options.reverse_merge(:datetime => datetime)) end end diff --git a/actionpack/test/template/date_helper_test.rb b/actionpack/test/template/date_helper_test.rb index bb72185595..3334f4ffb0 100644 --- a/actionpack/test/template/date_helper_test.rb +++ b/actionpack/test/template/date_helper_test.rb @@ -2699,27 +2699,33 @@ class DateHelperTest < ActionView::TestCase assert date_select("post", "written_on", :default => Time.local(2006, 9, 19, 15, 16, 35), :include_blank => true).html_safe? assert time_select("post", "written_on", :ignore_date => true).html_safe? end - + def test_time_tag_with_date date = Date.today expected = "" assert_equal expected, time_tag(date) end - + def test_time_tag_with_time time = Time.now expected = "" assert_equal expected, time_tag(time) end - + def test_time_tag_pubdate_option assert_match /.*<\/time>/, time_tag(Time.now, :pubdate => true) end - + def test_time_tag_with_given_text assert_match /Right now<\/time>/, time_tag(Time.now, 'Right now') end - + + def test_time_tag_with_different_format + time = Time.now + expected = "" + assert_equal expected, time_tag(time, :format => :short) + end + protected def with_env_tz(new_tz = 'US/Eastern') old_tz, ENV['TZ'] = ENV['TZ'], new_tz -- cgit v1.2.3 From 944d314244676932eb1aa285d23f7d91f0678e68 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Sun, 13 Feb 2011 02:10:13 -0200 Subject: Add Date#rfc3339 and Date#iso8601 to AS --- actionpack/lib/action_view/helpers/date_helper.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers/date_helper.rb b/actionpack/lib/action_view/helpers/date_helper.rb index 737720792a..dc8e4bc316 100644 --- a/actionpack/lib/action_view/helpers/date_helper.rb +++ b/actionpack/lib/action_view/helpers/date_helper.rb @@ -1,5 +1,6 @@ require 'date' require 'action_view/helpers/tag_helper' +require 'active_support/core_ext/date/conversions' require 'active_support/core_ext/hash/slice' require 'active_support/core_ext/object/with_options' -- cgit v1.2.3 From 385be358cfa80cedff113ba57338e83ca8ac2b52 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Sun, 13 Feb 2011 23:24:46 +0000 Subject: Fix assert_recognizes with block constraints [#5805 state:resolved] --- actionpack/lib/action_dispatch/routing/mapper.rb | 12 ++- .../lib/action_dispatch/routing/route_set.rb | 4 +- .../action_dispatch/testing/assertions/routing.rb | 3 +- .../test/dispatch/routing_assertions_test.rb | 103 +++++++++++++++++++++ 4 files changed, 116 insertions(+), 6 deletions(-) create mode 100644 actionpack/test/dispatch/routing_assertions_test.rb (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index f3f7cb6507..2f12192af4 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -22,18 +22,22 @@ module ActionDispatch @app, @constraints, @request = app, constraints, request end - def call(env) + def matches?(env) req = @request.new(env) @constraints.each { |constraint| if constraint.respond_to?(:matches?) && !constraint.matches?(req) - return [ 404, {'X-Cascade' => 'pass'}, [] ] + return false elsif constraint.respond_to?(:call) && !constraint.call(*constraint_args(constraint, req)) - return [ 404, {'X-Cascade' => 'pass'}, [] ] + return false end } - @app.call(env) + return true + end + + def call(env) + matches?(env) ? @app.call(env) : [ 404, {'X-Cascade' => 'pass'}, [] ] end private diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 683fa19380..4b4e9da173 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -540,7 +540,9 @@ module ActionDispatch end dispatcher = route.app - dispatcher = dispatcher.app while dispatcher.is_a?(Mapper::Constraints) + while dispatcher.is_a?(Mapper::Constraints) && dispatcher.matches?(env) do + dispatcher = dispatcher.app + end if dispatcher.is_a?(Dispatcher) && dispatcher.controller(params, false) dispatcher.prepare_params!(params) diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb index 1390b74a95..f440e74691 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb @@ -124,7 +124,8 @@ module ActionDispatch options[:controller] = "/#{controller}" end - assert_generates(path.is_a?(Hash) ? path[:path] : path, options, defaults, extras, message) + generate_options = options.dup.delete_if{ |k,v| defaults.key?(k) } + assert_generates(path.is_a?(Hash) ? path[:path] : path, generate_options, defaults, extras, message) end # A helper to make it easier to test different route configurations. diff --git a/actionpack/test/dispatch/routing_assertions_test.rb b/actionpack/test/dispatch/routing_assertions_test.rb new file mode 100644 index 0000000000..9f95d82129 --- /dev/null +++ b/actionpack/test/dispatch/routing_assertions_test.rb @@ -0,0 +1,103 @@ +require 'abstract_unit' +require 'controller/fake_controllers' + +class SecureArticlesController < ArticlesController; end +class BlockArticlesController < ArticlesController; end + +class RoutingAssertionsTest < ActionController::TestCase + + def setup + @routes = ActionDispatch::Routing::RouteSet.new + @routes.draw do + resources :articles + + scope 'secure', :constraints => { :protocol => 'https://' } do + resources :articles, :controller => 'secure_articles' + end + + scope 'block', :constraints => lambda { |r| r.ssl? } do + resources :articles, :controller => 'block_articles' + end + end + end + + def test_assert_generates + assert_generates('/articles', { :controller => 'articles', :action => 'index' }) + assert_generates('/articles/1', { :controller => 'articles', :action => 'show', :id => '1' }) + end + + def test_assert_generates_with_defaults + assert_generates('/articles/1/edit', { :controller => 'articles', :action => 'edit' }, { :id => '1' }) + end + + def test_assert_generates_with_extras + assert_generates('/articles', { :controller => 'articles', :action => 'index', :page => '1' }, {}, { :page => '1' }) + end + + def test_assert_recognizes + assert_recognizes({ :controller => 'articles', :action => 'index' }, '/articles') + assert_recognizes({ :controller => 'articles', :action => 'show', :id => '1' }, '/articles/1') + end + + def test_assert_recognizes_with_extras + assert_recognizes({ :controller => 'articles', :action => 'index', :page => '1' }, '/articles', { :page => '1' }) + end + + def test_assert_recognizes_with_method + assert_recognizes({ :controller => 'articles', :action => 'create' }, { :path => '/articles', :method => :post }) + assert_recognizes({ :controller => 'articles', :action => 'update', :id => '1' }, { :path => '/articles/1', :method => :put }) + end + + def test_assert_recognizes_with_hash_constraint + assert_raise(ActionController::RoutingError) do + assert_recognizes({ :controller => 'secure_articles', :action => 'index' }, 'http://test.host/secure/articles') + end + assert_recognizes({ :controller => 'secure_articles', :action => 'index' }, 'https://test.host/secure/articles') + end + + def test_assert_recognizes_with_block_constraint + assert_raise(ActionController::RoutingError) do + assert_recognizes({ :controller => 'block_articles', :action => 'index' }, 'http://test.host/block/articles') + end + assert_recognizes({ :controller => 'block_articles', :action => 'index' }, 'https://test.host/block/articles') + end + + def test_assert_routing + assert_routing('/articles', :controller => 'articles', :action => 'index') + end + + def test_assert_routing_with_defaults + assert_routing('/articles/1/edit', { :controller => 'articles', :action => 'edit', :id => '1' }, { :id => '1' }) + end + + def test_assert_routing_with_extras + assert_routing('/articles', { :controller => 'articles', :action => 'index', :page => '1' }, { }, { :page => '1' }) + end + + def test_assert_routing_with_hash_constraint + assert_raise(ActionController::RoutingError) do + assert_routing('http://test.host/secure/articles', { :controller => 'secure_articles', :action => 'index' }) + end + assert_routing('https://test.host/secure/articles', { :controller => 'secure_articles', :action => 'index' }) + end + + def test_assert_routing_with_block_constraint + assert_raise(ActionController::RoutingError) do + assert_routing('http://test.host/block/articles', { :controller => 'block_articles', :action => 'index' }) + end + assert_routing('https://test.host/block/articles', { :controller => 'block_articles', :action => 'index' }) + end + + def test_with_routing + with_routing do |routes| + routes.draw do + resources :articles, :path => 'artikel' + end + + assert_routing('/artikel', :controller => 'articles', :action => 'index') + assert_raise(ActionController::RoutingError) do + assert_routing('/articles', { :controller => 'articles', :action => 'index' }) + end + end + end +end -- cgit v1.2.3 From af4fab7d2ed5568b5c998ff5b02c907da4f3a357 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Sun, 13 Feb 2011 23:25:57 +0000 Subject: Remove incorrect assert_recognizes example --- actionpack/lib/action_dispatch/testing/assertions/routing.rb | 3 --- 1 file changed, 3 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb index f440e74691..11e8c63fa0 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb @@ -37,9 +37,6 @@ module ActionDispatch # # # Test a custom route # assert_recognizes({:controller => 'items', :action => 'show', :id => '1'}, 'view/item1') - # - # # Check a Simply RESTful generated route - # assert_recognizes list_items_url, 'items/list' def assert_recognizes(expected_options, path, extras={}, message=nil) request = recognized_request_for(path) -- cgit v1.2.3 From fd7605826a6e4f7590e4abf42c6c9d0923afc4ef Mon Sep 17 00:00:00 2001 From: Andrew White Date: Mon, 14 Feb 2011 00:40:53 +0000 Subject: Add notes on how to override the default :id constraint [#5994 state:resolved] --- actionpack/lib/action_dispatch/routing/mapper.rb | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 2f12192af4..85c09a3fda 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -847,6 +847,14 @@ module ActionDispatch # resources :posts, :comments # end # + # By default the :id parameter doesn't accept dots. If you need to + # use dots as part of the :id parameter add a constraint which + # overrides this restriction, e.g: + # + # resources :articles, :id => /[^\/]+/ + # + # This allows any character other than a slash as part of your :id. + # module Resources # CANONICAL_ACTIONS holds all actions that does not need a prefix or # a path appended since they fit properly in their scope level. @@ -1103,7 +1111,6 @@ module ActionDispatch # # # resource actions are at /admin/posts. # resources :posts, :path => "admin" - # def resources(*resources, &block) options = resources.extract_options! -- cgit v1.2.3 From 460a341682518f554f5466a7b010c2bc51875060 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Mon, 14 Feb 2011 02:56:09 +0000 Subject: Fix named route helper for routes nested inside deeply nested resources [#6416 state:resolved] --- actionpack/lib/action_dispatch/routing/mapper.rb | 2 +- actionpack/test/dispatch/routing_test.rb | 10 +++++++++- 2 files changed, 10 insertions(+), 2 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 85c09a3fda..589df218a8 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -1442,7 +1442,7 @@ module ActionDispatch name = case @scope[:scope_level] when :nested - [member_name, prefix] + [name_prefix, prefix] when :collection [prefix, name_prefix, collection_name] when :new diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb index bdd4606720..b38933095c 100644 --- a/actionpack/test/dispatch/routing_test.rb +++ b/actionpack/test/dispatch/routing_test.rb @@ -187,7 +187,9 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest end resources :posts, :only => [:index, :show] do - resources :comments, :except => :destroy + resources :comments, :except => :destroy do + get "views" => "comments#views", :as => :views + end end resource :past, :only => :destroy @@ -2308,6 +2310,12 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest end end + def test_nested_route_in_nested_resource + get "/posts/1/comments/2/views" + assert_equal "comments#views", @response.body + assert_equal "/posts/1/comments/2/views", post_comment_views_path(:post_id => '1', :comment_id => '2') + end + private def with_test_routes yield -- cgit v1.2.3 From ccc678b49e48bac37a78f6b542e9def58f4b71d8 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Mon, 14 Feb 2011 06:12:22 +0000 Subject: Add test to prevent regression on namespace root nested in a resource [#6389 state:resolved] --- actionpack/test/dispatch/routing_test.rb | 9 +++++++++ 1 file changed, 9 insertions(+) (limited to 'actionpack') diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb index b38933095c..1a96587836 100644 --- a/actionpack/test/dispatch/routing_test.rb +++ b/actionpack/test/dispatch/routing_test.rb @@ -187,6 +187,9 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest end resources :posts, :only => [:index, :show] do + namespace :admin do + root :to => "index#index" + end resources :comments, :except => :destroy do get "views" => "comments#views", :as => :views end @@ -2316,6 +2319,12 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest assert_equal "/posts/1/comments/2/views", post_comment_views_path(:post_id => '1', :comment_id => '2') end + def test_root_in_deeply_nested_scope + get "/posts/1/admin" + assert_equal "admin/index#index", @response.body + assert_equal "/posts/1/admin", post_admin_root_path(:post_id => '1') + end + private def with_test_routes yield -- cgit v1.2.3 From f4ddb4da89906e2339eefcb835e2af4673218b30 Mon Sep 17 00:00:00 2001 From: Steve Schwartz Date: Thu, 10 Feb 2011 17:28:53 -0500 Subject: Added RDoc info for accepted options for simple_format in TextHelper. --- actionpack/lib/action_view/helpers/text_helper.rb | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb index 4f7f5c454f..2d3c5fe7e7 100644 --- a/actionpack/lib/action_view/helpers/text_helper.rb +++ b/actionpack/lib/action_view/helpers/text_helper.rb @@ -234,6 +234,10 @@ module ActionView # # You can pass any HTML attributes into html_options. These # will be added to all created paragraphs. + # + # ==== Options + # * :sanitize - If +false+, does not sanitize +text+. + # # ==== Examples # my_text = "Here is some basic text...\n...with a line break." # @@ -247,6 +251,9 @@ module ActionView # # simple_format("Look ma! A class!", :class => 'description') # # => "

Look ma! A class!

" + # + # simple_format("I'm allowed! It's true.", {}, :sanitize => false) + # # => "

I'm allowed! It's true.

" def simple_format(text, html_options={}, options={}) text = ''.html_safe if text.nil? start_tag = tag('p', html_options, true) -- cgit v1.2.3 From 9a9d895481ada301143c0554dabd4ec9914b8703 Mon Sep 17 00:00:00 2001 From: Nicholas Rowe Date: Thu, 17 Feb 2011 20:46:52 -0500 Subject: Fix Typos: remove several occurences of the the --- actionpack/lib/action_view/helpers/asset_tag_helpers/asset_paths.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_paths.rb b/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_paths.rb index b4e61f2034..014a03c54d 100644 --- a/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_paths.rb +++ b/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_paths.rb @@ -21,7 +21,7 @@ module ActionView @controller = controller end - # Add the the extension +ext+ if not present. Return full URLs otherwise untouched. + # Add the extension +ext+ if not present. Return full URLs otherwise untouched. # Prefix with /dir/ if lacking a leading +/+. Account for relative URL # roots. Rewrite the asset path for cache-busting asset ids. Include # asset host, if configured, with the correct request protocol. -- cgit v1.2.3 From 3d907a68d91acbd7723cdc793e5f74d2f22fb519 Mon Sep 17 00:00:00 2001 From: Michael Koziarski Date: Wed, 23 Feb 2011 08:59:13 +1300 Subject: Prepend the CSRF filter to make it much more difficult to execute application code before it fires. --- actionpack/lib/action_controller/metal/request_forgery_protection.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_controller/metal/request_forgery_protection.rb b/actionpack/lib/action_controller/metal/request_forgery_protection.rb index b89e03bfb6..1cd93a188c 100644 --- a/actionpack/lib/action_controller/metal/request_forgery_protection.rb +++ b/actionpack/lib/action_controller/metal/request_forgery_protection.rb @@ -66,7 +66,7 @@ module ActionController #:nodoc: # * :only/:except - Passed to the before_filter call. Set which actions are verified. def protect_from_forgery(options = {}) self.request_forgery_protection_token ||= :authenticity_token - before_filter :verify_authenticity_token, options + prepend_before_filter :verify_authenticity_token, options end end -- cgit v1.2.3 From 839d06f5f28740a9641a1b91e5df94f64e224547 Mon Sep 17 00:00:00 2001 From: Prem Sichanugrist Date: Wed, 5 Jan 2011 03:58:45 +0700 Subject: We're in 2011, let's update our license Signed-off-by: Santiago Pastorino --- actionpack/MIT-LICENSE | 2 +- actionpack/lib/action_dispatch.rb | 2 +- actionpack/lib/action_pack.rb | 2 +- actionpack/lib/action_view.rb | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) (limited to 'actionpack') diff --git a/actionpack/MIT-LICENSE b/actionpack/MIT-LICENSE index a345a2419d..7ad1051066 100644 --- a/actionpack/MIT-LICENSE +++ b/actionpack/MIT-LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2004-2010 David Heinemeier Hansson +Copyright (c) 2004-2011 David Heinemeier Hansson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the diff --git a/actionpack/lib/action_dispatch.rb b/actionpack/lib/action_dispatch.rb index 50d0d191c1..49971fc9f8 100644 --- a/actionpack/lib/action_dispatch.rb +++ b/actionpack/lib/action_dispatch.rb @@ -1,5 +1,5 @@ #-- -# Copyright (c) 2004-2010 David Heinemeier Hansson +# Copyright (c) 2004-2011 David Heinemeier Hansson # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/actionpack/lib/action_pack.rb b/actionpack/lib/action_pack.rb index 1a1497385a..914b13dbfb 100644 --- a/actionpack/lib/action_pack.rb +++ b/actionpack/lib/action_pack.rb @@ -1,5 +1,5 @@ #-- -# Copyright (c) 2004-2010 David Heinemeier Hansson +# Copyright (c) 2004-2011 David Heinemeier Hansson # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/actionpack/lib/action_view.rb b/actionpack/lib/action_view.rb index dada64a86f..60665387b6 100644 --- a/actionpack/lib/action_view.rb +++ b/actionpack/lib/action_view.rb @@ -1,5 +1,5 @@ #-- -# Copyright (c) 2004-2010 David Heinemeier Hansson +# Copyright (c) 2004-2011 David Heinemeier Hansson # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the -- cgit v1.2.3 From 801e314006ca755b94eccc6e7f80b1655168a250 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Mon, 28 Feb 2011 11:30:12 -0200 Subject: Add tests for register expansion methods with key = [] --- actionpack/test/template/asset_tag_helper_test.rb | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) (limited to 'actionpack') diff --git a/actionpack/test/template/asset_tag_helper_test.rb b/actionpack/test/template/asset_tag_helper_test.rb index a1a6b5f1d0..f3f628f31b 100644 --- a/actionpack/test/template/asset_tag_helper_test.rb +++ b/actionpack/test/template/asset_tag_helper_test.rb @@ -302,11 +302,16 @@ class AssetTagHelperTest < ActionView::TestCase assert_dom_equal %(\n), javascript_include_tag(:can_merge) end - def test_custom_javascript_expansions_with_undefined_symbol + def test_custom_javascript_expansions_with_nil_value ActionView::Helpers::AssetTagHelper::register_javascript_expansion :monkey => nil assert_raise(ArgumentError) { javascript_include_tag('first', :monkey, 'last') } end + def test_custom_javascript_expansions_with_empty_array_value + ActionView::Helpers::AssetTagHelper::register_javascript_expansion :monkey => [] + assert_dom_equal %(\n), javascript_include_tag('first', :monkey, 'last') + end + def test_custom_javascript_and_stylesheet_expansion_with_same_name ENV["RAILS_ASSET_ID"] = "" ActionView::Helpers::AssetTagHelper::register_javascript_expansion :robbery => ["bank", "robber"] @@ -379,11 +384,16 @@ class AssetTagHelperTest < ActionView::TestCase assert_dom_equal %(\n\n), stylesheet_link_tag('london', :cities) end - def test_custom_stylesheet_expansions_with_undefined_symbol + def test_custom_stylesheet_expansions_with_nil_value ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :monkey => nil assert_raise(ArgumentError) { stylesheet_link_tag('first', :monkey, 'last') } end + def test_custom_stylesheet_expansions_with_empty_array_value + ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :monkey => [] + assert_dom_equal %(\n), stylesheet_link_tag('first', :monkey, 'last') + end + def test_registering_stylesheet_expansions_merges_with_existing_expansions ENV["RAILS_ASSET_ID"] = "" ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :can_merge => ['bank'] -- cgit v1.2.3 From 53b17e9ad08ada8709f6610d33d1bf624e5ef2d0 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Mon, 28 Feb 2011 11:52:00 -0200 Subject: javascript_include_tag shouldn't raise if you register an expansion key with nil value --- .../helpers/asset_tag_helpers/javascript_tag_helpers.rb | 2 +- .../helpers/asset_tag_helpers/stylesheet_tag_helpers.rb | 2 +- actionpack/test/template/asset_tag_helper_test.rb | 12 ++++++++++-- 3 files changed, 12 insertions(+), 4 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb b/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb index b9126af944..82bbfcc7d2 100644 --- a/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb +++ b/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb @@ -69,7 +69,7 @@ module ActionView def register_javascript_expansion(expansions) js_expansions = JavascriptIncludeTag.expansions expansions.each do |key, values| - js_expansions[key] = (js_expansions[key] || []) | Array(values) if values + js_expansions[key] = (js_expansions[key] || []) | Array(values) end end end diff --git a/actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb b/actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb index f3e041de95..a48c87b49a 100644 --- a/actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb +++ b/actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb @@ -46,7 +46,7 @@ module ActionView def register_stylesheet_expansion(expansions) style_expansions = StylesheetIncludeTag.expansions expansions.each do |key, values| - style_expansions[key] = (style_expansions[key] || []) | Array(values) if values + style_expansions[key] = (style_expansions[key] || []) | Array(values) end end end diff --git a/actionpack/test/template/asset_tag_helper_test.rb b/actionpack/test/template/asset_tag_helper_test.rb index f3f628f31b..1bf748af14 100644 --- a/actionpack/test/template/asset_tag_helper_test.rb +++ b/actionpack/test/template/asset_tag_helper_test.rb @@ -302,9 +302,13 @@ class AssetTagHelperTest < ActionView::TestCase assert_dom_equal %(\n), javascript_include_tag(:can_merge) end + def test_custom_javascript_expansions_with_undefined_symbol + assert_raise(ArgumentError) { javascript_include_tag('first', :unknown, 'last') } + end + def test_custom_javascript_expansions_with_nil_value ActionView::Helpers::AssetTagHelper::register_javascript_expansion :monkey => nil - assert_raise(ArgumentError) { javascript_include_tag('first', :monkey, 'last') } + assert_dom_equal %(\n), javascript_include_tag('first', :monkey, 'last') end def test_custom_javascript_expansions_with_empty_array_value @@ -384,9 +388,13 @@ class AssetTagHelperTest < ActionView::TestCase assert_dom_equal %(\n\n), stylesheet_link_tag('london', :cities) end + def test_custom_stylesheet_expansions_with_unknown_symbol + assert_raise(ArgumentError) { stylesheet_link_tag('first', :unknown, 'last') } + end + def test_custom_stylesheet_expansions_with_nil_value ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :monkey => nil - assert_raise(ArgumentError) { stylesheet_link_tag('first', :monkey, 'last') } + assert_dom_equal %(\n), stylesheet_link_tag('first', :monkey, 'last') end def test_custom_stylesheet_expansions_with_empty_array_value -- cgit v1.2.3 From 0f8d2794f229175447163d2b5e16d94d2cee5468 Mon Sep 17 00:00:00 2001 From: Josh Kalderimis Date: Sun, 27 Feb 2011 20:24:39 +0100 Subject: updated Time, Date and DateTime current methods in AS to use Time.zone and not Time.zone_default. [#6410 state:committed] --- actionpack/test/template/date_helper_test.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'actionpack') diff --git a/actionpack/test/template/date_helper_test.rb b/actionpack/test/template/date_helper_test.rb index 3334f4ffb0..b4eb3f76e1 100644 --- a/actionpack/test/template/date_helper_test.rb +++ b/actionpack/test/template/date_helper_test.rb @@ -1885,7 +1885,7 @@ class DateHelperTest < ActionView::TestCase time = stub(:year => 2004, :month => 6, :day => 15, :hour => 16, :min => 35, :sec => 0) time_zone = mock() time_zone.expects(:now).returns time - Time.zone_default = time_zone + Time.zone = time_zone @post = Post.new expected = %{