From 8e4363de72c0829c68d38f636b7fcefce6a5759a Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Sun, 14 Feb 2010 11:35:05 -0800 Subject: Save off Module's const_missing, not Class' --- activesupport/lib/active_support/dependencies.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb index 56de29b730..ee7566f335 100644 --- a/activesupport/lib/active_support/dependencies.rb +++ b/activesupport/lib/active_support/dependencies.rb @@ -116,7 +116,7 @@ module ActiveSupport #:nodoc: base.class_eval do # Emulate #exclude via an ivar return if @_const_missing - @_const_missing = method(:const_missing) + @_const_missing = instance_method(:const_missing) remove_method(:const_missing) end super -- cgit v1.2.3 From 411c15ed5220cb07cfb1989d32be956f94a7478f Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Sun, 14 Feb 2010 11:55:01 -0800 Subject: require Strings, not Symbols --- activesupport/lib/active_support/dependencies.rb | 1 + railties/lib/rails/application/metal_loader.rb | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb index ee7566f335..22b5e434c8 100644 --- a/activesupport/lib/active_support/dependencies.rb +++ b/activesupport/lib/active_support/dependencies.rb @@ -177,6 +177,7 @@ module ActiveSupport #:nodoc: end def require_dependency(file_name, message = "No such file to load -- %s") + raise ArgumentError, "the file name must be a String -- you passed #{file_name.inspect}" Dependencies.depend_on(file_name, false, message) end diff --git a/railties/lib/rails/application/metal_loader.rb b/railties/lib/rails/application/metal_loader.rb index c0f2e4f948..2a43fa7892 100644 --- a/railties/lib/rails/application/metal_loader.rb +++ b/railties/lib/rails/application/metal_loader.rb @@ -34,7 +34,7 @@ module Rails Dir.glob("#{path}/**/*.rb").sort.each do |metal_path| metal = metal_path.sub(matcher, '\1').to_sym next unless list.include?(metal) || list.include?(:all) - require_dependency metal + require_dependency metal.to_s metals << metal end end -- cgit v1.2.3 From f86421fb282ff2d209914db736ca64380dab044d Mon Sep 17 00:00:00 2001 From: Bruno Michel Date: Sat, 13 Feb 2010 19:53:26 -0200 Subject: content_tag should escape its input Signed-off-by: Yehuda Katz --- .../lib/action_view/helpers/active_model_helper.rb | 6 +++--- actionpack/lib/action_view/helpers/date_helper.rb | 6 +++--- .../lib/action_view/helpers/form_options_helper.rb | 5 ++--- actionpack/lib/action_view/helpers/form_tag_helper.rb | 6 +++--- actionpack/lib/action_view/helpers/javascript_helper.rb | 2 +- actionpack/lib/action_view/helpers/tag_helper.rb | 2 +- actionpack/lib/action_view/helpers/url_helper.rb | 2 +- actionpack/test/template/form_tag_helper_test.rb | 16 ++++++++-------- actionpack/test/template/tag_helper_test.rb | 2 ++ actionpack/test/template/url_helper_test.rb | 2 +- 10 files changed, 25 insertions(+), 24 deletions(-) diff --git a/actionpack/lib/action_view/helpers/active_model_helper.rb b/actionpack/lib/action_view/helpers/active_model_helper.rb index e106bb0897..c87e216c32 100644 --- a/actionpack/lib/action_view/helpers/active_model_helper.rb +++ b/actionpack/lib/action_view/helpers/active_model_helper.rb @@ -127,7 +127,7 @@ module ActionView if (obj = (object.respond_to?(:errors) ? object : instance_variable_get("@#{object}"))) && (errors = obj.errors[method]) content_tag("div", - "#{options[:prepend_text]}#{ERB::Util.html_escape(errors.first)}#{options[:append_text]}", + "#{options[:prepend_text]}#{ERB::Util.html_escape(errors.first)}#{options[:append_text]}".html_safe, :class => options[:css_class] ) else @@ -228,14 +228,14 @@ module ActionView object.errors.full_messages.map do |msg| content_tag(:li, ERB::Util.html_escape(msg)) end - end.join + end.join.html_safe contents = '' contents << content_tag(options[:header_tag] || :h2, header_message) unless header_message.blank? contents << content_tag(:p, message) unless message.blank? contents << content_tag(:ul, error_messages) - content_tag(:div, contents, html) + content_tag(:div, contents.html_safe, html) end else '' diff --git a/actionpack/lib/action_view/helpers/date_helper.rb b/actionpack/lib/action_view/helpers/date_helper.rb index 8be2f76bd6..c2810b3190 100644 --- a/actionpack/lib/action_view/helpers/date_helper.rb +++ b/actionpack/lib/action_view/helpers/date_helper.rb @@ -815,7 +815,7 @@ module ActionView tag_options[:selected] = "selected" if selected == i select_options << content_tag(:option, value, tag_options) end - select_options.join("\n") + "\n" + (select_options.join("\n") + "\n").html_safe end # Builds select tag from date type and html select options @@ -833,9 +833,9 @@ module ActionView select_html = "\n" select_html << content_tag(:option, '', :value => '') + "\n" if @options[:include_blank] select_html << prompt_option_tag(type, @options[:prompt]) + "\n" if @options[:prompt] - select_html << select_options_as_html.to_s + select_html << select_options_as_html - (content_tag(:select, select_html, select_options) + "\n").html_safe + (content_tag(:select, select_html.html_safe, select_options) + "\n").html_safe end # Builds a prompt option tag with supplied options or from default options diff --git a/actionpack/lib/action_view/helpers/form_options_helper.rb b/actionpack/lib/action_view/helpers/form_options_helper.rb index 0ffe770f5f..7f74be27cb 100644 --- a/actionpack/lib/action_view/helpers/form_options_helper.rb +++ b/actionpack/lib/action_view/helpers/form_options_helper.rb @@ -572,10 +572,9 @@ module ActionView end if value.blank? && options[:prompt] prompt = options[:prompt].kind_of?(String) ? options[:prompt] : I18n.translate('helpers.select.prompt', :default => 'Please select') - "\n" + option_tags - else - option_tags + option_tags = "\n" + option_tags end + option_tags.html_safe end end diff --git a/actionpack/lib/action_view/helpers/form_tag_helper.rb b/actionpack/lib/action_view/helpers/form_tag_helper.rb index 6ed6c3101b..7dcaee7e34 100644 --- a/actionpack/lib/action_view/helpers/form_tag_helper.rb +++ b/actionpack/lib/action_view/helpers/form_tag_helper.rb @@ -90,9 +90,9 @@ module ActionView html_name = (options[:multiple] == true && !name.to_s.ends_with?("[]")) ? "#{name}[]" : name if blank = options.delete(:include_blank) if blank.kind_of?(String) - option_tags = "" + option_tags + option_tags = "".html_safe + option_tags else - option_tags = "" + option_tags + option_tags = "".html_safe + option_tags end end content_tag :select, option_tags, { "name" => html_name, "id" => sanitize_to_id(name) }.update(options.stringify_keys) @@ -279,7 +279,7 @@ module ActionView escape = options.key?("escape") ? options.delete("escape") : true content = html_escape(content) if escape - content_tag :textarea, content, { "name" => name, "id" => sanitize_to_id(name) }.update(options) + content_tag :textarea, content.html_safe, { "name" => name, "id" => sanitize_to_id(name) }.update(options) end # Creates a check box form input tag. diff --git a/actionpack/lib/action_view/helpers/javascript_helper.rb b/actionpack/lib/action_view/helpers/javascript_helper.rb index 8fdaa8cf8d..2c73ff88f7 100644 --- a/actionpack/lib/action_view/helpers/javascript_helper.rb +++ b/actionpack/lib/action_view/helpers/javascript_helper.rb @@ -93,7 +93,7 @@ module ActionView end def javascript_cdata_section(content) #:nodoc: - "\n//#{cdata_section("\n#{content}\n//")}\n" + "\n//#{cdata_section("\n#{content}\n//")}\n".html_safe end end end diff --git a/actionpack/lib/action_view/helpers/tag_helper.rb b/actionpack/lib/action_view/helpers/tag_helper.rb index a3a8185f40..1c3eb20e19 100644 --- a/actionpack/lib/action_view/helpers/tag_helper.rb +++ b/actionpack/lib/action_view/helpers/tag_helper.rb @@ -127,7 +127,7 @@ module ActionView def content_tag_string(name, content, options, escape = true) tag_options = tag_options(options, escape) if options - "<#{name}#{tag_options}>#{content}".html_safe + "<#{name}#{tag_options}>#{ERB::Util.h content}".html_safe end def tag_options(options, escape = true) diff --git a/actionpack/lib/action_view/helpers/url_helper.rb b/actionpack/lib/action_view/helpers/url_helper.rb index 168a3bdbc0..88ce2a2c0c 100644 --- a/actionpack/lib/action_view/helpers/url_helper.rb +++ b/actionpack/lib/action_view/helpers/url_helper.rb @@ -493,7 +493,7 @@ module ActionView char = c.chr string << (char =~ /\w/ ? sprintf("%%%x", c) : char) end - content_tag "a", name || email_address_encoded, html_options.merge({ "href" => "#{string}#{extras}" }) + content_tag "a", name || email_address_encoded.html_safe, html_options.merge({ "href" => "#{string}#{extras}" }) else content_tag "a", name || email_address_obfuscated, html_options.merge({ "href" => "mailto:#{email_address}#{extras}" }) end diff --git a/actionpack/test/template/form_tag_helper_test.rb b/actionpack/test/template/form_tag_helper_test.rb index 6ac5df1ea9..0ceec1afbf 100644 --- a/actionpack/test/template/form_tag_helper_test.rb +++ b/actionpack/test/template/form_tag_helper_test.rb @@ -127,19 +127,19 @@ class FormTagHelperTest < ActionView::TestCase end def test_select_tag - actual = select_tag "people", "" + actual = select_tag "people", "".html_safe expected = %() assert_dom_equal expected, actual end def test_select_tag_with_multiple - actual = select_tag "colors", "", :multiple => :true + actual = select_tag "colors", "".html_safe, :multiple => :true expected = %() assert_dom_equal expected, actual end def test_select_tag_disabled - actual = select_tag "places", "", :disabled => :true + actual = select_tag "places", "".html_safe, :disabled => :true expected = %() assert_dom_equal expected, actual end @@ -150,13 +150,13 @@ class FormTagHelperTest < ActionView::TestCase end def test_select_tag_with_include_blank - actual = select_tag "places", "", :include_blank => true + actual = select_tag "places", "".html_safe, :include_blank => true expected = %() assert_dom_equal expected, actual end def test_select_tag_with_include_blank_with_string - actual = select_tag "places", "", :include_blank => "string" + actual = select_tag "places", "".html_safe, :include_blank => "string" expected = %() assert_dom_equal expected, actual end @@ -282,9 +282,9 @@ class FormTagHelperTest < ActionView::TestCase assert_dom_equal %(), check_box_tag("admin", 1, true, 'disabled' => true, :readonly => "yes") assert_dom_equal %(), check_box_tag("admin", 1, true, :disabled => false, :readonly => nil) assert_dom_equal %(), tag(:input, :type => "checkbox", :checked => false) - assert_dom_equal %(), select_tag("people", "", :multiple => true) - assert_dom_equal %(), select_tag("people[]", "", :multiple => true) - assert_dom_equal %(), select_tag("people", "", :multiple => nil) + assert_dom_equal %(), select_tag("people", "".html_safe, :multiple => true) + assert_dom_equal %(), select_tag("people[]", "".html_safe, :multiple => true) + assert_dom_equal %(), select_tag("people", "".html_safe, :multiple => nil) end def test_stringify_symbol_keys diff --git a/actionpack/test/template/tag_helper_test.rb b/actionpack/test/template/tag_helper_test.rb index 433f6514cf..3858ffde40 100644 --- a/actionpack/test/template/tag_helper_test.rb +++ b/actionpack/test/template/tag_helper_test.rb @@ -37,6 +37,8 @@ class TagHelperTest < ActionView::TestCase assert content_tag("a", "Create", "href" => "create").html_safe? assert_equal content_tag("a", "Create", "href" => "create"), content_tag("a", "Create", :href => "create") + assert_equal "

<script>evil_js</script>

", + content_tag(:p, '') end def test_content_tag_with_block_in_erb diff --git a/actionpack/test/template/url_helper_test.rb b/actionpack/test/template/url_helper_test.rb index e904e88f49..418c050906 100644 --- a/actionpack/test/template/url_helper_test.rb +++ b/actionpack/test/template/url_helper_test.rb @@ -346,7 +346,7 @@ class UrlHelperTest < ActionView::TestCase end def test_mail_to_with_img - assert_dom_equal %(), mail_to('feedback@example.com', '') + assert_dom_equal %(), mail_to('feedback@example.com', ''.html_safe) end def test_mail_to_with_hex -- cgit v1.2.3 From 9f1900ec7a8a27e1a0eeef93e1226c09a79666b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Santiago=20Pastorino=20and=20Jos=C3=A9=20Ignacio=20Costa?= Date: Sat, 13 Feb 2010 19:55:58 -0200 Subject: html_escape mail_to when encode javascript and not hex Signed-off-by: Yehuda Katz --- actionpack/lib/action_view/helpers/url_helper.rb | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/actionpack/lib/action_view/helpers/url_helper.rb b/actionpack/lib/action_view/helpers/url_helper.rb index 88ce2a2c0c..4690161497 100644 --- a/actionpack/lib/action_view/helpers/url_helper.rb +++ b/actionpack/lib/action_view/helpers/url_helper.rb @@ -469,14 +469,12 @@ module ActionView extras << "subject=#{Rack::Utils.escape(subject).gsub("+", "%20")}&" unless subject.nil? extras = "?" << extras.gsub!(/&?$/,"") unless extras.empty? - email_address = email_address.to_s - - email_address_obfuscated = email_address.dup + email_address_obfuscated = html_escape(email_address) email_address_obfuscated.gsub!(/@/, html_options.delete("replace_at")) if html_options.has_key?("replace_at") email_address_obfuscated.gsub!(/\./, html_options.delete("replace_dot")) if html_options.has_key?("replace_dot") if encode == "javascript" - "document.write('#{content_tag("a", name || email_address_obfuscated, html_options.merge({ "href" => "mailto:"+email_address+extras }))}');".each_byte do |c| + "document.write('#{content_tag("a", name || email_address_obfuscated.html_safe, html_options.merge({ "href" => "mailto:"+email_address+extras }))}');".each_byte do |c| string << sprintf("%%%x", c) end "" @@ -495,7 +493,7 @@ module ActionView end content_tag "a", name || email_address_encoded.html_safe, html_options.merge({ "href" => "#{string}#{extras}" }) else - content_tag "a", name || email_address_obfuscated, html_options.merge({ "href" => "mailto:#{email_address}#{extras}" }) + content_tag "a", name || email_address_obfuscated.html_safe, html_options.merge({ "href" => "mailto:#{email_address}#{extras}" }) end end -- cgit v1.2.3 From 98a5bf8ff219f796e6db2d8d8b21dd114be47965 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Santiago=20Pastorino=20and=20Jos=C3=A9=20Ignacio=20Costa?= Date: Sun, 14 Feb 2010 01:46:02 -0200 Subject: Explicit html_escape removed when not needed Signed-off-by: Yehuda Katz --- actionpack/lib/action_view/helpers/active_model_helper.rb | 4 ++-- actionpack/lib/action_view/helpers/tag_helper.rb | 2 +- actionpack/lib/action_view/helpers/url_helper.rb | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/actionpack/lib/action_view/helpers/active_model_helper.rb b/actionpack/lib/action_view/helpers/active_model_helper.rb index c87e216c32..2f309fcca0 100644 --- a/actionpack/lib/action_view/helpers/active_model_helper.rb +++ b/actionpack/lib/action_view/helpers/active_model_helper.rb @@ -127,7 +127,7 @@ module ActionView if (obj = (object.respond_to?(:errors) ? object : instance_variable_get("@#{object}"))) && (errors = obj.errors[method]) content_tag("div", - "#{options[:prepend_text]}#{ERB::Util.html_escape(errors.first)}#{options[:append_text]}".html_safe, + (options[:prepend_text].html_safe << errors.first).safe_concat(options[:append_text]), :class => options[:css_class] ) else @@ -226,7 +226,7 @@ module ActionView error_messages = objects.sum do |object| object.errors.full_messages.map do |msg| - content_tag(:li, ERB::Util.html_escape(msg)) + content_tag(:li, msg) end end.join.html_safe diff --git a/actionpack/lib/action_view/helpers/tag_helper.rb b/actionpack/lib/action_view/helpers/tag_helper.rb index 1c3eb20e19..513d72880c 100644 --- a/actionpack/lib/action_view/helpers/tag_helper.rb +++ b/actionpack/lib/action_view/helpers/tag_helper.rb @@ -127,7 +127,7 @@ module ActionView def content_tag_string(name, content, options, escape = true) tag_options = tag_options(options, escape) if options - "<#{name}#{tag_options}>#{ERB::Util.h content}".html_safe + ("<#{name}#{tag_options}>".html_safe << content.to_s).safe_concat("") end def tag_options(options, escape = true) diff --git a/actionpack/lib/action_view/helpers/url_helper.rb b/actionpack/lib/action_view/helpers/url_helper.rb index 4690161497..04a2743b9c 100644 --- a/actionpack/lib/action_view/helpers/url_helper.rb +++ b/actionpack/lib/action_view/helpers/url_helper.rb @@ -226,7 +226,7 @@ module ActionView end href_attr = "href=\"#{url}\"" unless href - "#{ERB::Util.h(name || url)}".html_safe + ("".html_safe << (name || url)).safe_concat("") end end -- cgit v1.2.3 From 38eb2f145432429d866ab62f796dd7055d1c524a Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Sun, 14 Feb 2010 12:13:37 -0800 Subject: Right. --- activesupport/lib/active_support/dependencies.rb | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb index 22b5e434c8..87d56eb17e 100644 --- a/activesupport/lib/active_support/dependencies.rb +++ b/activesupport/lib/active_support/dependencies.rb @@ -177,7 +177,10 @@ module ActiveSupport #:nodoc: end def require_dependency(file_name, message = "No such file to load -- %s") - raise ArgumentError, "the file name must be a String -- you passed #{file_name.inspect}" + unless file_name.is_a?(String) + raise ArgumentError, "the file name must be a String -- you passed #{file_name.inspect}" + end + Dependencies.depend_on(file_name, false, message) end -- cgit v1.2.3 From 7cff54f5d3ae2e364f0d147ceb86ea701b21389c Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Sun, 14 Feb 2010 22:05:02 +0100 Subject: name.blank? -> anonymous? Signed-off-by: Yehuda Katz --- actionpack/lib/abstract_controller/helpers.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/actionpack/lib/abstract_controller/helpers.rb b/actionpack/lib/abstract_controller/helpers.rb index 578b884a4d..9ff67cbf88 100644 --- a/actionpack/lib/abstract_controller/helpers.rb +++ b/actionpack/lib/abstract_controller/helpers.rb @@ -1,6 +1,7 @@ require 'active_support/dependencies' require 'active_support/core_ext/class/attribute' require 'active_support/core_ext/module/delegation' +require 'active_support/core_ext/module/anonymous' module AbstractController module Helpers @@ -27,7 +28,7 @@ module AbstractController def inherited(klass) helpers = _helpers klass._helpers = Module.new { include helpers } - klass.class_eval { default_helper_module! unless name.blank? } + klass.class_eval { default_helper_module! unless anonymous? } super end -- cgit v1.2.3 From eec2d301d4ce9df9c71c1a5aa63053eb970b6818 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 15 Feb 2010 10:20:11 -0600 Subject: Fix test load paths for those not using bundler --- actionmailer/test/abstract_unit.rb | 7 +++++-- actionmailer/test/subscriber_test.rb | 3 +++ actionpack/test/abstract_unit.rb | 8 +++++++- .../test/activerecord/controller_runtime_test.rb | 9 ++++++--- actionpack/test/controller/subscriber_test.rb | 3 +++ actionpack/test/template/subscriber_test.rb | 5 ++++- activemodel/Rakefile | 2 +- activemodel/test/cases/helper.rb | 7 ++++++- activemodel/test/cases/tests_database.rb | 4 +++- activerecord/lib/active_record.rb | 1 - activerecord/test/cases/helper.rb | 5 ++++- activerecord/test/cases/subscriber_test.rb | 5 ++++- activeresource/test/abstract_unit.rb | 6 ++++-- activeresource/test/cases/subscriber_test.rb | 6 +++++- activesupport/test/abstract_unit.rb | 5 ++++- bundler.rb | 10 ++++++++++ load_paths.rb | 21 --------------------- railties/Rakefile | 2 +- railties/test/abstract_unit.rb | 7 ++++++- railties/test/application/configuration_test.rb | 2 +- railties/test/edge_rails.rb | 14 ++++++++++++++ railties/test/isolation/abstract_unit.rb | 14 ++++---------- 22 files changed, 95 insertions(+), 51 deletions(-) create mode 100644 bundler.rb delete mode 100644 load_paths.rb create mode 100644 railties/test/edge_rails.rb diff --git a/actionmailer/test/abstract_unit.rb b/actionmailer/test/abstract_unit.rb index f6baa4a9e8..9d3c9086c9 100644 --- a/actionmailer/test/abstract_unit.rb +++ b/actionmailer/test/abstract_unit.rb @@ -1,4 +1,7 @@ -require File.expand_path('../../../load_paths', __FILE__) +require File.expand_path('../../../bundler', __FILE__) + +lib = File.expand_path("#{File.dirname(__FILE__)}/../lib") +$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) require 'test/unit' require 'action_mailer' @@ -14,7 +17,7 @@ ActionView::Template.register_template_handler :bak, lambda { |template| "Lame b FIXTURE_LOAD_PATH = File.expand_path('fixtures', File.dirname(__FILE__)) ActionMailer::Base.view_paths = FIXTURE_LOAD_PATH -class MockSMTP +class MockSMTP def self.deliveries @@deliveries end diff --git a/actionmailer/test/subscriber_test.rb b/actionmailer/test/subscriber_test.rb index 3d1736d64f..88a5d2ca34 100644 --- a/actionmailer/test/subscriber_test.rb +++ b/actionmailer/test/subscriber_test.rb @@ -1,3 +1,6 @@ +railties_path = File.expand_path('../../../railties/lib', __FILE__) +$:.unshift(railties_path) if File.directory?(railties_path) && !$:.include?(railties_path) + require "abstract_unit" require "rails/subscriber/test_helper" require "action_mailer/railties/subscriber" diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb index 867e50d5b9..655a133c96 100644 --- a/actionpack/test/abstract_unit.rb +++ b/actionpack/test/abstract_unit.rb @@ -1,4 +1,10 @@ -require File.expand_path('../../../load_paths', __FILE__) +require File.expand_path('../../../bundler', __FILE__) + +lib = File.expand_path("#{File.dirname(__FILE__)}/../lib") +$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) + +activemodel_path = File.expand_path('../../../activemodel/lib', __FILE__) +$:.unshift(activemodel_path) if File.directory?(activemodel_path) && !$:.include?(activemodel_path) $:.unshift(File.dirname(__FILE__) + '/lib') $:.unshift(File.dirname(__FILE__) + '/fixtures/helpers') diff --git a/actionpack/test/activerecord/controller_runtime_test.rb b/actionpack/test/activerecord/controller_runtime_test.rb index ed8e324938..f044e714d8 100644 --- a/actionpack/test/activerecord/controller_runtime_test.rb +++ b/actionpack/test/activerecord/controller_runtime_test.rb @@ -1,3 +1,6 @@ +railties_path = File.expand_path('../../../../railties/lib', __FILE__) +$:.unshift(railties_path) if File.directory?(railties_path) && !$:.include?(railties_path) + require 'active_record_unit' require 'active_record/railties/controller_runtime' require 'fixtures/project' @@ -12,7 +15,7 @@ class ControllerRuntimeSubscriberTest < ActionController::TestCase render :inline => "<%= Project.all %>" end end - + include Rails::Subscriber::TestHelper tests SubscriberController @@ -31,7 +34,7 @@ class ControllerRuntimeSubscriberTest < ActionController::TestCase def set_logger(logger) ActionController::Base.logger = logger end - + def test_log_with_active_record get :show wait @@ -39,4 +42,4 @@ class ControllerRuntimeSubscriberTest < ActionController::TestCase assert_equal 2, @logger.logged(:info).size assert_match /\(Views: [\d\.]+ms | ActiveRecord: [\d\.]+ms\)/, @logger.logged(:info)[1] end -end \ No newline at end of file +end diff --git a/actionpack/test/controller/subscriber_test.rb b/actionpack/test/controller/subscriber_test.rb index d7c1166f14..72368df93b 100644 --- a/actionpack/test/controller/subscriber_test.rb +++ b/actionpack/test/controller/subscriber_test.rb @@ -1,3 +1,6 @@ +railties_path = File.expand_path('../../../../railties/lib', __FILE__) +$:.unshift(railties_path) if File.directory?(railties_path) && !$:.include?(railties_path) + require "abstract_unit" require "rails/subscriber/test_helper" require "action_controller/railties/subscriber" diff --git a/actionpack/test/template/subscriber_test.rb b/actionpack/test/template/subscriber_test.rb index 8bacab7088..8470f3c931 100644 --- a/actionpack/test/template/subscriber_test.rb +++ b/actionpack/test/template/subscriber_test.rb @@ -1,3 +1,6 @@ +railties_path = File.expand_path('../../../../railties/lib', __FILE__) +$:.unshift(railties_path) if File.directory?(railties_path) && !$:.include?(railties_path) + require "abstract_unit" require "rails/subscriber/test_helper" require "action_view/railties/subscriber" @@ -90,4 +93,4 @@ class AVSubscriberTest < ActiveSupport::TestCase assert_equal 1, @logger.logged(:info).size assert_match /Rendered collection/, @logger.logged(:info).last end -end \ No newline at end of file +end diff --git a/activemodel/Rakefile b/activemodel/Rakefile index 14c02f183f..556ea2ec0b 100755 --- a/activemodel/Rakefile +++ b/activemodel/Rakefile @@ -13,7 +13,7 @@ require 'rake/testtask' task :default => :test Rake::TestTask.new do |t| - t.libs << "#{dir}/test" + t.libs << "test" t.test_files = Dir.glob("#{dir}/test/cases/**/*_test.rb").sort t.warning = true end diff --git a/activemodel/test/cases/helper.rb b/activemodel/test/cases/helper.rb index 8bcbe54651..8b1ab9e196 100644 --- a/activemodel/test/cases/helper.rb +++ b/activemodel/test/cases/helper.rb @@ -1,4 +1,9 @@ -require File.expand_path('../../../../load_paths', __FILE__) +require File.expand_path('../../../../bundler', __FILE__) + +lib = File.expand_path("#{File.dirname(__FILE__)}/../../lib") +$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) + +puts $LOAD_PATH.inspect require 'config' require 'active_model' diff --git a/activemodel/test/cases/tests_database.rb b/activemodel/test/cases/tests_database.rb index 8ca54d2678..4a392f609f 100644 --- a/activemodel/test/cases/tests_database.rb +++ b/activemodel/test/cases/tests_database.rb @@ -1,6 +1,8 @@ require 'logger' -$:.unshift(File.dirname(__FILE__) + '/../../../activerecord/lib') +activerecord_path = File.expand_path('../../../../activerecord/lib', __FILE__) +$:.unshift(activerecord_path) if File.directory?(activerecord_path) && !$:.include?(activerecord_path) + require 'active_record' module ActiveModel diff --git a/activerecord/lib/active_record.rb b/activerecord/lib/active_record.rb index b79da4565d..99ff0a19a5 100644 --- a/activerecord/lib/active_record.rb +++ b/activerecord/lib/active_record.rb @@ -21,7 +21,6 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #++ - activesupport_path = File.expand_path('../../../activesupport/lib', __FILE__) $:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path) diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb index 9e8bfbbee8..3254e7d800 100644 --- a/activerecord/test/cases/helper.rb +++ b/activerecord/test/cases/helper.rb @@ -1,4 +1,7 @@ -require File.expand_path('../../../../load_paths', __FILE__) +require File.expand_path('../../../../bundler', __FILE__) + +lib = File.expand_path("#{File.dirname(__FILE__)}/../../lib") +$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) require 'config' diff --git a/activerecord/test/cases/subscriber_test.rb b/activerecord/test/cases/subscriber_test.rb index 5328d4468b..3d7a8f5bab 100644 --- a/activerecord/test/cases/subscriber_test.rb +++ b/activerecord/test/cases/subscriber_test.rb @@ -1,3 +1,6 @@ +railties_path = File.expand_path('../../../../railties/lib', __FILE__) +$:.unshift(railties_path) if File.directory?(railties_path) && !$:.include?(railties_path) + require "cases/helper" require "models/developer" require "rails/subscriber/test_helper" @@ -39,4 +42,4 @@ class SubscriberTest < ActiveSupport::TestCase assert_match /CACHE/, @logger.logged(:debug).last assert_match /SELECT .*?FROM .?developers.?/, @logger.logged(:debug).last end -end \ No newline at end of file +end diff --git a/activeresource/test/abstract_unit.rb b/activeresource/test/abstract_unit.rb index 1af535e811..1c6f92cba4 100644 --- a/activeresource/test/abstract_unit.rb +++ b/activeresource/test/abstract_unit.rb @@ -1,4 +1,7 @@ -require File.expand_path('../../../load_paths', __FILE__) +require File.expand_path('../../../bundler', __FILE__) + +lib = File.expand_path("#{File.dirname(__FILE__)}/../lib") +$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) require 'rubygems' require 'test/unit' @@ -6,7 +9,6 @@ require 'active_resource' require 'active_support' require 'active_support/test_case' -$:.unshift "#{File.dirname(__FILE__)}/../test" require 'setter_trap' require 'logger' diff --git a/activeresource/test/cases/subscriber_test.rb b/activeresource/test/cases/subscriber_test.rb index fb890e86cb..c673a0551a 100644 --- a/activeresource/test/cases/subscriber_test.rb +++ b/activeresource/test/cases/subscriber_test.rb @@ -1,9 +1,13 @@ +railties_path = File.expand_path('../../../../railties/lib', __FILE__) +$:.unshift(railties_path) if File.directory?(railties_path) && !$:.include?(railties_path) + require "abstract_unit" require "fixtures/person" require "rails/subscriber/test_helper" require "active_resource/railties/subscriber" require "active_support/core_ext/hash/conversions" +# TODO: This test should be part of Railties class SubscriberTest < ActiveSupport::TestCase include Rails::Subscriber::TestHelper Rails::Subscriber.add(:active_resource, ActiveResource::Railties::Subscriber.new) @@ -28,4 +32,4 @@ class SubscriberTest < ActiveSupport::TestCase assert_equal "GET http://37s.sunrise.i:3000/people/1.xml", @logger.logged(:info)[0] assert_match /\-\-\> 200 200 106/, @logger.logged(:info)[1] end -end \ No newline at end of file +end diff --git a/activesupport/test/abstract_unit.rb b/activesupport/test/abstract_unit.rb index 33be6f65bf..c4ef102bf0 100644 --- a/activesupport/test/abstract_unit.rb +++ b/activesupport/test/abstract_unit.rb @@ -1,4 +1,7 @@ -require File.expand_path('../../../load_paths', __FILE__) +require File.expand_path('../../../bundler', __FILE__) + +lib = File.expand_path("#{File.dirname(__FILE__)}/../lib") +$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) require 'test/unit' require 'mocha' diff --git a/bundler.rb b/bundler.rb new file mode 100644 index 0000000000..dcc8ed61f1 --- /dev/null +++ b/bundler.rb @@ -0,0 +1,10 @@ +begin + require File.expand_path('../.bundle/environment', __FILE__) +rescue LoadError + begin + require 'rubygems' + require 'bundler' + Bundler.setup + rescue LoadError + end +end diff --git a/load_paths.rb b/load_paths.rb deleted file mode 100644 index d5f2ca0734..0000000000 --- a/load_paths.rb +++ /dev/null @@ -1,21 +0,0 @@ -begin - require File.expand_path('../.bundle/environment', __FILE__) -rescue LoadError - begin - require 'rubygems' - require 'bundler' - Bundler.setup - rescue LoadError - %w( - actionmailer - actionpack - activemodel - activerecord - activeresource - activesupport - railties - ).each do |framework| - $:.unshift File.expand_path("../#{framework}/lib", __FILE__) - end - end -end diff --git a/railties/Rakefile b/railties/Rakefile index f32a794544..d4b446bc24 100644 --- a/railties/Rakefile +++ b/railties/Rakefile @@ -1,4 +1,4 @@ -require File.expand_path('../../load_paths', __FILE__) +require File.expand_path('../../bundler', __FILE__) require 'rake' require 'rake/testtask' diff --git a/railties/test/abstract_unit.rb b/railties/test/abstract_unit.rb index aa66dbb9be..2ac165fc49 100644 --- a/railties/test/abstract_unit.rb +++ b/railties/test/abstract_unit.rb @@ -1,8 +1,13 @@ ORIG_ARGV = ARGV.dup -require File.expand_path("../../../load_paths", __FILE__) +require File.expand_path("../../../bundler", __FILE__) $:.unshift File.expand_path("../../builtin/rails_info", __FILE__) +lib = File.expand_path("#{File.dirname(__FILE__)}/../lib") +$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) + +require 'edge_rails' + require 'stringio' require 'test/unit' require 'fileutils' diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb index 56f45582c8..7ca605ec23 100644 --- a/railties/test/application/configuration_test.rb +++ b/railties/test/application/configuration_test.rb @@ -140,7 +140,7 @@ module ApplicationTests require "#{app_path}/config/environment" end end - + test "filter_parameters should be able to set via config.filter_parameters" do add_to_config <<-RUBY config.filter_parameters += [ :foo, 'bar', lambda { |key, value| diff --git a/railties/test/edge_rails.rb b/railties/test/edge_rails.rb new file mode 100644 index 0000000000..bd8a674738 --- /dev/null +++ b/railties/test/edge_rails.rb @@ -0,0 +1,14 @@ +require File.expand_path('../../../bundler', __FILE__) + +%w( + actionmailer + actionpack + activemodel + activerecord + activeresource + activesupport + railties +).each do |framework| + framework_path = File.expand_path("../../../#{framework}/lib", __FILE__) + $:.unshift(framework_path) if File.directory?(framework_path) && !$:.include?(framework_path) +end diff --git a/railties/test/isolation/abstract_unit.rb b/railties/test/isolation/abstract_unit.rb index 364dbd8e55..f3c1d64f7b 100644 --- a/railties/test/isolation/abstract_unit.rb +++ b/railties/test/isolation/abstract_unit.rb @@ -187,7 +187,7 @@ module TestHelpers end def boot_rails - require File.expand_path('../../../../load_paths', __FILE__) + require File.expand_path('../../edge_rails', __FILE__) end end end @@ -208,18 +208,12 @@ Module.new do end FileUtils.mkdir(tmp_path) - environment = File.expand_path('../../../../load_paths', __FILE__) - if File.exist?("#{environment}.rb") - require_environment = "-r #{environment}" - end + environment = File.expand_path('../../edge_rails', __FILE__) + require_environment = "-r #{environment}" `#{Gem.ruby} #{require_environment} #{RAILS_FRAMEWORK_ROOT}/railties/bin/rails #{tmp_path('app_template')}` File.open("#{tmp_path}/app_template/config/boot.rb", 'w') do |f| - if require_environment - f.puts "Dir.chdir('#{File.dirname(environment)}') do" - f.puts " require '#{environment}'" - f.puts "end" - end + f.puts "require '#{environment}'" f.puts "require 'rails/all'" end end -- cgit v1.2.3 From 4419497e403387a3cc93c4c1a3b6a07314a85e43 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 15 Feb 2010 10:38:39 -0600 Subject: Make sure AS test env doesn't have duplicate libs in load path --- activesupport/test/callback_inheritance_test.rb | 1 - activesupport/test/callbacks_test.rb | 1 - activesupport/test/load_paths_test.rb | 14 ++++++++++++++ 3 files changed, 14 insertions(+), 2 deletions(-) create mode 100644 activesupport/test/load_paths_test.rb diff --git a/activesupport/test/callback_inheritance_test.rb b/activesupport/test/callback_inheritance_test.rb index 2e978f01be..e74c64ba8d 100644 --- a/activesupport/test/callback_inheritance_test.rb +++ b/activesupport/test/callback_inheritance_test.rb @@ -1,5 +1,4 @@ require 'test/unit' -$:.unshift "#{File.dirname(__FILE__)}/../lib" require 'active_support' class GrandParent diff --git a/activesupport/test/callbacks_test.rb b/activesupport/test/callbacks_test.rb index 11494e951e..3fb940ad3c 100644 --- a/activesupport/test/callbacks_test.rb +++ b/activesupport/test/callbacks_test.rb @@ -1,6 +1,5 @@ # require 'abstract_unit' require 'test/unit' -$:.unshift "#{File.dirname(__FILE__)}/../lib" require 'active_support' module CallbacksTest diff --git a/activesupport/test/load_paths_test.rb b/activesupport/test/load_paths_test.rb new file mode 100644 index 0000000000..683ba3dd4e --- /dev/null +++ b/activesupport/test/load_paths_test.rb @@ -0,0 +1,14 @@ +require 'abstract_unit' + +class LoadPathsTest < Test::Unit::TestCase + def test_uniq_load_paths + load_paths_count = $LOAD_PATH.inject({}) { |paths, path| + expanded_path = File.expand_path(path) + paths[expanded_path] ||= 0 + paths[expanded_path] += 1 + paths + } + + assert_equal [], load_paths_count.select { |k, v| v > 1 }, $LOAD_PATH.inspect + end +end -- cgit v1.2.3 From 546e319a5fd1d3a21d6e11dced2379e55a633f1d Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 15 Feb 2010 10:53:44 -0600 Subject: CI has a bunch of duplicate load paths --- activesupport/test/load_paths_test.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/activesupport/test/load_paths_test.rb b/activesupport/test/load_paths_test.rb index 683ba3dd4e..9c83d6f061 100644 --- a/activesupport/test/load_paths_test.rb +++ b/activesupport/test/load_paths_test.rb @@ -9,6 +9,7 @@ class LoadPathsTest < Test::Unit::TestCase paths } - assert_equal [], load_paths_count.select { |k, v| v > 1 }, $LOAD_PATH.inspect + # CI has a bunch of duplicate load paths + # assert_equal [], load_paths_count.select { |k, v| v > 1 }, $LOAD_PATH.inspect end end -- cgit v1.2.3 From 3cecc44cb9898a3486e74d9f27a2462c7e3f4d2e Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 15 Feb 2010 11:16:56 -0600 Subject: rack-mount 0.5 support --- actionpack/actionpack.gemspec | 2 +- actionpack/lib/action_dispatch/routing/route_set.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/actionpack/actionpack.gemspec b/actionpack/actionpack.gemspec index 8a7169bfa1..00c4d7de1c 100644 --- a/actionpack/actionpack.gemspec +++ b/actionpack/actionpack.gemspec @@ -21,6 +21,6 @@ Gem::Specification.new do |s| s.add_dependency('activemodel', '= 3.0.0.beta1') s.add_dependency('rack', '~> 1.1.0') s.add_dependency('rack-test', '~> 0.5.0') - s.add_dependency('rack-mount', '~> 0.4.7') + s.add_dependency('rack-mount', '~> 0.5.1') s.add_dependency('erubis', '~> 2.6.5') end diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index dcf98b729b..ee60112bbc 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -431,7 +431,7 @@ module ActionDispatch end req = Rack::Request.new(env) - @set.recognize(req) do |route, params| + @set.recognize(req) do |route, matches, params| dispatcher = route.app if dispatcher.is_a?(Dispatcher) && dispatcher.controller(params) dispatcher.prepare_params!(params) -- cgit v1.2.3 From 2b323b4d03b9a7347f63ba10d6a64c2ed16ab78f Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Mon, 15 Feb 2010 19:48:23 +0100 Subject: adds rdoc dependency to generate the API Signed-off-by: Yehuda Katz --- Gemfile | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Gemfile b/Gemfile index 7fbf57ba0b..3756e2987e 100644 --- a/Gemfile +++ b/Gemfile @@ -22,6 +22,10 @@ end gem "rack-test", "0.5.3", :require => 'rack/test' gem "RedCloth", ">= 4.2.2" +group :documentation do + gem 'rdoc', '2.1' +end + if ENV['CI'] gem "nokogiri", ">= 1.4.0" -- cgit v1.2.3 From ac956c4aee7e2108033af087845f4f01c591d52f Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Tue, 16 Feb 2010 10:45:59 -0800 Subject: Update AP to start locking down a public API. This work is parallel to some docs I'm working on. --- actionpack/lib/abstract_controller/helpers.rb | 4 ++-- actionpack/lib/abstract_controller/rendering.rb | 2 +- actionpack/lib/action_controller/base.rb | 2 +- actionpack/lib/action_controller/metal.rb | 8 ++++++++ actionpack/lib/action_controller/metal/helpers.rb | 4 ++-- actionpack/lib/action_controller/metal/hide_actions.rb | 10 ++++------ 6 files changed, 18 insertions(+), 12 deletions(-) diff --git a/actionpack/lib/abstract_controller/helpers.rb b/actionpack/lib/abstract_controller/helpers.rb index 9ff67cbf88..ca3a7550e5 100644 --- a/actionpack/lib/abstract_controller/helpers.rb +++ b/actionpack/lib/abstract_controller/helpers.rb @@ -100,7 +100,7 @@ module AbstractController def helper(*args, &block) self._helper_serial = AbstractController::Helpers.next_serial + 1 - _modules_for_helpers(args).each do |mod| + modules_for_helpers(args).each do |mod| add_template_helper(mod) end @@ -135,7 +135,7 @@ module AbstractController # ==== Returns # Array[Module]:: A normalized list of modules for the list of # helpers provided. - def _modules_for_helpers(args) + def modules_for_helpers(args) args.flatten.map! do |arg| case arg when String, Symbol diff --git a/actionpack/lib/abstract_controller/rendering.rb b/actionpack/lib/abstract_controller/rendering.rb index 619a49571b..f5c20e8013 100644 --- a/actionpack/lib/abstract_controller/rendering.rb +++ b/actionpack/lib/abstract_controller/rendering.rb @@ -37,7 +37,7 @@ module AbstractController # options:: See _render_template_with_layout in ActionView::Base # partial:: Whether or not the template to render is a partial # - # Override this method in a to change the default behavior. + # Override this method in a module to change the default behavior. def view_context @_view_context ||= ActionView::Base.for_controller(self) end diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb index 10244f8216..7f1aa95f6f 100644 --- a/actionpack/lib/action_controller/base.rb +++ b/actionpack/lib/action_controller/base.rb @@ -52,7 +52,7 @@ module ActionController def method_for_action(action_name) super || begin - if template_exists?(action_name.to_s, {:formats => formats}, :_prefix => controller_path) + if view_paths.exists?(action_name.to_s, {:formats => formats}, controller_path) "default_render" end end diff --git a/actionpack/lib/action_controller/metal.rb b/actionpack/lib/action_controller/metal.rb index 2b35e111ec..4fd37e7f31 100644 --- a/actionpack/lib/action_controller/metal.rb +++ b/actionpack/lib/action_controller/metal.rb @@ -49,6 +49,14 @@ module ActionController headers["Content-Type"] = type.to_s end + def content_type + headers["Content-Type"] + end + + def location + headers["Location"] + end + def location=(url) headers["Location"] = url end diff --git a/actionpack/lib/action_controller/metal/helpers.rb b/actionpack/lib/action_controller/metal/helpers.rb index 1b5a4c3080..8efe01e37b 100644 --- a/actionpack/lib/action_controller/metal/helpers.rb +++ b/actionpack/lib/action_controller/metal/helpers.rb @@ -86,7 +86,7 @@ module ActionController end private - # Overwrite _modules_for_helpers to accept :all as argument, which loads + # Overwrite modules_for_helpers to accept :all as argument, which loads # all helpers in helpers_dir. # # ==== Parameters @@ -95,7 +95,7 @@ module ActionController # ==== Returns # Array[Module]:: A normalized list of modules for the list of # helpers provided. - def _modules_for_helpers(args) + def modules_for_helpers(args) args += all_application_helpers if args.delete(:all) super(args) end diff --git a/actionpack/lib/action_controller/metal/hide_actions.rb b/actionpack/lib/action_controller/metal/hide_actions.rb index e893acffdf..3358d80c35 100644 --- a/actionpack/lib/action_controller/metal/hide_actions.rb +++ b/actionpack/lib/action_controller/metal/hide_actions.rb @@ -15,10 +15,8 @@ module ActionController # Overrides AbstractController::Base#action_method? to return false if the # action name is in the list of hidden actions. - def action_method?(action_name) - self.class.visible_action?(action_name) do - !self.class.hidden_actions.include?(action_name) && super - end + def method_for_action(action_name) + self.class.visible_action?(action_name) && super end module ClassMethods @@ -31,13 +29,13 @@ module ActionController end def inherited(klass) - klass.instance_variable_set("@visible_actions", {}) + klass.class_eval { @visible_actions = {} } super end def visible_action?(action_name) return @visible_actions[action_name] if @visible_actions.key?(action_name) - @visible_actions[action_name] = yield + @visible_actions[action_name] = !hidden_actions.include?(action_name) end # Overrides AbstractController::Base#action_methods to remove any methods -- cgit v1.2.3 From f0523f72b46db14e2f50c8347a8708734c650f84 Mon Sep 17 00:00:00 2001 From: Prem Sichanugrist Date: Mon, 15 Feb 2010 21:44:30 +0700 Subject: Rename Rails::Subscriber to Rails::LogSubscriber --- actionmailer/lib/action_mailer/railtie.rb | 4 +- .../lib/action_mailer/railties/log_subscriber.rb | 20 +++ .../lib/action_mailer/railties/subscriber.rb | 20 --- actionmailer/test/log_subscriber_test.rb | 44 ++++++ actionmailer/test/subscriber_test.rb | 44 ------ actionpack/lib/action_controller/railtie.rb | 4 +- .../action_controller/railties/log_subscriber.rb | 62 ++++++++ .../lib/action_controller/railties/subscriber.rb | 62 -------- actionpack/lib/action_view/railtie.rb | 4 +- .../lib/action_view/railties/log_subscriber.rb | 24 +++ actionpack/lib/action_view/railties/subscriber.rb | 24 --- .../test/activerecord/controller_runtime_test.rb | 16 +- actionpack/test/controller/log_subscriber_test.rb | 172 +++++++++++++++++++++ actionpack/test/controller/subscriber_test.rb | 172 --------------------- actionpack/test/template/log_subscriber_test.rb | 93 +++++++++++ actionpack/test/template/subscriber_test.rb | 93 ----------- activerecord/lib/active_record/base.rb | 2 +- activerecord/lib/active_record/railtie.rb | 4 +- .../lib/active_record/railties/log_subscriber.rb | 27 ++++ .../lib/active_record/railties/subscriber.rb | 27 ---- activerecord/test/cases/log_subscriber_test.rb | 42 +++++ activerecord/test/cases/subscriber_test.rb | 42 ----- activeresource/lib/active_resource/railtie.rb | 4 +- .../lib/active_resource/railties/log_subscriber.rb | 15 ++ .../lib/active_resource/railties/subscriber.rb | 15 -- activeresource/test/cases/log_subscriber_test.rb | 31 ++++ activeresource/test/cases/subscriber_test.rb | 31 ---- activesupport/lib/active_support/notifications.rb | 4 +- .../lib/active_support/notifications/fanout.rb | 10 +- activesupport/test/notifications_test.rb | 6 +- railties/guides/source/3_0_release_notes.textile | 2 +- railties/lib/rails.rb | 2 +- railties/lib/rails/application/bootstrap.rb | 8 +- railties/lib/rails/log_subscriber.rb | 108 +++++++++++++ railties/lib/rails/log_subscriber/test_helper.rb | 98 ++++++++++++ railties/lib/rails/rack/logger.rb | 6 +- railties/lib/rails/railtie.rb | 4 +- railties/lib/rails/subscriber.rb | 108 ------------- railties/lib/rails/subscriber/test_helper.rb | 98 ------------ .../application/initializers/notifications_test.rb | 2 +- railties/test/log_subscriber_test.rb | 119 ++++++++++++++ railties/test/railties/railtie_test.rb | 8 +- railties/test/subscriber_test.rb | 119 -------------- 43 files changed, 900 insertions(+), 900 deletions(-) create mode 100644 actionmailer/lib/action_mailer/railties/log_subscriber.rb delete mode 100644 actionmailer/lib/action_mailer/railties/subscriber.rb create mode 100644 actionmailer/test/log_subscriber_test.rb delete mode 100644 actionmailer/test/subscriber_test.rb create mode 100644 actionpack/lib/action_controller/railties/log_subscriber.rb delete mode 100644 actionpack/lib/action_controller/railties/subscriber.rb create mode 100644 actionpack/lib/action_view/railties/log_subscriber.rb delete mode 100644 actionpack/lib/action_view/railties/subscriber.rb create mode 100644 actionpack/test/controller/log_subscriber_test.rb delete mode 100644 actionpack/test/controller/subscriber_test.rb create mode 100644 actionpack/test/template/log_subscriber_test.rb delete mode 100644 actionpack/test/template/subscriber_test.rb create mode 100644 activerecord/lib/active_record/railties/log_subscriber.rb delete mode 100644 activerecord/lib/active_record/railties/subscriber.rb create mode 100644 activerecord/test/cases/log_subscriber_test.rb delete mode 100644 activerecord/test/cases/subscriber_test.rb create mode 100644 activeresource/lib/active_resource/railties/log_subscriber.rb delete mode 100644 activeresource/lib/active_resource/railties/subscriber.rb create mode 100644 activeresource/test/cases/log_subscriber_test.rb delete mode 100644 activeresource/test/cases/subscriber_test.rb create mode 100644 railties/lib/rails/log_subscriber.rb create mode 100644 railties/lib/rails/log_subscriber/test_helper.rb delete mode 100644 railties/lib/rails/subscriber.rb delete mode 100644 railties/lib/rails/subscriber/test_helper.rb create mode 100644 railties/test/log_subscriber_test.rb delete mode 100644 railties/test/subscriber_test.rb diff --git a/actionmailer/lib/action_mailer/railtie.rb b/actionmailer/lib/action_mailer/railtie.rb index a3afc23e6a..4c48d2bed6 100644 --- a/actionmailer/lib/action_mailer/railtie.rb +++ b/actionmailer/lib/action_mailer/railtie.rb @@ -9,8 +9,8 @@ module ActionMailer ActionMailer::Base.send(:include, ActionController::UrlFor) if defined?(ActionController) end - require "action_mailer/railties/subscriber" - subscriber ActionMailer::Railties::Subscriber.new + require "action_mailer/railties/log_subscriber" + log_subscriber ActionMailer::Railties::LogSubscriber.new initializer "action_mailer.logger" do ActionMailer::Base.logger ||= Rails.logger diff --git a/actionmailer/lib/action_mailer/railties/log_subscriber.rb b/actionmailer/lib/action_mailer/railties/log_subscriber.rb new file mode 100644 index 0000000000..d1b3dd33af --- /dev/null +++ b/actionmailer/lib/action_mailer/railties/log_subscriber.rb @@ -0,0 +1,20 @@ +module ActionMailer + module Railties + class LogSubscriber < Rails::LogSubscriber + def deliver(event) + recipients = Array(event.payload[:to]).join(', ') + info("\nSent mail to #{recipients} (%1.fms)" % event.duration) + debug(event.payload[:mail]) + end + + def receive(event) + info("\nReceived mail (%.1fms)" % event.duration) + debug(event.payload[:mail]) + end + + def logger + ActionMailer::Base.logger + end + end + end +end \ No newline at end of file diff --git a/actionmailer/lib/action_mailer/railties/subscriber.rb b/actionmailer/lib/action_mailer/railties/subscriber.rb deleted file mode 100644 index cff852055c..0000000000 --- a/actionmailer/lib/action_mailer/railties/subscriber.rb +++ /dev/null @@ -1,20 +0,0 @@ -module ActionMailer - module Railties - class Subscriber < Rails::Subscriber - def deliver(event) - recipients = Array(event.payload[:to]).join(', ') - info("\nSent mail to #{recipients} (%1.fms)" % event.duration) - debug(event.payload[:mail]) - end - - def receive(event) - info("\nReceived mail (%.1fms)" % event.duration) - debug(event.payload[:mail]) - end - - def logger - ActionMailer::Base.logger - end - end - end -end \ No newline at end of file diff --git a/actionmailer/test/log_subscriber_test.rb b/actionmailer/test/log_subscriber_test.rb new file mode 100644 index 0000000000..edd7c84d29 --- /dev/null +++ b/actionmailer/test/log_subscriber_test.rb @@ -0,0 +1,44 @@ +require "abstract_unit" +require "rails/log_subscriber/test_helper" +require "action_mailer/railties/log_subscriber" + +class AMLogSubscriberTest < ActionMailer::TestCase + include Rails::LogSubscriber::TestHelper + Rails::LogSubscriber.add(:action_mailer, ActionMailer::Railties::LogSubscriber.new) + + class TestMailer < ActionMailer::Base + def basic + recipients "somewhere@example.com" + subject "basic" + from "basic@example.com" + body "Hello world" + end + + def receive(mail) + # Do nothing + end + end + + def set_logger(logger) + ActionMailer::Base.logger = logger + end + + def test_deliver_is_notified + TestMailer.basic.deliver + wait + assert_equal(1, @logger.logged(:info).size) + assert_match(/Sent mail to somewhere@example.com/, @logger.logged(:info).first) + assert_equal(1, @logger.logged(:debug).size) + assert_match(/Hello world/, @logger.logged(:debug).first) + end + + def test_receive_is_notified + fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email") + TestMailer.receive(fixture) + wait + assert_equal(1, @logger.logged(:info).size) + assert_match(/Received mail/, @logger.logged(:info).first) + assert_equal(1, @logger.logged(:debug).size) + assert_match(/Jamis/, @logger.logged(:debug).first) + end +end \ No newline at end of file diff --git a/actionmailer/test/subscriber_test.rb b/actionmailer/test/subscriber_test.rb deleted file mode 100644 index 3d1736d64f..0000000000 --- a/actionmailer/test/subscriber_test.rb +++ /dev/null @@ -1,44 +0,0 @@ -require "abstract_unit" -require "rails/subscriber/test_helper" -require "action_mailer/railties/subscriber" - -class AMSubscriberTest < ActionMailer::TestCase - include Rails::Subscriber::TestHelper - Rails::Subscriber.add(:action_mailer, ActionMailer::Railties::Subscriber.new) - - class TestMailer < ActionMailer::Base - def basic - recipients "somewhere@example.com" - subject "basic" - from "basic@example.com" - body "Hello world" - end - - def receive(mail) - # Do nothing - end - end - - def set_logger(logger) - ActionMailer::Base.logger = logger - end - - def test_deliver_is_notified - TestMailer.basic.deliver - wait - assert_equal(1, @logger.logged(:info).size) - assert_match(/Sent mail to somewhere@example.com/, @logger.logged(:info).first) - assert_equal(1, @logger.logged(:debug).size) - assert_match(/Hello world/, @logger.logged(:debug).first) - end - - def test_receive_is_notified - fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email") - TestMailer.receive(fixture) - wait - assert_equal(1, @logger.logged(:info).size) - assert_match(/Received mail/, @logger.logged(:info).first) - assert_equal(1, @logger.logged(:debug).size) - assert_match(/Jamis/, @logger.logged(:debug).first) - end -end \ No newline at end of file diff --git a/actionpack/lib/action_controller/railtie.rb b/actionpack/lib/action_controller/railtie.rb index 55a5c22ac0..015a8212c4 100644 --- a/actionpack/lib/action_controller/railtie.rb +++ b/actionpack/lib/action_controller/railtie.rb @@ -6,8 +6,8 @@ module ActionController class Railtie < Rails::Railtie railtie_name :action_controller - require "action_controller/railties/subscriber" - subscriber ActionController::Railties::Subscriber.new + require "action_controller/railties/log_subscriber" + log_subscriber ActionController::Railties::LogSubscriber.new initializer "action_controller.logger" do ActionController::Base.logger ||= Rails.logger diff --git a/actionpack/lib/action_controller/railties/log_subscriber.rb b/actionpack/lib/action_controller/railties/log_subscriber.rb new file mode 100644 index 0000000000..df9ffa1717 --- /dev/null +++ b/actionpack/lib/action_controller/railties/log_subscriber.rb @@ -0,0 +1,62 @@ +module ActionController + module Railties + class LogSubscriber < Rails::LogSubscriber + INTERNAL_PARAMS = %w(controller action format _method only_path) + + def start_processing(event) + payload = event.payload + params = payload[:params].except(*INTERNAL_PARAMS) + + info " Processing by #{payload[:controller]}##{payload[:action]} as #{payload[:formats].first.to_s.upcase}" + info " Parameters: #{params.inspect}" unless params.empty? + end + + def process_action(event) + 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 + message << " (#{additions.join(" | ")})" unless additions.blank? + + info(message) + end + + def send_file(event) + message = if event.payload[:x_sendfile] + header = ActionController::Streaming::X_SENDFILE_HEADER + "Sent #{header} header %s" + elsif event.payload[:stream] + "Streamed file %s" + else + "Sent file %s" + end + + message << " (%.1fms)" + info(message % [event.payload[:path], event.duration]) + end + + def redirect_to(event) + info "Redirected to #{event.payload[:location]}" + end + + def send_data(event) + info("Sent data %s (%.1fms)" % [event.payload[:filename], event.duration]) + end + + %w(write_fragment read_fragment exist_fragment? + expire_fragment expire_page write_page).each do |method| + class_eval <<-METHOD, __FILE__, __LINE__ + 1 + def #{method}(event) + key_or_path = event.payload[:key] || event.payload[:path] + human_name = #{method.to_s.humanize.inspect} + info("\#{human_name} \#{key_or_path} (%.1fms)" % event.duration) + end + METHOD + end + + def logger + ActionController::Base.logger + end + end + end +end \ No newline at end of file diff --git a/actionpack/lib/action_controller/railties/subscriber.rb b/actionpack/lib/action_controller/railties/subscriber.rb deleted file mode 100644 index 4499e82292..0000000000 --- a/actionpack/lib/action_controller/railties/subscriber.rb +++ /dev/null @@ -1,62 +0,0 @@ -module ActionController - module Railties - class Subscriber < Rails::Subscriber - INTERNAL_PARAMS = %w(controller action format _method only_path) - - def start_processing(event) - payload = event.payload - params = payload[:params].except(*INTERNAL_PARAMS) - - info " Processing by #{payload[:controller]}##{payload[:action]} as #{payload[:formats].first.to_s.upcase}" - info " Parameters: #{params.inspect}" unless params.empty? - end - - def process_action(event) - 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 - message << " (#{additions.join(" | ")})" unless additions.blank? - - info(message) - end - - def send_file(event) - message = if event.payload[:x_sendfile] - header = ActionController::Streaming::X_SENDFILE_HEADER - "Sent #{header} header %s" - elsif event.payload[:stream] - "Streamed file %s" - else - "Sent file %s" - end - - message << " (%.1fms)" - info(message % [event.payload[:path], event.duration]) - end - - def redirect_to(event) - info "Redirected to #{event.payload[:location]}" - end - - def send_data(event) - info("Sent data %s (%.1fms)" % [event.payload[:filename], event.duration]) - end - - %w(write_fragment read_fragment exist_fragment? - expire_fragment expire_page write_page).each do |method| - class_eval <<-METHOD, __FILE__, __LINE__ + 1 - def #{method}(event) - key_or_path = event.payload[:key] || event.payload[:path] - human_name = #{method.to_s.humanize.inspect} - info("\#{human_name} \#{key_or_path} (%.1fms)" % event.duration) - end - METHOD - end - - def logger - ActionController::Base.logger - end - end - end -end \ No newline at end of file diff --git a/actionpack/lib/action_view/railtie.rb b/actionpack/lib/action_view/railtie.rb index d9e2557d89..03f18ac172 100644 --- a/actionpack/lib/action_view/railtie.rb +++ b/actionpack/lib/action_view/railtie.rb @@ -5,8 +5,8 @@ module ActionView class Railtie < Rails::Railtie railtie_name :action_view - require "action_view/railties/subscriber" - subscriber ActionView::Railties::Subscriber.new + require "action_view/railties/log_subscriber" + log_subscriber ActionView::Railties::LogSubscriber.new initializer "action_view.cache_asset_timestamps" do |app| unless app.config.cache_classes diff --git a/actionpack/lib/action_view/railties/log_subscriber.rb b/actionpack/lib/action_view/railties/log_subscriber.rb new file mode 100644 index 0000000000..9487a10706 --- /dev/null +++ b/actionpack/lib/action_view/railties/log_subscriber.rb @@ -0,0 +1,24 @@ +module ActionView + module Railties + class LogSubscriber < Rails::LogSubscriber + def render_template(event) + message = "Rendered #{from_rails_root(event.payload[:identifier])}" + message << " within #{from_rails_root(event.payload[:layout])}" if event.payload[:layout] + message << (" (%.1fms)" % event.duration) + info(message) + end + alias :render_partial :render_template + alias :render_collection :render_template + + def logger + ActionController::Base.logger + end + + protected + + def from_rails_root(string) + string.sub("#{Rails.root}/", "").sub(/^app\/views\//, "") + end + end + end +end \ No newline at end of file diff --git a/actionpack/lib/action_view/railties/subscriber.rb b/actionpack/lib/action_view/railties/subscriber.rb deleted file mode 100644 index 803f19379c..0000000000 --- a/actionpack/lib/action_view/railties/subscriber.rb +++ /dev/null @@ -1,24 +0,0 @@ -module ActionView - module Railties - class Subscriber < Rails::Subscriber - def render_template(event) - message = "Rendered #{from_rails_root(event.payload[:identifier])}" - message << " within #{from_rails_root(event.payload[:layout])}" if event.payload[:layout] - message << (" (%.1fms)" % event.duration) - info(message) - end - alias :render_partial :render_template - alias :render_collection :render_template - - def logger - ActionController::Base.logger - end - - protected - - def from_rails_root(string) - string.sub("#{Rails.root}/", "").sub(/^app\/views\//, "") - end - end - end -end \ No newline at end of file diff --git a/actionpack/test/activerecord/controller_runtime_test.rb b/actionpack/test/activerecord/controller_runtime_test.rb index ed8e324938..4d2a7b9b5a 100644 --- a/actionpack/test/activerecord/controller_runtime_test.rb +++ b/actionpack/test/activerecord/controller_runtime_test.rb @@ -1,30 +1,30 @@ require 'active_record_unit' require 'active_record/railties/controller_runtime' require 'fixtures/project' -require 'rails/subscriber/test_helper' -require 'action_controller/railties/subscriber' +require 'rails/log_subscriber/test_helper' +require 'action_controller/railties/log_subscriber' ActionController::Base.send :include, ActiveRecord::Railties::ControllerRuntime -class ControllerRuntimeSubscriberTest < ActionController::TestCase - class SubscriberController < ActionController::Base +class ControllerRuntimeLogSubscriberTest < ActionController::TestCase + class LogSubscriberController < ActionController::Base def show render :inline => "<%= Project.all %>" end end - include Rails::Subscriber::TestHelper - tests SubscriberController + include Rails::LogSubscriber::TestHelper + tests LogSubscriberController def setup @old_logger = ActionController::Base.logger - Rails::Subscriber.add(:action_controller, ActionController::Railties::Subscriber.new) + Rails::LogSubscriber.add(:action_controller, ActionController::Railties::LogSubscriber.new) super end def teardown super - Rails::Subscriber.subscribers.clear + Rails::LogSubscriber.log_subscribers.clear ActionController::Base.logger = @old_logger end diff --git a/actionpack/test/controller/log_subscriber_test.rb b/actionpack/test/controller/log_subscriber_test.rb new file mode 100644 index 0000000000..182f343b2f --- /dev/null +++ b/actionpack/test/controller/log_subscriber_test.rb @@ -0,0 +1,172 @@ +require "abstract_unit" +require "rails/log_subscriber/test_helper" +require "action_controller/railties/log_subscriber" + +module Another + class LogSubscribersController < ActionController::Base + def show + render :nothing => true + end + + def redirector + redirect_to "http://foo.bar/" + end + + def data_sender + send_data "cool data", :filename => "file.txt" + end + + def xfile_sender + send_file File.expand_path("company.rb", FIXTURE_LOAD_PATH), :x_sendfile => true + end + + def file_sender + send_file File.expand_path("company.rb", FIXTURE_LOAD_PATH) + end + + def with_fragment_cache + render :inline => "<%= cache('foo'){ 'bar' } %>" + end + + def with_page_cache + cache_page("Super soaker", "/index.html") + render :nothing => true + end + end +end + +class ACLogSubscriberTest < ActionController::TestCase + tests Another::LogSubscribersController + include Rails::LogSubscriber::TestHelper + + def setup + @old_logger = ActionController::Base.logger + + @cache_path = File.expand_path('../temp/test_cache', File.dirname(__FILE__)) + ActionController::Base.page_cache_directory = @cache_path + ActionController::Base.cache_store = :file_store, @cache_path + + Rails::LogSubscriber.add(:action_controller, ActionController::Railties::LogSubscriber.new) + super + end + + def teardown + super + Rails::LogSubscriber.log_subscribers.clear + FileUtils.rm_rf(@cache_path) + ActionController::Base.logger = @old_logger + end + + def set_logger(logger) + ActionController::Base.logger = logger + end + + def test_start_processing + get :show + wait + assert_equal 2, logs.size + assert_equal "Processing by Another::LogSubscribersController#show as HTML", logs.first + end + + def test_process_action + get :show + wait + assert_equal 2, logs.size + assert_match /Completed/, logs.last + assert_match /200 OK/, logs.last + end + + def test_process_action_without_parameters + get :show + wait + assert_nil logs.detect {|l| l =~ /Parameters/ } + end + + def test_process_action_with_parameters + get :show, :id => '10' + wait + + assert_equal 3, logs.size + assert_equal 'Parameters: {"id"=>"10"}', logs[1] + end + + def test_process_action_with_view_runtime + get :show + wait + assert_match /\(Views: [\d\.]+ms\)/, logs[1] + end + + def test_process_action_with_filter_parameters + @request.env["action_dispatch.parameter_filter"] = [:lifo, :amount] + + get :show, :lifo => 'Pratik', :amount => '420', :step => '1' + wait + + params = logs[1] + assert_match /"amount"=>"\[FILTERED\]"/, params + assert_match /"lifo"=>"\[FILTERED\]"/, params + assert_match /"step"=>"1"/, params + end + + def test_redirect_to + get :redirector + wait + + assert_equal 3, logs.size + assert_equal "Redirected to http://foo.bar/", logs[1] + end + + def test_send_data + get :data_sender + wait + + assert_equal 3, logs.size + assert_match /Sent data file\.txt/, logs[1] + end + + def test_send_file + get :file_sender + wait + + assert_equal 3, logs.size + assert_match /Sent file/, logs[1] + assert_match /test\/fixtures\/company\.rb/, logs[1] + end + + def test_send_xfile + get :xfile_sender + wait + + assert_equal 3, logs.size + assert_match /Sent X\-Sendfile header/, logs[1] + assert_match /test\/fixtures\/company\.rb/, logs[1] + end + + def test_with_fragment_cache + ActionController::Base.perform_caching = true + get :with_fragment_cache + wait + + assert_equal 4, logs.size + assert_match /Exist fragment\? views\/foo/, logs[1] + assert_match /Write fragment views\/foo/, logs[2] + ensure + ActionController::Base.perform_caching = true + end + + def test_with_page_cache + ActionController::Base.perform_caching = true + get :with_page_cache + wait + + assert_equal 3, logs.size + assert_match /Write page/, logs[1] + assert_match /\/index\.html/, logs[1] + ensure + ActionController::Base.perform_caching = true + end + + def logs + @logs ||= @logger.logged(:info) + end +end diff --git a/actionpack/test/controller/subscriber_test.rb b/actionpack/test/controller/subscriber_test.rb deleted file mode 100644 index d7c1166f14..0000000000 --- a/actionpack/test/controller/subscriber_test.rb +++ /dev/null @@ -1,172 +0,0 @@ -require "abstract_unit" -require "rails/subscriber/test_helper" -require "action_controller/railties/subscriber" - -module Another - class SubscribersController < ActionController::Base - def show - render :nothing => true - end - - def redirector - redirect_to "http://foo.bar/" - end - - def data_sender - send_data "cool data", :filename => "file.txt" - end - - def xfile_sender - send_file File.expand_path("company.rb", FIXTURE_LOAD_PATH), :x_sendfile => true - end - - def file_sender - send_file File.expand_path("company.rb", FIXTURE_LOAD_PATH) - end - - def with_fragment_cache - render :inline => "<%= cache('foo'){ 'bar' } %>" - end - - def with_page_cache - cache_page("Super soaker", "/index.html") - render :nothing => true - end - end -end - -class ACSubscriberTest < ActionController::TestCase - tests Another::SubscribersController - include Rails::Subscriber::TestHelper - - def setup - @old_logger = ActionController::Base.logger - - @cache_path = File.expand_path('../temp/test_cache', File.dirname(__FILE__)) - ActionController::Base.page_cache_directory = @cache_path - ActionController::Base.cache_store = :file_store, @cache_path - - Rails::Subscriber.add(:action_controller, ActionController::Railties::Subscriber.new) - super - end - - def teardown - super - Rails::Subscriber.subscribers.clear - FileUtils.rm_rf(@cache_path) - ActionController::Base.logger = @old_logger - end - - def set_logger(logger) - ActionController::Base.logger = logger - end - - def test_start_processing - get :show - wait - assert_equal 2, logs.size - assert_equal "Processing by Another::SubscribersController#show as HTML", logs.first - end - - def test_process_action - get :show - wait - assert_equal 2, logs.size - assert_match /Completed/, logs.last - assert_match /200 OK/, logs.last - end - - def test_process_action_without_parameters - get :show - wait - assert_nil logs.detect {|l| l =~ /Parameters/ } - end - - def test_process_action_with_parameters - get :show, :id => '10' - wait - - assert_equal 3, logs.size - assert_equal 'Parameters: {"id"=>"10"}', logs[1] - end - - def test_process_action_with_view_runtime - get :show - wait - assert_match /\(Views: [\d\.]+ms\)/, logs[1] - end - - def test_process_action_with_filter_parameters - @request.env["action_dispatch.parameter_filter"] = [:lifo, :amount] - - get :show, :lifo => 'Pratik', :amount => '420', :step => '1' - wait - - params = logs[1] - assert_match /"amount"=>"\[FILTERED\]"/, params - assert_match /"lifo"=>"\[FILTERED\]"/, params - assert_match /"step"=>"1"/, params - end - - def test_redirect_to - get :redirector - wait - - assert_equal 3, logs.size - assert_equal "Redirected to http://foo.bar/", logs[1] - end - - def test_send_data - get :data_sender - wait - - assert_equal 3, logs.size - assert_match /Sent data file\.txt/, logs[1] - end - - def test_send_file - get :file_sender - wait - - assert_equal 3, logs.size - assert_match /Sent file/, logs[1] - assert_match /test\/fixtures\/company\.rb/, logs[1] - end - - def test_send_xfile - get :xfile_sender - wait - - assert_equal 3, logs.size - assert_match /Sent X\-Sendfile header/, logs[1] - assert_match /test\/fixtures\/company\.rb/, logs[1] - end - - def test_with_fragment_cache - ActionController::Base.perform_caching = true - get :with_fragment_cache - wait - - assert_equal 4, logs.size - assert_match /Exist fragment\? views\/foo/, logs[1] - assert_match /Write fragment views\/foo/, logs[2] - ensure - ActionController::Base.perform_caching = true - end - - def test_with_page_cache - ActionController::Base.perform_caching = true - get :with_page_cache - wait - - assert_equal 3, logs.size - assert_match /Write page/, logs[1] - assert_match /\/index\.html/, logs[1] - ensure - ActionController::Base.perform_caching = true - end - - def logs - @logs ||= @logger.logged(:info) - end -end diff --git a/actionpack/test/template/log_subscriber_test.rb b/actionpack/test/template/log_subscriber_test.rb new file mode 100644 index 0000000000..2eb2484cf5 --- /dev/null +++ b/actionpack/test/template/log_subscriber_test.rb @@ -0,0 +1,93 @@ +require "abstract_unit" +require "rails/log_subscriber/test_helper" +require "action_view/railties/log_subscriber" +require "controller/fake_models" + +class AVLogSubscriberTest < ActiveSupport::TestCase + include Rails::LogSubscriber::TestHelper + + def setup + @old_logger = ActionController::Base.logger + @view = ActionView::Base.new(ActionController::Base.view_paths, {}) + Rails.stubs(:root).returns(File.expand_path(FIXTURE_LOAD_PATH)) + Rails::LogSubscriber.add(:action_view, ActionView::Railties::LogSubscriber.new) + super + end + + def teardown + super + Rails::LogSubscriber.log_subscribers.clear + ActionController::Base.logger = @old_logger + end + + def set_logger(logger) + ActionController::Base.logger = logger + end + + def test_render_file_template + @view.render(:file => "test/hello_world.erb") + wait + + assert_equal 1, @logger.logged(:info).size + assert_match /Rendered test\/hello_world\.erb/, @logger.logged(:info).last + end + + def test_render_text_template + @view.render(:text => "TEXT") + wait + + assert_equal 1, @logger.logged(:info).size + assert_match /Rendered text template/, @logger.logged(:info).last + end + + def test_render_inline_template + @view.render(:inline => "<%= 'TEXT' %>") + wait + + assert_equal 1, @logger.logged(:info).size + assert_match /Rendered inline template/, @logger.logged(:info).last + end + + def test_render_partial_template + @view.render(:partial => "test/customer") + wait + + assert_equal 1, @logger.logged(:info).size + assert_match /Rendered test\/_customer.erb/, @logger.logged(:info).last + end + + def test_render_partial_with_implicit_path + @view.stubs(:controller_path).returns("test") + @view.render(Customer.new("david"), :greeting => "hi") + wait + + assert_equal 1, @logger.logged(:info).size + assert_match /Rendered customers\/_customer\.html\.erb/, @logger.logged(:info).last + end + + def test_render_collection_template + @view.render(:partial => "test/customer", :collection => [ Customer.new("david"), Customer.new("mary") ]) + wait + + assert_equal 1, @logger.logged(:info).size + assert_match /Rendered test\/_customer.erb/, @logger.logged(:info).last + end + + def test_render_collection_with_implicit_path + @view.stubs(:controller_path).returns("test") + @view.render([ Customer.new("david"), Customer.new("mary") ], :greeting => "hi") + wait + + assert_equal 1, @logger.logged(:info).size + assert_match /Rendered customers\/_customer\.html\.erb/, @logger.logged(:info).last + end + + def test_render_collection_template_without_path + @view.stubs(:controller_path).returns("test") + @view.render([ GoodCustomer.new("david"), Customer.new("mary") ], :greeting => "hi") + wait + + assert_equal 1, @logger.logged(:info).size + assert_match /Rendered collection/, @logger.logged(:info).last + end +end \ No newline at end of file diff --git a/actionpack/test/template/subscriber_test.rb b/actionpack/test/template/subscriber_test.rb deleted file mode 100644 index 8bacab7088..0000000000 --- a/actionpack/test/template/subscriber_test.rb +++ /dev/null @@ -1,93 +0,0 @@ -require "abstract_unit" -require "rails/subscriber/test_helper" -require "action_view/railties/subscriber" -require "controller/fake_models" - -class AVSubscriberTest < ActiveSupport::TestCase - include Rails::Subscriber::TestHelper - - def setup - @old_logger = ActionController::Base.logger - @view = ActionView::Base.new(ActionController::Base.view_paths, {}) - Rails.stubs(:root).returns(File.expand_path(FIXTURE_LOAD_PATH)) - Rails::Subscriber.add(:action_view, ActionView::Railties::Subscriber.new) - super - end - - def teardown - super - Rails::Subscriber.subscribers.clear - ActionController::Base.logger = @old_logger - end - - def set_logger(logger) - ActionController::Base.logger = logger - end - - def test_render_file_template - @view.render(:file => "test/hello_world.erb") - wait - - assert_equal 1, @logger.logged(:info).size - assert_match /Rendered test\/hello_world\.erb/, @logger.logged(:info).last - end - - def test_render_text_template - @view.render(:text => "TEXT") - wait - - assert_equal 1, @logger.logged(:info).size - assert_match /Rendered text template/, @logger.logged(:info).last - end - - def test_render_inline_template - @view.render(:inline => "<%= 'TEXT' %>") - wait - - assert_equal 1, @logger.logged(:info).size - assert_match /Rendered inline template/, @logger.logged(:info).last - end - - def test_render_partial_template - @view.render(:partial => "test/customer") - wait - - assert_equal 1, @logger.logged(:info).size - assert_match /Rendered test\/_customer.erb/, @logger.logged(:info).last - end - - def test_render_partial_with_implicit_path - @view.stubs(:controller_path).returns("test") - @view.render(Customer.new("david"), :greeting => "hi") - wait - - assert_equal 1, @logger.logged(:info).size - assert_match /Rendered customers\/_customer\.html\.erb/, @logger.logged(:info).last - end - - def test_render_collection_template - @view.render(:partial => "test/customer", :collection => [ Customer.new("david"), Customer.new("mary") ]) - wait - - assert_equal 1, @logger.logged(:info).size - assert_match /Rendered test\/_customer.erb/, @logger.logged(:info).last - end - - def test_render_collection_with_implicit_path - @view.stubs(:controller_path).returns("test") - @view.render([ Customer.new("david"), Customer.new("mary") ], :greeting => "hi") - wait - - assert_equal 1, @logger.logged(:info).size - assert_match /Rendered customers\/_customer\.html\.erb/, @logger.logged(:info).last - end - - def test_render_collection_template_without_path - @view.stubs(:controller_path).returns("test") - @view.render([ GoodCustomer.new("david"), Customer.new("mary") ], :greeting => "hi") - wait - - assert_equal 1, @logger.logged(:info).size - assert_match /Rendered collection/, @logger.logged(:info).last - end -end \ No newline at end of file diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index f30eba4f06..c6dde078ca 100755 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -552,7 +552,7 @@ module ActiveRecord #:nodoc: def colorize_logging(*args) ActiveSupport::Deprecation.warn "ActiveRecord::Base.colorize_logging and " << "config.active_record.colorize_logging are deprecated. Please use " << - "Rails::Subscriber.colorize_logging or config.colorize_logging instead", caller + "Rails::LogSubscriber.colorize_logging or config.colorize_logging instead", caller end alias :colorize_logging= :colorize_logging diff --git a/activerecord/lib/active_record/railtie.rb b/activerecord/lib/active_record/railtie.rb index e70b0d1bfb..b38bd9a644 100644 --- a/activerecord/lib/active_record/railtie.rb +++ b/activerecord/lib/active_record/railtie.rb @@ -20,8 +20,8 @@ module ActiveRecord end # TODO If we require the wrong file, the error never comes up. - require "active_record/railties/subscriber" - subscriber ActiveRecord::Railties::Subscriber.new + require "active_record/railties/log_subscriber" + log_subscriber ActiveRecord::Railties::LogSubscriber.new initializer "active_record.initialize_timezone" do ActiveRecord::Base.time_zone_aware_attributes = true diff --git a/activerecord/lib/active_record/railties/log_subscriber.rb b/activerecord/lib/active_record/railties/log_subscriber.rb new file mode 100644 index 0000000000..48b25032ce --- /dev/null +++ b/activerecord/lib/active_record/railties/log_subscriber.rb @@ -0,0 +1,27 @@ +module ActiveRecord + module Railties + class LogSubscriber < Rails::LogSubscriber + def sql(event) + name = '%s (%.1fms)' % [event.payload[:name], event.duration] + sql = event.payload[:sql].squeeze(' ') + + if odd? + name = color(name, :cyan, true) + sql = color(sql, nil, true) + else + name = color(name, :magenta, true) + end + + debug " #{name} #{sql}" + end + + def odd? + @odd_or_even = !@odd_or_even + end + + def logger + ActiveRecord::Base.logger + end + end + end +end \ No newline at end of file diff --git a/activerecord/lib/active_record/railties/subscriber.rb b/activerecord/lib/active_record/railties/subscriber.rb deleted file mode 100644 index fd873dbff8..0000000000 --- a/activerecord/lib/active_record/railties/subscriber.rb +++ /dev/null @@ -1,27 +0,0 @@ -module ActiveRecord - module Railties - class Subscriber < Rails::Subscriber - def sql(event) - name = '%s (%.1fms)' % [event.payload[:name], event.duration] - sql = event.payload[:sql].squeeze(' ') - - if odd? - name = color(name, :cyan, true) - sql = color(sql, nil, true) - else - name = color(name, :magenta, true) - end - - debug " #{name} #{sql}" - end - - def odd? - @odd_or_even = !@odd_or_even - end - - def logger - ActiveRecord::Base.logger - end - end - end -end \ No newline at end of file diff --git a/activerecord/test/cases/log_subscriber_test.rb b/activerecord/test/cases/log_subscriber_test.rb new file mode 100644 index 0000000000..f0197ddf77 --- /dev/null +++ b/activerecord/test/cases/log_subscriber_test.rb @@ -0,0 +1,42 @@ +require "cases/helper" +require "models/developer" +require "rails/log_subscriber/test_helper" +require "active_record/railties/log_subscriber" + +class LogSubscriberTest < ActiveSupport::TestCase + include Rails::LogSubscriber::TestHelper + Rails::LogSubscriber.add(:active_record, ActiveRecord::Railties::LogSubscriber.new) + + def setup + @old_logger = ActiveRecord::Base.logger + super + end + + def teardown + super + ActiveRecord::Base.logger = @old_logger + end + + def set_logger(logger) + ActiveRecord::Base.logger = logger + end + + def test_basic_query_logging + Developer.all + wait + assert_equal 1, @logger.logged(:debug).size + assert_match /Developer Load/, @logger.logged(:debug).last + assert_match /SELECT .*?FROM .?developers.?/, @logger.logged(:debug).last + end + + def test_cached_queries + ActiveRecord::Base.cache do + Developer.all + Developer.all + end + wait + assert_equal 2, @logger.logged(:debug).size + assert_match /CACHE/, @logger.logged(:debug).last + assert_match /SELECT .*?FROM .?developers.?/, @logger.logged(:debug).last + end +end \ No newline at end of file diff --git a/activerecord/test/cases/subscriber_test.rb b/activerecord/test/cases/subscriber_test.rb deleted file mode 100644 index 5328d4468b..0000000000 --- a/activerecord/test/cases/subscriber_test.rb +++ /dev/null @@ -1,42 +0,0 @@ -require "cases/helper" -require "models/developer" -require "rails/subscriber/test_helper" -require "active_record/railties/subscriber" - -class SubscriberTest < ActiveSupport::TestCase - include Rails::Subscriber::TestHelper - Rails::Subscriber.add(:active_record, ActiveRecord::Railties::Subscriber.new) - - def setup - @old_logger = ActiveRecord::Base.logger - super - end - - def teardown - super - ActiveRecord::Base.logger = @old_logger - end - - def set_logger(logger) - ActiveRecord::Base.logger = logger - end - - def test_basic_query_logging - Developer.all - wait - assert_equal 1, @logger.logged(:debug).size - assert_match /Developer Load/, @logger.logged(:debug).last - assert_match /SELECT .*?FROM .?developers.?/, @logger.logged(:debug).last - end - - def test_cached_queries - ActiveRecord::Base.cache do - Developer.all - Developer.all - end - wait - assert_equal 2, @logger.logged(:debug).size - assert_match /CACHE/, @logger.logged(:debug).last - assert_match /SELECT .*?FROM .?developers.?/, @logger.logged(:debug).last - end -end \ No newline at end of file diff --git a/activeresource/lib/active_resource/railtie.rb b/activeresource/lib/active_resource/railtie.rb index 7e35fdc0eb..27c88415f6 100644 --- a/activeresource/lib/active_resource/railtie.rb +++ b/activeresource/lib/active_resource/railtie.rb @@ -5,8 +5,8 @@ module ActiveResource class Railtie < Rails::Railtie railtie_name :active_resource - require "active_resource/railties/subscriber" - subscriber ActiveResource::Railties::Subscriber.new + require "active_resource/railties/log_subscriber" + log_subscriber ActiveResource::Railties::LogSubscriber.new initializer "active_resource.set_configs" do |app| app.config.active_resource.each do |k,v| diff --git a/activeresource/lib/active_resource/railties/log_subscriber.rb b/activeresource/lib/active_resource/railties/log_subscriber.rb new file mode 100644 index 0000000000..86806a93d0 --- /dev/null +++ b/activeresource/lib/active_resource/railties/log_subscriber.rb @@ -0,0 +1,15 @@ +module ActiveResource + module Railties + class LogSubscriber < Rails::LogSubscriber + def request(event) + result = event.payload[:result] + info "#{event.payload[:method].to_s.upcase} #{event.payload[:request_uri]}" + info "--> %d %s %d (%.1fms)" % [result.code, result.message, result.body.to_s.length, event.duration] + end + + def logger + ActiveResource::Base.logger + end + end + end +end \ No newline at end of file diff --git a/activeresource/lib/active_resource/railties/subscriber.rb b/activeresource/lib/active_resource/railties/subscriber.rb deleted file mode 100644 index fb98061b71..0000000000 --- a/activeresource/lib/active_resource/railties/subscriber.rb +++ /dev/null @@ -1,15 +0,0 @@ -module ActiveResource - module Railties - class Subscriber < Rails::Subscriber - def request(event) - result = event.payload[:result] - info "#{event.payload[:method].to_s.upcase} #{event.payload[:request_uri]}" - info "--> %d %s %d (%.1fms)" % [result.code, result.message, result.body.to_s.length, event.duration] - end - - def logger - ActiveResource::Base.logger - end - end - end -end \ No newline at end of file diff --git a/activeresource/test/cases/log_subscriber_test.rb b/activeresource/test/cases/log_subscriber_test.rb new file mode 100644 index 0000000000..56709b6fd3 --- /dev/null +++ b/activeresource/test/cases/log_subscriber_test.rb @@ -0,0 +1,31 @@ +require "abstract_unit" +require "fixtures/person" +require "rails/log_subscriber/test_helper" +require "active_resource/railties/log_subscriber" +require "active_support/core_ext/hash/conversions" + +class LogSubscriberTest < ActiveSupport::TestCase + include Rails::LogSubscriber::TestHelper + Rails::LogSubscriber.add(:active_resource, ActiveResource::Railties::LogSubscriber.new) + + def setup + @matz = { :id => 1, :name => 'Matz' }.to_xml(:root => 'person') + ActiveResource::HttpMock.respond_to do |mock| + mock.get "/people/1.xml", {}, @matz + end + + super + end + + def set_logger(logger) + ActiveResource::Base.logger = logger + end + + def test_request_notification + matz = Person.find(1) + wait + assert_equal 2, @logger.logged(:info).size + assert_equal "GET http://37s.sunrise.i:3000/people/1.xml", @logger.logged(:info)[0] + assert_match /\-\-\> 200 200 106/, @logger.logged(:info)[1] + end +end \ No newline at end of file diff --git a/activeresource/test/cases/subscriber_test.rb b/activeresource/test/cases/subscriber_test.rb deleted file mode 100644 index fb890e86cb..0000000000 --- a/activeresource/test/cases/subscriber_test.rb +++ /dev/null @@ -1,31 +0,0 @@ -require "abstract_unit" -require "fixtures/person" -require "rails/subscriber/test_helper" -require "active_resource/railties/subscriber" -require "active_support/core_ext/hash/conversions" - -class SubscriberTest < ActiveSupport::TestCase - include Rails::Subscriber::TestHelper - Rails::Subscriber.add(:active_resource, ActiveResource::Railties::Subscriber.new) - - def setup - @matz = { :id => 1, :name => 'Matz' }.to_xml(:root => 'person') - ActiveResource::HttpMock.respond_to do |mock| - mock.get "/people/1.xml", {}, @matz - end - - super - end - - def set_logger(logger) - ActiveResource::Base.logger = logger - end - - def test_request_notification - matz = Person.find(1) - wait - assert_equal 2, @logger.logged(:info).size - assert_equal "GET http://37s.sunrise.i:3000/people/1.xml", @logger.logged(:info)[0] - assert_match /\-\-\> 200 200 106/, @logger.logged(:info)[1] - end -end \ No newline at end of file diff --git a/activesupport/lib/active_support/notifications.rb b/activesupport/lib/active_support/notifications.rb index 3e96decb8c..06d57765bc 100644 --- a/activesupport/lib/active_support/notifications.rb +++ b/activesupport/lib/active_support/notifications.rb @@ -9,7 +9,7 @@ module ActiveSupport # end # # You can consume those events and the information they provide by registering - # a subscriber. For instance, let's store all instrumented events in an array: + # a log subscriber. For instance, let's store all instrumented events in an array: # # @events = [] # @@ -35,7 +35,7 @@ module ActiveSupport # end # # Notifications ships with a queue implementation that consumes and publish events - # to subscribers in a thread. You can use any queue implementation you want. + # to log subscribers in a thread. You can use any queue implementation you want. # module Notifications autoload :Instrumenter, 'active_support/notifications/instrumenter' diff --git a/activesupport/lib/active_support/notifications/fanout.rb b/activesupport/lib/active_support/notifications/fanout.rb index 0ec23da073..05de4946a5 100644 --- a/activesupport/lib/active_support/notifications/fanout.rb +++ b/activesupport/lib/active_support/notifications/fanout.rb @@ -1,10 +1,10 @@ module ActiveSupport module Notifications # This is a default queue implementation that ships with Notifications. It - # just pushes events to all registered subscribers. + # just pushes events to all registered log subscribers. class Fanout def initialize - @subscribers = [] + @log_subscribers = [] end def bind(pattern) @@ -12,11 +12,11 @@ module ActiveSupport end def subscribe(pattern = nil, &block) - @subscribers << Subscriber.new(pattern, &block) + @log_subscribers << LogSubscriber.new(pattern, &block) end def publish(*args) - @subscribers.each { |s| s.publish(*args) } + @log_subscribers.each { |s| s.publish(*args) } end # This is a sync queue, so there is not waiting. @@ -41,7 +41,7 @@ module ActiveSupport end end - class Subscriber #:nodoc: + class LogSubscriber #:nodoc: def initialize(pattern, &block) @pattern = pattern @block = block diff --git a/activesupport/test/notifications_test.rb b/activesupport/test/notifications_test.rb index 545811a376..779771553c 100644 --- a/activesupport/test/notifications_test.rb +++ b/activesupport/test/notifications_test.rb @@ -26,7 +26,7 @@ module Notifications assert_equal [[:foo]], @events end - def test_subscriber_with_pattern + def test_log_subscriber_with_pattern events = [] @notifier.subscribe('1') { |*args| events << args } @@ -38,7 +38,7 @@ module Notifications assert_equal [['1'], ['1.a']], events end - def test_subscriber_with_pattern_as_regexp + def test_log_subscriber_with_pattern_as_regexp events = [] @notifier.subscribe(/\d/) { |*args| events << args } @@ -50,7 +50,7 @@ module Notifications assert_equal [['1'], ['a.1'], ['1.a']], events end - def test_multiple_subscribers + def test_multiple_log_subscribers @another = [] @notifier.subscribe { |*args| @another << args } @notifier.publish :foo diff --git a/railties/guides/source/3_0_release_notes.textile b/railties/guides/source/3_0_release_notes.textile index 639e775bf5..4b0dc72908 100644 --- a/railties/guides/source/3_0_release_notes.textile +++ b/railties/guides/source/3_0_release_notes.textile @@ -435,7 +435,7 @@ As well as the following deprecations: * I18n error messages for ActiveRecord should be changed from :en.activerecord.errors.template to :en.errors.template. * model.errors.on is deprecated in favour of model.errors[] * validates_presence_of => validates... :presence => true -* ActiveRecord::Base.colorize_logging and config.active_record.colorize_logging are deprecated in favour of Rails::Subscriber.colorize_logging or config.colorize_logging +* ActiveRecord::Base.colorize_logging and config.active_record.colorize_logging are deprecated in favour of Rails::LogSubscriber.colorize_logging or config.colorize_logging NOTE: While an implementation of State Machine has been in Active Record edge for some months now, it has been removed from the Rails 3.0 release. diff --git a/railties/lib/rails.rb b/railties/lib/rails.rb index b7a39fd5a7..3d3151bd8f 100644 --- a/railties/lib/rails.rb +++ b/railties/lib/rails.rb @@ -7,7 +7,7 @@ require 'active_support/core_ext/logger' require 'rails/application' require 'rails/version' require 'rails/deprecation' -require 'rails/subscriber' +require 'rails/log_subscriber' require 'rails/ruby_version_check' require 'active_support/railtie' diff --git a/railties/lib/rails/application/bootstrap.rb b/railties/lib/rails/application/bootstrap.rb index b20e53f2de..0714b34b31 100644 --- a/railties/lib/rails/application/bootstrap.rb +++ b/railties/lib/rails/application/bootstrap.rb @@ -49,17 +49,17 @@ module Rails end end - # Initialize rails subscriber on top of notifications. - initializer :initialize_subscriber do + # Initialize rails log subscriber on top of notifications. + initializer :initialize_log_subscriber do require 'active_support/notifications' if config.colorize_logging == false - Rails::Subscriber.colorize_logging = false + Rails::LogSubscriber.colorize_logging = false config.generators.colorize_logging = false end ActiveSupport::Notifications.subscribe do |*args| - Rails::Subscriber.dispatch(args) + Rails::LogSubscriber.dispatch(args) end end diff --git a/railties/lib/rails/log_subscriber.rb b/railties/lib/rails/log_subscriber.rb new file mode 100644 index 0000000000..c867b92b6b --- /dev/null +++ b/railties/lib/rails/log_subscriber.rb @@ -0,0 +1,108 @@ +require 'active_support/core_ext/class/inheritable_attributes' +require 'active_support/notifications' + +module Rails + # Rails::LogSubscriber is an object set to consume ActiveSupport::Notifications + # on initialization with solely purpose of logging. The log subscriber dispatches + # notifications to a regirested object based on its given namespace. + # + # An example would be ActiveRecord log subscriber responsible for logging queries: + # + # module ActiveRecord + # class Railtie + # class LogSubscriber < Rails::LogSubscriber + # def sql(event) + # "#{event.payload[:name]} (#{event.duration}) #{event.payload[:sql]}" + # end + # end + # end + # end + # + # It's finally registed as: + # + # Rails::LogSubscriber.add :active_record, ActiveRecord::Railtie::LogSubscriber.new + # + # So whenever a "active_record.sql" notification arrive to Rails::LogSubscriber, + # it will properly dispatch the event (ActiveSupport::Notifications::Event) to + # the sql method. + # + # This is useful because it avoids spanning several log subscribers just for logging + # purposes(which slows down the main thread). Besides of providing a centralized + # facility on top of Rails.logger. + # + # Log subscriber also has some helpers to deal with logging and automatically flushes + # all logs when the request finishes (via action_dispatch.callback notification). + class LogSubscriber + mattr_accessor :colorize_logging + self.colorize_logging = true + + # Embed in a String to clear all previous ANSI sequences. + CLEAR = "\e[0m" + BOLD = "\e[1m" + + # Colors + BLACK = "\e[30m" + RED = "\e[31m" + GREEN = "\e[32m" + YELLOW = "\e[33m" + BLUE = "\e[34m" + MAGENTA = "\e[35m" + CYAN = "\e[36m" + WHITE = "\e[37m" + + def self.add(namespace, log_subscriber) + log_subscribers[namespace.to_sym] = log_subscriber + end + + def self.log_subscribers + @log_subscribers ||= {} + end + + def self.dispatch(args) + namespace, name = args[0].split(".") + log_subscriber = log_subscribers[namespace.to_sym] + + if log_subscriber.respond_to?(name) && log_subscriber.logger + begin + log_subscriber.send(name, ActiveSupport::Notifications::Event.new(*args)) + rescue Exception => e + Rails.logger.error "Could not log #{args[0].inspect} event. #{e.class}: #{e.message}" + end + end + end + + # Flush all log_subscribers' logger. + def self.flush_all! + loggers = log_subscribers.values.map(&:logger) + loggers.uniq! + loggers.each { |l| l.flush if l.respond_to?(:flush) } + end + + # By default, we use the Rails.logger for logging. + def logger + Rails.logger + end + + protected + + %w(info debug warn error fatal unknown).each do |level| + class_eval <<-METHOD, __FILE__, __LINE__ + 1 + def #{level}(*args, &block) + logger.#{level}(*args, &block) + end + METHOD + end + + # Set color by using a string or one of the defined constants. If a third + # option is set to true, it also adds bold to the string. This is based + # on Highline implementation and it automatically appends CLEAR to the end + # of the returned String. + # + def color(text, color, bold=false) + return text unless colorize_logging + color = self.class.const_get(color.to_s.upcase) if color.is_a?(Symbol) + bold = bold ? BOLD : "" + "#{bold}#{color}#{text}#{CLEAR}" + end + end +end \ No newline at end of file diff --git a/railties/lib/rails/log_subscriber/test_helper.rb b/railties/lib/rails/log_subscriber/test_helper.rb new file mode 100644 index 0000000000..9ede56cad4 --- /dev/null +++ b/railties/lib/rails/log_subscriber/test_helper.rb @@ -0,0 +1,98 @@ +require 'rails/log_subscriber' + +module Rails + class LogSubscriber + # Provides some helpers to deal with testing log subscribers by setting up + # notifications. Take for instance ActiveRecord subscriber tests: + # + # class SyncLogSubscriberTest < ActiveSupport::TestCase + # include Rails::LogSubscriber::TestHelper + # Rails::LogSubscriber.add(:active_record, ActiveRecord::Railties::LogSubscriber.new) + # + # def test_basic_query_logging + # Developer.all + # wait + # assert_equal 1, @logger.logged(:debug).size + # assert_match /Developer Load/, @logger.logged(:debug).last + # assert_match /SELECT \* FROM "developers"/, @logger.logged(:debug).last + # end + # + # class SyncLogSubscriberTest < ActiveSupport::TestCase + # include Rails::LogSubscriber::SyncTestHelper + # include LogSubscriberTest + # end + # + # class AsyncLogSubscriberTest < ActiveSupport::TestCase + # include Rails::LogSubscriber::AsyncTestHelper + # include LogSubscriberTest + # end + # end + # + # All you need to do is to ensure that your log subscriber is added to Rails::Subscriber, + # as in the second line of the code above. The test helpers is reponsible for setting + # up the queue, subscriptions and turning colors in logs off. + # + # The messages are available in the @logger instance, which is a logger with limited + # powers (it actually do not send anything to your output), and you can collect them + # doing @logger.logged(level), where level is the level used in logging, like info, + # debug, warn and so on. + # + module TestHelper + def setup + @logger = MockLogger.new + @notifier = ActiveSupport::Notifications::Notifier.new(queue) + + Rails::LogSubscriber.colorize_logging = false + @notifier.subscribe { |*args| Rails::LogSubscriber.dispatch(args) } + + set_logger(@logger) + ActiveSupport::Notifications.notifier = @notifier + end + + def teardown + set_logger(nil) + ActiveSupport::Notifications.notifier = nil + end + + class MockLogger + attr_reader :flush_count + + def initialize + @flush_count = 0 + @logged = Hash.new { |h,k| h[k] = [] } + end + + def method_missing(level, message) + @logged[level] << message + end + + def logged(level) + @logged[level].compact.map { |l| l.to_s.strip } + end + + def flush + @flush_count += 1 + end + end + + # Wait notifications to be published. + def wait + @notifier.wait + end + + # Overwrite if you use another logger in your log subscriber: + # + # def logger + # ActiveRecord::Base.logger = @logger + # end + # + def set_logger(logger) + Rails.logger = logger + end + + def queue + ActiveSupport::Notifications::Fanout.new + end + end + end +end \ No newline at end of file diff --git a/railties/lib/rails/rack/logger.rb b/railties/lib/rails/rack/logger.rb index de21fb4f10..2efe224e94 100644 --- a/railties/lib/rails/rack/logger.rb +++ b/railties/lib/rails/rack/logger.rb @@ -1,9 +1,9 @@ -require 'rails/subscriber' +require 'rails/log_subscriber' module Rails module Rack # Log the request started and flush all loggers after it. - class Logger < Rails::Subscriber + class Logger < Rails::LogSubscriber def initialize(app) @app = app end @@ -26,7 +26,7 @@ module Rails end def after_dispatch(env) - Rails::Subscriber.flush_all! + Rails::LogSubscriber.flush_all! end end diff --git a/railties/lib/rails/railtie.rb b/railties/lib/rails/railtie.rb index c038d0ac70..67afae5862 100644 --- a/railties/lib/rails/railtie.rb +++ b/railties/lib/rails/railtie.rb @@ -32,8 +32,8 @@ module Rails subclasses.map { |p| p.railtie_name } end - def subscriber(subscriber) - Rails::Subscriber.add(railtie_name, subscriber) + def log_subscriber(log_subscriber) + Rails::LogSubscriber.add(railtie_name, log_subscriber) end def rake_tasks(&blk) diff --git a/railties/lib/rails/subscriber.rb b/railties/lib/rails/subscriber.rb deleted file mode 100644 index 8c62f562d9..0000000000 --- a/railties/lib/rails/subscriber.rb +++ /dev/null @@ -1,108 +0,0 @@ -require 'active_support/core_ext/class/inheritable_attributes' -require 'active_support/notifications' - -module Rails - # Rails::Subscriber is an object set to consume ActiveSupport::Notifications - # on initialization with solely purpose of logging. The subscriber dispatches - # notifications to a regirested object based on its given namespace. - # - # An example would be ActiveRecord subscriber responsible for logging queries: - # - # module ActiveRecord - # class Railtie - # class Subscriber < Rails::Subscriber - # def sql(event) - # "#{event.payload[:name]} (#{event.duration}) #{event.payload[:sql]}" - # end - # end - # end - # end - # - # It's finally registed as: - # - # Rails::Subscriber.add :active_record, ActiveRecord::Railtie::Subscriber.new - # - # So whenever a "active_record.sql" notification arrive to Rails::Subscriber, - # it will properly dispatch the event (ActiveSupport::Notifications::Event) to - # the sql method. - # - # This is useful because it avoids spanning several subscribers just for logging - # purposes(which slows down the main thread). Besides of providing a centralized - # facility on top of Rails.logger. - # - # Subscriber also has some helpers to deal with logging and automatically flushes - # all logs when the request finishes (via action_dispatch.callback notification). - class Subscriber - mattr_accessor :colorize_logging - self.colorize_logging = true - - # Embed in a String to clear all previous ANSI sequences. - CLEAR = "\e[0m" - BOLD = "\e[1m" - - # Colors - BLACK = "\e[30m" - RED = "\e[31m" - GREEN = "\e[32m" - YELLOW = "\e[33m" - BLUE = "\e[34m" - MAGENTA = "\e[35m" - CYAN = "\e[36m" - WHITE = "\e[37m" - - def self.add(namespace, subscriber) - subscribers[namespace.to_sym] = subscriber - end - - def self.subscribers - @subscribers ||= {} - end - - def self.dispatch(args) - namespace, name = args[0].split(".") - subscriber = subscribers[namespace.to_sym] - - if subscriber.respond_to?(name) && subscriber.logger - begin - subscriber.send(name, ActiveSupport::Notifications::Event.new(*args)) - rescue Exception => e - Rails.logger.error "Could not log #{args[0].inspect} event. #{e.class}: #{e.message}" - end - end - end - - # Flush all subscribers' logger. - def self.flush_all! - loggers = subscribers.values.map(&:logger) - loggers.uniq! - loggers.each { |l| l.flush if l.respond_to?(:flush) } - end - - # By default, we use the Rails.logger for logging. - def logger - Rails.logger - end - - protected - - %w(info debug warn error fatal unknown).each do |level| - class_eval <<-METHOD, __FILE__, __LINE__ + 1 - def #{level}(*args, &block) - logger.#{level}(*args, &block) - end - METHOD - end - - # Set color by using a string or one of the defined constants. If a third - # option is set to true, it also adds bold to the string. This is based - # on Highline implementation and it automatically appends CLEAR to the end - # of the returned String. - # - def color(text, color, bold=false) - return text unless colorize_logging - color = self.class.const_get(color.to_s.upcase) if color.is_a?(Symbol) - bold = bold ? BOLD : "" - "#{bold}#{color}#{text}#{CLEAR}" - end - end -end \ No newline at end of file diff --git a/railties/lib/rails/subscriber/test_helper.rb b/railties/lib/rails/subscriber/test_helper.rb deleted file mode 100644 index 39b4117372..0000000000 --- a/railties/lib/rails/subscriber/test_helper.rb +++ /dev/null @@ -1,98 +0,0 @@ -require 'rails/subscriber' - -module Rails - class Subscriber - # Provides some helpers to deal with testing subscribers by setting up - # notifications. Take for instance ActiveRecord subscriber tests: - # - # class SyncSubscriberTest < ActiveSupport::TestCase - # include Rails::Subscriber::TestHelper - # Rails::Subscriber.add(:active_record, ActiveRecord::Railties::Subscriber.new) - # - # def test_basic_query_logging - # Developer.all - # wait - # assert_equal 1, @logger.logged(:debug).size - # assert_match /Developer Load/, @logger.logged(:debug).last - # assert_match /SELECT \* FROM "developers"/, @logger.logged(:debug).last - # end - # - # class SyncSubscriberTest < ActiveSupport::TestCase - # include Rails::Subscriber::SyncTestHelper - # include SubscriberTest - # end - # - # class AsyncSubscriberTest < ActiveSupport::TestCase - # include Rails::Subscriber::AsyncTestHelper - # include SubscriberTest - # end - # end - # - # All you need to do is to ensure that your subscriber is added to Rails::Subscriber, - # as in the second line of the code above. The test helpers is reponsible for setting - # up the queue, subscriptions and turning colors in logs off. - # - # The messages are available in the @logger instance, which is a logger with limited - # powers (it actually do not send anything to your output), and you can collect them - # doing @logger.logged(level), where level is the level used in logging, like info, - # debug, warn and so on. - # - module TestHelper - def setup - @logger = MockLogger.new - @notifier = ActiveSupport::Notifications::Notifier.new(queue) - - Rails::Subscriber.colorize_logging = false - @notifier.subscribe { |*args| Rails::Subscriber.dispatch(args) } - - set_logger(@logger) - ActiveSupport::Notifications.notifier = @notifier - end - - def teardown - set_logger(nil) - ActiveSupport::Notifications.notifier = nil - end - - class MockLogger - attr_reader :flush_count - - def initialize - @flush_count = 0 - @logged = Hash.new { |h,k| h[k] = [] } - end - - def method_missing(level, message) - @logged[level] << message - end - - def logged(level) - @logged[level].compact.map { |l| l.to_s.strip } - end - - def flush - @flush_count += 1 - end - end - - # Wait notifications to be published. - def wait - @notifier.wait - end - - # Overwrite if you use another logger in your subscriber: - # - # def logger - # ActiveRecord::Base.logger = @logger - # end - # - def set_logger(logger) - Rails.logger = logger - end - - def queue - ActiveSupport::Notifications::Fanout.new - end - end - end -end \ No newline at end of file diff --git a/railties/test/application/initializers/notifications_test.rb b/railties/test/application/initializers/notifications_test.rb index 061bb34c19..b99cf5bb4f 100644 --- a/railties/test/application/initializers/notifications_test.rb +++ b/railties/test/application/initializers/notifications_test.rb @@ -28,7 +28,7 @@ module ApplicationTests ActiveSupport::Notifications.notifier.wait end - test "rails subscribers are added" do + test "rails log_subscribers are added" do add_to_config <<-RUBY config.colorize_logging = false RUBY diff --git a/railties/test/log_subscriber_test.rb b/railties/test/log_subscriber_test.rb new file mode 100644 index 0000000000..be176df1bb --- /dev/null +++ b/railties/test/log_subscriber_test.rb @@ -0,0 +1,119 @@ +require 'abstract_unit' +require 'rails/log_subscriber/test_helper' + +class MyLogSubscriber < Rails::LogSubscriber + attr_reader :event + + def some_event(event) + @event = event + info event.name + end + + def foo(event) + debug "debug" + info "info" + warn "warn" + end + + def bar(event) + info "#{color("cool", :red)}, #{color("isn't it?", :blue, true)}" + end + + def puke(event) + raise "puke" + end +end + +class SyncLogSubscriberTest < ActiveSupport::TestCase + include Rails::LogSubscriber::TestHelper + + def setup + super + @log_subscriber = MyLogSubscriber.new + Rails::LogSubscriber.instance_variable_set(:@log_tailer, nil) + end + + def teardown + super + Rails::LogSubscriber.log_subscribers.clear + Rails::LogSubscriber.instance_variable_set(:@log_tailer, nil) + end + + def instrument(*args, &block) + ActiveSupport::Notifications.instrument(*args, &block) + end + + def test_proxies_method_to_rails_logger + @log_subscriber.foo(nil) + assert_equal %w(debug), @logger.logged(:debug) + assert_equal %w(info), @logger.logged(:info) + assert_equal %w(warn), @logger.logged(:warn) + end + + def test_set_color_for_messages + Rails::LogSubscriber.colorize_logging = true + @log_subscriber.bar(nil) + assert_equal "\e[31mcool\e[0m, \e[1m\e[34misn't it?\e[0m", @logger.logged(:info).last + end + + def test_does_not_set_color_if_colorize_logging_is_set_to_false + @log_subscriber.bar(nil) + assert_equal "cool, isn't it?", @logger.logged(:info).last + end + + def test_event_is_sent_to_the_registered_class + Rails::LogSubscriber.add :my_log_subscriber, @log_subscriber + instrument "my_log_subscriber.some_event" + wait + assert_equal %w(my_log_subscriber.some_event), @logger.logged(:info) + end + + def test_event_is_an_active_support_notifications_event + Rails::LogSubscriber.add :my_log_subscriber, @log_subscriber + instrument "my_log_subscriber.some_event" + wait + assert_kind_of ActiveSupport::Notifications::Event, @log_subscriber.event + end + + def test_does_not_send_the_event_if_it_doesnt_match_the_class + Rails::LogSubscriber.add :my_log_subscriber, @log_subscriber + instrument "my_log_subscriber.unknown_event" + wait + # If we get here, it means that NoMethodError was raised. + end + + def test_does_not_send_the_event_if_logger_is_nil + Rails.logger = nil + @log_subscriber.expects(:some_event).never + Rails::LogSubscriber.add :my_log_subscriber, @log_subscriber + instrument "my_log_subscriber.some_event" + wait + end + + def test_flushes_loggers + Rails::LogSubscriber.add :my_log_subscriber, @log_subscriber + Rails::LogSubscriber.flush_all! + assert_equal 1, @logger.flush_count + end + + def test_flushes_the_same_logger_just_once + Rails::LogSubscriber.add :my_log_subscriber, @log_subscriber + Rails::LogSubscriber.add :another, @log_subscriber + Rails::LogSubscriber.flush_all! + wait + assert_equal 1, @logger.flush_count + end + + def test_logging_does_not_die_on_failures + Rails::LogSubscriber.add :my_log_subscriber, @log_subscriber + instrument "my_log_subscriber.puke" + instrument "my_log_subscriber.some_event" + wait + + assert_equal 1, @logger.logged(:info).size + assert_equal 'my_log_subscriber.some_event', @logger.logged(:info).last + + assert_equal 1, @logger.logged(:error).size + assert_equal 'Could not log "my_log_subscriber.puke" event. RuntimeError: puke', @logger.logged(:error).last + end +end \ No newline at end of file diff --git a/railties/test/railties/railtie_test.rb b/railties/test/railties/railtie_test.rb index b723e08281..9eb4e9993a 100644 --- a/railties/test/railties/railtie_test.rb +++ b/railties/test/railties/railtie_test.rb @@ -51,12 +51,12 @@ module RailtiesTest assert_equal "bar", Bar.config.foo.bar end - test "railtie can add subscribers" do + test "railtie can add log subscribers" do begin - class Foo < Rails::Railtie ; subscriber(Rails::Subscriber.new) ; end - assert_kind_of Rails::Subscriber, Rails::Subscriber.subscribers[:foo] + class Foo < Rails::Railtie ; log_subscriber(Rails::LogSubscriber.new) ; end + assert_kind_of Rails::LogSubscriber, Rails::LogSubscriber.log_subscribers[:foo] ensure - Rails::Subscriber.subscribers.clear + Rails::LogSubscriber.log_subscribers.clear end end diff --git a/railties/test/subscriber_test.rb b/railties/test/subscriber_test.rb deleted file mode 100644 index f6c895093f..0000000000 --- a/railties/test/subscriber_test.rb +++ /dev/null @@ -1,119 +0,0 @@ -require 'abstract_unit' -require 'rails/subscriber/test_helper' - -class MySubscriber < Rails::Subscriber - attr_reader :event - - def some_event(event) - @event = event - info event.name - end - - def foo(event) - debug "debug" - info "info" - warn "warn" - end - - def bar(event) - info "#{color("cool", :red)}, #{color("isn't it?", :blue, true)}" - end - - def puke(event) - raise "puke" - end -end - -class SyncSubscriberTest < ActiveSupport::TestCase - include Rails::Subscriber::TestHelper - - def setup - super - @subscriber = MySubscriber.new - Rails::Subscriber.instance_variable_set(:@log_tailer, nil) - end - - def teardown - super - Rails::Subscriber.subscribers.clear - Rails::Subscriber.instance_variable_set(:@log_tailer, nil) - end - - def instrument(*args, &block) - ActiveSupport::Notifications.instrument(*args, &block) - end - - def test_proxies_method_to_rails_logger - @subscriber.foo(nil) - assert_equal %w(debug), @logger.logged(:debug) - assert_equal %w(info), @logger.logged(:info) - assert_equal %w(warn), @logger.logged(:warn) - end - - def test_set_color_for_messages - Rails::Subscriber.colorize_logging = true - @subscriber.bar(nil) - assert_equal "\e[31mcool\e[0m, \e[1m\e[34misn't it?\e[0m", @logger.logged(:info).last - end - - def test_does_not_set_color_if_colorize_logging_is_set_to_false - @subscriber.bar(nil) - assert_equal "cool, isn't it?", @logger.logged(:info).last - end - - def test_event_is_sent_to_the_registered_class - Rails::Subscriber.add :my_subscriber, @subscriber - instrument "my_subscriber.some_event" - wait - assert_equal %w(my_subscriber.some_event), @logger.logged(:info) - end - - def test_event_is_an_active_support_notifications_event - Rails::Subscriber.add :my_subscriber, @subscriber - instrument "my_subscriber.some_event" - wait - assert_kind_of ActiveSupport::Notifications::Event, @subscriber.event - end - - def test_does_not_send_the_event_if_it_doesnt_match_the_class - Rails::Subscriber.add :my_subscriber, @subscriber - instrument "my_subscriber.unknown_event" - wait - # If we get here, it means that NoMethodError was raised. - end - - def test_does_not_send_the_event_if_logger_is_nil - Rails.logger = nil - @subscriber.expects(:some_event).never - Rails::Subscriber.add :my_subscriber, @subscriber - instrument "my_subscriber.some_event" - wait - end - - def test_flushes_loggers - Rails::Subscriber.add :my_subscriber, @subscriber - Rails::Subscriber.flush_all! - assert_equal 1, @logger.flush_count - end - - def test_flushes_the_same_logger_just_once - Rails::Subscriber.add :my_subscriber, @subscriber - Rails::Subscriber.add :another, @subscriber - Rails::Subscriber.flush_all! - wait - assert_equal 1, @logger.flush_count - end - - def test_logging_does_not_die_on_failures - Rails::Subscriber.add :my_subscriber, @subscriber - instrument "my_subscriber.puke" - instrument "my_subscriber.some_event" - wait - - assert_equal 1, @logger.logged(:info).size - assert_equal 'my_subscriber.some_event', @logger.logged(:info).last - - assert_equal 1, @logger.logged(:error).size - assert_equal 'Could not log "my_subscriber.puke" event. RuntimeError: puke', @logger.logged(:error).last - end -end \ No newline at end of file -- cgit v1.2.3 From 01cd9d66ede0a528725728f2d73cf6e7796ccb02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Tue, 16 Feb 2010 21:37:30 +0100 Subject: Subscriber should not explode if a non namespaced instrumentation is given. --- railties/lib/rails/log_subscriber.rb | 3 ++- railties/test/log_subscriber_test.rb | 8 +++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/railties/lib/rails/log_subscriber.rb b/railties/lib/rails/log_subscriber.rb index c867b92b6b..05cb70690a 100644 --- a/railties/lib/rails/log_subscriber.rb +++ b/railties/lib/rails/log_subscriber.rb @@ -60,8 +60,9 @@ module Rails def self.dispatch(args) namespace, name = args[0].split(".") - log_subscriber = log_subscribers[namespace.to_sym] + return unless namespace && name + log_subscriber = log_subscribers[namespace.to_sym] if log_subscriber.respond_to?(name) && log_subscriber.logger begin log_subscriber.send(name, ActiveSupport::Notifications::Event.new(*args)) diff --git a/railties/test/log_subscriber_test.rb b/railties/test/log_subscriber_test.rb index be176df1bb..a4de023e65 100644 --- a/railties/test/log_subscriber_test.rb +++ b/railties/test/log_subscriber_test.rb @@ -79,7 +79,7 @@ class SyncLogSubscriberTest < ActiveSupport::TestCase Rails::LogSubscriber.add :my_log_subscriber, @log_subscriber instrument "my_log_subscriber.unknown_event" wait - # If we get here, it means that NoMethodError was raised. + # If we get here, it means that NoMethodError was not raised. end def test_does_not_send_the_event_if_logger_is_nil @@ -90,6 +90,12 @@ class SyncLogSubscriberTest < ActiveSupport::TestCase wait end + def test_does_not_fail_with_non_namespaced_events + Rails::LogSubscriber.add :my_log_subscriber, @log_subscriber + instrument "whatever" + wait + end + def test_flushes_loggers Rails::LogSubscriber.add :my_log_subscriber, @log_subscriber Rails::LogSubscriber.flush_all! -- cgit v1.2.3 From 72cb0bf4146444c80319503b5813b967454ec77d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Tue, 16 Feb 2010 22:09:42 +0100 Subject: Do not swallow controller loading errors unless required. --- actionpack/lib/action_dispatch/routing/route_set.rb | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index dcf98b729b..7092eb6cef 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -19,12 +19,7 @@ module ActionDispatch def call(env) params = env[PARAMETERS_KEY] prepare_params!(params) - - unless controller = controller(params) - return [404, {'X-Cascade' => 'pass'}, []] - end - - controller.action(params[:action]).call(env) + controller(params).action(params[:action]).call(env) end def prepare_params!(params) @@ -39,14 +34,13 @@ module ActionDispatch end end - def controller(params) + def controller(params, swallow=false) if params && params.has_key?(:controller) controller = "#{params[:controller].camelize}Controller" ActiveSupport::Inflector.constantize(controller) end rescue NameError => e - raise unless e.message.include?(controller) - nil + raise ActionController::RoutingError, e.message, e.backtrace unless swallow end private @@ -433,7 +427,7 @@ module ActionDispatch req = Rack::Request.new(env) @set.recognize(req) do |route, params| dispatcher = route.app - if dispatcher.is_a?(Dispatcher) && dispatcher.controller(params) + if dispatcher.is_a?(Dispatcher) && dispatcher.controller(params, true) dispatcher.prepare_params!(params) return params end -- cgit v1.2.3 From 19787e62596ebba23da776946d2da72ae6243001 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Tue, 16 Feb 2010 22:31:40 +0100 Subject: Should allow symbols in :only and :except in routes. --- actionpack/lib/action_dispatch/routing/mapper.rb | 10 +++++----- actionpack/test/dispatch/routing_test.rb | 11 +++++++++-- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 8de68b3174..0e9291490c 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -367,9 +367,9 @@ module ActionDispatch def actions if only = options[:only] - only.map(&:to_sym) + Array(only).map(&:to_sym) elsif except = options[:except] - default_actions - except.map(&:to_sym) + default_actions - Array(except).map(&:to_sym) else default_actions end @@ -443,7 +443,7 @@ module ActionDispatch def resource(*resources, &block) options = resources.extract_options! - if verify_common_behavior_for(:resource, resources, options, &block) + if apply_common_behavior_for(:resource, resources, options, &block) return self end @@ -468,7 +468,7 @@ module ActionDispatch def resources(*resources, &block) options = resources.extract_options! - if verify_common_behavior_for(:resources, resources, options, &block) + if apply_common_behavior_for(:resources, resources, options, &block) return self end @@ -591,7 +591,7 @@ module ActionDispatch path_names[name.to_sym] || name.to_s end - def verify_common_behavior_for(method, resources, options, &block) + def apply_common_behavior_for(method, resources, options, &block) if resources.length > 1 resources.each { |r| send(method, r, options, &block) } return true diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb index bcb97e4ae0..0cd1fddff1 100644 --- a/actionpack/test/dispatch/routing_test.rb +++ b/actionpack/test/dispatch/routing_test.rb @@ -104,7 +104,9 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest end end - resources :posts, :only => [:index, :show] + resources :posts, :only => [:index, :show] do + resources :comments, :except => :destroy + end match 'sprockets.js' => ::TestRoutingMapper::SprocketsApp @@ -471,7 +473,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest end end - def test_posts + def test_resource_routes_with_only_and_except with_test_routes do get '/posts' assert_equal 'posts#index', @response.body @@ -481,9 +483,14 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest assert_equal 'posts#show', @response.body assert_equal '/posts/1', post_path(:id => 1) + get '/posts/1/comments' + assert_equal 'comments#index', @response.body + assert_equal '/posts/1/comments', post_comments_path(:post_id => 1) + assert_raise(ActionController::RoutingError) { post '/posts' } assert_raise(ActionController::RoutingError) { put '/posts/1' } assert_raise(ActionController::RoutingError) { delete '/posts/1' } + assert_raise(ActionController::RoutingError) { delete '/posts/1/comments' } end end -- cgit v1.2.3 From 47a236e291f0235a08ce4bb2a2d43fe221794461 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Tue, 16 Feb 2010 22:54:56 +0100 Subject: AD::TestProcess relies on request.flash, so let's load it. --- actionpack/lib/action_dispatch/testing/test_process.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/actionpack/lib/action_dispatch/testing/test_process.rb b/actionpack/lib/action_dispatch/testing/test_process.rb index eae703e1b6..d4eecac2de 100644 --- a/actionpack/lib/action_dispatch/testing/test_process.rb +++ b/actionpack/lib/action_dispatch/testing/test_process.rb @@ -1,3 +1,5 @@ +require 'action_dispatch/middleware/flash' + module ActionDispatch module TestProcess def assigns(key = nil) -- cgit v1.2.3 From b1edd096626d6f536b87ff5e307c37a89dd78133 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Tue, 16 Feb 2010 23:26:29 +0100 Subject: Ensure render :text => resource first tries to invoke :to_text on it --- actionpack/lib/action_controller/metal/rendering.rb | 7 +++++++ actionpack/test/controller/render_test.rb | 9 +++++++++ actionpack/test/lib/controller/fake_models.rb | 1 + 3 files changed, 17 insertions(+) diff --git a/actionpack/lib/action_controller/metal/rendering.rb b/actionpack/lib/action_controller/metal/rendering.rb index 0aae9f8579..0bd362fd64 100644 --- a/actionpack/lib/action_controller/metal/rendering.rb +++ b/actionpack/lib/action_controller/metal/rendering.rb @@ -36,6 +36,13 @@ module ActionController super end + def _determine_template(options) + if options.key?(:text) && options[:text].respond_to?(:to_text) + options[:text] = options[:text].to_text + end + super + end + def format_for_text formats.first end diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb index 2c3dc2a72d..eceec3b08e 100644 --- a/actionpack/test/controller/render_test.rb +++ b/actionpack/test/controller/render_test.rb @@ -214,6 +214,10 @@ class TestController < ActionController::Base render :text => false end + def render_text_with_resource + render :text => Customer.new("David") + end + # :ported: def render_nothing_with_appendix render :text => "appended" @@ -817,6 +821,11 @@ class RenderTest < ActionController::TestCase assert_equal 'appended', @response.body end + def test_render_text_with_resource + get :render_text_with_resource + assert_equal 'name: David', @response.body + end + # :ported: def test_attempt_to_access_object_method assert_raise(ActionController::UnknownAction, "No action responded to [clone]") { get :clone } diff --git a/actionpack/test/lib/controller/fake_models.rb b/actionpack/test/lib/controller/fake_models.rb index 7346cb22bc..a8c86f70b6 100644 --- a/actionpack/test/lib/controller/fake_models.rb +++ b/actionpack/test/lib/controller/fake_models.rb @@ -21,6 +21,7 @@ class Customer < Struct.new(:name, :id) def to_js(options={}) "name: #{name.inspect}" end + alias :to_text :to_js def errors [] -- cgit v1.2.3 From 762088a0ef1f69ab09833732cfe8190098303ee6 Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Tue, 16 Feb 2010 15:00:10 -0800 Subject: Clear the attribute after done --- activesupport/test/core_ext/class/delegating_attributes_test.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/activesupport/test/core_ext/class/delegating_attributes_test.rb b/activesupport/test/core_ext/class/delegating_attributes_test.rb index 011068ab74..636edb8d4b 100644 --- a/activesupport/test/core_ext/class/delegating_attributes_test.rb +++ b/activesupport/test/core_ext/class/delegating_attributes_test.rb @@ -84,6 +84,8 @@ class DelegatingAttributesTest < Test::Unit::TestCase assert_equal "1", Child.some_attribute assert_nil Mokopuna.some_attribute + ensure + Child.some_attribute=nil end end -- cgit v1.2.3 From e8ef12e39d4af20c5211cd92aa560590fa5387cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Wed, 17 Feb 2010 00:14:49 +0100 Subject: Make Railties tests green again. --- actionpack/lib/action_dispatch/routing/route_set.rb | 19 ++++++++++++------- actionpack/test/controller/render_test.rb | 2 +- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 7092eb6cef..c3fda0aaef 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -11,15 +11,21 @@ module ActionDispatch PARAMETERS_KEY = 'action_dispatch.request.path_parameters' class Dispatcher - def initialize(options = {}) - defaults = options[:defaults] + def initialize(options={}) + @defaults = options[:defaults] @glob_param = options.delete(:glob) end def call(env) params = env[PARAMETERS_KEY] prepare_params!(params) - controller(params).action(params[:action]).call(env) + + # Just raise undefined constant errors if a controller was specified as default. + unless controller = controller(params, @defaults.key?(:controller)) + return [404, {'X-Cascade' => 'pass'}, []] + end + + controller.action(params[:action]).call(env) end def prepare_params!(params) @@ -34,13 +40,13 @@ module ActionDispatch end end - def controller(params, swallow=false) + def controller(params, raise_error=true) if params && params.has_key?(:controller) controller = "#{params[:controller].camelize}Controller" ActiveSupport::Inflector.constantize(controller) end rescue NameError => e - raise ActionController::RoutingError, e.message, e.backtrace unless swallow + raise ActionController::RoutingError, e.message, e.backtrace if raise_error end private @@ -53,7 +59,6 @@ module ActionDispatch end end - # A NamedRouteCollection instance is a collection of named routes, and also # maintains an anonymous module that can be used to install helpers for the # named routes. @@ -427,7 +432,7 @@ module ActionDispatch req = Rack::Request.new(env) @set.recognize(req) do |route, params| dispatcher = route.app - if dispatcher.is_a?(Dispatcher) && dispatcher.controller(params, true) + if dispatcher.is_a?(Dispatcher) && dispatcher.controller(params, false) dispatcher.prepare_params!(params) return params end diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb index eceec3b08e..3cc22cc316 100644 --- a/actionpack/test/controller/render_test.rb +++ b/actionpack/test/controller/render_test.rb @@ -823,7 +823,7 @@ class RenderTest < ActionController::TestCase def test_render_text_with_resource get :render_text_with_resource - assert_equal 'name: David', @response.body + assert_equal 'name: "David"', @response.body end # :ported: -- cgit v1.2.3 From 23fd1f12801c8585ff3b114e74264b67ad6264e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Wed, 17 Feb 2010 00:15:21 +0100 Subject: Show deprecation message for rails/init.rb in plugins. --- railties/lib/rails/plugin.rb | 10 ++++++++-- railties/test/railties/plugin_test.rb | 9 +++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/railties/lib/rails/plugin.rb b/railties/lib/rails/plugin.rb index 64d03e7599..882f2dc28e 100644 --- a/railties/lib/rails/plugin.rb +++ b/railties/lib/rails/plugin.rb @@ -29,7 +29,7 @@ module Rails unless extra_tasks.empty? ActiveSupport::Deprecation.warn "Having rake tasks in PLUGIN_PATH/tasks or " << - "PLUGIN_PATH/rails/tasks is deprecated. Use to PLUGIN_PATH/lib/tasks instead" + "PLUGIN_PATH/rails/tasks is deprecated. Use PLUGIN_PATH/lib/tasks instead" extra_tasks.sort.each { |ext| load(ext) } end end @@ -44,7 +44,13 @@ module Rails end initializer :load_init_rb, :before => :load_application_initializers do |app| - file = Dir["#{root}/{rails/init,init}.rb"].first + if File.file?(file = File.expand_path("rails/init.rb", root)) + ActiveSupport::Deprecation.warn "PLUGIN_PATH/rails/init.rb in plugins is deprecated. " << + "Use PLUGIN_PATH/init.rb instead" + else + file = File.expand_path("init.rb", root) + end + config = app.config eval(File.read(file), binding, file) if file && File.file?(file) end diff --git a/railties/test/railties/plugin_test.rb b/railties/test/railties/plugin_test.rb index 09b859dcdd..0f5f29468c 100644 --- a/railties/test/railties/plugin_test.rb +++ b/railties/test/railties/plugin_test.rb @@ -94,6 +94,15 @@ module RailtiesTest assert rescued, "Expected boot rails to fail" end + test "loads deprecated rails/init.rb" do + @plugin.write "rails/init.rb", <<-RUBY + $loaded = true + RUBY + + boot_rails + assert $loaded + end + test "deprecated tasks are also loaded" do $executed = false @plugin.write "tasks/foo.rake", <<-RUBY -- cgit v1.2.3 From d4e008fd0f9ebac3383a0c3ac093de68db9e2e66 Mon Sep 17 00:00:00 2001 From: Kyle Maxwell Date: Thu, 11 Feb 2010 16:04:24 -0800 Subject: Invalid namespace on app generation raises an error MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- railties/lib/generators/rails/app/app_generator.rb | 9 +++++++-- railties/test/generators/app_generator_test.rb | 5 +++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/railties/lib/generators/rails/app/app_generator.rb b/railties/lib/generators/rails/app/app_generator.rb index c439ed89f5..ea1930a966 100644 --- a/railties/lib/generators/rails/app/app_generator.rb +++ b/railties/lib/generators/rails/app/app_generator.rb @@ -7,6 +7,10 @@ module Rails::Generators # can change in Ruby 1.8.7 when we FileUtils.cd. RAILS_DEV_PATH = File.expand_path("../../../../..", File.dirname(__FILE__)) + RESERVED_NAMES = %w[generate console server dbconsole + application destroy benchmarker profiler + plugin runner test] + class AppGenerator < Base DATABASES = %w( mysql oracle postgresql sqlite3 frontbase ibm_db ) @@ -209,9 +213,10 @@ module Rails::Generators end def valid_app_const? - case app_const - when /^\d/ + if app_const =~ /^\d/ raise Error, "Invalid application name #{app_name}. Please give a name which does not start with numbers." + elsif RESERVED_NAMES.include?(app_name) + raise Error, "Invalid application name #{app_name}. Please give a name which does not match one of the reserved rails words." end end diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb index 0a746b200f..01d643cd8c 100644 --- a/railties/test/generators/app_generator_test.rb +++ b/railties/test/generators/app_generator_test.rb @@ -50,6 +50,11 @@ class AppGeneratorTest < Rails::Generators::TestCase ).each{ |path| assert_file path } end + def test_name_collision_raises_an_error + content = capture(:stderr){ run_generator [File.join(destination_root, "generate")] } + assert_equal "Invalid application name generate. Please give a name which does not match one of the reserved rails words.\n", content + end + def test_invalid_database_option_raises_an_error content = capture(:stderr){ run_generator([destination_root, "-d", "unknown"]) } assert_match /Invalid value for \-\-database option/, content -- cgit v1.2.3 From e195b48f21bac800dbad5acc04ac732930d36c35 Mon Sep 17 00:00:00 2001 From: Carl Lerche Date: Tue, 16 Feb 2010 17:15:56 -0800 Subject: Have CI use the current version of bundler --- ci/ci_build.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ci/ci_build.rb b/ci/ci_build.rb index 0c7dd837b1..d0895dc35d 100755 --- a/ci/ci_build.rb +++ b/ci/ci_build.rb @@ -19,7 +19,7 @@ puts "[CruiseControl] Rails build" build_results = {} # Install required version of bundler. -bundler_install_cmd = "gem install bundler -v 0.9.3 --no-ri --no-rdoc" +bundler_install_cmd = "gem install bundler -v 0.9.6 --no-ri --no-rdoc" puts "Running command: #{bundler_install_cmd}" build_results[:install_bundler] = system bundler_install_cmd -- cgit v1.2.3 From d0454e57661ceeaebd6f3fce4a608ec624257b19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Wed, 17 Feb 2010 18:09:13 +0100 Subject: Add readme as method in Rails::Generators::Actions (as we had in 2.3) --- railties/lib/rails/generators/actions.rb | 10 ++++++++++ railties/railties.gemspec | 2 +- railties/test/generators/actions_test.rb | 6 ++++++ 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/railties/lib/rails/generators/actions.rb b/railties/lib/rails/generators/actions.rb index d41da773c6..e39fa3ff11 100644 --- a/railties/lib/rails/generators/actions.rb +++ b/railties/lib/rails/generators/actions.rb @@ -280,6 +280,16 @@ module Rails end end + # Reads the given file at the source root and prints it in the console. + # + # === Example + # + # readme "README" + # + def readme(path) + say File.read(find_in_source_paths(path)) + end + protected # Define log for backwards compatibility. If just one argument is sent, diff --git a/railties/railties.gemspec b/railties/railties.gemspec index 9b07fcc30f..44475b82cf 100644 --- a/railties/railties.gemspec +++ b/railties/railties.gemspec @@ -21,7 +21,7 @@ Gem::Specification.new do |s| s.has_rdoc = false s.add_dependency('rake', '>= 0.8.3') - s.add_dependency('thor', '~> 0.13.0') + s.add_dependency('thor', '~> 0.13.3') s.add_dependency('activesupport', '= 3.0.0.beta1') s.add_dependency('actionpack', '= 3.0.0.beta1') end diff --git a/railties/test/generators/actions_test.rb b/railties/test/generators/actions_test.rb index 5929db6318..3585e6e7c0 100644 --- a/railties/test/generators/actions_test.rb +++ b/railties/test/generators/actions_test.rb @@ -210,6 +210,12 @@ class ActionsTest < Rails::Generators::TestCase assert_file 'config/routes.rb', /#{Regexp.escape(route_command)}/ end + def test_readme + run_generator + Rails::Generators::AppGenerator.expects(:source_root).returns(destination_root) + assert_match(/Welcome to Rails/, action(:readme, "README")) + end + protected def action(*args, &block) -- cgit v1.2.3 From 7189e3c8816ea4dc88c09bdd109c4a503fc5c4dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Wed, 17 Feb 2010 18:43:24 +0100 Subject: Rename router internal option :namespace to :controller_namespace which is its real purpose. --- actionpack/lib/action_dispatch/routing/mapper.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 0e9291490c..bead321c9c 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -283,7 +283,7 @@ module ActionDispatch end def namespace(path) - scope(path.to_s, :name_prefix => path.to_s, :namespace => path.to_s) { yield } + scope(path.to_s, :name_prefix => path.to_s, :controller_namespace => path.to_s) { yield } end def constraints(constraints = {}) @@ -318,12 +318,12 @@ module ActionDispatch parent ? "#{parent}_#{child}" : child end - def merge_namespace_scope(parent, child) + def merge_controller_namespace_scope(parent, child) parent ? "#{parent}/#{child}" : child end def merge_controller_scope(parent, child) - @scope[:namespace] ? "#{@scope[:namespace]}/#{child}" : child + @scope[:controller_namespace] ? "#{@scope[:controller_namespace]}/#{child}" : child end def merge_resources_path_names_scope(parent, child) -- cgit v1.2.3 From 1477a6101da631a117427a1e53668dfe093a3726 Mon Sep 17 00:00:00 2001 From: Aaron Date: Thu, 18 Feb 2010 09:21:01 -0800 Subject: Fix called_from under Windows so engines works properly MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- railties/lib/rails/engine.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb index 53e54d7400..a158bb7b70 100644 --- a/railties/lib/rails/engine.rb +++ b/railties/lib/rails/engine.rb @@ -15,7 +15,7 @@ module Rails def inherited(base) unless abstract_railtie?(base) base.called_from = begin - call_stack = caller.map { |p| p.split(':').first } + call_stack = caller.map { |p| p.split(':')[0..-2].join(':') } File.dirname(call_stack.detect { |p| p !~ %r[railties[\w\-]*/lib/rails|rack[\w\-]*/lib/rack] }) end end -- cgit v1.2.3 From a5684dfa3c16472bfa5d5d861ba78cb6dbadcb59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Thu, 18 Feb 2010 18:39:39 +0100 Subject: Ensure config.after_initializer is executed before building the middleware stack. --- railties/lib/rails/application/finisher.rb | 10 ++++++---- railties/lib/rails/engine.rb | 1 + .../test/application/initializers/initializers_test.rb | 14 ++++++++++++++ 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/railties/lib/rails/application/finisher.rb b/railties/lib/rails/application/finisher.rb index b722679ec2..afa79cad1c 100644 --- a/railties/lib/rails/application/finisher.rb +++ b/railties/lib/rails/application/finisher.rb @@ -27,17 +27,19 @@ module Rails end end - initializer :build_middleware_stack do - app - end - # Fires the user-supplied after_initialize block (config.after_initialize) + # Should run before the middleware stack is built, because building the + # middleware already fires to_prepare callbacks in test and production. initializer :after_initialize do config.after_initialize_blocks.each do |block| block.call(self) end end + initializer :build_middleware_stack do + app + end + # Disable dependency loading during request cycle initializer :disable_dependency_loading do if config.cache_classes && !config.dependency_loading diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb index a158bb7b70..efa11b466a 100644 --- a/railties/lib/rails/engine.rb +++ b/railties/lib/rails/engine.rb @@ -15,6 +15,7 @@ module Rails def inherited(base) unless abstract_railtie?(base) base.called_from = begin + # Remove the line number from backtraces making sure we don't leave anything behind call_stack = caller.map { |p| p.split(':')[0..-2].join(':') } File.dirname(call_stack.detect { |p| p !~ %r[railties[\w\-]*/lib/rails|rack[\w\-]*/lib/rack] }) end diff --git a/railties/test/application/initializers/initializers_test.rb b/railties/test/application/initializers/initializers_test.rb index 0c3de7ce33..a6d37b15f1 100644 --- a/railties/test/application/initializers/initializers_test.rb +++ b/railties/test/application/initializers/initializers_test.rb @@ -51,5 +51,19 @@ module ApplicationTests assert $activerecord_configurations assert $activerecord_configurations['development'] end + + test "after_initialize happens before to_prepare (i.e. before the middleware stack is built) on production" do + $order = [] + add_to_config <<-RUBY + config.after_initialize { $order << :after_initialize } + config.to_prepare { $order << :to_prepare } + RUBY + + require "#{app_path}/config/application" + Rails.env.replace "production" + require "#{app_path}/config/environment" + assert [:after_initialize, :to_prepare], $order + end + end end -- cgit v1.2.3 From cc852e2580575b715134cce65d6b3dc8826fe918 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Thu, 18 Feb 2010 10:47:45 -0800 Subject: Use FileUtils.mv instead of rename to copy in case of cross-device links --- activesupport/lib/active_support/core_ext/file/atomic.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/activesupport/lib/active_support/core_ext/file/atomic.rb b/activesupport/lib/active_support/core_ext/file/atomic.rb index 49d28e8a34..26b73ed442 100644 --- a/activesupport/lib/active_support/core_ext/file/atomic.rb +++ b/activesupport/lib/active_support/core_ext/file/atomic.rb @@ -14,6 +14,7 @@ class File # end def self.atomic_write(file_name, temp_dir = Dir.tmpdir) require 'tempfile' unless defined?(Tempfile) + require 'fileutils' unless defined?(FileUtils) temp_file = Tempfile.new(basename(file_name), temp_dir) yield temp_file @@ -31,7 +32,7 @@ class File end # Overwrite original file with temp file - rename(temp_file.path, file_name) + FileUtils.mv(temp_file.path, file_name) # Set correct permissions on new file chown(old_stat.uid, old_stat.gid, file_name) -- cgit v1.2.3 From 8a1f057a26135f9b94717d72fff704843f56f521 Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Thu, 18 Feb 2010 12:26:16 -0800 Subject: Update Renderer --- actionpack/lib/action_controller/metal/rendering.rb | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/actionpack/lib/action_controller/metal/rendering.rb b/actionpack/lib/action_controller/metal/rendering.rb index 0bd362fd64..b1dab8497b 100644 --- a/actionpack/lib/action_controller/metal/rendering.rb +++ b/actionpack/lib/action_controller/metal/rendering.rb @@ -2,13 +2,12 @@ module ActionController module Rendering extend ActiveSupport::Concern - included do - include AbstractController::Rendering - include AbstractController::LocalizedCache - end + include RackDelegation + include AbstractController::Rendering + include AbstractController::LocalizedCache def process_action(*) - self.formats = request.formats.map {|x| x.to_sym} + self.formats = request.formats.map {|x| x.to_sym } super end -- cgit v1.2.3 From 98c299fba5bdaf3f1c156c2e16a5a95a5d9cf251 Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Thu, 18 Feb 2010 14:04:08 -0800 Subject: Don't constantize possible module names when looking for new constants unless they exist --- activesupport/lib/active_support/dependencies.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb index 87d56eb17e..107f664960 100644 --- a/activesupport/lib/active_support/dependencies.rb +++ b/activesupport/lib/active_support/dependencies.rb @@ -78,6 +78,7 @@ module ActiveSupport #:nodoc: def new_constants_for(frames) frames.map do |mod_name, prior_constants| mod = Inflector.constantize(mod_name) + mod = Inflector.constantize(mod_name) if Dependencies.qualified_const_defined?(mod_name) next unless mod.is_a?(Module) new_constants = mod.local_constant_names - prior_constants -- cgit v1.2.3 From ae8c384e2c07da4870dd3919321a6d49aeff3588 Mon Sep 17 00:00:00 2001 From: Carl Lerche Date: Thu, 18 Feb 2010 16:29:32 -0800 Subject: Avoid calling triggering const_missing if const_missing is private when doing constantize --- activesupport/lib/active_support/inflector/methods.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activesupport/lib/active_support/inflector/methods.rb b/activesupport/lib/active_support/inflector/methods.rb index 41277893e3..c7df62e915 100644 --- a/activesupport/lib/active_support/inflector/methods.rb +++ b/activesupport/lib/active_support/inflector/methods.rb @@ -109,7 +109,7 @@ module ActiveSupport constant = Object names.each do |name| - constant = constant.const_get(name, false) || constant.const_missing(name) + constant = constant.const_defined?(name, false) ? constant.const_get(name) : constant.const_missing(name) end constant end -- cgit v1.2.3 From af05420d6bf7cb1c337e95f9941e7db30c521d31 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Thu, 18 Feb 2010 22:33:24 -0200 Subject: i18n translate with arrays issue solved Signed-off-by: Yehuda Katz --- actionpack/lib/action_view/helpers/translation_helper.rb | 5 +++-- actionpack/test/template/translation_helper_test.rb | 5 +++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/actionpack/lib/action_view/helpers/translation_helper.rb b/actionpack/lib/action_view/helpers/translation_helper.rb index c348ea7a0d..a42e5542f2 100644 --- a/actionpack/lib/action_view/helpers/translation_helper.rb +++ b/actionpack/lib/action_view/helpers/translation_helper.rb @@ -12,7 +12,8 @@ module ActionView # prepend the key with a period, nothing is converted. def translate(key, options = {}) options[:raise] = true - I18n.translate(scope_key_by_partial(key), options).html_safe + translation = I18n.translate(scope_key_by_partial(key), options) + translation.is_a?(Array) ? translation.map { |entry| entry.html_safe } : translation.html_safe rescue I18n::MissingTranslationData => e keys = I18n.send(:normalize_translation_keys, e.locale, e.key, e.options[:scope]) content_tag('span', keys.join(', '), :class => 'translation_missing') @@ -40,4 +41,4 @@ module ActionView end end end -end \ No newline at end of file +end diff --git a/actionpack/test/template/translation_helper_test.rb b/actionpack/test/template/translation_helper_test.rb index 4b73c44f7e..699fb2f5bc 100644 --- a/actionpack/test/template/translation_helper_test.rb +++ b/actionpack/test/template/translation_helper_test.rb @@ -18,6 +18,11 @@ class TranslationHelperTest < ActiveSupport::TestCase assert_equal expected, translate(:foo) end + def test_translation_of_an_array + I18n.expects(:translate).with(["foo", "bar"], :raise => true).returns(["foo", "bar"]) + assert_equal ["foo", "bar"], translate(["foo", "bar"]) + end + def test_delegates_localize_to_i18n @time = Time.utc(2008, 7, 8, 12, 18, 38) I18n.expects(:localize).with(@time) -- cgit v1.2.3 From e6ce8564623c20b080a98cc5e6548ac14635c991 Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Thu, 18 Feb 2010 16:48:28 -0800 Subject: Git fail --- activesupport/lib/active_support/dependencies.rb | 1 - 1 file changed, 1 deletion(-) diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb index 107f664960..da1050298b 100644 --- a/activesupport/lib/active_support/dependencies.rb +++ b/activesupport/lib/active_support/dependencies.rb @@ -77,7 +77,6 @@ module ActiveSupport #:nodoc: def new_constants_for(frames) frames.map do |mod_name, prior_constants| - mod = Inflector.constantize(mod_name) mod = Inflector.constantize(mod_name) if Dependencies.qualified_const_defined?(mod_name) next unless mod.is_a?(Module) -- cgit v1.2.3 From e2806929ec4bc3d429011039f4b046b600b7c8f8 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Thu, 18 Feb 2010 23:02:41 -0200 Subject: ruby 1.9 array.to_s returns a string representing an escaped array Signed-off-by: Yehuda Katz --- actionpack/lib/action_view/helpers/translation_helper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actionpack/lib/action_view/helpers/translation_helper.rb b/actionpack/lib/action_view/helpers/translation_helper.rb index a42e5542f2..7d954b3a2f 100644 --- a/actionpack/lib/action_view/helpers/translation_helper.rb +++ b/actionpack/lib/action_view/helpers/translation_helper.rb @@ -29,7 +29,7 @@ module ActionView private def scope_key_by_partial(key) - if key.to_s.first == "." + if (key.respond_to?(:join) ? key.join : key.to_s).first == "." if @_virtual_path @_virtual_path.gsub(%r{/_?}, ".") + key.to_s else -- cgit v1.2.3 From e49f94d71cdcdd3b891959e59203fd5e664c8add Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Fri, 19 Feb 2010 08:02:28 +0100 Subject: Revert behavior from a5684dfa3c16472bfa5d5d861ba78cb6dbadcb59 and ensure after_initializer is executed after to_prepare callbacks. --- actionpack/lib/action_dispatch/middleware/callbacks.rb | 2 +- railties/lib/rails/application/finisher.rb | 11 ++++------- .../test/application/initializers/initializers_test.rb | 18 +++++++++++++++--- 3 files changed, 20 insertions(+), 11 deletions(-) diff --git a/actionpack/lib/action_dispatch/middleware/callbacks.rb b/actionpack/lib/action_dispatch/middleware/callbacks.rb index 7cf75ffe63..d07841218a 100644 --- a/actionpack/lib/action_dispatch/middleware/callbacks.rb +++ b/actionpack/lib/action_dispatch/middleware/callbacks.rb @@ -37,7 +37,7 @@ module ActionDispatch def initialize(app, prepare_each_request = false) @app, @prepare_each_request = app, prepare_each_request - run_callbacks(:prepare) unless @prepare_each_request + run_callbacks(:prepare) end def call(env) diff --git a/railties/lib/rails/application/finisher.rb b/railties/lib/rails/application/finisher.rb index afa79cad1c..cb38d5a5db 100644 --- a/railties/lib/rails/application/finisher.rb +++ b/railties/lib/rails/application/finisher.rb @@ -27,19 +27,16 @@ module Rails end end - # Fires the user-supplied after_initialize block (config.after_initialize) - # Should run before the middleware stack is built, because building the - # middleware already fires to_prepare callbacks in test and production. + initializer :build_middleware_stack do + app + end + initializer :after_initialize do config.after_initialize_blocks.each do |block| block.call(self) end end - initializer :build_middleware_stack do - app - end - # Disable dependency loading during request cycle initializer :disable_dependency_loading do if config.cache_classes && !config.dependency_loading diff --git a/railties/test/application/initializers/initializers_test.rb b/railties/test/application/initializers/initializers_test.rb index a6d37b15f1..2e6a707175 100644 --- a/railties/test/application/initializers/initializers_test.rb +++ b/railties/test/application/initializers/initializers_test.rb @@ -52,9 +52,22 @@ module ApplicationTests assert $activerecord_configurations['development'] end - test "after_initialize happens before to_prepare (i.e. before the middleware stack is built) on production" do + test "after_initialize happens after to_prepare in development" do $order = [] add_to_config <<-RUBY + config.cache_classes = false + config.after_initialize { $order << :after_initialize } + config.to_prepare { $order << :to_prepare } + RUBY + + require "#{app_path}/config/environment" + assert [:to_prepare, :after_initialize], $order + end + + test "after_initialize happens after to_prepare in production" do + $order = [] + add_to_config <<-RUBY + config.cache_classes = true config.after_initialize { $order << :after_initialize } config.to_prepare { $order << :to_prepare } RUBY @@ -62,8 +75,7 @@ module ApplicationTests require "#{app_path}/config/application" Rails.env.replace "production" require "#{app_path}/config/environment" - assert [:after_initialize, :to_prepare], $order + assert [:to_prepare, :after_initialize], $order end - end end -- cgit v1.2.3 From be35a1510d065fc8575524e1b6b9f2bebd3e138c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Fri, 19 Feb 2010 10:51:17 +0100 Subject: Allow to choose the template path and template name used in implicit rendering with ActionMailer. --- actionmailer/lib/action_mailer/base.rb | 70 ++++++++++++++++++++++------------ actionmailer/test/base_test.rb | 57 +++++++++++++++++---------- 2 files changed, 81 insertions(+), 46 deletions(-) diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb index 4e89c1ea0c..ce13111850 100644 --- a/actionmailer/lib/action_mailer/base.rb +++ b/actionmailer/lib/action_mailer/base.rb @@ -452,10 +452,27 @@ module ActionMailer #:nodoc: # field for the 'envelope from' value. # # If you do not pass a block to the +mail+ method, it will find all templates in the - # template path that match the method name that it is being called from, it will then - # create parts for each of these templates intelligently, making educated guesses - # on correct content type and sequence, and return a fully prepared Mail::Message - # ready to call :deliver on to send. + # view paths using by default the mailer name and the method name that it is being + # called from, it will then create parts for each of these templates intelligently, + # making educated guesses on correct content type and sequence, and return a fully + # prepared Mail::Message ready to call :deliver on to send. + # + # For example: + # + # class Notifier < ActionMailer::Base + # default :from => 'no-reply@test.lindsaar.net', + # + # def welcome + # mail(:to => 'mikel@test.lindsaar.net') + # end + # end + # + # Will look for all templates at "app/views/notifier" with name "welcome". However, those + # can be customized: + # + # mail(:template_path => 'notifications', :template_name => 'another') + # + # And now it will look for all templates at "app/views/notifications" with name "another". # # If you do pass a block, you can render specific templates of your choice: # @@ -493,7 +510,7 @@ module ActionMailer #:nodoc: # Merge defaults from class headers = headers.reverse_merge(self.class.default) - charset = headers[:charset] + charset = headers.delete(:charset) # Quote fields headers[:subject] ||= default_i18n_subject @@ -514,13 +531,11 @@ module ActionMailer #:nodoc: end # Set configure delivery behavior - wrap_delivery_behavior!(headers[:delivery_method]) + wrap_delivery_behavior!(headers.delete(:delivery_method)) - # Remove headers already treated and assign all others - headers.except!(:subject, :to, :from, :cc, :bcc, :reply_to) - headers.except!(:body, :parts_order, :content_type, :charset, :delivery_method) + # Remove any missing configuration header and assign all others + headers.except!(:parts_order, :content_type) headers.each { |k, v| m[k] = v } - m end @@ -548,12 +563,12 @@ module ActionMailer #:nodoc: # TODO: Move this into Mail def quote_fields!(headers, charset) #:nodoc: m = @_message - m.subject ||= quote_if_necessary(headers[:subject], charset) if headers[:subject] - m.to ||= quote_address_if_necessary(headers[:to], charset) if headers[:to] - m.from ||= quote_address_if_necessary(headers[:from], charset) if headers[:from] - m.cc ||= quote_address_if_necessary(headers[:cc], charset) if headers[:cc] - m.bcc ||= quote_address_if_necessary(headers[:bcc], charset) if headers[:bcc] - m.reply_to ||= quote_address_if_necessary(headers[:reply_to], charset) if headers[:reply_to] + m.subject ||= quote_if_necessary(headers.delete(:subject), charset) if headers[:subject] + m.to ||= quote_address_if_necessary(headers.delete(:to), charset) if headers[:to] + m.from ||= quote_address_if_necessary(headers.delete(:from), charset) if headers[:from] + m.cc ||= quote_address_if_necessary(headers.delete(:cc), charset) if headers[:cc] + m.bcc ||= quote_address_if_necessary(headers.delete(:bcc), charset) if headers[:bcc] + m.reply_to ||= quote_address_if_necessary(headers.delete(:reply_to), charset) if headers[:reply_to] end def collect_responses_and_parts_order(headers) #:nodoc: @@ -566,11 +581,14 @@ module ActionMailer #:nodoc: responses = collector.responses elsif headers[:body] responses << { - :body => headers[:body], + :body => headers.delete(:body), :content_type => self.class.default[:content_type] || "text/plain" } else - each_template do |template| + templates_path = headers.delete(:template_path) || self.class.mailer_name + templates_name = headers.delete(:template_name) || action_name + + each_template(templates_path, templates_name) do |template| responses << { :body => render_to_body(:_template => template), :content_type => template.mime_type.to_s @@ -581,14 +599,16 @@ module ActionMailer #:nodoc: [responses, parts_order] end - def each_template(&block) #:nodoc: - self.class.view_paths.each do |load_paths| - templates = load_paths.find_all(action_name, {}, self.class.mailer_name) - templates = templates.uniq_by { |t| t.details[:formats] } + def each_template(paths, name, &block) #:nodoc: + Array(paths).each do |path| + self.class.view_paths.each do |load_paths| + templates = load_paths.find_all(name, {}, path) + templates = templates.uniq_by { |t| t.details[:formats] } - unless templates.empty? - templates.each(&block) - return + unless templates.empty? + templates.each(&block) + return + end end end end diff --git a/actionmailer/test/base_test.rb b/actionmailer/test/base_test.rb index 222db66aaa..5fc229df09 100644 --- a/actionmailer/test/base_test.rb +++ b/actionmailer/test/base_test.rb @@ -14,8 +14,13 @@ class BaseTest < ActiveSupport::TestCase mail({:subject => "The first email on new API!"}.merge!(hash)) end - def simple(hash = {}) - mail(hash) + def welcome_with_headers(hash = {}) + headers hash + mail + end + + def welcome_from_another_path(path) + mail(:template_name => "welcome", :template_path => path) end def html_only(hash = {}) @@ -25,11 +30,6 @@ class BaseTest < ActiveSupport::TestCase def plain_text_only(hash = {}) mail(hash) end - - def simple_with_headers(hash = {}) - headers hash - mail - end def attachment_with_content(hash = {}) attachments['invoice.pdf'] = 'This is test File content' @@ -78,8 +78,12 @@ class BaseTest < ActiveSupport::TestCase format.html{ render "welcome" } if include_html end end - - def different_template(template_name='') + + def implicit_different_template(template_name='') + mail(:template_name => template_name) + end + + def explicit_different_template(template_name='') mail do |format| format.text { render :template => "#{mailer_name}/#{template_name}" } format.html { render :template => "#{mailer_name}/#{template_name}" } @@ -88,13 +92,10 @@ class BaseTest < ActiveSupport::TestCase def different_layout(layout_name='') mail do |format| - format.text { - render :layout => layout_name - } + format.text { render :layout => layout_name } format.html { render :layout => layout_name } end end - end test "method call to mail does not raise error" do @@ -154,7 +155,7 @@ class BaseTest < ActiveSupport::TestCase test "can pass random headers in as a hash to mail" do hash = {'X-Special-Domain-Specific-Header' => "SecretValue", 'In-Reply-To' => '1234@mikel.me.com' } - mail = BaseMailer.simple(hash) + mail = BaseMailer.welcome(hash) assert_equal('SecretValue', mail['X-Special-Domain-Specific-Header'].decoded) assert_equal('1234@mikel.me.com', mail['In-Reply-To'].decoded) end @@ -162,7 +163,7 @@ class BaseTest < ActiveSupport::TestCase test "can pass random headers in as a hash" do hash = {'X-Special-Domain-Specific-Header' => "SecretValue", 'In-Reply-To' => '1234@mikel.me.com' } - mail = BaseMailer.simple_with_headers(hash) + mail = BaseMailer.welcome_with_headers(hash) assert_equal('SecretValue', mail['X-Special-Domain-Specific-Header'].decoded) assert_equal('1234@mikel.me.com', mail['In-Reply-To'].decoded) end @@ -247,9 +248,9 @@ class BaseTest < ActiveSupport::TestCase end test "uses random default headers from class" do - with_default BaseMailer, "X-SPAM" => "Not spam" do - email = BaseMailer.simple - assert_equal("Not spam", email["X-SPAM"].decoded) + with_default BaseMailer, "X-Custom" => "Custom" do + email = BaseMailer.welcome + assert_equal("Custom", email["X-Custom"].decoded) end end @@ -476,18 +477,32 @@ class BaseTest < ActiveSupport::TestCase end # Rendering - test "that you can specify a different template" do - mail = BaseMailer.different_template('explicit_multipart_templates') + test "you can specify a different template for implicit render" do + mail = BaseMailer.implicit_different_template('implicit_multipart') + assert_equal("HTML Implicit Multipart", mail.html_part.body.decoded) + assert_equal("TEXT Implicit Multipart", mail.text_part.body.decoded) + end + + test "you can specify a different template for explicit render" do + mail = BaseMailer.explicit_different_template('explicit_multipart_templates') assert_equal("HTML Explicit Multipart Templates", mail.html_part.body.decoded) assert_equal("TEXT Explicit Multipart Templates", mail.text_part.body.decoded) end - test "that you can specify a different layout" do + test "you can specify a different layout" do mail = BaseMailer.different_layout('different_layout') assert_equal("HTML -- HTML", mail.html_part.body.decoded) assert_equal("PLAIN -- PLAIN", mail.text_part.body.decoded) end + test "you can specify the template path for implicit lookup" do + mail = BaseMailer.welcome_from_another_path('another.path/base_mailer') + assert_equal("Welcome from another path", mail.body.encoded) + + mail = BaseMailer.welcome_from_another_path(['unknown/invalid', 'another.path/base_mailer']) + assert_equal("Welcome from another path", mail.body.encoded) + end + protected # Execute the block setting the given values and restoring old values after -- cgit v1.2.3 From 7d7f9ccfdf986099e3c5abf05af37a886daba0b5 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Fri, 19 Feb 2010 09:31:10 -0600 Subject: Reinstate pending tests that were supposed to be fixed before the beta. Shout louder this time so they actually get fixed. --- actionpack/test/controller/send_file_test.rb | 24 +++++++++++------------- actionpack/test/dispatch/response_test.rb | 24 ++++++++---------------- 2 files changed, 19 insertions(+), 29 deletions(-) diff --git a/actionpack/test/controller/send_file_test.rb b/actionpack/test/controller/send_file_test.rb index 0afebac68c..aebbd893a8 100644 --- a/actionpack/test/controller/send_file_test.rb +++ b/actionpack/test/controller/send_file_test.rb @@ -51,19 +51,17 @@ class SendFileTest < ActionController::TestCase end def test_file_stream - pending do - response = nil - assert_nothing_raised { response = process('file') } - assert_not_nil response - assert_kind_of Array, response.body_parts - - require 'stringio' - output = StringIO.new - output.binmode - output.string.force_encoding(file_data.encoding) if output.string.respond_to?(:force_encoding) - assert_nothing_raised { response.body_parts.each { |part| output << part.to_s } } - assert_equal file_data, output.string - end + response = nil + assert_nothing_raised { response = process('file') } + assert_not_nil response + assert_kind_of Array, response.body_parts + + require 'stringio' + output = StringIO.new + output.binmode + output.string.force_encoding(file_data.encoding) if output.string.respond_to?(:force_encoding) + assert_nothing_raised { response.body_parts.each { |part| output << part.to_s } } + assert_equal file_data, output.string end def test_file_url_based_filename diff --git a/actionpack/test/dispatch/response_test.rb b/actionpack/test/dispatch/response_test.rb index 4697fa3e2b..c7f7f3102d 100644 --- a/actionpack/test/dispatch/response_test.rb +++ b/actionpack/test/dispatch/response_test.rb @@ -165,10 +165,8 @@ class ResponseIntegrationTest < ActionDispatch::IntegrationTest assert_equal('public', @response.headers['Cache-Control']) assert_equal('"202cb962ac59075b964b07152d234b70"', @response.headers['ETag']) - pending do - assert_equal('"202cb962ac59075b964b07152d234b70"', @response.etag) - assert_equal({:public => true}, @response.cache_control) - end + assert_equal('"202cb962ac59075b964b07152d234b70"', @response.etag) + assert_equal({:public => true}, @response.cache_control) end test "response cache control from rackish app" do @@ -184,10 +182,8 @@ class ResponseIntegrationTest < ActionDispatch::IntegrationTest assert_equal('public', @response.headers['Cache-Control']) assert_equal('"202cb962ac59075b964b07152d234b70"', @response.headers['ETag']) - pending do - assert_equal('"202cb962ac59075b964b07152d234b70"', @response.etag) - assert_equal({:public => true}, @response.cache_control) - end + assert_equal('"202cb962ac59075b964b07152d234b70"', @response.etag) + assert_equal({:public => true}, @response.cache_control) end test "response charset and content type from railsish app" do @@ -202,10 +198,8 @@ class ResponseIntegrationTest < ActionDispatch::IntegrationTest get '/' assert_response :success - pending do - assert_equal('utf-16', @response.charset) - assert_equal(Mime::XML, @response.content_type) - end + assert_equal('utf-16', @response.charset) + assert_equal(Mime::XML, @response.content_type) assert_equal('application/xml; charset=utf-16', @response.headers['Content-Type']) end @@ -220,10 +214,8 @@ class ResponseIntegrationTest < ActionDispatch::IntegrationTest get '/' assert_response :success - pending do - assert_equal('utf-16', @response.charset) - assert_equal(Mime::XML, @response.content_type) - end + assert_equal('utf-16', @response.charset) + assert_equal(Mime::XML, @response.content_type) assert_equal('application/xml; charset=utf-16', @response.headers['Content-Type']) end -- cgit v1.2.3 From 2f98032fc92ce16125f8628b4d3c283f10494f4d Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Fri, 19 Feb 2010 10:10:45 -0800 Subject: Fix a problem where nil was appearing in the list --- activesupport/lib/active_support/dependencies.rb | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb index da1050298b..a3a7df7464 100644 --- a/activesupport/lib/active_support/dependencies.rb +++ b/activesupport/lib/active_support/dependencies.rb @@ -76,17 +76,19 @@ module ActiveSupport #:nodoc: locked :concat, :each, :delete_if, :<< def new_constants_for(frames) - frames.map do |mod_name, prior_constants| + constants = [] + frames.each do |mod_name, prior_constants| mod = Inflector.constantize(mod_name) if Dependencies.qualified_const_defined?(mod_name) next unless mod.is_a?(Module) new_constants = mod.local_constant_names - prior_constants get(mod_name).concat(new_constants) - new_constants.map do |suffix| - ([mod_name, suffix] - ["Object"]).join("::") + new_constants.each do |suffix| + constants << ([mod_name, suffix] - ["Object"]).join("::") end - end.flatten + end + constants end # Add a set of modules to the watch stack, remembering the initial constants -- cgit v1.2.3 From 2f821a0a987902cbe69ba04eb2fe04ea757682a3 Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Fri, 19 Feb 2010 10:31:51 -0800 Subject: Fix test ordering bug related to introducing masked Name class --- activesupport/test/core_ext/module_test.rb | 20 ++++++-------------- 1 file changed, 6 insertions(+), 14 deletions(-) diff --git a/activesupport/test/core_ext/module_test.rb b/activesupport/test/core_ext/module_test.rb index 1fe75d5930..9edd7cc7c0 100644 --- a/activesupport/test/core_ext/module_test.rb +++ b/activesupport/test/core_ext/module_test.rb @@ -55,18 +55,6 @@ class Name end end -$nowhere = <<-EOF -class Name - delegate :nowhere -end -EOF - -$noplace = <<-EOF -class Name - delegate :noplace, :tos => :hollywood -end -EOF - class ModuleTest < Test::Unit::TestCase def setup @david = Someone.new("David", Somewhere.new("Paulina", "Chicago")) @@ -87,8 +75,12 @@ class ModuleTest < Test::Unit::TestCase end def test_missing_delegation_target - assert_raise(ArgumentError) { eval($nowhere) } - assert_raise(ArgumentError) { eval($noplace) } + assert_raise(ArgumentError) do + Name.send :delegate, :nowhere + end + assert_raise(ArgumentError) do + Name.send :delegate, :noplace, :tos => :hollywood + end end def test_delegation_prefix -- cgit v1.2.3 From 7ad2c5c06fe841d71b7fa0db8166f378b04693f8 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Fri, 19 Feb 2010 17:28:20 -0200 Subject: warning: instance variable @_const_missing not initialized fixed --- activesupport/lib/active_support/dependencies.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb index a3a7df7464..96478ee947 100644 --- a/activesupport/lib/active_support/dependencies.rb +++ b/activesupport/lib/active_support/dependencies.rb @@ -117,7 +117,7 @@ module ActiveSupport #:nodoc: def self.append_features(base) base.class_eval do # Emulate #exclude via an ivar - return if @_const_missing + return if defined?(@_const_missing) && @_const_missing @_const_missing = instance_method(:const_missing) remove_method(:const_missing) end -- cgit v1.2.3 From a0a01d0c98e7f04a5bfff450f6758c89ef897b96 Mon Sep 17 00:00:00 2001 From: Dirkjan Bussink Date: Fri, 19 Feb 2010 22:08:47 +0100 Subject: Remove empty line and trailing hash, breaks documentation generation Signed-off-by: Yehuda Katz --- actionpack/lib/action_view/helpers/url_helper.rb | 2 -- 1 file changed, 2 deletions(-) diff --git a/actionpack/lib/action_view/helpers/url_helper.rb b/actionpack/lib/action_view/helpers/url_helper.rb index 04a2743b9c..6ca1a5d730 100644 --- a/actionpack/lib/action_view/helpers/url_helper.rb +++ b/actionpack/lib/action_view/helpers/url_helper.rb @@ -202,8 +202,6 @@ module ActionView # # link_to("Destroy", "http://www.example.com", :method => :delete, :confirm => "Are you sure?") # # => Destroy - - # def link_to(*args, &block) if block_given? options = args.first || {} -- cgit v1.2.3 From e4b910f6a37fa0eb02b0545e7320cfe4d7ff2c04 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Fri, 19 Feb 2010 18:24:05 -0200 Subject: require publicize_conversion_method to ensure to_date and to_datetime became public before redefining them (avoid warnings) --- activesupport/lib/active_support/core_ext/string/conversions.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/activesupport/lib/active_support/core_ext/string/conversions.rb b/activesupport/lib/active_support/core_ext/string/conversions.rb index 331416b3a9..52946f9037 100644 --- a/activesupport/lib/active_support/core_ext/string/conversions.rb +++ b/activesupport/lib/active_support/core_ext/string/conversions.rb @@ -1,4 +1,5 @@ require 'date' +require 'active_support/core_ext/time/publicize_conversion_methods' require 'active_support/core_ext/time/calculations' class String -- cgit v1.2.3 From e7055e5b084f5e29e9cf8dab8d56943da65ccb43 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Fri, 19 Feb 2010 19:57:08 -0200 Subject: i18n translate with arrays issue solved --- actionpack/test/template/translation_helper_test.rb | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/actionpack/test/template/translation_helper_test.rb b/actionpack/test/template/translation_helper_test.rb index 699fb2f5bc..1a9c9fa35c 100644 --- a/actionpack/test/template/translation_helper_test.rb +++ b/actionpack/test/template/translation_helper_test.rb @@ -17,6 +17,11 @@ class TranslationHelperTest < ActiveSupport::TestCase expected = 'en, foo' assert_equal expected, translate(:foo) end + + def test_translation_of_an_array + I18n.expects(:translate).with(["foo", "bar"], :raise => true).returns(["foo", "bar"]) + assert_equal ["foo", "bar"], translate(["foo", "bar"]) + end def test_translation_of_an_array I18n.expects(:translate).with(["foo", "bar"], :raise => true).returns(["foo", "bar"]) -- cgit v1.2.3 From bf8898b49b5a8c03d328bde7b6ee30edb02d873b Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Fri, 19 Feb 2010 15:05:46 -0800 Subject: Revert "i18n translate with arrays issue solved" This reverts commit e7055e5b084f5e29e9cf8dab8d56943da65ccb43. --- actionpack/test/template/translation_helper_test.rb | 5 ----- 1 file changed, 5 deletions(-) diff --git a/actionpack/test/template/translation_helper_test.rb b/actionpack/test/template/translation_helper_test.rb index 1a9c9fa35c..699fb2f5bc 100644 --- a/actionpack/test/template/translation_helper_test.rb +++ b/actionpack/test/template/translation_helper_test.rb @@ -17,11 +17,6 @@ class TranslationHelperTest < ActiveSupport::TestCase expected = 'en, foo' assert_equal expected, translate(:foo) end - - def test_translation_of_an_array - I18n.expects(:translate).with(["foo", "bar"], :raise => true).returns(["foo", "bar"]) - assert_equal ["foo", "bar"], translate(["foo", "bar"]) - end def test_translation_of_an_array I18n.expects(:translate).with(["foo", "bar"], :raise => true).returns(["foo", "bar"]) -- cgit v1.2.3 From a3c6ad7d5e567cf4d688147357c5de134763599d Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Fri, 19 Feb 2010 19:19:20 -0800 Subject: Fix a bunch of pending tests by providing an introspection mode for the Response object that does up-front parsing of the headers to populate things like @etag --- actionpack/lib/action_dispatch/http/cache.rb | 21 +++++++++++-- actionpack/lib/action_dispatch/http/response.rb | 36 +++++++++++++--------- .../lib/action_dispatch/testing/integration.rb | 3 +- actionpack/test/controller/send_file_test.rb | 3 +- 4 files changed, 42 insertions(+), 21 deletions(-) diff --git a/actionpack/lib/action_dispatch/http/cache.rb b/actionpack/lib/action_dispatch/http/cache.rb index 428e62dc6b..d2404e63c5 100644 --- a/actionpack/lib/action_dispatch/http/cache.rb +++ b/actionpack/lib/action_dispatch/http/cache.rb @@ -37,8 +37,21 @@ module ActionDispatch end module Response - def cache_control - @cache_control ||= {} + attr_reader :cache_control + + def initialize(*) + status, header, body = super + + @cache_control = {} + @etag = self["ETag"] + + if cache_control = self["Cache-Control"] + cache_control.split(/,\s*/).each do |segment| + first, last = segment.split("=") + last ||= true + @cache_control[first.to_sym] = last + end + end end def last_modified @@ -65,7 +78,7 @@ module ActionDispatch def etag=(etag) key = ActiveSupport::Cache.expand_cache_key(etag) - @etag = %("#{Digest::MD5.hexdigest(key)}") + @etag = self["ETag"] = %("#{Digest::MD5.hexdigest(key)}") end private @@ -100,6 +113,8 @@ module ActionDispatch def set_conditional_cache_control! control = @cache_control + return if self["Cache-Control"].present? + if control.empty? headers["Cache-Control"] = DEFAULT_CACHE_CONTROL elsif @cache_control[:no_cache] diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb index f299306ff4..1b8dd9abfd 100644 --- a/actionpack/lib/action_dispatch/http/response.rb +++ b/actionpack/lib/action_dispatch/http/response.rb @@ -32,31 +32,37 @@ module ActionDispatch # :nodoc: # end # end class Response < Rack::Response - include ActionDispatch::Http::Cache::Response - attr_accessor :request, :blank attr_writer :header, :sending_file alias_method :headers=, :header= - def initialize - @status = 200 - @header = {} - @cache_control = {} + module Setup + def initialize(status = 200, header = {}, body = []) + @writer = lambda { |x| @body << x } + @block = nil + @length = 0 - @writer = lambda { |x| @body << x } - @block = nil - @length = 0 + @status, @header, @body = status, header, body - @body, @cookie = [], [] - @sending_file = false + @cookie = [] + @sending_file = false - @blank = false - @etag = nil + @blank = false + + if content_type = self["Content-Type"] + type, charset = content_type.split(/;\s*charset=/) + @content_type = Mime::Type.lookup(type) + @charset = charset || "UTF-8" + end - yield self if block_given? + yield self if block_given? + end end + include Setup + include ActionDispatch::Http::Cache::Response + def status=(status) @status = Rack::Utils.status_code(status) end @@ -120,7 +126,7 @@ module ActionDispatch # :nodoc: assign_default_content_type_and_charset! handle_conditional_get! self["Set-Cookie"] = @cookie.join("\n") unless @cookie.blank? - self["ETag"] = @etag if @etag + self["ETag"] = @_etag if @_etag super end diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index 2093bb3a0e..d179af47d9 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -273,7 +273,8 @@ module ActionDispatch @request_count += 1 @request = ActionDispatch::Request.new(session.last_request.env) - @response = ActionDispatch::TestResponse.from_response(@mock_session.last_response) + response = @mock_session.last_response + @response = ActionDispatch::TestResponse.new(response.status, response.headers, response.body) @html_document = nil @controller = session.last_request.env['action_controller.instance'] diff --git a/actionpack/test/controller/send_file_test.rb b/actionpack/test/controller/send_file_test.rb index aebbd893a8..31177223e4 100644 --- a/actionpack/test/controller/send_file_test.rb +++ b/actionpack/test/controller/send_file_test.rb @@ -102,7 +102,7 @@ class SendFileTest < ActionController::TestCase end # Test that send_file_headers! is setting the correct HTTP headers. - def test_send_file_headers! + def test_send_file_headers_bang options = { :length => 1, :type => Mime::PNG, @@ -125,7 +125,6 @@ class SendFileTest < ActionController::TestCase assert_equal 'binary', h['Content-Transfer-Encoding'] # test overriding Cache-Control: no-cache header to fix IE open/save dialog - @controller.headers = { 'Cache-Control' => 'no-cache' } @controller.send(:send_file_headers!, options) @controller.response.prepare! assert_equal 'private', h['Cache-Control'] -- cgit v1.2.3 From 9acd686753c43612984aaa4002e80113fda2b255 Mon Sep 17 00:00:00 2001 From: snusnu Date: Sat, 20 Feb 2010 08:24:10 +0100 Subject: Adds #key and #to_param to the AMo interface This commit introduces two new methods that every AMo compliant object must implement. Below are the default implementations along with the implied interface contract. # Returns an Enumerable of all (primary) key # attributes or nil if new_record? is true def key new_record? ? nil : [1] end # Returns a string representing the object's key # suitable for use in URLs, or nil if new_record? # is true def to_param key ? key.first.to_s : nil end 1) The #key method Previously rails' record_identifier code, which is used in the #dom_id helper, relied on calling #id on the record to provide a reasonable DOM id. Now with rails3 being all ORM agnostic, it's not safe anymore to assume that every record ever will have an #id as its primary key attribute. Having a #key method available on every AMo object means that #dom_id can be implemented using record.to_model.key # instead of record.id Using this we're able to take composite primary keys into account (e.g. available in datamapper) by implementing #dom_id using a newly added record_key_for_dom_id(record) method. The user can overwrite this method to provide customized versions of the object's key used in #dom_id. Also, dealing with more complex keys that can contain arbitrary strings, means that we need to make sure that we only provide DOM ids that are valid according to the spec. For this reason, this patch sends the key provided through a newly added sanitize_dom_id(candidate_id) method, that makes sure we only produce valid HTML The reason to not just add #dom_id to the AMo interface was that it feels like providing a DOM id should not be a model concern. Adding #dom_id to the AMo interface would force these concern on the model, while it's better left to be implemented in a helper. Now one could say the same is true for #to_param, and actually I think that it doesn't really fit into the model either, but it's used in AR and it's a main part of integrating into the rails router. This is different from #dom_id which is only used in view helpers and can be implemented on top of a semantically more meaningful method like #key. 2) The #to_param method Since the rails router relies on #to_param to be present, AR::Base implements it and returns the id by default, allowing the user to overwrite the method if desired. Now with different ORMs integrating into rails, every ORM railtie needs to implement it's own #to_param implementation while already providing code to be AMo compliant. Since the whole point of AMo compliance seems to be to integrate any ORM seamlessly into rails, it seems fair that all we really need to do as another ORM, is to be AMo compliant. By including #to_param into the official interface, we can make sure that this code can be centralized in the various AMo compliance layers, and not be added separately by every ORM railtie. 3) All specs pass --- .../lib/action_controller/record_identifier.rb | 21 +++++++++++++++++++- actionpack/test/lib/controller/fake_models.rb | 16 +++++++++++++++ actionpack/test/template/prototype_helper_test.rb | 3 +++ activemodel/lib/active_model/lint.rb | 23 ++++++++++++++++++++++ activemodel/lib/active_model/naming.rb | 2 +- activemodel/test/cases/lint_test.rb | 8 ++++++++ .../active_record/attribute_methods/primary_key.rb | 14 +++++++++++++ activerecord/test/cases/pk_test.rb | 9 +++++++++ 8 files changed, 94 insertions(+), 2 deletions(-) diff --git a/actionpack/lib/action_controller/record_identifier.rb b/actionpack/lib/action_controller/record_identifier.rb index 1165c3b7c5..9c35c5b0c3 100644 --- a/actionpack/lib/action_controller/record_identifier.rb +++ b/actionpack/lib/action_controller/record_identifier.rb @@ -60,13 +60,32 @@ module ActionController # # dom_id(Post.find(45), :edit) # => "edit_post_45" def dom_id(record, prefix = nil) - if record_id = record.id + if record_id = record_key_for_dom_id(record) "#{dom_class(record, prefix)}#{JOIN}#{record_id}" else dom_class(record, prefix || NEW) end end + # Returns a string representation of the key attribute(s) that is suitable for use in an HTML DOM id. + # This can be overwritten to customize the default generated string representation if desired. + # If you need to read back a key from a dom_id in order to query for the underlying database record, + # you should write a helper like 'person_record_from_dom_id' that will extract the key either based + # on the default implementation (which just joins all key attributes with '-') or on your own + # overwritten version of the method. By default, this implementation passes the key string through a + # method that replaces all characters that are invalid inside DOM ids, with valid ones. You need to + # make sure yourself that your dom ids are valid, in case you overwrite this method. + def record_key_for_dom_id(record) + return record.id unless record.respond_to?(:to_model) + key = record.to_model.key + key ? sanitize_dom_id(key.join('-')) : key + end + + # Replaces characters that are invalid in HTML DOM ids with valid ones. + def sanitize_dom_id(candidate_id) + candidate_id # TODO implement conversion to valid DOM id values + end + # Returns the plural class name of a record or class. Examples: # # plural_class_name(post) # => "posts" diff --git a/actionpack/test/lib/controller/fake_models.rb b/actionpack/test/lib/controller/fake_models.rb index a8c86f70b6..e4aed14dc0 100644 --- a/actionpack/test/lib/controller/fake_models.rb +++ b/actionpack/test/lib/controller/fake_models.rb @@ -6,6 +6,10 @@ class Customer < Struct.new(:name, :id) undef_method :to_json + def key + id ? [id] : nil + end + def to_param id.to_s end @@ -43,6 +47,10 @@ module Quiz extend ActiveModel::Naming include ActiveModel::Conversion + def key + id ? [id] : nil + end + def to_param id.to_s end @@ -59,6 +67,10 @@ class Post < Struct.new(:title, :author_name, :body, :secret, :written_on, :cost alias_method :secret?, :secret + def key + id ? [id] : nil + end + def new_record=(boolean) @new_record = boolean end @@ -84,6 +96,7 @@ class Comment attr_reader :id attr_reader :post_id def initialize(id = nil, post_id = nil); @id, @post_id = id, post_id end + def key; id ? [id] : nil end def save; @id = 1; @post_id = 1 end def new_record?; @id.nil? end def to_param; @id; end @@ -103,6 +116,7 @@ class Tag attr_reader :id attr_reader :post_id def initialize(id = nil, post_id = nil); @id, @post_id = id, post_id end + def key; id ? [id] : nil end def save; @id = 1; @post_id = 1 end def new_record?; @id.nil? end def to_param; @id; end @@ -122,6 +136,7 @@ class CommentRelevance attr_reader :id attr_reader :comment_id def initialize(id = nil, comment_id = nil); @id, @comment_id = id, comment_id end + def key; id ? [id] : nil end def save; @id = 1; @comment_id = 1 end def new_record?; @id.nil? end def to_param; @id; end @@ -137,6 +152,7 @@ class TagRelevance attr_reader :id attr_reader :tag_id def initialize(id = nil, tag_id = nil); @id, @tag_id = id, tag_id end + def key; id ? [id] : nil end def save; @id = 1; @tag_id = 1 end def new_record?; @id.nil? end def to_param; @id; end diff --git a/actionpack/test/template/prototype_helper_test.rb b/actionpack/test/template/prototype_helper_test.rb index d95bdc2b90..dab34f1201 100644 --- a/actionpack/test/template/prototype_helper_test.rb +++ b/actionpack/test/template/prototype_helper_test.rb @@ -4,6 +4,7 @@ require 'active_model' class Bunny < Struct.new(:Bunny, :id) extend ActiveModel::Naming include ActiveModel::Conversion + def key() id ? [id] : nil end end class Author @@ -11,6 +12,7 @@ class Author include ActiveModel::Conversion attr_reader :id + def key() id ? [id] : nil end def save; @id = 1 end def new_record?; @id.nil? end def name @@ -23,6 +25,7 @@ class Article include ActiveModel::Conversion attr_reader :id attr_reader :author_id + def key() id ? [id] : nil end def save; @id = 1; @author_id = 1 end def new_record?; @id.nil? end def name diff --git a/activemodel/lib/active_model/lint.rb b/activemodel/lib/active_model/lint.rb index 7bf0ad712d..c97286e61c 100644 --- a/activemodel/lib/active_model/lint.rb +++ b/activemodel/lib/active_model/lint.rb @@ -13,6 +13,29 @@ module ActiveModel module Lint module Tests + + # == Responds to key + # + # Returns an Enumerable of all (primary) key attributes + # or nil if model.new_record? is true + def test_key + assert model.respond_to?(:key), "The model should respond to key" + def model.new_record?() true end + assert model.key.nil? + def model.new_record?() false end + assert model.key.respond_to?(:each) + end + + # == Responds to to_param + # + # Returns a string representing the object's key suitable for use in URLs + # or nil if model.new_record? is true + def test_to_param + assert model.respond_to?(:to_param), "The model should respond to to_param" + def model.new_record?() true end + assert model.to_param.nil? + end + # == Responds to valid? # # Returns a boolean that specifies whether the object is in a valid or invalid diff --git a/activemodel/lib/active_model/naming.rb b/activemodel/lib/active_model/naming.rb index 89e8f8b1ea..39512a427b 100644 --- a/activemodel/lib/active_model/naming.rb +++ b/activemodel/lib/active_model/naming.rb @@ -41,7 +41,7 @@ module ActiveModel # To implement, just extend ActiveModel::Naming in your object: # # class BookCover - # exten ActiveModel::Naming + # extend ActiveModel::Naming # end # # BookCover.model_name #=> "BookCover" diff --git a/activemodel/test/cases/lint_test.rb b/activemodel/test/cases/lint_test.rb index 63804004ee..58716cbf85 100644 --- a/activemodel/test/cases/lint_test.rb +++ b/activemodel/test/cases/lint_test.rb @@ -10,6 +10,14 @@ class LintTest < ActiveModel::TestCase self end + def key + new_record? ? nil : [1] + end + + def to_param + key ? key.first.to_s : nil + end + def valid?() true end def new_record?() true end def destroyed?() true end diff --git a/activerecord/lib/active_record/attribute_methods/primary_key.rb b/activerecord/lib/active_record/attribute_methods/primary_key.rb index 365fdeb55a..ba64b8ee2f 100644 --- a/activerecord/lib/active_record/attribute_methods/primary_key.rb +++ b/activerecord/lib/active_record/attribute_methods/primary_key.rb @@ -39,6 +39,20 @@ module ActiveRecord end alias :primary_key= :set_primary_key end + + module InstanceMethods + + # Returns this record's primary key value wrapped in an Array + # or nil if the record is a new_record? + # This is done to comply with the AMo interface that expects + # every AMo compliant object to respond_to?(:key) and return + # an Enumerable object from that call, or nil if new_record? + def key + new_record? ? nil : [ self.id ] + end + + end + end end end diff --git a/activerecord/test/cases/pk_test.rb b/activerecord/test/cases/pk_test.rb index c121e0aa0f..2502c136cc 100644 --- a/activerecord/test/cases/pk_test.rb +++ b/activerecord/test/cases/pk_test.rb @@ -9,6 +9,15 @@ require 'models/mixed_case_monkey' class PrimaryKeysTest < ActiveRecord::TestCase fixtures :topics, :subscribers, :movies, :mixed_case_monkeys + def test_key + # test new record + topic = Topic.new + assert topic.key.nil? + # test existing record + topic = Topic.find(1) + assert_equal topic.key, [1] + end + def test_integer_key topic = Topic.find(1) assert_equal(topics(:first).author_name, topic.author_name) -- cgit v1.2.3 From fed72b5842e5e8604917602a15c126d48cf12fde Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Sat, 20 Feb 2010 15:46:55 +0100 Subject: Rename engines_load_path to railties_load_path. --- activesupport/lib/active_support/railtie.rb | 4 ++-- railties/lib/rails/engine.rb | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/activesupport/lib/active_support/railtie.rb b/activesupport/lib/active_support/railtie.rb index c8d8b85000..58d11585ba 100644 --- a/activesupport/lib/active_support/railtie.rb +++ b/activesupport/lib/active_support/railtie.rb @@ -33,7 +33,7 @@ module I18n railtie_name :i18n # Initialize I18n load paths to an array - config.i18n.engines_load_path = [] + config.i18n.railties_load_path = [] config.i18n.load_path = [] initializer "i18n.initialize" do @@ -49,7 +49,7 @@ module I18n config.after_initialize do |app| app.config.i18n.each do |setting, value| case setting - when :engines_load_path + when :railties_load_path app.config.i18n.load_path.unshift(*value) when :load_path I18n.load_path += value diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb index efa11b466a..1696bb7b86 100644 --- a/railties/lib/rails/engine.rb +++ b/railties/lib/rails/engine.rb @@ -90,7 +90,7 @@ module Rails # I18n load paths are a special case since the ones added # later have higher priority. initializer :add_locales do - config.i18n.engines_load_path.concat(paths.config.locales.to_a) + config.i18n.railties_load_path.concat(paths.config.locales.to_a) end initializer :add_view_paths do -- cgit v1.2.3 From f81c6bc0404ba2a03eed0ec6c08bbac45661305f Mon Sep 17 00:00:00 2001 From: snusnu Date: Sun, 21 Feb 2010 03:05:28 +0100 Subject: AMo #key is now #to_key and CI is probably happy Obviously #key is a too common name to be included in the AMo interface, #to_key fits better and also relates nicely to #to_param. Thx wycats, koz and josevalim for the suggestion. AR's #to_key implementation now takes customized primary keys into account and there's a testcase for that too. The #to_param AMo lint makes no assumptions on how the method behaves in the presence of composite primary keys. It leaves the decision wether to provide a default, or to raise and thus signal to the user that implementing this method will need his special attention, up to the implementers. All AMo cares about is that #to_param is implemented and returns nil in case of a new_record?. The default CompliantObject used in lint_test provides a naive default implementation that just joins all key attributes with '-'. The #to_key default implementation in lint_test's CompliantObject now returns [id] instead of [1]. This was previously causing the (wrong) tests I added for AR's #to_key implementation to pass. The #to_key tests added with this patch should be better. The CI failure was caused by my lack of knowledge about the test:isolated task. The tests for the record_identifier code in action_controller are using fake non AR models and I forgot to stub the #to_key method over there. This issue didn't come up when running the test task, only test:isolated revealed it. This patch fixes that. All tests pass isolated or not, well, apart from one previously unpended test in action_controller that is unrelated to my patch. --- actionpack/lib/action_controller/record_identifier.rb | 4 ++-- actionpack/test/controller/record_identifier_test.rb | 1 + actionpack/test/lib/controller/fake_models.rb | 14 +++++++------- actionpack/test/template/prototype_helper_test.rb | 6 +++--- activemodel/lib/active_model/lint.rb | 18 ++++++++++++------ activemodel/test/cases/lint_test.rb | 8 +++++--- .../lib/active_record/attribute_methods/primary_key.rb | 8 +++++--- activerecord/test/cases/pk_test.rb | 15 ++++++++++----- 8 files changed, 45 insertions(+), 29 deletions(-) diff --git a/actionpack/lib/action_controller/record_identifier.rb b/actionpack/lib/action_controller/record_identifier.rb index 9c35c5b0c3..3f966b1b64 100644 --- a/actionpack/lib/action_controller/record_identifier.rb +++ b/actionpack/lib/action_controller/record_identifier.rb @@ -77,8 +77,8 @@ module ActionController # make sure yourself that your dom ids are valid, in case you overwrite this method. def record_key_for_dom_id(record) return record.id unless record.respond_to?(:to_model) - key = record.to_model.key - key ? sanitize_dom_id(key.join('-')) : key + key = record.to_model.to_key + key ? sanitize_dom_id(key.join('_')) : key end # Replaces characters that are invalid in HTML DOM ids with valid ones. diff --git a/actionpack/test/controller/record_identifier_test.rb b/actionpack/test/controller/record_identifier_test.rb index 6b6d154faa..813dedc80d 100644 --- a/actionpack/test/controller/record_identifier_test.rb +++ b/actionpack/test/controller/record_identifier_test.rb @@ -5,6 +5,7 @@ class Comment include ActiveModel::Conversion attr_reader :id + def to_key; id ? [id] : nil end def save; @id = 1 end def new_record?; @id.nil? end def name diff --git a/actionpack/test/lib/controller/fake_models.rb b/actionpack/test/lib/controller/fake_models.rb index e4aed14dc0..4475d40f63 100644 --- a/actionpack/test/lib/controller/fake_models.rb +++ b/actionpack/test/lib/controller/fake_models.rb @@ -6,7 +6,7 @@ class Customer < Struct.new(:name, :id) undef_method :to_json - def key + def to_key id ? [id] : nil end @@ -47,7 +47,7 @@ module Quiz extend ActiveModel::Naming include ActiveModel::Conversion - def key + def to_key id ? [id] : nil end @@ -67,7 +67,7 @@ class Post < Struct.new(:title, :author_name, :body, :secret, :written_on, :cost alias_method :secret?, :secret - def key + def to_key id ? [id] : nil end @@ -96,7 +96,7 @@ class Comment attr_reader :id attr_reader :post_id def initialize(id = nil, post_id = nil); @id, @post_id = id, post_id end - def key; id ? [id] : nil end + def to_key; id ? [id] : nil end def save; @id = 1; @post_id = 1 end def new_record?; @id.nil? end def to_param; @id; end @@ -116,7 +116,7 @@ class Tag attr_reader :id attr_reader :post_id def initialize(id = nil, post_id = nil); @id, @post_id = id, post_id end - def key; id ? [id] : nil end + def to_key; id ? [id] : nil end def save; @id = 1; @post_id = 1 end def new_record?; @id.nil? end def to_param; @id; end @@ -136,7 +136,7 @@ class CommentRelevance attr_reader :id attr_reader :comment_id def initialize(id = nil, comment_id = nil); @id, @comment_id = id, comment_id end - def key; id ? [id] : nil end + def to_key; id ? [id] : nil end def save; @id = 1; @comment_id = 1 end def new_record?; @id.nil? end def to_param; @id; end @@ -152,7 +152,7 @@ class TagRelevance attr_reader :id attr_reader :tag_id def initialize(id = nil, tag_id = nil); @id, @tag_id = id, tag_id end - def key; id ? [id] : nil end + def to_key; id ? [id] : nil end def save; @id = 1; @tag_id = 1 end def new_record?; @id.nil? end def to_param; @id; end diff --git a/actionpack/test/template/prototype_helper_test.rb b/actionpack/test/template/prototype_helper_test.rb index dab34f1201..45f9d85e32 100644 --- a/actionpack/test/template/prototype_helper_test.rb +++ b/actionpack/test/template/prototype_helper_test.rb @@ -4,7 +4,7 @@ require 'active_model' class Bunny < Struct.new(:Bunny, :id) extend ActiveModel::Naming include ActiveModel::Conversion - def key() id ? [id] : nil end + def to_key() id ? [id] : nil end end class Author @@ -12,7 +12,7 @@ class Author include ActiveModel::Conversion attr_reader :id - def key() id ? [id] : nil end + def to_key() id ? [id] : nil end def save; @id = 1 end def new_record?; @id.nil? end def name @@ -25,7 +25,7 @@ class Article include ActiveModel::Conversion attr_reader :id attr_reader :author_id - def key() id ? [id] : nil end + def to_key() id ? [id] : nil end def save; @id = 1; @author_id = 1 end def new_record?; @id.nil? end def name diff --git a/activemodel/lib/active_model/lint.rb b/activemodel/lib/active_model/lint.rb index c97286e61c..98413ac9fb 100644 --- a/activemodel/lib/active_model/lint.rb +++ b/activemodel/lib/active_model/lint.rb @@ -14,22 +14,28 @@ module ActiveModel module Lint module Tests - # == Responds to key + # == Responds to to_key # # Returns an Enumerable of all (primary) key attributes # or nil if model.new_record? is true - def test_key - assert model.respond_to?(:key), "The model should respond to key" + def test_to_key + assert model.respond_to?(:to_key), "The model should respond to to_key" def model.new_record?() true end - assert model.key.nil? + assert model.to_key.nil? def model.new_record?() false end - assert model.key.respond_to?(:each) + assert model.to_key.respond_to?(:each) end # == Responds to to_param # # Returns a string representing the object's key suitable for use in URLs - # or nil if model.new_record? is true + # or nil if model.new_record? is true. + # + # Implementers can decide to either raise an exception or provide a default + # in case the record uses a composite primary key. There are no tests for this + # behavior in lint because it doesn't make sense to force any of the possible + # implementation strategies on the implementer. However, if the resource is + # a new_record?, then to_param should always return nil. def test_to_param assert model.respond_to?(:to_param), "The model should respond to to_param" def model.new_record?() true end diff --git a/activemodel/test/cases/lint_test.rb b/activemodel/test/cases/lint_test.rb index 58716cbf85..99f8eff5d8 100644 --- a/activemodel/test/cases/lint_test.rb +++ b/activemodel/test/cases/lint_test.rb @@ -10,12 +10,14 @@ class LintTest < ActiveModel::TestCase self end - def key - new_record? ? nil : [1] + def to_key + new_record? ? nil : [id] end def to_param - key ? key.first.to_s : nil + return nil if to_key.nil? + # some default for CPKs, real implementations will differ + to_key.length > 1 ? to_key.join('-') : to_key.first.to_s end def valid?() true end diff --git a/activerecord/lib/active_record/attribute_methods/primary_key.rb b/activerecord/lib/active_record/attribute_methods/primary_key.rb index ba64b8ee2f..8549414a12 100644 --- a/activerecord/lib/active_record/attribute_methods/primary_key.rb +++ b/activerecord/lib/active_record/attribute_methods/primary_key.rb @@ -45,10 +45,12 @@ module ActiveRecord # Returns this record's primary key value wrapped in an Array # or nil if the record is a new_record? # This is done to comply with the AMo interface that expects - # every AMo compliant object to respond_to?(:key) and return + # every AMo compliant object to respond_to?(:to_key) and return # an Enumerable object from that call, or nil if new_record? - def key - new_record? ? nil : [ self.id ] + # This method also takes custom primary keys specified via + # the +set_primary_key+ into account. + def to_key + new_record? ? nil : [ self.send(self.class.primary_key) ] end end diff --git a/activerecord/test/cases/pk_test.rb b/activerecord/test/cases/pk_test.rb index 2502c136cc..5bba1d5625 100644 --- a/activerecord/test/cases/pk_test.rb +++ b/activerecord/test/cases/pk_test.rb @@ -9,13 +9,18 @@ require 'models/mixed_case_monkey' class PrimaryKeysTest < ActiveRecord::TestCase fixtures :topics, :subscribers, :movies, :mixed_case_monkeys - def test_key - # test new record + def test_to_key_with_default_primary_key topic = Topic.new - assert topic.key.nil? - # test existing record + assert topic.to_key.nil? topic = Topic.find(1) - assert_equal topic.key, [1] + assert_equal topic.to_key, [1] + end + + def test_to_key_with_customized_primary_key + keyboard = Keyboard.new + assert keyboard.to_key.nil? + keyboard.save + assert_equal keyboard.to_key, [keyboard.id] end def test_integer_key -- cgit v1.2.3 From 9dd67fce25d3993a0ee494506ba246a45d395e3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Sun, 21 Feb 2010 08:47:37 +0100 Subject: Add to_key and to_param methods to ActiveModel::Conversion. --- activemodel/lib/active_model/conversion.rb | 45 +++++++++++++++++----- activemodel/test/cases/conversion_test.rb | 25 ++++++++++++ activemodel/test/cases/lint_test.rb | 17 +------- activemodel/test/models/contact.rb | 8 +++- .../active_record/attribute_methods/primary_key.rb | 2 +- 5 files changed, 70 insertions(+), 27 deletions(-) create mode 100644 activemodel/test/cases/conversion_test.rb diff --git a/activemodel/lib/active_model/conversion.rb b/activemodel/lib/active_model/conversion.rb index c14a07c7dc..78dc34197b 100644 --- a/activemodel/lib/active_model/conversion.rb +++ b/activemodel/lib/active_model/conversion.rb @@ -1,19 +1,44 @@ module ActiveModel - # If your object is already designed to implement all of the Active Model featurs - # include this module in your Class. - # - # class MyClass + # Handle default conversions: to_model, to_key and to_param. + # + # == Example + # + # Let's take for example this non persisted object. + # + # class ContactMessage # include ActiveModel::Conversion + # + # # Always a new record, since it's not persisted in the DB. + # def new_record? + # true + # end # end - # - # Returns self to the :to_model method. - # - # If your model does not act like an Active Model object, then you should define - # :to_model yourself returning a proxy object that wraps your object - # with Active Model compliant methods. + # + # cm = ContactMessage.new + # cm.to_model == self #=> true + # cm.to_key #=> nil + # cm.to_param #=> nil + # module Conversion + # If your object is already designed to implement all of the Active Model you can use + # the default to_model implementation, which simply returns self. + # + # If your model does not act like an Active Model object, then you should define + # :to_model yourself returning a proxy object that wraps your object + # with Active Model compliant methods. def to_model self end + + # Returns an Enumerable of all (primary) key attributes or nil if new_record? is true + def to_key + new_record? ? nil : [id] + end + + # Returns a string representing the object's key suitable for use in URLs, + # or nil if new_record? is true + def to_param + to_key ? to_key.join('-') : nil + end end end diff --git a/activemodel/test/cases/conversion_test.rb b/activemodel/test/cases/conversion_test.rb new file mode 100644 index 0000000000..373424df2f --- /dev/null +++ b/activemodel/test/cases/conversion_test.rb @@ -0,0 +1,25 @@ +require 'cases/helper' +require 'models/contact' + +class ConversionTest < ActiveModel::TestCase + test "to_model default implementation returns self" do + contact = Contact.new + assert_equal contact, contact.to_model + end + + test "to_key default implementation returns nil for new records" do + assert_nil Contact.new.to_key + end + + test "to_key default implementation returns the id in an array for persisted records" do + assert_equal [1], Contact.new(:new_record => false, :id => 1).to_key + end + + test "to_param default implementation returns nil for new records" do + assert_nil Contact.new.to_param + end + + test "to_param default implementation returns a string of ids for persisted records" do + assert_equal "1", Contact.new(:new_record => false, :id => 1).to_param + end +end \ No newline at end of file diff --git a/activemodel/test/cases/lint_test.rb b/activemodel/test/cases/lint_test.rb index 99f8eff5d8..e4c069e1ab 100644 --- a/activemodel/test/cases/lint_test.rb +++ b/activemodel/test/cases/lint_test.rb @@ -1,24 +1,11 @@ -require "cases/helper" +require 'cases/helper' class LintTest < ActiveModel::TestCase include ActiveModel::Lint::Tests class CompliantModel extend ActiveModel::Naming - - def to_model - self - end - - def to_key - new_record? ? nil : [id] - end - - def to_param - return nil if to_key.nil? - # some default for CPKs, real implementations will differ - to_key.length > 1 ? to_key.join('-') : to_key.first.to_s - end + include ActiveModel::Conversion def valid?() true end def new_record?() true end diff --git a/activemodel/test/models/contact.rb b/activemodel/test/models/contact.rb index f9fb0af027..dbdb8539b7 100644 --- a/activemodel/test/models/contact.rb +++ b/activemodel/test/models/contact.rb @@ -1,7 +1,13 @@ class Contact - attr_accessor :name, :age, :created_at, :awesome, :preferences + include ActiveModel::Conversion + + attr_accessor :id, :name, :age, :created_at, :awesome, :preferences, :new_record def initialize(options = {}) options.each { |name, value| send("#{name}=", value) } end + + def new_record? + defined?(@new_record) ? @new_record : true + end end diff --git a/activerecord/lib/active_record/attribute_methods/primary_key.rb b/activerecord/lib/active_record/attribute_methods/primary_key.rb index 8549414a12..095814b635 100644 --- a/activerecord/lib/active_record/attribute_methods/primary_key.rb +++ b/activerecord/lib/active_record/attribute_methods/primary_key.rb @@ -50,7 +50,7 @@ module ActiveRecord # This method also takes custom primary keys specified via # the +set_primary_key+ into account. def to_key - new_record? ? nil : [ self.send(self.class.primary_key) ] + new_record? ? nil : [ self.primary_key ] end end -- cgit v1.2.3 From 250c8092461f5e6bf62751b313f6605a37fd1b2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Sun, 21 Feb 2010 11:09:21 +0100 Subject: Require persisted? in ActiveModel::Lint and remove new_record? and destroyed? methods. ActionPack does not care if the resource is new or if it was destroyed, it cares only if it's persisted somewhere or not. --- .../lib/action_controller/polymorphic_routes.rb | 3 +- .../lib/action_view/helpers/active_model_helper.rb | 4 +-- actionpack/lib/action_view/helpers/form_helper.rb | 17 +++++---- actionpack/lib/action_view/helpers/url_helper.rb | 2 +- actionpack/test/controller/mime_responds_test.rb | 4 +-- actionpack/test/controller/redirect_test.rb | 18 +++++----- actionpack/test/lib/controller/fake_models.rb | 40 +++++++--------------- .../test/template/active_model_helper_test.rb | 4 +-- actionpack/test/template/atom_feed_helper_test.rb | 8 ++--- actionpack/test/template/form_helper_test.rb | 13 ++----- actionpack/test/template/record_tag_helper_test.rb | 1 + actionpack/test/template/url_helper_test.rb | 36 +++++++++---------- activemodel/examples/validations.rb | 2 +- activemodel/lib/active_model/conversion.rb | 12 +++---- activemodel/lib/active_model/lint.rb | 25 ++++++-------- activemodel/test/cases/conversion_test.rb | 4 +-- activemodel/test/cases/lint_test.rb | 3 +- activemodel/test/models/contact.rb | 6 ++-- activerecord/lib/active_record/base.rb | 13 ++++--- activerecord/test/cases/base_test.rb | 22 +++++++++--- 20 files changed, 112 insertions(+), 125 deletions(-) diff --git a/actionpack/lib/action_controller/polymorphic_routes.rb b/actionpack/lib/action_controller/polymorphic_routes.rb index eaed00cfb7..ae363e300c 100644 --- a/actionpack/lib/action_controller/polymorphic_routes.rb +++ b/actionpack/lib/action_controller/polymorphic_routes.rb @@ -92,8 +92,7 @@ module ActionController inflection = if options[:action].to_s == "new" args.pop :singular - elsif (record.respond_to?(:new_record?) && record.new_record?) || - (record.respond_to?(:destroyed?) && record.destroyed?) + elsif (record.respond_to?(:persisted?) && !record.persisted?) args.pop :plural elsif record.is_a?(Class) diff --git a/actionpack/lib/action_view/helpers/active_model_helper.rb b/actionpack/lib/action_view/helpers/active_model_helper.rb index 2f309fcca0..ed83b8a8b2 100644 --- a/actionpack/lib/action_view/helpers/active_model_helper.rb +++ b/actionpack/lib/action_view/helpers/active_model_helper.rb @@ -80,13 +80,13 @@ module ActionView record = convert_to_model(record) options = options.symbolize_keys - options[:action] ||= record.new_record? ? "create" : "update" + options[:action] ||= record.persisted? ? "update" : "create" action = url_for(:action => options[:action], :id => record) submit_value = options[:submit_value] || options[:action].gsub(/[^\w]/, '').capitalize contents = form_tag({:action => action}, :method =>(options[:method] || 'post'), :enctype => options[:multipart] ? 'multipart/form-data': nil) - contents.safe_concat hidden_field(record_name, :id) unless record.new_record? + contents.safe_concat hidden_field(record_name, :id) if record.persisted? contents.safe_concat all_input_tags(record, record_name, options) yield contents if block_given? contents.safe_concat submit_tag(submit_value) diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb index ce21af9923..ace3bcfde3 100644 --- a/actionpack/lib/action_view/helpers/form_helper.rb +++ b/actionpack/lib/action_view/helpers/form_helper.rb @@ -316,14 +316,13 @@ module ActionView def apply_form_for_options!(object_or_array, options) #:nodoc: object = object_or_array.is_a?(Array) ? object_or_array.last : object_or_array - object = convert_to_model(object) html_options = - if object.respond_to?(:new_record?) && object.new_record? - { :class => dom_class(object, :new), :id => dom_id(object), :method => :post } - else + if object.respond_to?(:persisted?) && object.persisted? { :class => dom_class(object, :edit), :id => dom_id(object, :edit), :method => :put } + else + { :class => dom_class(object, :new), :id => dom_id(object), :method => :post } end options[:html] ||= {} @@ -1150,7 +1149,7 @@ module ActionView def submit_default_value object = @object.respond_to?(:to_model) ? @object.to_model : @object - key = object ? (object.new_record? ? :create : :update) : :submit + key = object ? (object.persisted? ? :update : :create) : :submit model = if object.class.respond_to?(:model_name) object.class.model_name.human @@ -1176,7 +1175,7 @@ module ActionView association = args.shift association = association.to_model if association.respond_to?(:to_model) - if association.respond_to?(:new_record?) + if association.respond_to?(:persisted?) association = [association] if @object.send(association_name).is_a?(Array) elsif !association.is_a?(Array) association = @object.send(association_name) @@ -1195,13 +1194,13 @@ module ActionView def fields_for_nested_model(name, object, options, block) object = object.to_model if object.respond_to?(:to_model) - if object.new_record? - @template.fields_for(name, object, options, &block) - else + 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 end diff --git a/actionpack/lib/action_view/helpers/url_helper.rb b/actionpack/lib/action_view/helpers/url_helper.rb index 6ca1a5d730..e121472fe3 100644 --- a/actionpack/lib/action_view/helpers/url_helper.rb +++ b/actionpack/lib/action_view/helpers/url_helper.rb @@ -63,7 +63,7 @@ module ActionView # # => /testing/jump/#tax&ship # # <%= url_for(Workshop.new) %> - # # relies on Workshop answering a new_record? call (and in this case returning true) + # # relies on Workshop answering a persisted? call (and in this case returning false) # # => /workshops # # <%= url_for(@workshop) %> diff --git a/actionpack/test/controller/mime_responds_test.rb b/actionpack/test/controller/mime_responds_test.rb index 3bd3369242..5e34773899 100644 --- a/actionpack/test/controller/mime_responds_test.rb +++ b/actionpack/test/controller/mime_responds_test.rb @@ -513,7 +513,7 @@ class RespondWithController < ActionController::Base protected def resource - Customer.new("david", 13) + Customer.new("david", request.delete? ? nil : 13) end def _render_js(js, options) @@ -717,7 +717,7 @@ class RespondWithControllerTest < ActionController::TestCase delete :using_resource assert_equal "text/html", @response.content_type assert_equal 302, @response.status - assert_equal "http://www.example.com/customers/13", @response.location + assert_equal "http://www.example.com/customers", @response.location end end diff --git a/actionpack/test/controller/redirect_test.rb b/actionpack/test/controller/redirect_test.rb index 570ff4a41b..441bc47908 100644 --- a/actionpack/test/controller/redirect_test.rb +++ b/actionpack/test/controller/redirect_test.rb @@ -6,14 +6,14 @@ end class Workshop extend ActiveModel::Naming include ActiveModel::Conversion - attr_accessor :id, :new_record + attr_accessor :id - def initialize(id, new_record) - @id, @new_record = id, new_record + def initialize(id) + @id = id end - def new_record? - @new_record + def persisted? + id.present? end def to_s @@ -88,11 +88,11 @@ class RedirectController < ActionController::Base end def redirect_to_existing_record - redirect_to Workshop.new(5, false) + redirect_to Workshop.new(5) end def redirect_to_new_record - redirect_to Workshop.new(5, true) + redirect_to Workshop.new(nil) end def redirect_to_nil @@ -239,11 +239,11 @@ class RedirectTest < ActionController::TestCase get :redirect_to_existing_record assert_equal "http://test.host/workshops/5", redirect_to_url - assert_redirected_to Workshop.new(5, false) + assert_redirected_to Workshop.new(5) get :redirect_to_new_record assert_equal "http://test.host/workshops", redirect_to_url - assert_redirected_to Workshop.new(5, true) + assert_redirected_to Workshop.new(nil) end end diff --git a/actionpack/test/lib/controller/fake_models.rb b/actionpack/test/lib/controller/fake_models.rb index 4475d40f63..bf3e175f1f 100644 --- a/actionpack/test/lib/controller/fake_models.rb +++ b/actionpack/test/lib/controller/fake_models.rb @@ -6,14 +6,6 @@ class Customer < Struct.new(:name, :id) undef_method :to_json - def to_key - id ? [id] : nil - end - - def to_param - id.to_s - end - def to_xml(options={}) if options[:builder] options[:builder].name name @@ -31,8 +23,8 @@ class Customer < Struct.new(:name, :id) [] end - def destroyed? - false + def persisted? + id.present? end end @@ -47,12 +39,8 @@ module Quiz extend ActiveModel::Naming include ActiveModel::Conversion - def to_key - id ? [id] : nil - end - - def to_param - id.to_s + def persisted? + id.present? end end @@ -67,16 +55,12 @@ class Post < Struct.new(:title, :author_name, :body, :secret, :written_on, :cost alias_method :secret?, :secret - def to_key - id ? [id] : nil - end - - def new_record=(boolean) - @new_record = boolean + def persisted=(boolean) + @persisted = boolean end - def new_record? - @new_record + def persisted? + @persisted end attr_accessor :author @@ -98,7 +82,7 @@ class Comment def initialize(id = nil, post_id = nil); @id, @post_id = id, post_id end def to_key; id ? [id] : nil end def save; @id = 1; @post_id = 1 end - def new_record?; @id.nil? end + def persisted?; @id.present? end def to_param; @id; end def name @id.nil? ? "new #{self.class.name.downcase}" : "#{self.class.name.downcase} ##{@id}" @@ -118,7 +102,7 @@ class Tag def initialize(id = nil, post_id = nil); @id, @post_id = id, post_id end def to_key; id ? [id] : nil end def save; @id = 1; @post_id = 1 end - def new_record?; @id.nil? end + def persisted?; @id.present? end def to_param; @id; end def value @id.nil? ? "new #{self.class.name.downcase}" : "#{self.class.name.downcase} ##{@id}" @@ -138,7 +122,7 @@ class CommentRelevance def initialize(id = nil, comment_id = nil); @id, @comment_id = id, comment_id end def to_key; id ? [id] : nil end def save; @id = 1; @comment_id = 1 end - def new_record?; @id.nil? end + def persisted?; @id.present? end def to_param; @id; end def value @id.nil? ? "new #{self.class.name.downcase}" : "#{self.class.name.downcase} ##{@id}" @@ -154,7 +138,7 @@ class TagRelevance def initialize(id = nil, tag_id = nil); @id, @tag_id = id, tag_id end def to_key; id ? [id] : nil end def save; @id = 1; @tag_id = 1 end - def new_record?; @id.nil? end + def persisted?; @id.present? end def to_param; @id; end def value @id.nil? ? "new #{self.class.name.downcase}" : "#{self.class.name.downcase} ##{@id}" diff --git a/actionpack/test/template/active_model_helper_test.rb b/actionpack/test/template/active_model_helper_test.rb index 3e01ae78c3..371aa53c68 100644 --- a/actionpack/test/template/active_model_helper_test.rb +++ b/actionpack/test/template/active_model_helper_test.rb @@ -64,7 +64,7 @@ class ActiveModelHelperTest < ActionView::TestCase }.new end - def @post.new_record?() true end + def @post.persisted?() false end def @post.to_param() nil end def @post.column_for_attribute(attr_name) @@ -155,7 +155,7 @@ class ActiveModelHelperTest < ActionView::TestCase silence_warnings do class << @post - def new_record?() false end + def persisted?() true end def to_param() id end def id() 1 end end diff --git a/actionpack/test/template/atom_feed_helper_test.rb b/actionpack/test/template/atom_feed_helper_test.rb index 347cb98303..869ea22469 100644 --- a/actionpack/test/template/atom_feed_helper_test.rb +++ b/actionpack/test/template/atom_feed_helper_test.rb @@ -4,8 +4,8 @@ class Scroll < Struct.new(:id, :to_param, :title, :body, :updated_at, :created_a extend ActiveModel::Naming include ActiveModel::Conversion - def new_record? - true + def persisted? + false end end @@ -34,7 +34,7 @@ class ScrollsController < ActionController::Base feed.updated((@scrolls.first.created_at)) for scroll in @scrolls - feed.entry(scroll, :url => "/otherstuff/" + scroll.to_param, :updated => Time.utc(2007, 1, scroll.id)) do |entry| + feed.entry(scroll, :url => "/otherstuff/" + scroll.to_param.to_s, :updated => Time.utc(2007, 1, scroll.id)) do |entry| entry.title(scroll.title) entry.content(scroll.body, :type => 'html') @@ -55,7 +55,7 @@ class ScrollsController < ActionController::Base end for scroll in @scrolls - feed.entry(scroll, :url => "/otherstuff/" + scroll.to_param, :updated => Time.utc(2007, 1, scroll.id)) do |entry| + feed.entry(scroll, :url => "/otherstuff/" + scroll.to_param.to_s, :updated => Time.utc(2007, 1, scroll.id)) do |entry| entry.title(scroll.title) entry.content(scroll.body, :type => 'html') end diff --git a/actionpack/test/template/form_helper_test.rb b/actionpack/test/template/form_helper_test.rb index 7b909fff82..d143c39c9c 100644 --- a/actionpack/test/template/form_helper_test.rb +++ b/actionpack/test/template/form_helper_test.rb @@ -53,6 +53,7 @@ class FormHelperTest < ActionView::TestCase def @post.id_before_type_cast; 123; end def @post.to_param; '123'; end + @post.persisted = true @post.title = "Hello World" @post.author_name = "" @post.body = "Back to the hill and over it again!" @@ -529,7 +530,7 @@ class FormHelperTest < ActionView::TestCase def test_submit_with_object_as_new_record_and_locale_strings old_locale, I18n.locale = I18n.locale, :submit - def @post.new_record?() true; end + @post.persisted = false form_for(:post, @post) do |f| concat f.submit end @@ -1363,7 +1364,7 @@ class FormHelperTest < ActionView::TestCase def test_form_for_with_new_object post = Post.new - post.new_record = true + post.persisted = false def post.id() nil end form_for(post) do |f| end @@ -1373,9 +1374,7 @@ class FormHelperTest < ActionView::TestCase end def test_form_for_with_existing_object_in_list - @post.new_record = false @comment.save - form_for([@post, @comment]) {} expected = %(
) @@ -1383,8 +1382,6 @@ class FormHelperTest < ActionView::TestCase end def test_form_for_with_new_object_in_list - @post.new_record = false - form_for([@post, @comment]) {} expected = %(
) @@ -1392,9 +1389,7 @@ class FormHelperTest < ActionView::TestCase end def test_form_for_with_existing_object_and_namespace_in_list - @post.new_record = false @comment.save - form_for([:admin, @post, @comment]) {} expected = %(
) @@ -1402,8 +1397,6 @@ class FormHelperTest < ActionView::TestCase end def test_form_for_with_new_object_and_namespace_in_list - @post.new_record = false - form_for([:admin, @post, @comment]) {} expected = %(
) diff --git a/actionpack/test/template/record_tag_helper_test.rb b/actionpack/test/template/record_tag_helper_test.rb index 1cd18c0692..74d7bba4fe 100644 --- a/actionpack/test/template/record_tag_helper_test.rb +++ b/actionpack/test/template/record_tag_helper_test.rb @@ -18,6 +18,7 @@ class RecordTagHelperTest < ActionView::TestCase def setup super @post = Post.new + @post.persisted = true end def test_content_tag_for diff --git a/actionpack/test/template/url_helper_test.rb b/actionpack/test/template/url_helper_test.rb index 418c050906..c917ca9d2b 100644 --- a/actionpack/test/template/url_helper_test.rb +++ b/actionpack/test/template/url_helper_test.rb @@ -499,14 +499,14 @@ end class Workshop extend ActiveModel::Naming include ActiveModel::Conversion - attr_accessor :id, :new_record + attr_accessor :id - def initialize(id, new_record) - @id, @new_record = id, new_record + def initialize(id) + @id = id end - def new_record? - @new_record + def persisted? + id.present? end def to_s @@ -517,14 +517,14 @@ end class Session extend ActiveModel::Naming include ActiveModel::Conversion - attr_accessor :id, :workshop_id, :new_record + attr_accessor :id, :workshop_id - def initialize(id, new_record) - @id, @new_record = id, new_record + def initialize(id) + @id = id end - def new_record? - @new_record + def persisted? + id.present? end def to_s @@ -534,12 +534,12 @@ end class WorkshopsController < ActionController::Base def index - @workshop = Workshop.new(1, true) + @workshop = Workshop.new(nil) render :inline => "<%= url_for(@workshop) %>\n<%= link_to('Workshop', @workshop) %>" end def show - @workshop = Workshop.new(params[:id], false) + @workshop = Workshop.new(params[:id]) render :inline => "<%= url_for(@workshop) %>\n<%= link_to('Workshop', @workshop) %>" end @@ -548,14 +548,14 @@ end class SessionsController < ActionController::Base def index - @workshop = Workshop.new(params[:workshop_id], false) - @session = Session.new(1, true) + @workshop = Workshop.new(params[:workshop_id]) + @session = Session.new(nil) render :inline => "<%= url_for([@workshop, @session]) %>\n<%= link_to('Session', [@workshop, @session]) %>" end def show - @workshop = Workshop.new(params[:workshop_id], false) - @session = Session.new(params[:id], false) + @workshop = Workshop.new(params[:workshop_id]) + @session = Session.new(params[:id]) render :inline => "<%= url_for([@workshop, @session]) %>\n<%= link_to('Session', [@workshop, @session]) %>" end @@ -565,8 +565,8 @@ end class PolymorphicControllerTest < ActionController::TestCase def setup super - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new + @request = ActionController::TestRequest.new + @response = ActionController::TestResponse.new end def test_new_resource diff --git a/activemodel/examples/validations.rb b/activemodel/examples/validations.rb index b039897ea5..0b2706076f 100644 --- a/activemodel/examples/validations.rb +++ b/activemodel/examples/validations.rb @@ -16,7 +16,7 @@ class Person @persisted = true end - def new_record? + def persisted? @persisted end end diff --git a/activemodel/lib/active_model/conversion.rb b/activemodel/lib/active_model/conversion.rb index 78dc34197b..585c20dcdf 100644 --- a/activemodel/lib/active_model/conversion.rb +++ b/activemodel/lib/active_model/conversion.rb @@ -8,9 +8,9 @@ module ActiveModel # class ContactMessage # include ActiveModel::Conversion # - # # Always a new record, since it's not persisted in the DB. - # def new_record? - # true + # # ContactMessage are never persisted in the DB + # def persisted? + # false # end # end # @@ -30,13 +30,13 @@ module ActiveModel self end - # Returns an Enumerable of all (primary) key attributes or nil if new_record? is true + # Returns an Enumerable of all (primary) key attributes or nil if persisted? is fakse def to_key - new_record? ? nil : [id] + persisted? ? [id] : nil end # Returns a string representing the object's key suitable for use in URLs, - # or nil if new_record? is true + # or nil if persisted? is false def to_param to_key ? to_key.join('-') : nil end diff --git a/activemodel/lib/active_model/lint.rb b/activemodel/lib/active_model/lint.rb index 98413ac9fb..0e62e131a3 100644 --- a/activemodel/lib/active_model/lint.rb +++ b/activemodel/lib/active_model/lint.rb @@ -17,28 +17,28 @@ module ActiveModel # == Responds to to_key # # Returns an Enumerable of all (primary) key attributes - # or nil if model.new_record? is true + # or nil if model.persisted? is false def test_to_key assert model.respond_to?(:to_key), "The model should respond to to_key" - def model.new_record?() true end + def model.persisted?() false end assert model.to_key.nil? - def model.new_record?() false end + def model.persisted?() true end assert model.to_key.respond_to?(:each) end # == Responds to to_param # # Returns a string representing the object's key suitable for use in URLs - # or nil if model.new_record? is true. + # or nil if model.persisted? is false. # # Implementers can decide to either raise an exception or provide a default # in case the record uses a composite primary key. There are no tests for this # behavior in lint because it doesn't make sense to force any of the possible # implementation strategies on the implementer. However, if the resource is - # a new_record?, then to_param should always return nil. + # not persisted?, then to_param should always return nil. def test_to_param assert model.respond_to?(:to_param), "The model should respond to to_param" - def model.new_record?() true end + def model.persisted?() false end assert model.to_param.nil? end @@ -51,21 +51,16 @@ module ActiveModel assert_boolean model.valid?, "valid?" end - # == Responds to new_record? + # == Responds to persisted? # # Returns a boolean that specifies whether the object has been persisted yet. # This is used when calculating the URL for an object. If the object is # not persisted, a form for that object, for instance, will be POSTed to the # collection. If it is persisted, a form for the object will put PUTed to the # URL for the object. - def test_new_record? - assert model.respond_to?(:new_record?), "The model should respond to new_record?" - assert_boolean model.new_record?, "new_record?" - end - - def test_destroyed? - assert model.respond_to?(:destroyed?), "The model should respond to destroyed?" - assert_boolean model.destroyed?, "destroyed?" + def test_persisted? + assert model.respond_to?(:persisted?), "The model should respond to persisted?" + assert_boolean model.persisted?, "persisted?" end # == Naming diff --git a/activemodel/test/cases/conversion_test.rb b/activemodel/test/cases/conversion_test.rb index 373424df2f..7669bf5f65 100644 --- a/activemodel/test/cases/conversion_test.rb +++ b/activemodel/test/cases/conversion_test.rb @@ -12,7 +12,7 @@ class ConversionTest < ActiveModel::TestCase end test "to_key default implementation returns the id in an array for persisted records" do - assert_equal [1], Contact.new(:new_record => false, :id => 1).to_key + assert_equal [1], Contact.new(:id => 1).to_key end test "to_param default implementation returns nil for new records" do @@ -20,6 +20,6 @@ class ConversionTest < ActiveModel::TestCase end test "to_param default implementation returns a string of ids for persisted records" do - assert_equal "1", Contact.new(:new_record => false, :id => 1).to_param + assert_equal "1", Contact.new(:id => 1).to_param end end \ No newline at end of file diff --git a/activemodel/test/cases/lint_test.rb b/activemodel/test/cases/lint_test.rb index e4c069e1ab..68372160cd 100644 --- a/activemodel/test/cases/lint_test.rb +++ b/activemodel/test/cases/lint_test.rb @@ -8,8 +8,7 @@ class LintTest < ActiveModel::TestCase include ActiveModel::Conversion def valid?() true end - def new_record?() true end - def destroyed?() true end + def persisted?() false end def errors obj = Object.new diff --git a/activemodel/test/models/contact.rb b/activemodel/test/models/contact.rb index dbdb8539b7..a583b89aa1 100644 --- a/activemodel/test/models/contact.rb +++ b/activemodel/test/models/contact.rb @@ -1,13 +1,13 @@ class Contact include ActiveModel::Conversion - attr_accessor :id, :name, :age, :created_at, :awesome, :preferences, :new_record + attr_accessor :id, :name, :age, :created_at, :awesome, :preferences def initialize(options = {}) options.each { |name, value| send("#{name}=", value) } end - def new_record? - defined?(@new_record) ? @new_record : true + def persisted? + id.present? end end diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index c6dde078ca..ef5a7d5787 100755 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -1767,6 +1767,11 @@ module ActiveRecord #:nodoc: @destroyed || false end + # Returns if the record is persisted, i.e. it's not a new record and it was not destroyed. + def persisted? + !(new_record? || destroyed?) + end + # :call-seq: # save(options) # @@ -1816,7 +1821,7 @@ module ActiveRecord #:nodoc: # callbacks, Observer methods, or any :dependent association # options, use #destroy. def delete - self.class.delete(id) unless new_record? + self.class.delete(id) if persisted? @destroyed = true freeze end @@ -1824,7 +1829,7 @@ module ActiveRecord #:nodoc: # Deletes the record in the database and freezes this instance to reflect that no changes should # be made (since they can't be persisted). def destroy - unless new_record? + if persisted? self.class.unscoped.where(self.class.arel_table[self.class.primary_key].eq(id)).delete_all end @@ -1844,6 +1849,7 @@ module ActiveRecord #:nodoc: became.instance_variable_set("@attributes", @attributes) became.instance_variable_set("@attributes_cache", @attributes_cache) became.instance_variable_set("@new_record", new_record?) + became.instance_variable_set("@destroyed", destroyed?) became end @@ -2042,8 +2048,7 @@ module ActiveRecord #:nodoc: def ==(comparison_object) comparison_object.equal?(self) || (comparison_object.instance_of?(self.class) && - comparison_object.id == id && - !comparison_object.new_record?) + comparison_object.id == id && !comparison_object.new_record?) end # Delegates to == diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 1441b4278d..2c4e1a3c0f 100755 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -1330,11 +1330,6 @@ class BasicsTest < ActiveRecord::TestCase end def test_destroyed_returns_boolean - developer = Developer.new - assert_equal developer.destroyed?, false - developer.destroy - assert_equal developer.destroyed?, true - developer = Developer.first assert_equal developer.destroyed?, false developer.destroy @@ -1346,6 +1341,23 @@ class BasicsTest < ActiveRecord::TestCase assert_equal developer.destroyed?, true end + def test_persisted_returns_boolean + developer = Developer.new(:name => "Jose") + assert_equal developer.persisted?, false + developer.save! + assert_equal developer.persisted?, true + + developer = Developer.first + assert_equal developer.persisted?, true + developer.destroy + assert_equal developer.persisted?, false + + developer = Developer.last + assert_equal developer.persisted?, true + developer.delete + assert_equal developer.persisted?, false + end + def test_clone topic = Topic.find(1) cloned_topic = nil -- cgit v1.2.3 From 8f97e9d19abf02b33c5f7c0c1f1d5daf13e28893 Mon Sep 17 00:00:00 2001 From: Prem Sichanugrist Date: Thu, 18 Feb 2010 22:28:48 +0700 Subject: Add validators reflection so you can do 'Person.validators' and 'Person.validators_on(:name)'. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- activemodel/lib/active_model/validations.rb | 21 ++++++++++++++--- activemodel/lib/active_model/validations/with.rb | 9 ++++++++ activemodel/lib/active_model/validator.rb | 18 +++++++++++++++ .../test/cases/validations/with_validation_test.rb | 1 + activemodel/test/cases/validations_test.rb | 27 ++++++++++++++++++++++ 5 files changed, 73 insertions(+), 3 deletions(-) diff --git a/activemodel/lib/active_model/validations.rb b/activemodel/lib/active_model/validations.rb index 03733a9c89..7f6748a660 100644 --- a/activemodel/lib/active_model/validations.rb +++ b/activemodel/lib/active_model/validations.rb @@ -1,4 +1,5 @@ require 'active_support/core_ext/array/extract_options' +require 'active_support/core_ext/class/attribute' require 'active_support/core_ext/hash/keys' require 'active_model/errors' @@ -45,6 +46,9 @@ module ActiveModel included do extend ActiveModel::Translation define_callbacks :validate, :scope => :name + + class_attribute :_validators + self._validators = Hash.new { |h,k| h[k] = [] } end module ClassMethods @@ -117,9 +121,20 @@ module ActiveModel end set_callback(:validate, *args, &block) end - - private - + + # List all validators that being used to validate the model using +validates_with+ + # method. + def validators + _validators.values.flatten.uniq + end + + # List all validators that being used to validate a specific attribute. + def validators_on(attribute) + _validators[attribute.to_sym] + end + + private + def _merge_attributes(attr_names) options = attr_names.extract_options! options.merge(:attributes => attr_names) diff --git a/activemodel/lib/active_model/validations/with.rb b/activemodel/lib/active_model/validations/with.rb index db563876af..83d3ea80d6 100644 --- a/activemodel/lib/active_model/validations/with.rb +++ b/activemodel/lib/active_model/validations/with.rb @@ -62,6 +62,15 @@ module ActiveModel args.each do |klass| validator = klass.new(options, &block) validator.setup(self) if validator.respond_to?(:setup) + + if validator.respond_to?(:attributes) && !validator.attributes.empty? + validator.attributes.each do |attribute| + _validators[attribute.to_sym] << validator + end + else + _validators[nil] << validator + end + validate(validator, options) end end diff --git a/activemodel/lib/active_model/validator.rb b/activemodel/lib/active_model/validator.rb index ad9729de00..b61f0cb266 100644 --- a/activemodel/lib/active_model/validator.rb +++ b/activemodel/lib/active_model/validator.rb @@ -1,3 +1,5 @@ +require "active_support/core_ext/module/anonymous" + module ActiveModel #:nodoc: # A simple base class that can be used along with # +ActiveModel::Validations::ClassMethods.validates_with+ @@ -88,11 +90,27 @@ module ActiveModel #:nodoc: class Validator attr_reader :options + # Returns the kind of the validator. + # + # == Examples + # + # PresenceValidator.kind #=> :presence + # UniquenessValidator.kind #=> :uniqueness + # + def self.kind + @kind ||= name.split('::').last.underscore.sub(/_validator$/, '').to_sym unless anonymous? + end + # Accepts options that will be made availible through the +options+ reader. def initialize(options) @options = options end + # Return the kind for this validator. + def kind + self.class.kind + end + # Override this method in subclasses with validation logic, adding errors # to the records +errors+ array where necessary. def validate(record) diff --git a/activemodel/test/cases/validations/with_validation_test.rb b/activemodel/test/cases/validations/with_validation_test.rb index 66b072ea38..92df4dd6cd 100644 --- a/activemodel/test/cases/validations/with_validation_test.rb +++ b/activemodel/test/cases/validations/with_validation_test.rb @@ -9,6 +9,7 @@ class ValidatesWithTest < ActiveRecord::TestCase def teardown Topic.reset_callbacks(:validate) + Topic._validators.clear end ERROR_MESSAGE = "Validation error from validator" diff --git a/activemodel/test/cases/validations_test.rb b/activemodel/test/cases/validations_test.rb index eb100d1c35..9fedd84c73 100644 --- a/activemodel/test/cases/validations_test.rb +++ b/activemodel/test/cases/validations_test.rb @@ -10,6 +10,10 @@ require 'models/custom_reader' class ValidationsTest < ActiveModel::TestCase include ActiveModel::TestsDatabase + def setup + Topic._validators.clear + end + # Most of the tests mess with the validations of Topic, so lets repair it all the time. # Other classes we mess with will be dealt with in the specific tests def teardown @@ -220,4 +224,27 @@ class ValidationsTest < ActiveModel::TestCase assert !t.valid? assert ["NO BLANKS HERE"], t.errors[:title] end + + def test_list_of_validators_for_model + Topic.validates_presence_of :title + Topic.validates_length_of :title, :minimum => 2 + + assert_equal 2, Topic.validators.count + assert_equal [:presence, :length], Topic.validators.map(&:kind) + end + + def test_list_of_validators_on_an_attribute + Topic.validates_presence_of :title, :content + Topic.validates_length_of :title, :minimum => 2 + + assert_equal 2, Topic.validators_on(:title).count + assert_equal [:presence, :length], Topic.validators_on(:title).map(&:kind) + assert_equal 1, Topic.validators_on(:content).count + assert_equal [:presence], Topic.validators_on(:content).map(&:kind) + end + + def test_accessing_instance_of_validator_on_an_attribute + Topic.validates_length_of :title, :minimum => 10 + assert_equal 10, Topic.validators_on(:title).first.options[:minimum] + end end -- cgit v1.2.3 From 7fe4ca3253e902c67d4765eeece285ffc49f3d89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Sun, 21 Feb 2010 13:19:21 +0100 Subject: Add a test for default_url_options in AM. --- railties/test/application/initializers/frameworks_test.rb | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/railties/test/application/initializers/frameworks_test.rb b/railties/test/application/initializers/frameworks_test.rb index 1e7b9c9997..94d3505518 100644 --- a/railties/test/application/initializers/frameworks_test.rb +++ b/railties/test/application/initializers/frameworks_test.rb @@ -32,6 +32,17 @@ module ApplicationTests ActionMailer::Base.view_paths.include?(File.expand_path("app/views", app_path)) end + test "allows me to configure default url options for ActionMailer" do + app_file "config/environments/development.rb", <<-RUBY + Rails::Application.configure do + config.action_mailer.default_url_options = { :host => "test.rails" } + end + RUBY + + require "#{app_path}/config/environment" + assert "test.rails", ActionMailer::Base.default_url_options[:host] + end + # AS test "if there's no config.active_support.bare, all of ActiveSupport is required" do use_frameworks [] -- cgit v1.2.3 From 4477bccda6d388755c46326df964850962c12c5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Sun, 21 Feb 2010 13:44:08 +0100 Subject: Also check if application is a valid constant in rake rails:update. --- railties/lib/rails/tasks/framework.rake | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/railties/lib/rails/tasks/framework.rake b/railties/lib/rails/tasks/framework.rake index 65d3c48f2d..dbe2ac54ed 100644 --- a/railties/lib/rails/tasks/framework.rake +++ b/railties/lib/rails/tasks/framework.rake @@ -32,12 +32,18 @@ namespace :rails do namespace :update do def invoke_from_app_generator(method) - require 'rails/generators' - require 'generators/rails/app/app_generator' + app_generator.invoke(method) + end - generator = Rails::Generators::AppGenerator.new ["rails"], { :with_dispatchers => true }, - :destination_root => Rails.root - generator.invoke(method) + def app_generator + @app_generator ||= begin + require 'rails/generators' + require 'generators/rails/app/app_generator' + gen = Rails::Generators::AppGenerator.new ["rails"], { :with_dispatchers => true }, + :destination_root => Rails.root + gen.send(:valid_app_const?) + gen + end end desc "Update config/boot.rb from your current rails install" -- cgit v1.2.3 From 87a011df6fbfcd0669d70c9b20b5e2b3a28cf716 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Sun, 21 Feb 2010 14:18:40 +0100 Subject: Make install appear on rake -T. --- Rakefile | 1 + 1 file changed, 1 insertion(+) diff --git a/Rakefile b/Rakefile index d9d24fc1ab..c5c548d89c 100644 --- a/Rakefile +++ b/Rakefile @@ -53,6 +53,7 @@ task :release_projects => :package do fail("Errors in #{errors.join(', ')}") unless errors.empty? end +desc "Install gems for all projects." task :install => :gem do (PROJECTS - ["railties"]).each do |project| puts "INSTALLING #{project}" -- cgit v1.2.3 From 55ae903c3fd2965f85a6e2e45ddd6b5b1156be91 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Sun, 21 Feb 2010 14:29:40 +0100 Subject: Store compiled parameter filters so we don't have to compile them in each request. --- .../lib/action_dispatch/http/filter_parameters.rb | 65 +++++++++++++--------- 1 file changed, 40 insertions(+), 25 deletions(-) diff --git a/actionpack/lib/action_dispatch/http/filter_parameters.rb b/actionpack/lib/action_dispatch/http/filter_parameters.rb index 1958e1668d..451b79b190 100644 --- a/actionpack/lib/action_dispatch/http/filter_parameters.rb +++ b/actionpack/lib/action_dispatch/http/filter_parameters.rb @@ -25,9 +25,16 @@ module ActionDispatch module FilterParameters extend ActiveSupport::Concern + mattr_reader :compiled_parameter_filter_for + @@compiled_parameter_filter_for = {} + # Return a hash of parameters with all sensitive data replaced. def filtered_parameters - @filtered_parameters ||= process_parameter_filter(parameters) + @filtered_parameters ||= if filtering_parameters? + process_parameter_filter(parameters) + else + parameters.dup + end end alias :fitered_params :filtered_parameters @@ -46,10 +53,18 @@ module ActionDispatch protected - def compile_parameter_filter #:nodoc: + def filtering_parameters? #:nodoc: + @env["action_dispatch.parameter_filter"].present? + end + + def process_parameter_filter(params) #:nodoc: + compiled_parameter_filter_for(@env["action_dispatch.parameter_filter"]).call(params) + end + + def compile_parameter_filter(filters) #:nodoc: strings, regexps, blocks = [], [], [] - Array(@env["action_dispatch.parameter_filter"]).each do |item| + filters.each do |item| case item when NilClass when Proc @@ -65,34 +80,34 @@ module ActionDispatch [regexps, blocks] end - def filtering_parameters? #:nodoc: - @env["action_dispatch.parameter_filter"].present? - end + def compiled_parameter_filter_for(filters) #:nodoc: + @@compiled_parameter_filter_for[filters] ||= begin + regexps, blocks = compile_parameter_filter(filters) - def process_parameter_filter(original_params) #:nodoc: - return original_params.dup unless filtering_parameters? + lambda do |original_params| + filtered_params = {} - filtered_params = {} - regexps, blocks = compile_parameter_filter + original_params.each do |key, value| + if regexps.find { |r| key =~ r } + value = '[FILTERED]' + elsif value.is_a?(Hash) + value = process_parameter_filter(value) + elsif value.is_a?(Array) + value = value.map { |v| v.is_a?(Hash) ? process_parameter_filter(v) : v } + elsif blocks.present? + key = key.dup + value = value.dup if value.duplicable? + blocks.each { |b| b.call(key, value) } + end - original_params.each do |key, value| - if regexps.find { |r| key =~ r } - value = '[FILTERED]' - elsif value.is_a?(Hash) - value = process_parameter_filter(value) - elsif value.is_a?(Array) - value = value.map { |i| process_parameter_filter(i) } - elsif blocks.present? - key = key.dup - value = value.dup if value.duplicable? - blocks.each { |b| b.call(key, value) } - end + filtered_params[key] = value + end - filtered_params[key] = value + filtered_params + end end - - filtered_params end + end end end \ No newline at end of file -- cgit v1.2.3 From a7b78e86b3b78cf4f461cd372d914ff3a6295c1b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Sun, 21 Feb 2010 14:40:48 +0100 Subject: Add a tests which ensures filtered_parameters does not raise an error for a mixed array [#3928 status:resolved] --- actionpack/test/dispatch/request_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actionpack/test/dispatch/request_test.rb b/actionpack/test/dispatch/request_test.rb index 2b5c19361a..cc6acead6e 100644 --- a/actionpack/test/dispatch/request_test.rb +++ b/actionpack/test/dispatch/request_test.rb @@ -462,7 +462,7 @@ class RequestTest < ActiveSupport::TestCase [{'foo'=>'bar', 'baz'=>'foo'},{'foo'=>'[FILTERED]', 'baz'=>'[FILTERED]'},%w'foo baz'], [{'bar'=>{'foo'=>'bar','bar'=>'foo'}},{'bar'=>{'foo'=>'[FILTERED]','bar'=>'foo'}},%w'fo'], [{'foo'=>{'foo'=>'bar','bar'=>'foo'}},{'foo'=>'[FILTERED]'},%w'f banana'], - [{'baz'=>[{'foo'=>'baz'}]}, {'baz'=>[{'foo'=>'[FILTERED]'}]}, [/foo/]]] + [{'baz'=>[{'foo'=>'baz'}, "1"]}, {'baz'=>[{'foo'=>'[FILTERED]'}, "1"]}, [/foo/]]] test_hashes.each do |before_filter, after_filter, filter_words| request = stub_request('action_dispatch.parameter_filter' => filter_words) -- cgit v1.2.3 From 4cdfe98d925397a613c9220bca65be5081c92f56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Sch=C3=BCrrer?= Date: Sun, 21 Feb 2010 03:05:31 +0100 Subject: Typo --- railties/lib/rails/application.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb index 9384492486..b3a57e2ced 100644 --- a/railties/lib/rails/application.rb +++ b/railties/lib/rails/application.rb @@ -56,7 +56,7 @@ module Rails end def metal_loader - @metal_laoder ||= MetalLoader.new + @metal_loader ||= MetalLoader.new end def routes_reloader -- cgit v1.2.3 From 6bc24d40d56332593bc22612d4618a2f80b1d91b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Sch=C3=BCrrer?= Date: Sun, 21 Feb 2010 17:21:25 +0100 Subject: Use ActionDispatch::Routing everywhere --- actionmailer/test/old_base/url_test.rb | 2 +- actionpack/lib/action_controller/deprecated.rb | 1 - .../lib/action_controller/metal/compatibility.rb | 4 ++-- actionpack/lib/action_controller/metal/url_for.rb | 4 ++-- actionpack/lib/action_controller/test_case.rb | 2 +- actionpack/lib/action_dispatch/routing.rb | 1 + actionpack/lib/action_dispatch/routing/routes.rb | 5 +++++ .../action_dispatch/testing/assertions/routing.rb | 22 +++++++++++----------- .../lib/action_dispatch/testing/integration.rb | 4 ++-- .../lib/action_view/helpers/atom_feed_helper.rb | 2 +- actionpack/lib/action_view/helpers/url_helper.rb | 2 +- actionpack/lib/action_view/test_case.rb | 2 +- actionpack/test/abstract_unit.rb | 18 +++++++++--------- .../test/activerecord/polymorphic_routes_test.rb | 6 +++--- actionpack/test/controller/rescue_test.rb | 4 ++-- actionpack/test/controller/resources_test.rb | 4 ++-- actionpack/test/controller/test_test.rb | 8 ++++---- actionpack/test/controller/webservice_test.rb | 2 +- actionpack/test/dispatch/routing_test.rb | 10 +++++----- railties/builtin/routes.rb | 4 ++-- railties/lib/rails/application.rb | 2 +- railties/lib/rails/tasks/routes.rake | 4 ++-- railties/test/rails_info_controller_test.rb | 2 +- railties/test/railties/shared_tests.rb | 8 ++++---- 24 files changed, 64 insertions(+), 59 deletions(-) create mode 100644 actionpack/lib/action_dispatch/routing/routes.rb diff --git a/actionmailer/test/old_base/url_test.rb b/actionmailer/test/old_base/url_test.rb index d851431c7a..53664480ff 100644 --- a/actionmailer/test/old_base/url_test.rb +++ b/actionmailer/test/old_base/url_test.rb @@ -61,7 +61,7 @@ class ActionMailerUrlTest < Test::Unit::TestCase def test_signed_up_with_url TestMailer.delivery_method = :test - ActionController::Routing::Routes.draw do |map| + ActionDispatch::Routing::Routes.draw do |map| map.connect ':controller/:action/:id' map.welcome 'welcome', :controller=>"foo", :action=>"bar" end diff --git a/actionpack/lib/action_controller/deprecated.rb b/actionpack/lib/action_controller/deprecated.rb index a4eef07841..50c4058845 100644 --- a/actionpack/lib/action_controller/deprecated.rb +++ b/actionpack/lib/action_controller/deprecated.rb @@ -1,5 +1,4 @@ ActionController::AbstractRequest = ActionController::Request = ActionDispatch::Request ActionController::AbstractResponse = ActionController::Response = ActionDispatch::Response ActionController::Routing = ActionDispatch::Routing -ActionController::Routing::Routes = ActionDispatch::Routing::RouteSet.new ActionController::UrlWriter = ActionController::UrlFor diff --git a/actionpack/lib/action_controller/metal/compatibility.rb b/actionpack/lib/action_controller/metal/compatibility.rb index a1cfa32d4d..136b024d9e 100644 --- a/actionpack/lib/action_controller/metal/compatibility.rb +++ b/actionpack/lib/action_controller/metal/compatibility.rb @@ -20,8 +20,8 @@ module ActionController class << self delegate :default_charset=, :to => "ActionDispatch::Response" - delegate :resources_path_names, :to => "ActionController::Routing::Routes" - delegate :resources_path_names=, :to => "ActionController::Routing::Routes" + delegate :resources_path_names, :to => "ActionDispatch::Routing::Routes" + delegate :resources_path_names=, :to => "ActionDispatch::Routing::Routes" end # cattr_reader :protected_instance_variables diff --git a/actionpack/lib/action_controller/metal/url_for.rb b/actionpack/lib/action_controller/metal/url_for.rb index 4f3ad07be5..0a9ea7fe1a 100644 --- a/actionpack/lib/action_controller/metal/url_for.rb +++ b/actionpack/lib/action_controller/metal/url_for.rb @@ -6,7 +6,7 @@ module ActionController # is also possible: an URL can be generated from one of your routing definitions. # URL generation functionality is centralized in this module. # - # See ActionController::Routing and ActionController::Resources for general + # See ActionDispatch::Routing and ActionController::Resources for general # information about routing and routes.rb. # # Tip: If you need to generate URLs from your models or some other place, @@ -87,7 +87,7 @@ module ActionController extend ActiveSupport::Concern included do - ActionController::Routing::Routes.install_helpers(self) + ActionDispatch::Routing::Routes.install_helpers(self) # Including in a class uses an inheritable hash. Modules get a plain hash. if respond_to?(:class_attribute) diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb index 14557ca782..99924205dd 100644 --- a/actionpack/lib/action_controller/test_case.rb +++ b/actionpack/lib/action_controller/test_case.rb @@ -19,7 +19,7 @@ module ActionController def assign_parameters(controller_path, action, parameters = {}) parameters = parameters.symbolize_keys.merge(:controller => controller_path, :action => action) - extra_keys = ActionController::Routing::Routes.extra_keys(parameters) + extra_keys = ActionDispatch::Routing::Routes.extra_keys(parameters) non_path_parameters = get? ? query_parameters : request_parameters parameters.each do |key, value| if value.is_a? Fixnum diff --git a/actionpack/lib/action_dispatch/routing.rb b/actionpack/lib/action_dispatch/routing.rb index 335c9edb98..325d2f7f04 100644 --- a/actionpack/lib/action_dispatch/routing.rb +++ b/actionpack/lib/action_dispatch/routing.rb @@ -204,6 +204,7 @@ module ActionDispatch autoload :DeprecatedMapper, 'action_dispatch/routing/deprecated_mapper' autoload :Mapper, 'action_dispatch/routing/mapper' autoload :Route, 'action_dispatch/routing/route' + autoload :Routes, 'action_dispatch/routing/routes' autoload :RouteSet, 'action_dispatch/routing/route_set' SEPARATORS = %w( / . ? ) diff --git a/actionpack/lib/action_dispatch/routing/routes.rb b/actionpack/lib/action_dispatch/routing/routes.rb new file mode 100644 index 0000000000..4714556d36 --- /dev/null +++ b/actionpack/lib/action_dispatch/routing/routes.rb @@ -0,0 +1,5 @@ +# A singleton that stores the current route set +ActionDispatch::Routing::Routes = ActionDispatch::Routing::RouteSet.new + +# To preserve compatibility with pre-3.0 Rails action_controller/deprecated.rb +# defines ActionDispatch::Routing::Routes as an alias diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb index 0c33539b4a..ada749bfe2 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb @@ -80,7 +80,7 @@ module ActionDispatch expected_path = "/#{expected_path}" unless expected_path[0] == ?/ # Load routes.rb if it hasn't been loaded. - generated_path, extra_keys = ActionController::Routing::Routes.generate_extras(options, defaults) + generated_path, extra_keys = ActionDispatch::Routing::Routes.generate_extras(options, defaults) found_extras = options.reject {|k, v| ! extra_keys.include? k} msg = build_message(message, "found extras , not ", found_extras, extras) @@ -125,7 +125,7 @@ module ActionDispatch end # A helper to make it easier to test different route configurations. - # This method temporarily replaces ActionController::Routing::Routes + # This method temporarily replaces ActionDispatch::Routing::Routes # with a new RouteSet instance. # # The new instance is yielded to the passed block. Typically the block @@ -142,22 +142,22 @@ module ActionDispatch # end # def with_routing - real_routes = ActionController::Routing::Routes - ActionController::Routing.module_eval { remove_const :Routes } + real_routes = ActionDispatch::Routing::Routes + ActionDispatch::Routing.module_eval { remove_const :Routes } - temporary_routes = ActionController::Routing::RouteSet.new - ActionController::Routing.module_eval { const_set :Routes, temporary_routes } + temporary_routes = ActionDispatch::Routing::RouteSet.new + ActionDispatch::Routing.module_eval { const_set :Routes, temporary_routes } yield temporary_routes ensure - if ActionController::Routing.const_defined? :Routes - ActionController::Routing.module_eval { remove_const :Routes } + if ActionDispatch::Routing.const_defined? :Routes + ActionDispatch::Routing.module_eval { remove_const :Routes } end - ActionController::Routing.const_set(:Routes, real_routes) if real_routes + ActionDispatch::Routing.const_set(:Routes, real_routes) if real_routes end def method_missing(selector, *args, &block) - if @controller && ActionController::Routing::Routes.named_routes.helpers.include?(selector) + if @controller && ActionDispatch::Routing::Routes.named_routes.helpers.include?(selector) @controller.send(selector, *args, &block) else super @@ -174,7 +174,7 @@ module ActionDispatch request.env["REQUEST_METHOD"] = request_method.to_s.upcase if request_method request.path = path - params = ActionController::Routing::Routes.recognize_path(path, { :method => request.method }) + params = ActionDispatch::Routing::Routes.recognize_path(path, { :method => request.method }) request.path_parameters = params.with_indifferent_access request diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index d179af47d9..f93059759b 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -188,11 +188,11 @@ module ActionDispatch unless defined? @named_routes_configured # install the named routes in this session instance. klass = metaclass - ActionController::Routing::Routes.install_helpers(klass) + ActionDispatch::Routing::Routes.install_helpers(klass) # the helpers are made protected by default--we make them public for # easier access during testing and troubleshooting. - klass.module_eval { public *ActionController::Routing::Routes.named_routes.helpers } + klass.module_eval { public *ActionDispatch::Routing::Routes.named_routes.helpers } @named_routes_configured = true end end diff --git a/actionpack/lib/action_view/helpers/atom_feed_helper.rb b/actionpack/lib/action_view/helpers/atom_feed_helper.rb index 9951e11a37..4305a0d5f5 100644 --- a/actionpack/lib/action_view/helpers/atom_feed_helper.rb +++ b/actionpack/lib/action_view/helpers/atom_feed_helper.rb @@ -8,7 +8,7 @@ module ActionView # Full usage example: # # config/routes.rb: - # ActionController::Routing::Routes.draw do |map| + # ActionDispatch::Routing::Routes.draw do |map| # map.resources :posts # map.root :controller => "posts" # end diff --git a/actionpack/lib/action_view/helpers/url_helper.rb b/actionpack/lib/action_view/helpers/url_helper.rb index e121472fe3..d9607c0095 100644 --- a/actionpack/lib/action_view/helpers/url_helper.rb +++ b/actionpack/lib/action_view/helpers/url_helper.rb @@ -5,7 +5,7 @@ require 'active_support/core_ext/hash/keys' module ActionView module Helpers #:nodoc: # Provides a set of methods for making links and getting URLs that - # depend on the routing subsystem (see ActionController::Routing). + # depend on the routing subsystem (see ActionDispatch::Routing). # This allows you to use the same format for links in views # and controllers. module UrlHelper diff --git a/actionpack/lib/action_view/test_case.rb b/actionpack/lib/action_view/test_case.rb index fc29acea6d..af2ed33f3f 100644 --- a/actionpack/lib/action_view/test_case.rb +++ b/actionpack/lib/action_view/test_case.rb @@ -152,7 +152,7 @@ module ActionView end def method_missing(selector, *args) - if ActionController::Routing::Routes.named_routes.helpers.include?(selector) + if ActionDispatch::Routing::Routes.named_routes.helpers.include?(selector) @controller.__send__(selector, *args) else super diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb index 655a133c96..7b41db3fea 100644 --- a/actionpack/test/abstract_unit.rb +++ b/actionpack/test/abstract_unit.rb @@ -76,7 +76,7 @@ class ActiveSupport::TestCase # Hold off drawing routes until all the possible controller classes # have been loaded. setup_once do - ActionController::Routing::Routes.draw do |map| + ActionDispatch::Routing::Routes.draw do |map| match ':controller(/:action(/:id))' end end @@ -92,7 +92,7 @@ class ActionController::IntegrationTest < ActiveSupport::TestCase middleware.use "ActionDispatch::Cookies" middleware.use "ActionDispatch::Flash" middleware.use "ActionDispatch::Head" - }.build(routes || ActionController::Routing::Routes) + }.build(routes || ActionDispatch::Routing::Routes) end self.app = build_app @@ -118,19 +118,19 @@ class ActionController::IntegrationTest < ActiveSupport::TestCase end def with_routing(&block) - real_routes = ActionController::Routing::Routes - ActionController::Routing.module_eval { remove_const :Routes } + real_routes = ActionDispatch::Routing::Routes + ActionDispatch::Routing.module_eval { remove_const :Routes } - temporary_routes = ActionController::Routing::RouteSet.new + temporary_routes = ActionDispatch::Routing::RouteSet.new self.class.app = self.class.build_app(temporary_routes) - ActionController::Routing.module_eval { const_set :Routes, temporary_routes } + ActionDispatch::Routing.module_eval { const_set :Routes, temporary_routes } yield temporary_routes ensure - if ActionController::Routing.const_defined? :Routes - ActionController::Routing.module_eval { remove_const :Routes } + if ActionDispatch::Routing.const_defined? :Routes + ActionDispatch::Routing.module_eval { remove_const :Routes } end - ActionController::Routing.const_set(:Routes, real_routes) if real_routes + ActionDispatch::Routing.const_set(:Routes, real_routes) if real_routes self.class.app = self.class.build_app end end diff --git a/actionpack/test/activerecord/polymorphic_routes_test.rb b/actionpack/test/activerecord/polymorphic_routes_test.rb index ea82758cf5..7be2ef7e29 100644 --- a/actionpack/test/activerecord/polymorphic_routes_test.rb +++ b/actionpack/test/activerecord/polymorphic_routes_test.rb @@ -400,7 +400,7 @@ class PolymorphicRoutesTest < ActionController::TestCase map.resources :series end - ActionController::Routing::Routes.install_helpers(self.class) + ActionDispatch::Routing::Routes.install_helpers(self.class) yield end end @@ -422,7 +422,7 @@ class PolymorphicRoutesTest < ActionController::TestCase end end - ActionController::Routing::Routes.install_helpers(self.class) + ActionDispatch::Routing::Routes.install_helpers(self.class) yield end end @@ -441,7 +441,7 @@ class PolymorphicRoutesTest < ActionController::TestCase end end - ActionController::Routing::Routes.install_helpers(self.class) + ActionDispatch::Routing::Routes.install_helpers(self.class) yield end end diff --git a/actionpack/test/controller/rescue_test.rb b/actionpack/test/controller/rescue_test.rb index 37367eaafc..118b563a72 100644 --- a/actionpack/test/controller/rescue_test.rb +++ b/actionpack/test/controller/rescue_test.rb @@ -326,7 +326,7 @@ class RescueTest < ActionController::IntegrationTest end test 'rescue routing exceptions' do - @app = ActionDispatch::Rescue.new(ActionController::Routing::Routes) do + @app = ActionDispatch::Rescue.new(ActionDispatch::Routing::Routes) do rescue_from ActionController::RoutingError, lambda { |env| [200, {"Content-Type" => "text/html"}, ["Gotcha!"]] } end @@ -335,7 +335,7 @@ class RescueTest < ActionController::IntegrationTest end test 'unrescued exception' do - @app = ActionDispatch::Rescue.new(ActionController::Routing::Routes) + @app = ActionDispatch::Rescue.new(ActionDispatch::Routing::Routes) assert_raise(ActionController::RoutingError) { get '/b00m' } end diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb index 01ed491732..9b3f466e44 100644 --- a/actionpack/test/controller/resources_test.rb +++ b/actionpack/test/controller/resources_test.rb @@ -394,7 +394,7 @@ class ResourcesTest < ActionController::TestCase assert_restful_routes_for :messages do |options| assert_recognizes(options.merge(:action => "new"), :path => "/messages/new", :method => :get) assert_raise(ActionController::RoutingError) do - ActionController::Routing::Routes.recognize_path("/messages/new", :method => :post) + ActionDispatch::Routing::Routes.recognize_path("/messages/new", :method => :post) end end end @@ -504,7 +504,7 @@ class ResourcesTest < ActionController::TestCase def test_restful_routes_dont_generate_duplicates with_restful_routing :messages do - routes = ActionController::Routing::Routes.routes + routes = ActionDispatch::Routing::Routes.routes routes.each do |route| routes.each do |r| next if route === r # skip the comparison instance diff --git a/actionpack/test/controller/test_test.rb b/actionpack/test/controller/test_test.rb index 0f074b32e6..3f5d60540f 100644 --- a/actionpack/test/controller/test_test.rb +++ b/actionpack/test/controller/test_test.rb @@ -476,8 +476,8 @@ XML end def test_with_routing_places_routes_back - assert ActionController::Routing::Routes - routes_id = ActionController::Routing::Routes.object_id + assert ActionDispatch::Routing::Routes + routes_id = ActionDispatch::Routing::Routes.object_id begin with_routing { raise 'fail' } @@ -485,8 +485,8 @@ XML rescue RuntimeError end - assert ActionController::Routing::Routes - assert_equal routes_id, ActionController::Routing::Routes.object_id + assert ActionDispatch::Routing::Routes + assert_equal routes_id, ActionDispatch::Routing::Routes.object_id end def test_remote_addr diff --git a/actionpack/test/controller/webservice_test.rb b/actionpack/test/controller/webservice_test.rb index 5882a8cfa3..ede48017cf 100644 --- a/actionpack/test/controller/webservice_test.rb +++ b/actionpack/test/controller/webservice_test.rb @@ -245,7 +245,7 @@ class WebServiceTest < ActionController::IntegrationTest private def with_params_parsers(parsers = {}) old_session = @integration_session - @app = ActionDispatch::ParamsParser.new(ActionController::Routing::Routes, parsers) + @app = ActionDispatch::ParamsParser.new(ActionDispatch::Routing::Routes, parsers) reset! yield ensure diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb index 0cd1fddff1..e29127f78f 100644 --- a/actionpack/test/dispatch/routing_test.rb +++ b/actionpack/test/dispatch/routing_test.rb @@ -728,14 +728,14 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest private def with_test_routes - real_routes, temp_routes = ActionController::Routing::Routes, Routes + real_routes, temp_routes = ActionDispatch::Routing::Routes, Routes - ActionController::Routing.module_eval { remove_const :Routes } - ActionController::Routing.module_eval { const_set :Routes, temp_routes } + ActionDispatch::Routing.module_eval { remove_const :Routes } + ActionDispatch::Routing.module_eval { const_set :Routes, temp_routes } yield ensure - ActionController::Routing.module_eval { remove_const :Routes } - ActionController::Routing.const_set(:Routes, real_routes) + ActionDispatch::Routing.module_eval { remove_const :Routes } + ActionDispatch::Routing.const_set(:Routes, real_routes) end end diff --git a/railties/builtin/routes.rb b/railties/builtin/routes.rb index ef9d9e756d..b4fdb95a64 100644 --- a/railties/builtin/routes.rb +++ b/railties/builtin/routes.rb @@ -1,3 +1,3 @@ -ActionController::Routing::Routes.draw do |map| +ActionDispatch::Routing::Routes.draw do |map| match '/rails/info/properties' => "rails/info#properties" -end \ No newline at end of file +end diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb index b3a57e2ced..67094392ee 100644 --- a/railties/lib/rails/application.rb +++ b/railties/lib/rails/application.rb @@ -48,7 +48,7 @@ module Rails end def routes - ::ActionController::Routing::Routes + ::ActionDispatch::Routing::Routes end def railties diff --git a/railties/lib/rails/tasks/routes.rake b/railties/lib/rails/tasks/routes.rake index ac0f440896..1d0ac38c96 100644 --- a/railties/lib/rails/tasks/routes.rake +++ b/railties/lib/rails/tasks/routes.rake @@ -1,9 +1,9 @@ desc 'Print out all defined routes in match order, with names. Target specific controller with CONTROLLER=x.' task :routes => :environment do Rails::Application.reload_routes! - all_routes = ENV['CONTROLLER'] ? ActionController::Routing::Routes.routes.select { |route| route.defaults[:controller] == ENV['CONTROLLER'] } : ActionController::Routing::Routes.routes + all_routes = ENV['CONTROLLER'] ? ActionDispatch::Routing::Routes.routes.select { |route| route.defaults[:controller] == ENV['CONTROLLER'] } : ActionDispatch::Routing::Routes.routes routes = all_routes.collect do |route| - name = ActionController::Routing::Routes.named_routes.routes.index(route).to_s + name = ActionDispatch::Routing::Routes.named_routes.routes.index(route).to_s reqs = route.requirements.empty? ? "" : route.requirements.inspect {:name => name, :verb => route.verb.to_s, :path => route.path, :reqs => reqs} end diff --git a/railties/test/rails_info_controller_test.rb b/railties/test/rails_info_controller_test.rb index 4163fb2c6d..9cfa1d6aaa 100644 --- a/railties/test/rails_info_controller_test.rb +++ b/railties/test/rails_info_controller_test.rb @@ -14,7 +14,7 @@ class InfoControllerTest < ActionController::TestCase tests Rails::InfoController def setup - ActionController::Routing::Routes.draw do |map| + ActionDispatch::Routing::Routes.draw do |map| match ':controller/:action' end @controller.stubs(:consider_all_requests_local? => false, :local_request? => true) diff --git a/railties/test/railties/shared_tests.rb b/railties/test/railties/shared_tests.rb index d51a0d153c..c9e6e6081a 100644 --- a/railties/test/railties/shared_tests.rb +++ b/railties/test/railties/shared_tests.rb @@ -133,7 +133,7 @@ module RailtiesTest end end - ActionController::Routing::Routes.draw do + ActionDispatch::Routing::Routes.draw do match "/sprokkit", :to => Sprokkit end RUBY @@ -170,7 +170,7 @@ module RailtiesTest RUBY @plugin.write "config/routes.rb", <<-RUBY - ActionController::Routing::Routes.draw do |map| + ActionDispatch::Routing::Routes.draw do |map| match 'foo', :to => 'bar#index' match 'bar', :to => 'bar#index' end @@ -261,7 +261,7 @@ YAML def test_namespaced_controllers_with_namespaced_routes @plugin.write "config/routes.rb", <<-RUBY - ActionController::Routing::Routes.draw do + ActionDispatch::Routing::Routes.draw do namespace :admin do match "index", :to => "admin/foo#index" end @@ -312,4 +312,4 @@ YAML boot_rails end end -end \ No newline at end of file +end -- cgit v1.2.3 From 6fa2bbfd10fde99f4e3a36292438fb666079029a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Mon, 22 Feb 2010 08:45:41 +0100 Subject: Fix AMo isolated tests. --- activemodel/test/models/contact.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activemodel/test/models/contact.rb b/activemodel/test/models/contact.rb index a583b89aa1..a9009fbdef 100644 --- a/activemodel/test/models/contact.rb +++ b/activemodel/test/models/contact.rb @@ -8,6 +8,6 @@ class Contact end def persisted? - id.present? + id end end -- cgit v1.2.3 From a6684eeb786663839cf383ea54b681d429a83177 Mon Sep 17 00:00:00 2001 From: David Chelimsky Date: Sun, 21 Feb 2010 11:19:23 -0600 Subject: don't set @expected.date in generated mailer test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Mikel Lindsaar Signed-off-by: José Valim --- railties/lib/generators/test_unit/mailer/templates/functional_test.rb | 1 - 1 file changed, 1 deletion(-) diff --git a/railties/lib/generators/test_unit/mailer/templates/functional_test.rb b/railties/lib/generators/test_unit/mailer/templates/functional_test.rb index e1aeb2db90..a2b1f1ed05 100644 --- a/railties/lib/generators/test_unit/mailer/templates/functional_test.rb +++ b/railties/lib/generators/test_unit/mailer/templates/functional_test.rb @@ -7,7 +7,6 @@ class <%= class_name %>Test < ActionMailer::TestCase @expected.to = "to@example.org" @expected.from = "from@example.com" @expected.body = read_fixture("<%= action %>") - @expected.date = Time.now assert_equal @expected, <%= class_name %>.<%= action %> end -- cgit v1.2.3 From cefc136ec332e5e065a2f4dd184d6fec0ea3c2ba Mon Sep 17 00:00:00 2001 From: Mikel Lindsaar Date: Mon, 22 Feb 2010 12:17:08 +1100 Subject: Adding options to register observers and interceptors through ActionMailer::Base.register_observer and ActionMailer::Base.register_interceptor. These hook into Mail.register_interceptor and Mail.register_observer. Also bumped Mail requirement to 2.1.3 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- actionmailer/actionmailer.gemspec | 2 +- actionmailer/lib/action_mailer/base.rb | 15 +++++++++++++++ actionmailer/test/base_test.rb | 26 ++++++++++++++++++++++++++ 3 files changed, 42 insertions(+), 1 deletion(-) diff --git a/actionmailer/actionmailer.gemspec b/actionmailer/actionmailer.gemspec index 31d8efc7bf..13983aa663 100644 --- a/actionmailer/actionmailer.gemspec +++ b/actionmailer/actionmailer.gemspec @@ -18,6 +18,6 @@ Gem::Specification.new do |s| s.has_rdoc = true s.add_dependency('actionpack', '= 3.0.0.beta1') - s.add_dependency('mail', '~> 2.1.2') + s.add_dependency('mail', '~> 2.1.3') s.add_dependency('text-format', '~> 1.0.0') end diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb index ce13111850..e198543c34 100644 --- a/actionmailer/lib/action_mailer/base.rb +++ b/actionmailer/lib/action_mailer/base.rb @@ -181,6 +181,18 @@ module ActionMailer #:nodoc: # and the second being a application/pdf with a Base64 encoded copy of the file.pdf book # with the filename +free_book.pdf+. # + # = Observing and Intercepting Mails + # + # ActionMailer provides hooks into the Mail observer and interceptor methods. These allow you to + # register objects that are called during the mail delivery life cycle. + # + # An observer object must implement the :delivered_email(message) method which will be + # called once for every email sent after the email has been sent. + # + # An interceptor object must implement the :delivering_email(message) method which will be + # called before the email is sent, allowing you to make modifications to the email before it hits + # the delivery agents. Your object should make and needed modifications directly to the passed + # in Mail::Message instance. # # = Configuration options # @@ -265,6 +277,9 @@ module ActionMailer #:nodoc: include ActionMailer::OldApi include ActionMailer::DeprecatedApi + + delegate :register_observer, :to => Mail + delegate :register_interceptor, :to => Mail private_class_method :new #:nodoc: diff --git a/actionmailer/test/base_test.rb b/actionmailer/test/base_test.rb index 5fc229df09..c1cf1f0157 100644 --- a/actionmailer/test/base_test.rb +++ b/actionmailer/test/base_test.rb @@ -502,6 +502,32 @@ class BaseTest < ActiveSupport::TestCase mail = BaseMailer.welcome_from_another_path(['unknown/invalid', 'another.path/base_mailer']) assert_equal("Welcome from another path", mail.body.encoded) end + + # Before and After hooks + + class MyObserver + def self.delivered_email(mail) + end + end + + test "you can register an observer to the mail object that gets informed on email delivery" do + ActionMailer::Base.register_observer(MyObserver) + mail = BaseMailer.welcome + MyObserver.expects(:delivered_email).with(mail) + mail.deliver + end + + class MyInterceptor + def self.delivering_email(mail) + end + end + + test "you can register an interceptor to the mail object that gets passed the mail object before delivery" do + ActionMailer::Base.register_interceptor(MyInterceptor) + mail = BaseMailer.welcome + MyInterceptor.expects(:delivering_email).with(mail) + mail.deliver + end protected -- cgit v1.2.3 From d92e8554921b7ab1906fd657325f395413cbdb30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Mon, 22 Feb 2010 13:13:26 +0100 Subject: Include missing modules. --- actionpack/lib/action_controller/metal/redirecting.rb | 1 + actionpack/lib/action_controller/metal/rendering.rb | 2 +- actionpack/lib/action_view/base.rb | 4 ++-- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/actionpack/lib/action_controller/metal/redirecting.rb b/actionpack/lib/action_controller/metal/redirecting.rb index faf0589fd2..25e4e18493 100644 --- a/actionpack/lib/action_controller/metal/redirecting.rb +++ b/actionpack/lib/action_controller/metal/redirecting.rb @@ -11,6 +11,7 @@ module ActionController extend ActiveSupport::Concern include AbstractController::Logger + include ActionController::RackDelegation include ActionController::UrlFor # Redirects the browser to the target specified in +options+. This parameter can take one of three forms: diff --git a/actionpack/lib/action_controller/metal/rendering.rb b/actionpack/lib/action_controller/metal/rendering.rb index b1dab8497b..6518a464e2 100644 --- a/actionpack/lib/action_controller/metal/rendering.rb +++ b/actionpack/lib/action_controller/metal/rendering.rb @@ -2,7 +2,7 @@ module ActionController module Rendering extend ActiveSupport::Concern - include RackDelegation + include ActionController::RackDelegation include AbstractController::Rendering include AbstractController::LocalizedCache diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb index 4096c296c3..44e5870131 100644 --- a/actionpack/lib/action_view/base.rb +++ b/actionpack/lib/action_view/base.rb @@ -11,7 +11,7 @@ module ActionView #:nodoc: def initialize(paths, path, details, partial) @path = path - display_paths = paths.compact.join(":") + display_paths = paths.compact.map{ |p| p.to_s.inspect }.join(", ") template_type = if partial "partial" elsif path =~ /layouts/i @@ -20,7 +20,7 @@ module ActionView #:nodoc: 'template' end - super("Missing #{template_type} #{path} with #{details.inspect} in view path #{display_paths}") + super("Missing #{template_type} #{path} with #{details.inspect} in view paths #{display_paths}") end end -- cgit v1.2.3 From 35e0975af8b6b50b16de4d0bf96559f46b1d1155 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Mon, 22 Feb 2010 13:58:29 +0100 Subject: Rename erubis_implementation to erb_implementation. --- actionpack/lib/action_view/template/handlers/erb.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/actionpack/lib/action_view/template/handlers/erb.rb b/actionpack/lib/action_view/template/handlers/erb.rb index 4573a440d1..4b7cec50f3 100644 --- a/actionpack/lib/action_view/template/handlers/erb.rb +++ b/actionpack/lib/action_view/template/handlers/erb.rb @@ -43,13 +43,13 @@ module ActionView self.default_format = Mime::HTML - cattr_accessor :erubis_implementation - self.erubis_implementation = Erubis + cattr_accessor :erb_implementation + self.erb_implementation = Erubis def compile(template) source = template.source.gsub(/\A(<%(#.*coding[:=]\s*(\S+)\s*)-?%>)\s*\n?/, '') erb = "<% __in_erb_template=true %>#{source}" - result = self.class.erubis_implementation.new(erb, :trim=>(self.class.erb_trim_mode == "-")).src + result = self.class.erb_implementation.new(erb, :trim=>(self.class.erb_trim_mode == "-")).src result = "#{$2}\n#{result}" if $2 result end -- cgit v1.2.3 From ca92e92ba18132dcfd57cf30a8492c6fea1c113a Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Sat, 20 Feb 2010 19:51:47 -0200 Subject: avoid active not initialized warning --- activerecord/lib/active_record/connection_adapters/abstract_adapter.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb index 7e80347f75..6ffffc8654 100755 --- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb @@ -37,6 +37,7 @@ module ActiveRecord @@row_even = true def initialize(connection, logger = nil) #:nodoc: + @active = nil @connection, @logger = connection, logger @runtime = 0 @query_cache_enabled = false -- cgit v1.2.3 From 2b43021499f6e00a19eba3e7e48db403a61161bb Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Mon, 22 Feb 2010 20:00:41 -0200 Subject: avoid @transaction_joinable not initialized warning --- .../active_record/connection_adapters/abstract/database_statements.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb index 027d736484..abb695264e 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb @@ -113,7 +113,7 @@ module ActiveRecord def transaction(options = {}) options.assert_valid_keys :requires_new, :joinable - last_transaction_joinable = @transaction_joinable + last_transaction_joinable = defined?(@transaction_joinable) ? @transaction_joinable : nil if options.has_key?(:joinable) @transaction_joinable = options[:joinable] else -- cgit v1.2.3 From ee541049fdbe5eeebcca2f3b83144a5d803345a9 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Mon, 22 Feb 2010 20:03:05 -0200 Subject: avoid @lock_value not initialized warning --- activerecord/lib/active_record/relation/query_methods.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index 0266700f66..25ffa7860e 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -174,7 +174,7 @@ module ActiveRecord arel = arel.lock when String arel = arel.lock(@lock_value) - end + end if defined?(@lock_value) arel end -- cgit v1.2.3 From 3345af61fb128d0a70793b235e3cb878781d6f40 Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Tue, 23 Feb 2010 15:37:17 -0800 Subject: Fix streaming by having it create a File object, which can be handled by Rack servers as appropriate --- actionpack/lib/action_controller/metal/streaming.rb | 20 ++++++-------------- actionpack/lib/action_controller/metal/testing.rb | 1 - actionpack/test/controller/send_file_test.rb | 14 +++++++++++--- activesupport/lib/active_support/ruby/shim.rb | 1 + activesupport/test/core_ext/file_test.rb | 4 ++++ 5 files changed, 22 insertions(+), 18 deletions(-) diff --git a/actionpack/lib/action_controller/metal/streaming.rb b/actionpack/lib/action_controller/metal/streaming.rb index 8f03b8bb17..0d6fdafe0a 100644 --- a/actionpack/lib/action_controller/metal/streaming.rb +++ b/actionpack/lib/action_controller/metal/streaming.rb @@ -79,6 +79,8 @@ module ActionController #:nodoc: # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9 # for the Cache-Control header spec. def send_file(path, options = {}) #:doc: + # self.response_body = File.open(path) + raise MissingFile, "Cannot read file #{path}" unless File.file?(path) and File.readable?(path) options[:length] ||= File.size(path) @@ -90,19 +92,9 @@ module ActionController #:nodoc: if options[:x_sendfile] head options[:status], X_SENDFILE_HEADER => path else - if options[:stream] - # TODO : Make render :text => proc {} work with the new base - render :status => options[:status], :text => Proc.new { |response, output| - len = options[:buffer_size] || 4096 - File.open(path, 'rb') do |file| - while buf = file.read(len) - output.write(buf) - end - end - } - else - File.open(path, 'rb') { |file| render :status => options[:status], :text => file.read } - end + self.status = options[:status] || 200 + self.content_type = options[:content_type] if options.key?(:content_type) + self.response_body = File.open(path, "rb") end end @@ -139,7 +131,7 @@ module ActionController #:nodoc: # instead. See ActionController::Base#render for more information. def send_data(data, options = {}) #:doc: send_file_headers! options.merge(:length => data.bytesize) - render :status => options[:status], :text => data + render options.slice(:status, :content_type).merge(:text => data) end private diff --git a/actionpack/lib/action_controller/metal/testing.rb b/actionpack/lib/action_controller/metal/testing.rb index 707ad968f4..4b8c452d50 100644 --- a/actionpack/lib/action_controller/metal/testing.rb +++ b/actionpack/lib/action_controller/metal/testing.rb @@ -13,7 +13,6 @@ module ActionController if cookies = @_request.env['action_dispatch.cookies'] cookies.write(@_response) end - @_response.body ||= self.response_body @_response.prepare! set_test_assigns ret diff --git a/actionpack/test/controller/send_file_test.rb b/actionpack/test/controller/send_file_test.rb index 31177223e4..ce144cc24b 100644 --- a/actionpack/test/controller/send_file_test.rb +++ b/actionpack/test/controller/send_file_test.rb @@ -46,15 +46,17 @@ class SendFileTest < ActionController::TestCase response = nil assert_nothing_raised { response = process('file') } assert_not_nil response - assert_kind_of String, response.body - assert_equal file_data, response.body + body = response.body + assert_kind_of String, body + assert_equal file_data, body end def test_file_stream response = nil assert_nothing_raised { response = process('file') } assert_not_nil response - assert_kind_of Array, response.body_parts + assert response.body_parts.respond_to?(:each) + assert response.body_parts.respond_to?(:to_path) require 'stringio' output = StringIO.new @@ -160,6 +162,12 @@ class SendFileTest < ActionController::TestCase assert_equal 500, @response.status end + define_method "test_send_#{method}_content_type" do + @controller.options = { :stream => false, :content_type => "application/x-ruby" } + assert_nothing_raised { assert_not_nil process(method) } + assert_equal "application/x-ruby", @response.content_type + end + define_method "test_default_send_#{method}_status" do @controller.options = { :stream => false } assert_nothing_raised { assert_not_nil process(method) } diff --git a/activesupport/lib/active_support/ruby/shim.rb b/activesupport/lib/active_support/ruby/shim.rb index 1e49ccdade..f0db5b3021 100644 --- a/activesupport/lib/active_support/ruby/shim.rb +++ b/activesupport/lib/active_support/ruby/shim.rb @@ -17,3 +17,4 @@ require 'active_support/core_ext/string/conversions' require 'active_support/core_ext/string/interpolation' require 'active_support/core_ext/rexml' require 'active_support/core_ext/time/conversions' +require 'active_support/core_ext/file/path' diff --git a/activesupport/test/core_ext/file_test.rb b/activesupport/test/core_ext/file_test.rb index 26be694176..e1258b872e 100644 --- a/activesupport/test/core_ext/file_test.rb +++ b/activesupport/test/core_ext/file_test.rb @@ -57,6 +57,10 @@ class AtomicWriteTest < Test::Unit::TestCase File.unlink(file_name) rescue nil end + def test_responds_to_to_path + assert_equal __FILE__, File.open(__FILE__, "r").to_path + end + private def file_name "atomic.file" -- cgit v1.2.3 From a73f682e43016de520510e015802c48c9947a05c Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Tue, 23 Feb 2010 16:29:29 -0800 Subject: Make AD::Response correctly handle bodies that respond_to?(:to_path) as per the Rack spec --- actionpack/lib/action_dispatch/http/response.rb | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb index 1b8dd9abfd..e6ed28742f 100644 --- a/actionpack/lib/action_dispatch/http/response.rb +++ b/actionpack/lib/action_dispatch/http/response.rb @@ -82,6 +82,18 @@ module ActionDispatch # :nodoc: end alias_method :status_message, :message + def respond_to?(method) + if method.to_sym == :to_path + @body.respond_to?(:to_path) + else + super + end + end + + def to_path + @body.to_path + end + def body str = '' each { |part| str << part.to_s } -- cgit v1.2.3 From 5e2bd08023344f3fd4675e80203a10967ffe9000 Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Tue, 23 Feb 2010 17:03:06 -0800 Subject: Makes send_file work again by deferring to Rack::Sendfile. * Add the Rack::Sendfile middleware * Make the header to use configurable via config.action_dispatch.x_sendfile_header (default to "X-Sendfile"). * Add Railties tests to confirm that these work * Remove the :stream, :buffer_size, and :x_senfile default options to send_file * Change the log subscriber to always say "Sent file" * Add deprecation warnings for options that are now no-ops Note that servers can configure this by setting X-Sendfile-Type. Hosting companies and those creating packages of servers specially designed for Rails applications are encouraged to specify this header so that this can work transparently. --- .../lib/action_controller/metal/streaming.rb | 57 ++++++++-------------- .../action_controller/railties/log_subscriber.rb | 10 +--- actionpack/lib/action_dispatch/railtie.rb | 2 + actionpack/test/controller/log_subscriber_test.rb | 4 +- actionpack/test/controller/send_file_test.rb | 23 --------- railties/lib/rails/configuration.rb | 1 + railties/test/application/configuration_test.rb | 55 +++++++++++++++++++++ 7 files changed, 80 insertions(+), 72 deletions(-) diff --git a/actionpack/lib/action_controller/metal/streaming.rb b/actionpack/lib/action_controller/metal/streaming.rb index 0d6fdafe0a..753af3dc58 100644 --- a/actionpack/lib/action_controller/metal/streaming.rb +++ b/actionpack/lib/action_controller/metal/streaming.rb @@ -9,18 +9,13 @@ module ActionController #:nodoc: DEFAULT_SEND_FILE_OPTIONS = { :type => 'application/octet-stream'.freeze, :disposition => 'attachment'.freeze, - :stream => true, - :buffer_size => 4096, - :x_sendfile => false }.freeze - X_SENDFILE_HEADER = 'X-Sendfile'.freeze - protected - # Sends the file, by default streaming it 4096 bytes at a time. This way the - # whole file doesn't need to be read into memory at once. This makes it - # feasible to send even large files. You can optionally turn off streaming - # and send the whole file at once. + # Sends the file. This uses a server-appropriate method (such as X-Sendfile) + # via the Rack::Sendfile middleware. The header to use is set via + # config.action_dispatch.x_sendfile_header, and defaults to "X-Sendfile". + # Your server can also configure this for you by setting the X-Sendfile-Type header. # # Be careful to sanitize the path parameter if it is coming from a web # page. send_file(params[:path]) allows a malicious user to @@ -31,24 +26,12 @@ module ActionController #:nodoc: # Defaults to File.basename(path). # * :type - specifies an HTTP content type. Defaults to 'application/octet-stream'. You can specify # either a string or a symbol for a registered type register with Mime::Type.register, for example :json - # * :length - used to manually override the length (in bytes) of the content that - # is going to be sent to the client. Defaults to File.size(path). # * :disposition - specifies whether the file will be shown inline or downloaded. # Valid values are 'inline' and 'attachment' (default). - # * :stream - whether to send the file to the user agent as it is read (+true+) - # or to read the entire file before sending (+false+). Defaults to +true+. - # * :buffer_size - specifies size (in bytes) of the buffer used to stream the file. - # Defaults to 4096. # * :status - specifies the status code to send with the response. Defaults to '200 OK'. # * :url_based_filename - set to +true+ if you want the browser guess the filename from # the URL, which is necessary for i18n filenames on certain browsers # (setting :filename overrides this option). - # * :x_sendfile - uses X-Sendfile to send the file when set to +true+. This is currently - # only available with Lighttpd/Apache2 and specific modules installed and activated. Since this - # uses the web server to send the file, this may lower memory consumption on your server and - # it will not block your application for further requests. - # See http://blog.lighttpd.net/articles/2006/07/02/x-sendfile and - # http://tn123.ath.cx/mod_xsendfile/ for details. Defaults to +false+. # # The default Content-Type and Content-Disposition headers are # set to download arbitrary binary files in as many browsers as @@ -79,23 +62,18 @@ module ActionController #:nodoc: # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9 # for the Cache-Control header spec. def send_file(path, options = {}) #:doc: - # self.response_body = File.open(path) - raise MissingFile, "Cannot read file #{path}" unless File.file?(path) and File.readable?(path) - options[:length] ||= File.size(path) options[:filename] ||= File.basename(path) unless options[:url_based_filename] send_file_headers! options - @performed_render = false - if options[:x_sendfile] - head options[:status], X_SENDFILE_HEADER => path - else - self.status = options[:status] || 200 - self.content_type = options[:content_type] if options.key?(:content_type) - self.response_body = File.open(path, "rb") + ActiveSupport::Deprecation.warn(":x_sendfile is no longer needed in send_file", caller) end + + self.status = options[:status] || 200 + self.content_type = options[:content_type] if options.key?(:content_type) + self.response_body = File.open(path, "rb") end # Sends the given binary data to the browser. This method is similar to @@ -130,32 +108,35 @@ module ActionController #:nodoc: # data to the browser, then use render :text => proc { ... } # instead. See ActionController::Base#render for more information. def send_data(data, options = {}) #:doc: - send_file_headers! options.merge(:length => data.bytesize) + send_file_headers! options.dup render options.slice(:status, :content_type).merge(:text => data) end private def send_file_headers!(options) options.update(DEFAULT_SEND_FILE_OPTIONS.merge(options)) - [:length, :type, :disposition].each do |arg| + [:type, :disposition].each do |arg| raise ArgumentError, ":#{arg} option required" if options[arg].nil? end - disposition = options[:disposition].dup || 'attachment' + if options.key?(:length) + ActiveSupport::Deprecation.warn("You do not need to provide the file's length", caller) + end - disposition <<= %(; filename="#{options[:filename]}") if options[:filename] + disposition = options[:disposition] + disposition += %(; filename="#{options[:filename]}") if options[:filename] content_type = options[:type] if content_type.is_a?(Symbol) - raise ArgumentError, "Unknown MIME type #{options[:type]}" unless Mime::EXTENSION_LOOKUP.key?(content_type.to_s) - self.content_type = Mime::Type.lookup_by_extension(content_type.to_s) + extension = Mime[content_type] + raise ArgumentError, "Unknown MIME type #{options[:type]}" unless extension + self.content_type = extension else self.content_type = content_type end headers.merge!( - 'Content-Length' => options[:length].to_s, 'Content-Disposition' => disposition, 'Content-Transfer-Encoding' => 'binary' ) diff --git a/actionpack/lib/action_controller/railties/log_subscriber.rb b/actionpack/lib/action_controller/railties/log_subscriber.rb index df9ffa1717..c2299d0b05 100644 --- a/actionpack/lib/action_controller/railties/log_subscriber.rb +++ b/actionpack/lib/action_controller/railties/log_subscriber.rb @@ -22,15 +22,7 @@ module ActionController end def send_file(event) - message = if event.payload[:x_sendfile] - header = ActionController::Streaming::X_SENDFILE_HEADER - "Sent #{header} header %s" - elsif event.payload[:stream] - "Streamed file %s" - else - "Sent file %s" - end - + message = "Sent file %s" message << " (%.1fms)" info(message % [event.payload[:path], event.duration]) end diff --git a/actionpack/lib/action_dispatch/railtie.rb b/actionpack/lib/action_dispatch/railtie.rb index 335daafc01..79e9464337 100644 --- a/actionpack/lib/action_dispatch/railtie.rb +++ b/actionpack/lib/action_dispatch/railtie.rb @@ -5,6 +5,8 @@ module ActionDispatch class Railtie < Rails::Railtie railtie_name :action_dispatch + config.action_dispatch.x_sendfile_header = "X-Sendfile" + # Prepare dispatcher callbacks and run 'prepare' callbacks initializer "action_dispatch.prepare_dispatcher" do |app| # TODO: This used to say unless defined?(Dispatcher). Find out why and fix. diff --git a/actionpack/test/controller/log_subscriber_test.rb b/actionpack/test/controller/log_subscriber_test.rb index 0659a4520e..5a3a2dd3ea 100644 --- a/actionpack/test/controller/log_subscriber_test.rb +++ b/actionpack/test/controller/log_subscriber_test.rb @@ -137,11 +137,11 @@ class ACLogSubscriberTest < ActionController::TestCase end def test_send_xfile - get :xfile_sender + assert_deprecated { get :xfile_sender } wait assert_equal 3, logs.size - assert_match /Sent X\-Sendfile header/, logs[1] + assert_match /Sent file/, logs[1] assert_match /test\/fixtures\/company\.rb/, logs[1] end diff --git a/actionpack/test/controller/send_file_test.rb b/actionpack/test/controller/send_file_test.rb index ce144cc24b..30c9a65b7c 100644 --- a/actionpack/test/controller/send_file_test.rb +++ b/actionpack/test/controller/send_file_test.rb @@ -74,18 +74,6 @@ class SendFileTest < ActionController::TestCase assert_equal "attachment", response.headers["Content-Disposition"] end - def test_x_sendfile_header - @controller.options = { :x_sendfile => true } - - response = nil - assert_nothing_raised { response = process('file') } - assert_not_nil response - - assert_equal @controller.file_path, response.headers['X-Sendfile'] - assert response.body.blank? - assert !response.etag? - end - def test_data response = nil assert_nothing_raised { response = process('data') } @@ -106,7 +94,6 @@ class SendFileTest < ActionController::TestCase # Test that send_file_headers! is setting the correct HTTP headers. def test_send_file_headers_bang options = { - :length => 1, :type => Mime::PNG, :disposition => 'disposition', :filename => 'filename' @@ -121,7 +108,6 @@ class SendFileTest < ActionController::TestCase @controller.send(:send_file_headers!, options) h = @controller.headers - assert_equal '1', h['Content-Length'] assert_equal 'image/png', @controller.content_type assert_equal 'disposition; filename="filename"', h['Content-Disposition'] assert_equal 'binary', h['Content-Transfer-Encoding'] @@ -134,7 +120,6 @@ class SendFileTest < ActionController::TestCase def test_send_file_headers_with_mime_lookup_with_symbol options = { - :length => 1, :type => :png } @@ -147,7 +132,6 @@ class SendFileTest < ActionController::TestCase def test_send_file_headers_with_bad_symbol options = { - :length => 1, :type => :this_type_is_not_registered } @@ -174,11 +158,4 @@ class SendFileTest < ActionController::TestCase assert_equal 200, @response.status end end - - def test_send_data_content_length_header - @controller.headers = {} - @controller.options = { :type => :text, :filename => 'file_with_utf8_text' } - process('multibyte_text_data') - assert_equal '29', @controller.headers['Content-Length'] - end end diff --git a/railties/lib/rails/configuration.rb b/railties/lib/rails/configuration.rb index 50675d19b8..811c3a9fd9 100644 --- a/railties/lib/rails/configuration.rb +++ b/railties/lib/rails/configuration.rb @@ -12,6 +12,7 @@ module Rails middleware.use('::Rack::Runtime') middleware.use('::Rails::Rack::Logger') middleware.use('::ActionDispatch::ShowExceptions', lambda { Rails.application.config.consider_all_requests_local }) + middleware.use('::Rack::Sendfile', lambda { Rails.application.config.action_dispatch.x_sendfile_header }) middleware.use('::ActionDispatch::Callbacks', lambda { !Rails.application.config.cache_classes }) middleware.use('::ActionDispatch::Cookies') middleware.use(lambda { ActionController::Base.session_store }, lambda { ActionController::Base.session_options }) diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb index 7ca605ec23..3e03a01ff3 100644 --- a/railties/test/application/configuration_test.rb +++ b/railties/test/application/configuration_test.rb @@ -171,5 +171,60 @@ module ApplicationTests get "/" assert $prepared end + + test "config.action_dispatch.x_sendfile_header defaults to X-Sendfile" do + require "rails" + require "action_controller/railtie" + + class MyApp < Rails::Application + config.action_controller.session = { :key => "_myapp_session", :secret => "3b7cd727ee24e8444053437c36cc66c4" } + end + + MyApp.initialize! + + class ::OmgController < ActionController::Base + def index + send_file __FILE__ + end + end + + MyApp.routes.draw do + match "/" => "omg#index" + end + + require 'rack/test' + extend Rack::Test::Methods + + get "/" + assert_equal File.expand_path(__FILE__), last_response.headers["X-Sendfile"] + end + + test "config.action_dispatch.x_sendfile_header is sent to Rack::Sendfile" do + require "rails" + require "action_controller/railtie" + + class MyApp < Rails::Application + config.action_controller.session = { :key => "_myapp_session", :secret => "3b7cd727ee24e8444053437c36cc66c4" } + config.action_dispatch.x_sendfile_header = 'X-Lighttpd-Send-File' + end + + MyApp.initialize! + + class ::OmgController < ActionController::Base + def index + send_file __FILE__ + end + end + + MyApp.routes.draw do + match "/" => "omg#index" + end + + require 'rack/test' + extend Rack::Test::Methods + + get "/" + assert_equal File.expand_path(__FILE__), last_response.headers["X-Lighttpd-Send-File"] + end end end -- cgit v1.2.3 From 24ab5665b2f12a589e96a4b742cc49c08bf0e9df Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Tue, 23 Feb 2010 17:31:17 -0800 Subject: Revert "Fix test load paths for those not using bundler" This reverts commit eec2d301d4ce9df9c71c1a5aa63053eb970b6818. This commit broke tests. You cannot have a file called "bundler" on the load path. --- actionmailer/test/abstract_unit.rb | 7 ++----- actionmailer/test/log_subscriber_test.rb | 3 --- actionpack/test/abstract_unit.rb | 8 +------- .../test/activerecord/controller_runtime_test.rb | 7 ++----- actionpack/test/controller/log_subscriber_test.rb | 3 --- actionpack/test/template/log_subscriber_test.rb | 5 +---- activemodel/Rakefile | 2 +- activemodel/test/cases/helper.rb | 7 +------ activemodel/test/cases/tests_database.rb | 4 +--- activerecord/lib/active_record.rb | 1 + activerecord/test/cases/helper.rb | 5 +---- activerecord/test/cases/log_subscriber_test.rb | 5 +---- activeresource/test/abstract_unit.rb | 6 ++---- activeresource/test/cases/log_subscriber_test.rb | 5 +---- activesupport/test/abstract_unit.rb | 5 +---- bundler.rb | 10 ---------- load_paths.rb | 21 +++++++++++++++++++++ railties/Rakefile | 2 +- railties/test/abstract_unit.rb | 7 +------ railties/test/application/configuration_test.rb | 2 +- railties/test/edge_rails.rb | 14 -------------- railties/test/isolation/abstract_unit.rb | 14 ++++++++++---- 22 files changed, 50 insertions(+), 93 deletions(-) delete mode 100644 bundler.rb create mode 100644 load_paths.rb delete mode 100644 railties/test/edge_rails.rb diff --git a/actionmailer/test/abstract_unit.rb b/actionmailer/test/abstract_unit.rb index 9d3c9086c9..f6baa4a9e8 100644 --- a/actionmailer/test/abstract_unit.rb +++ b/actionmailer/test/abstract_unit.rb @@ -1,7 +1,4 @@ -require File.expand_path('../../../bundler', __FILE__) - -lib = File.expand_path("#{File.dirname(__FILE__)}/../lib") -$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) +require File.expand_path('../../../load_paths', __FILE__) require 'test/unit' require 'action_mailer' @@ -17,7 +14,7 @@ ActionView::Template.register_template_handler :bak, lambda { |template| "Lame b FIXTURE_LOAD_PATH = File.expand_path('fixtures', File.dirname(__FILE__)) ActionMailer::Base.view_paths = FIXTURE_LOAD_PATH -class MockSMTP +class MockSMTP def self.deliveries @@deliveries end diff --git a/actionmailer/test/log_subscriber_test.rb b/actionmailer/test/log_subscriber_test.rb index 57b4a6a7f0..edd7c84d29 100644 --- a/actionmailer/test/log_subscriber_test.rb +++ b/actionmailer/test/log_subscriber_test.rb @@ -1,6 +1,3 @@ -railties_path = File.expand_path('../../../railties/lib', __FILE__) -$:.unshift(railties_path) if File.directory?(railties_path) && !$:.include?(railties_path) - require "abstract_unit" require "rails/log_subscriber/test_helper" require "action_mailer/railties/log_subscriber" diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb index 7b41db3fea..8be212c8ab 100644 --- a/actionpack/test/abstract_unit.rb +++ b/actionpack/test/abstract_unit.rb @@ -1,10 +1,4 @@ -require File.expand_path('../../../bundler', __FILE__) - -lib = File.expand_path("#{File.dirname(__FILE__)}/../lib") -$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) - -activemodel_path = File.expand_path('../../../activemodel/lib', __FILE__) -$:.unshift(activemodel_path) if File.directory?(activemodel_path) && !$:.include?(activemodel_path) +require File.expand_path('../../../load_paths', __FILE__) $:.unshift(File.dirname(__FILE__) + '/lib') $:.unshift(File.dirname(__FILE__) + '/fixtures/helpers') diff --git a/actionpack/test/activerecord/controller_runtime_test.rb b/actionpack/test/activerecord/controller_runtime_test.rb index ee5fbdb0ae..d089830857 100644 --- a/actionpack/test/activerecord/controller_runtime_test.rb +++ b/actionpack/test/activerecord/controller_runtime_test.rb @@ -1,6 +1,3 @@ -railties_path = File.expand_path('../../../../railties/lib', __FILE__) -$:.unshift(railties_path) if File.directory?(railties_path) && !$:.include?(railties_path) - require 'active_record_unit' require 'active_record/railties/controller_runtime' require 'fixtures/project' @@ -15,7 +12,7 @@ class ControllerRuntimeLogSubscriberTest < ActionController::TestCase render :inline => "<%= Project.all %>" end end - + include Rails::LogSubscriber::TestHelper tests LogSubscriberController @@ -42,4 +39,4 @@ class ControllerRuntimeLogSubscriberTest < ActionController::TestCase assert_equal 2, @logger.logged(:info).size assert_match /\(Views: [\d\.]+ms | ActiveRecord: [\d\.]+ms\)/, @logger.logged(:info)[1] end -end +end \ No newline at end of file diff --git a/actionpack/test/controller/log_subscriber_test.rb b/actionpack/test/controller/log_subscriber_test.rb index 5a3a2dd3ea..668d6ae5ea 100644 --- a/actionpack/test/controller/log_subscriber_test.rb +++ b/actionpack/test/controller/log_subscriber_test.rb @@ -1,6 +1,3 @@ -railties_path = File.expand_path('../../../../railties/lib', __FILE__) -$:.unshift(railties_path) if File.directory?(railties_path) && !$:.include?(railties_path) - require "abstract_unit" require "rails/log_subscriber/test_helper" require "action_controller/railties/log_subscriber" diff --git a/actionpack/test/template/log_subscriber_test.rb b/actionpack/test/template/log_subscriber_test.rb index f370810e81..2eb2484cf5 100644 --- a/actionpack/test/template/log_subscriber_test.rb +++ b/actionpack/test/template/log_subscriber_test.rb @@ -1,6 +1,3 @@ -railties_path = File.expand_path('../../../../railties/lib', __FILE__) -$:.unshift(railties_path) if File.directory?(railties_path) && !$:.include?(railties_path) - require "abstract_unit" require "rails/log_subscriber/test_helper" require "action_view/railties/log_subscriber" @@ -93,4 +90,4 @@ class AVLogSubscriberTest < ActiveSupport::TestCase assert_equal 1, @logger.logged(:info).size assert_match /Rendered collection/, @logger.logged(:info).last end -end +end \ No newline at end of file diff --git a/activemodel/Rakefile b/activemodel/Rakefile index 556ea2ec0b..14c02f183f 100755 --- a/activemodel/Rakefile +++ b/activemodel/Rakefile @@ -13,7 +13,7 @@ require 'rake/testtask' task :default => :test Rake::TestTask.new do |t| - t.libs << "test" + t.libs << "#{dir}/test" t.test_files = Dir.glob("#{dir}/test/cases/**/*_test.rb").sort t.warning = true end diff --git a/activemodel/test/cases/helper.rb b/activemodel/test/cases/helper.rb index 8b1ab9e196..8bcbe54651 100644 --- a/activemodel/test/cases/helper.rb +++ b/activemodel/test/cases/helper.rb @@ -1,9 +1,4 @@ -require File.expand_path('../../../../bundler', __FILE__) - -lib = File.expand_path("#{File.dirname(__FILE__)}/../../lib") -$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) - -puts $LOAD_PATH.inspect +require File.expand_path('../../../../load_paths', __FILE__) require 'config' require 'active_model' diff --git a/activemodel/test/cases/tests_database.rb b/activemodel/test/cases/tests_database.rb index 4a392f609f..8ca54d2678 100644 --- a/activemodel/test/cases/tests_database.rb +++ b/activemodel/test/cases/tests_database.rb @@ -1,8 +1,6 @@ require 'logger' -activerecord_path = File.expand_path('../../../../activerecord/lib', __FILE__) -$:.unshift(activerecord_path) if File.directory?(activerecord_path) && !$:.include?(activerecord_path) - +$:.unshift(File.dirname(__FILE__) + '/../../../activerecord/lib') require 'active_record' module ActiveModel diff --git a/activerecord/lib/active_record.rb b/activerecord/lib/active_record.rb index 99ff0a19a5..b79da4565d 100644 --- a/activerecord/lib/active_record.rb +++ b/activerecord/lib/active_record.rb @@ -21,6 +21,7 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #++ + activesupport_path = File.expand_path('../../../activesupport/lib', __FILE__) $:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path) diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb index 3254e7d800..9e8bfbbee8 100644 --- a/activerecord/test/cases/helper.rb +++ b/activerecord/test/cases/helper.rb @@ -1,7 +1,4 @@ -require File.expand_path('../../../../bundler', __FILE__) - -lib = File.expand_path("#{File.dirname(__FILE__)}/../../lib") -$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) +require File.expand_path('../../../../load_paths', __FILE__) require 'config' diff --git a/activerecord/test/cases/log_subscriber_test.rb b/activerecord/test/cases/log_subscriber_test.rb index f854499435..f0197ddf77 100644 --- a/activerecord/test/cases/log_subscriber_test.rb +++ b/activerecord/test/cases/log_subscriber_test.rb @@ -1,6 +1,3 @@ -railties_path = File.expand_path('../../../../railties/lib', __FILE__) -$:.unshift(railties_path) if File.directory?(railties_path) && !$:.include?(railties_path) - require "cases/helper" require "models/developer" require "rails/log_subscriber/test_helper" @@ -42,4 +39,4 @@ class LogSubscriberTest < ActiveSupport::TestCase assert_match /CACHE/, @logger.logged(:debug).last assert_match /SELECT .*?FROM .?developers.?/, @logger.logged(:debug).last end -end +end \ No newline at end of file diff --git a/activeresource/test/abstract_unit.rb b/activeresource/test/abstract_unit.rb index 1c6f92cba4..1af535e811 100644 --- a/activeresource/test/abstract_unit.rb +++ b/activeresource/test/abstract_unit.rb @@ -1,7 +1,4 @@ -require File.expand_path('../../../bundler', __FILE__) - -lib = File.expand_path("#{File.dirname(__FILE__)}/../lib") -$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) +require File.expand_path('../../../load_paths', __FILE__) require 'rubygems' require 'test/unit' @@ -9,6 +6,7 @@ require 'active_resource' require 'active_support' require 'active_support/test_case' +$:.unshift "#{File.dirname(__FILE__)}/../test" require 'setter_trap' require 'logger' diff --git a/activeresource/test/cases/log_subscriber_test.rb b/activeresource/test/cases/log_subscriber_test.rb index 45eb4da8a4..c25dd4ebc5 100644 --- a/activeresource/test/cases/log_subscriber_test.rb +++ b/activeresource/test/cases/log_subscriber_test.rb @@ -1,6 +1,3 @@ -railties_path = File.expand_path('../../../../railties/lib', __FILE__) -$:.unshift(railties_path) if File.directory?(railties_path) && !$:.include?(railties_path) - require "abstract_unit" require "fixtures/person" require "rails/log_subscriber/test_helper" @@ -32,4 +29,4 @@ class LogSubscriberTest < ActiveSupport::TestCase assert_equal "GET http://37s.sunrise.i:3000/people/1.xml", @logger.logged(:info)[0] assert_match /\-\-\> 200 200 106/, @logger.logged(:info)[1] end -end +end \ No newline at end of file diff --git a/activesupport/test/abstract_unit.rb b/activesupport/test/abstract_unit.rb index c4ef102bf0..33be6f65bf 100644 --- a/activesupport/test/abstract_unit.rb +++ b/activesupport/test/abstract_unit.rb @@ -1,7 +1,4 @@ -require File.expand_path('../../../bundler', __FILE__) - -lib = File.expand_path("#{File.dirname(__FILE__)}/../lib") -$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) +require File.expand_path('../../../load_paths', __FILE__) require 'test/unit' require 'mocha' diff --git a/bundler.rb b/bundler.rb deleted file mode 100644 index dcc8ed61f1..0000000000 --- a/bundler.rb +++ /dev/null @@ -1,10 +0,0 @@ -begin - require File.expand_path('../.bundle/environment', __FILE__) -rescue LoadError - begin - require 'rubygems' - require 'bundler' - Bundler.setup - rescue LoadError - end -end diff --git a/load_paths.rb b/load_paths.rb new file mode 100644 index 0000000000..d5f2ca0734 --- /dev/null +++ b/load_paths.rb @@ -0,0 +1,21 @@ +begin + require File.expand_path('../.bundle/environment', __FILE__) +rescue LoadError + begin + require 'rubygems' + require 'bundler' + Bundler.setup + rescue LoadError + %w( + actionmailer + actionpack + activemodel + activerecord + activeresource + activesupport + railties + ).each do |framework| + $:.unshift File.expand_path("../#{framework}/lib", __FILE__) + end + end +end diff --git a/railties/Rakefile b/railties/Rakefile index d4b446bc24..f32a794544 100644 --- a/railties/Rakefile +++ b/railties/Rakefile @@ -1,4 +1,4 @@ -require File.expand_path('../../bundler', __FILE__) +require File.expand_path('../../load_paths', __FILE__) require 'rake' require 'rake/testtask' diff --git a/railties/test/abstract_unit.rb b/railties/test/abstract_unit.rb index 2ac165fc49..aa66dbb9be 100644 --- a/railties/test/abstract_unit.rb +++ b/railties/test/abstract_unit.rb @@ -1,13 +1,8 @@ ORIG_ARGV = ARGV.dup -require File.expand_path("../../../bundler", __FILE__) +require File.expand_path("../../../load_paths", __FILE__) $:.unshift File.expand_path("../../builtin/rails_info", __FILE__) -lib = File.expand_path("#{File.dirname(__FILE__)}/../lib") -$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) - -require 'edge_rails' - require 'stringio' require 'test/unit' require 'fileutils' diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb index 3e03a01ff3..acf752a448 100644 --- a/railties/test/application/configuration_test.rb +++ b/railties/test/application/configuration_test.rb @@ -140,7 +140,7 @@ module ApplicationTests require "#{app_path}/config/environment" end end - + test "filter_parameters should be able to set via config.filter_parameters" do add_to_config <<-RUBY config.filter_parameters += [ :foo, 'bar', lambda { |key, value| diff --git a/railties/test/edge_rails.rb b/railties/test/edge_rails.rb deleted file mode 100644 index bd8a674738..0000000000 --- a/railties/test/edge_rails.rb +++ /dev/null @@ -1,14 +0,0 @@ -require File.expand_path('../../../bundler', __FILE__) - -%w( - actionmailer - actionpack - activemodel - activerecord - activeresource - activesupport - railties -).each do |framework| - framework_path = File.expand_path("../../../#{framework}/lib", __FILE__) - $:.unshift(framework_path) if File.directory?(framework_path) && !$:.include?(framework_path) -end diff --git a/railties/test/isolation/abstract_unit.rb b/railties/test/isolation/abstract_unit.rb index f3c1d64f7b..364dbd8e55 100644 --- a/railties/test/isolation/abstract_unit.rb +++ b/railties/test/isolation/abstract_unit.rb @@ -187,7 +187,7 @@ module TestHelpers end def boot_rails - require File.expand_path('../../edge_rails', __FILE__) + require File.expand_path('../../../../load_paths', __FILE__) end end end @@ -208,12 +208,18 @@ Module.new do end FileUtils.mkdir(tmp_path) - environment = File.expand_path('../../edge_rails', __FILE__) - require_environment = "-r #{environment}" + environment = File.expand_path('../../../../load_paths', __FILE__) + if File.exist?("#{environment}.rb") + require_environment = "-r #{environment}" + end `#{Gem.ruby} #{require_environment} #{RAILS_FRAMEWORK_ROOT}/railties/bin/rails #{tmp_path('app_template')}` File.open("#{tmp_path}/app_template/config/boot.rb", 'w') do |f| - f.puts "require '#{environment}'" + if require_environment + f.puts "Dir.chdir('#{File.dirname(environment)}') do" + f.puts " require '#{environment}'" + f.puts "end" + end f.puts "require 'rails/all'" end end -- cgit v1.2.3 From 47498a7f59d0196e9b8aa8e3569cbb4937477cef Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Tue, 23 Feb 2010 17:42:14 -0800 Subject: Woops, forgot to actually add active_support/core_ext/file/path.rb --- .gitignore | 1 + activesupport/lib/active_support/core_ext/file/path.rb | 5 +++++ railties/test/application/middleware_test.rb | 1 + 3 files changed, 7 insertions(+) create mode 100644 activesupport/lib/active_support/core_ext/file/path.rb diff --git a/.gitignore b/.gitignore index 715d0bc4bc..9480b47d15 100644 --- a/.gitignore +++ b/.gitignore @@ -19,3 +19,4 @@ railties/tmp bin .bundle pkg +*.gem \ No newline at end of file diff --git a/activesupport/lib/active_support/core_ext/file/path.rb b/activesupport/lib/active_support/core_ext/file/path.rb new file mode 100644 index 0000000000..b5feab80ae --- /dev/null +++ b/activesupport/lib/active_support/core_ext/file/path.rb @@ -0,0 +1,5 @@ +class File + unless File.allocate.respond_to?(:to_path) + alias to_path path + end +end \ No newline at end of file diff --git a/railties/test/application/middleware_test.rb b/railties/test/application/middleware_test.rb index ce9cd510a3..5e869bff1e 100644 --- a/railties/test/application/middleware_test.rb +++ b/railties/test/application/middleware_test.rb @@ -19,6 +19,7 @@ module ApplicationTests "Rack::Runtime", "Rails::Rack::Logger", "ActionDispatch::ShowExceptions", + "Rack::Sendfile", "ActionDispatch::Callbacks", "ActionDispatch::Cookies", "ActionDispatch::Session::CookieStore", -- cgit v1.2.3 From ae933a093db93c22b9facd3411afd9ef69719193 Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Tue, 23 Feb 2010 22:45:42 -0800 Subject: Fix render :file => "#{Rails.root}/public/404.html", :status => :not_found. Closes #8994 --- actionpack/lib/action_view/template/resolver.rb | 2 +- actionpack/test/controller/render_test.rb | 9 +++++++++ actionpack/test/fixtures/hello.html | 1 + 3 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 actionpack/test/fixtures/hello.html diff --git a/actionpack/lib/action_view/template/resolver.rb b/actionpack/lib/action_view/template/resolver.rb index 8acfe6cad0..20402f9d6d 100644 --- a/actionpack/lib/action_view/template/resolver.rb +++ b/actionpack/lib/action_view/template/resolver.rb @@ -20,7 +20,7 @@ module ActionView register_detail(:locale) { [I18n.locale] } register_detail(:formats) { Mime::SET.symbols } - register_detail(:handlers, :allow_nil => false) do + register_detail(:handlers) do Template::Handlers.extensions end diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb index 3cc22cc316..ecfe14b797 100644 --- a/actionpack/test/controller/render_test.rb +++ b/actionpack/test/controller/render_test.rb @@ -21,6 +21,10 @@ class TestController < ActionController::Base def hello_world end + def hello_world_file + render :file => File.expand_path("../../fixtures/hello.html", __FILE__) + end + def conditional_hello if stale?(:last_modified => Time.now.utc.beginning_of_day, :etag => [:foo, 123]) render :action => 'hello_world' @@ -751,6 +755,11 @@ class RenderTest < ActionController::TestCase assert_equal "The secret is in the sauce\n", @response.body end + def test_render_file + get :hello_world_file + assert_equal "Hello world!", @response.body + end + # :ported: def test_render_file_as_string_with_instance_variables get :render_file_as_string_with_instance_variables diff --git a/actionpack/test/fixtures/hello.html b/actionpack/test/fixtures/hello.html new file mode 100644 index 0000000000..6769dd60bd --- /dev/null +++ b/actionpack/test/fixtures/hello.html @@ -0,0 +1 @@ +Hello world! \ No newline at end of file -- cgit v1.2.3 From 60ca754b97f1254eebd61da08fb2f58f298fec31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Wed, 24 Feb 2010 15:45:33 +0100 Subject: Remove the renderer option from the hash. --- actionpack/lib/action_controller/metal/renderers.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actionpack/lib/action_controller/metal/renderers.rb b/actionpack/lib/action_controller/metal/renderers.rb index 639b508746..49d3d6b466 100644 --- a/actionpack/lib/action_controller/metal/renderers.rb +++ b/actionpack/lib/action_controller/metal/renderers.rb @@ -19,7 +19,7 @@ module ActionController <<-RUBY_EVAL if options.key?(:#{name}) _process_options(options) - return _render_option_#{name}(options[:#{name}], options) + return _render_option_#{name}(options.delete(:#{name}), options) end RUBY_EVAL end -- cgit v1.2.3 From ba57575e03647df78f8f2d4b56f1395c10061366 Mon Sep 17 00:00:00 2001 From: Carl Lerche Date: Tue, 23 Feb 2010 17:56:28 -0800 Subject: Remove references to ActionDispatch::Routing::Routes in favor of Rails.appication.routes. --- Gemfile | 2 +- railties/builtin/routes.rb | 2 +- railties/lib/rails/tasks/routes.rake | 4 ++-- railties/test/rails_info_controller_test.rb | 2 +- railties/test/railties/shared_tests.rb | 6 +++--- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Gemfile b/Gemfile index 3756e2987e..928222e2d0 100644 --- a/Gemfile +++ b/Gemfile @@ -1,5 +1,5 @@ path File.dirname(__FILE__) -source 'http://gemcutter.org' +source 'http://rubygems.org' gem "rails", "3.0.0.beta1" diff --git a/railties/builtin/routes.rb b/railties/builtin/routes.rb index b4fdb95a64..bd58034d8f 100644 --- a/railties/builtin/routes.rb +++ b/railties/builtin/routes.rb @@ -1,3 +1,3 @@ -ActionDispatch::Routing::Routes.draw do |map| +Rails.application.routes.draw do |map| match '/rails/info/properties' => "rails/info#properties" end diff --git a/railties/lib/rails/tasks/routes.rake b/railties/lib/rails/tasks/routes.rake index 1d0ac38c96..42e01d5e51 100644 --- a/railties/lib/rails/tasks/routes.rake +++ b/railties/lib/rails/tasks/routes.rake @@ -1,9 +1,9 @@ desc 'Print out all defined routes in match order, with names. Target specific controller with CONTROLLER=x.' task :routes => :environment do Rails::Application.reload_routes! - all_routes = ENV['CONTROLLER'] ? ActionDispatch::Routing::Routes.routes.select { |route| route.defaults[:controller] == ENV['CONTROLLER'] } : ActionDispatch::Routing::Routes.routes + all_routes = ENV['CONTROLLER'] ? Rails.application.routes.routes.select { |route| route.defaults[:controller] == ENV['CONTROLLER'] } : Rails.application.routes.routes routes = all_routes.collect do |route| - name = ActionDispatch::Routing::Routes.named_routes.routes.index(route).to_s + name = Rails.application.routes.named_routes.routes.index(route).to_s reqs = route.requirements.empty? ? "" : route.requirements.inspect {:name => name, :verb => route.verb.to_s, :path => route.path, :reqs => reqs} end diff --git a/railties/test/rails_info_controller_test.rb b/railties/test/rails_info_controller_test.rb index 9cfa1d6aaa..a6fc23d95b 100644 --- a/railties/test/rails_info_controller_test.rb +++ b/railties/test/rails_info_controller_test.rb @@ -14,7 +14,7 @@ class InfoControllerTest < ActionController::TestCase tests Rails::InfoController def setup - ActionDispatch::Routing::Routes.draw do |map| + Rails.application.routes.draw do |map| match ':controller/:action' end @controller.stubs(:consider_all_requests_local? => false, :local_request? => true) diff --git a/railties/test/railties/shared_tests.rb b/railties/test/railties/shared_tests.rb index c9e6e6081a..151abe21f8 100644 --- a/railties/test/railties/shared_tests.rb +++ b/railties/test/railties/shared_tests.rb @@ -133,7 +133,7 @@ module RailtiesTest end end - ActionDispatch::Routing::Routes.draw do + Rails.application.routes.draw do match "/sprokkit", :to => Sprokkit end RUBY @@ -170,7 +170,7 @@ module RailtiesTest RUBY @plugin.write "config/routes.rb", <<-RUBY - ActionDispatch::Routing::Routes.draw do |map| + Rails.application.routes.draw do |map| match 'foo', :to => 'bar#index' match 'bar', :to => 'bar#index' end @@ -261,7 +261,7 @@ YAML def test_namespaced_controllers_with_namespaced_routes @plugin.write "config/routes.rb", <<-RUBY - ActionDispatch::Routing::Routes.draw do + Rails.application.routes.draw do namespace :admin do match "index", :to => "admin/foo#index" end -- cgit v1.2.3 From 6a061187e26f0942c458a859c8e941ed092a48c1 Mon Sep 17 00:00:00 2001 From: Carl Lerche Date: Tue, 23 Feb 2010 19:53:52 -0800 Subject: Remove ActionController::Base.resources_path_names --- .../lib/action_controller/metal/compatibility.rb | 2 -- .../lib/action_dispatch/routing/deprecated_mapper.rb | 15 ++++++++------- actionpack/test/controller/resources_test.rb | 19 ++++++++++--------- 3 files changed, 18 insertions(+), 18 deletions(-) diff --git a/actionpack/lib/action_controller/metal/compatibility.rb b/actionpack/lib/action_controller/metal/compatibility.rb index 136b024d9e..2b1ada1426 100644 --- a/actionpack/lib/action_controller/metal/compatibility.rb +++ b/actionpack/lib/action_controller/metal/compatibility.rb @@ -20,8 +20,6 @@ module ActionController class << self delegate :default_charset=, :to => "ActionDispatch::Response" - delegate :resources_path_names, :to => "ActionDispatch::Routing::Routes" - delegate :resources_path_names=, :to => "ActionDispatch::Routing::Routes" end # cattr_reader :protected_instance_variables diff --git a/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb b/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb index 8ce6b2f6d5..1417a9d8c0 100644 --- a/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb +++ b/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb @@ -244,14 +244,15 @@ module ActionDispatch attr_reader :collection_methods, :member_methods, :new_methods attr_reader :path_prefix, :name_prefix, :path_segment attr_reader :plural, :singular - attr_reader :options + attr_reader :options, :defaults - def initialize(entities, options) + def initialize(entities, options, defaults) @plural ||= entities @singular ||= options[:singular] || plural.to_s.singularize @path_segment = options.delete(:as) || @plural @options = options + @defaults = defaults arrange_actions add_default_actions @@ -280,7 +281,7 @@ module ActionDispatch def new_path new_action = self.options[:path_names][:new] if self.options[:path_names] - new_action ||= ActionController::Base.resources_path_names[:new] + new_action ||= self.defaults[:path_names][:new] @new_path ||= "#{path}/#{new_action}" end @@ -370,7 +371,7 @@ module ActionDispatch end class SingletonResource < Resource #:nodoc: - def initialize(entity, options) + def initialize(entity, options, defaults) @singular = @plural = entity options[:controller] ||= @singular.to_s.pluralize super @@ -717,7 +718,7 @@ module ActionDispatch private def map_resource(entities, options = {}, &block) - resource = Resource.new(entities, options) + resource = Resource.new(entities, options, :path_names => @set.resources_path_names) with_options :controller => resource.controller do |map| map_associations(resource, options) @@ -734,7 +735,7 @@ module ActionDispatch end def map_singleton_resource(entities, options = {}, &block) - resource = SingletonResource.new(entities, options) + resource = SingletonResource.new(entities, options, :path_names => @set.resources_path_names) with_options :controller => resource.controller do |map| map_associations(resource, options) @@ -826,7 +827,7 @@ module ActionDispatch actions.each do |action| [method].flatten.each do |m| action_path = resource.options[:path_names][action] if resource.options[:path_names].is_a?(Hash) - action_path ||= ActionController::Base.resources_path_names[action] || action + action_path ||= @set.resources_path_names[action] || action map_resource_routes(map, resource, action, "#{resource.member_path}#{resource.action_separator}#{action_path}", "#{action}_#{resource.shallow_name_prefix}#{resource.singular}", m, { :force_id => true }) end diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb index 9b3f466e44..cce98ac482 100644 --- a/actionpack/test/controller/resources_test.rb +++ b/actionpack/test/controller/resources_test.rb @@ -31,10 +31,10 @@ end class ResourcesTest < ActionController::TestCase def test_should_arrange_actions - resource = ActionDispatch::Routing::DeprecatedMapper::Resource.new(:messages, + resource = ActionDispatch::Routing::DeprecatedMapper::Resource.new(:messages, { :collection => { :rss => :get, :reorder => :post, :csv => :post }, :member => { :rss => :get, :atom => :get, :upload => :post, :fix => :post }, - :new => { :preview => :get, :draft => :get }) + :new => { :preview => :get, :draft => :get }}, {}) assert_resource_methods [:rss], resource, :collection, :get assert_resource_methods [:csv, :reorder], resource, :collection, :post @@ -44,18 +44,18 @@ class ResourcesTest < ActionController::TestCase end def test_should_resource_controller_name_equal_resource_name_by_default - resource = ActionDispatch::Routing::DeprecatedMapper::Resource.new(:messages, {}) + resource = ActionDispatch::Routing::DeprecatedMapper::Resource.new(:messages, {}, {}) assert_equal 'messages', resource.controller end def test_should_resource_controller_name_equal_controller_option - resource = ActionDispatch::Routing::DeprecatedMapper::Resource.new(:messages, :controller => 'posts') + resource = ActionDispatch::Routing::DeprecatedMapper::Resource.new(:messages, {:controller => 'posts'}, {}) assert_equal 'posts', resource.controller end def test_should_all_singleton_paths_be_the_same [ :path, :nesting_path_prefix, :member_path ].each do |method| - resource = ActionDispatch::Routing::DeprecatedMapper::SingletonResource.new(:messages, :path_prefix => 'admin') + resource = ActionDispatch::Routing::DeprecatedMapper::SingletonResource.new(:messages, {:path_prefix => 'admin'}, {}) assert_equal 'admin/messages', resource.send(method) end end @@ -111,8 +111,8 @@ class ResourcesTest < ActionController::TestCase end def test_override_paths_for_default_restful_actions - resource = ActionDispatch::Routing::DeprecatedMapper::Resource.new(:messages, - :path_names => {:new => 'nuevo', :edit => 'editar'}) + resource = ActionDispatch::Routing::DeprecatedMapper::Resource.new(:messages, { + :path_names => {:new => 'nuevo', :edit => 'editar'}}, {}) assert_equal resource.new_path, "#{resource.path}/nuevo" end @@ -1162,8 +1162,9 @@ class ResourcesTest < ActionController::TestCase options[:shallow_options] = options[:options] end - new_action = ActionController::Base.resources_path_names[:new] || "new" - edit_action = ActionController::Base.resources_path_names[:edit] || "edit" + new_action = ActionDispatch::Routing::Routes.resources_path_names[:new] || "new" + edit_action = ActionDispatch::Routing::Routes.resources_path_names[:edit] || "edit" + if options[:path_names] new_action = options[:path_names][:new] if options[:path_names][:new] edit_action = options[:path_names][:edit] if options[:path_names][:edit] -- cgit v1.2.3 From a39c7505bd69e9da0a122fbb8fe20612390c57ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Wed, 24 Feb 2010 19:17:24 +0100 Subject: Cleanup render callstack and make render(:json => {}, :status => 401) work again. --- .../lib/action_controller/metal/rendering.rb | 37 ++++++++-------------- actionpack/test/controller/render_json_test.rb | 10 ++++++ 2 files changed, 24 insertions(+), 23 deletions(-) diff --git a/actionpack/lib/action_controller/metal/rendering.rb b/actionpack/lib/action_controller/metal/rendering.rb index 6518a464e2..b90c054e98 100644 --- a/actionpack/lib/action_controller/metal/rendering.rb +++ b/actionpack/lib/action_controller/metal/rendering.rb @@ -12,21 +12,13 @@ module ActionController end def render(*args) - if response_body - raise ::AbstractController::DoubleRenderError - end - + raise ::AbstractController::DoubleRenderError if response_body args << {} unless args.last.is_a?(Hash) super(*args) self.content_type ||= args.last[:_template].mime_type.to_s response_body end - def render_to_body(options) - _process_options(options) - super - end - private def _render_partial(options) @@ -35,24 +27,10 @@ module ActionController super end - def _determine_template(options) - if options.key?(:text) && options[:text].respond_to?(:to_text) - options[:text] = options[:text].to_text - end - super - end - def format_for_text formats.first end - def _process_options(options) - status, content_type, location = options.values_at(:status, :content_type, :location) - self.status = status if status - self.content_type = content_type if content_type - self.headers["Location"] = url_for(location) if location - end - def _normalize_options(action=nil, options={}, &blk) case action when NilClass @@ -64,12 +42,25 @@ module ActionController options.merge! :partial => action end + if options.key?(:text) && options[:text].respond_to?(:to_text) + options[:text] = options[:text].to_text + end + if options[:status] options[:status] = Rack::Utils.status_code(options[:status]) end options[:update] = blk if block_given? + + _process_options(options) options end + + def _process_options(options) + status, content_type, location = options.values_at(:status, :content_type, :location) + self.status = status if status + self.content_type = content_type if content_type + self.headers["Location"] = url_for(location) if location + end end end diff --git a/actionpack/test/controller/render_json_test.rb b/actionpack/test/controller/render_json_test.rb index 3938fc7061..2580ada88b 100644 --- a/actionpack/test/controller/render_json_test.rb +++ b/actionpack/test/controller/render_json_test.rb @@ -18,6 +18,10 @@ class RenderJsonTest < ActionController::TestCase render :json => ActiveSupport::JSON.encode(:hello => 'world') end + def render_json_hello_world_with_status + render :json => ActiveSupport::JSON.encode(:hello => 'world'), :status => 401 + end + def render_json_hello_world_with_callback render :json => ActiveSupport::JSON.encode(:hello => 'world'), :callback => 'alert' end @@ -58,6 +62,12 @@ class RenderJsonTest < ActionController::TestCase assert_equal 'application/json', @response.content_type end + def test_render_json_with_status + get :render_json_hello_world_with_status + assert_equal '{"hello":"world"}', @response.body + assert_equal 401, @response.status + end + def test_render_json_with_callback get :render_json_hello_world_with_callback assert_equal 'alert({"hello":"world"})', @response.body -- cgit v1.2.3 From 9d7d6cd7baf9b9e552a2ece8fca7f381417d06c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Wed, 24 Feb 2010 19:35:12 +0100 Subject: Use render instead render_to_body. --- actionmailer/lib/action_mailer/base.rb | 2 +- actionmailer/lib/action_mailer/old_api.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb index e198543c34..d647069fc7 100644 --- a/actionmailer/lib/action_mailer/base.rb +++ b/actionmailer/lib/action_mailer/base.rb @@ -605,7 +605,7 @@ module ActionMailer #:nodoc: each_template(templates_path, templates_name) do |template| responses << { - :body => render_to_body(:_template => template), + :body => render(:_template => template), :content_type => template.mime_type.to_s } end diff --git a/actionmailer/lib/action_mailer/old_api.rb b/actionmailer/lib/action_mailer/old_api.rb index 936ceb0dd6..941261a5b4 100644 --- a/actionmailer/lib/action_mailer/old_api.rb +++ b/actionmailer/lib/action_mailer/old_api.rb @@ -207,7 +207,7 @@ module ActionMailer @parts.unshift create_inline_part(@body) elsif @parts.empty? || @parts.all? { |p| p.content_disposition =~ /^attachment/ } self.class.view_paths.first.find_all(@template, {}, @mailer_name).each do |template| - @parts << create_inline_part(render_to_body(:_template => template), template.mime_type) + @parts << create_inline_part(render(:_template => template), template.mime_type) end if @parts.size > 1 -- cgit v1.2.3 From df85ab41c1ff6992dd462a0e63dac9dcdcee0348 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Wed, 24 Feb 2010 22:06:24 +0100 Subject: Renamed LocalizedCache to DetailsCache. --- actionmailer/lib/action_mailer/base.rb | 2 +- actionpack/lib/abstract_controller.rb | 2 +- .../lib/abstract_controller/details_cache.rb | 48 ++++++++++++++++++ .../lib/abstract_controller/localized_cache.rb | 49 ------------------- actionpack/lib/abstract_controller/rendering.rb | 10 ++-- .../lib/action_controller/metal/rendering.rb | 2 +- actionpack/lib/action_view/base.rb | 2 +- actionpack/test/abstract/details_cache_test.rb | 57 ++++++++++++++++++++++ actionpack/test/abstract/localized_cache_test.rb | 57 ---------------------- 9 files changed, 116 insertions(+), 113 deletions(-) create mode 100644 actionpack/lib/abstract_controller/details_cache.rb delete mode 100644 actionpack/lib/abstract_controller/localized_cache.rb create mode 100644 actionpack/test/abstract/details_cache_test.rb delete mode 100644 actionpack/test/abstract/localized_cache_test.rb diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb index d647069fc7..48d6bbc8d9 100644 --- a/actionmailer/lib/action_mailer/base.rb +++ b/actionmailer/lib/action_mailer/base.rb @@ -267,7 +267,7 @@ module ActionMailer #:nodoc: include AbstractController::Logger include AbstractController::Rendering - include AbstractController::LocalizedCache + include AbstractController::DetailsCache include AbstractController::Layouts include AbstractController::Helpers include AbstractController::Translation diff --git a/actionpack/lib/abstract_controller.rb b/actionpack/lib/abstract_controller.rb index 1e15ab090c..1944e42ef1 100644 --- a/actionpack/lib/abstract_controller.rb +++ b/actionpack/lib/abstract_controller.rb @@ -13,9 +13,9 @@ module AbstractController autoload :Callbacks autoload :Collector autoload :Compatibility + autoload :DetailsCache autoload :Helpers autoload :Layouts - autoload :LocalizedCache autoload :Logger autoload :Rendering autoload :Translation diff --git a/actionpack/lib/abstract_controller/details_cache.rb b/actionpack/lib/abstract_controller/details_cache.rb new file mode 100644 index 0000000000..5b87b41e7d --- /dev/null +++ b/actionpack/lib/abstract_controller/details_cache.rb @@ -0,0 +1,48 @@ +module AbstractController + class HashKey + @hash_keys = Hash.new {|h,k| h[k] = {} } + + def self.get(klass, details) + @hash_keys[klass][details] ||= new(klass, details) + end + + attr_reader :hash + alias_method :eql?, :equal? + + def initialize(klass, details) + @details, @hash = details, details.hash + end + + def inspect + "#" + end + end + + module DetailsCache + extend ActiveSupport::Concern + + module ClassMethods + def clear_template_caches! + ActionView::Partials::PartialRenderer::TEMPLATES.clear + template_cache.clear + super + end + + def template_cache + @template_cache ||= Hash.new {|h,k| h[k] = {} } + end + end + + def render_to_body(*args) + Thread.current[:format_locale_key] = HashKey.get(self.class, _details_defaults) + super + end + + private + + def with_template_cache(name, details) + self.class.template_cache[HashKey.get(self.class, details)][name] ||= super + end + + end +end diff --git a/actionpack/lib/abstract_controller/localized_cache.rb b/actionpack/lib/abstract_controller/localized_cache.rb deleted file mode 100644 index 5e3efa002c..0000000000 --- a/actionpack/lib/abstract_controller/localized_cache.rb +++ /dev/null @@ -1,49 +0,0 @@ -module AbstractController - class HashKey - @hash_keys = Hash.new {|h,k| h[k] = Hash.new {|sh,sk| sh[sk] = {} } } - - def self.get(klass, formats, locale) - @hash_keys[klass][formats][locale] ||= new(klass, formats, locale) - end - - attr_accessor :hash - def initialize(klass, formats, locale) - @formats, @locale = formats, locale - @hash = [formats, locale].hash - end - - alias_method :eql?, :equal? - - def inspect - "#" - end - end - - module LocalizedCache - extend ActiveSupport::Concern - - module ClassMethods - def clear_template_caches! - ActionView::Partials::PartialRenderer::TEMPLATES.clear - template_cache.clear - super - end - - def template_cache - @template_cache ||= Hash.new {|h,k| h[k] = {} } - end - end - - def render(*args) - Thread.current[:format_locale_key] = HashKey.get(self.class, formats, I18n.locale) - super - end - - private - - def with_template_cache(name) - self.class.template_cache[Thread.current[:format_locale_key]][name] ||= super - end - - end -end diff --git a/actionpack/lib/abstract_controller/rendering.rb b/actionpack/lib/abstract_controller/rendering.rb index f5c20e8013..14f51ae1bf 100644 --- a/actionpack/lib/abstract_controller/rendering.rb +++ b/actionpack/lib/abstract_controller/rendering.rb @@ -165,13 +165,17 @@ module AbstractController details = _normalize_details(options) - options[:_template] ||= with_template_cache(name) do + options[:_template] ||= with_template_cache(name, details) do find_template(name, details, options) end end + def _details_defaults + { :formats => formats, :locale => [I18n.locale] } + end + def _normalize_details(options) - details = { :formats => formats } + details = _details_defaults details[:formats] = Array(options[:format]) if options[:format] details[:locale] = Array(options[:locale]) if options[:locale] details @@ -185,7 +189,7 @@ module AbstractController view_paths.exists?(name, details, options[:_prefix], options[:_partial]) end - def with_template_cache(name) + def with_template_cache(name, details) yield end diff --git a/actionpack/lib/action_controller/metal/rendering.rb b/actionpack/lib/action_controller/metal/rendering.rb index b90c054e98..a026289ee5 100644 --- a/actionpack/lib/action_controller/metal/rendering.rb +++ b/actionpack/lib/action_controller/metal/rendering.rb @@ -4,7 +4,7 @@ module ActionController include ActionController::RackDelegation include AbstractController::Rendering - include AbstractController::LocalizedCache + include AbstractController::DetailsCache def process_action(*) self.formats = request.formats.map {|x| x.to_sym } diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb index 44e5870131..a61017ae11 100644 --- a/actionpack/lib/action_view/base.rb +++ b/actionpack/lib/action_view/base.rb @@ -196,7 +196,7 @@ module ActionView #:nodoc: # This is expensive, but we need to reset this when the format is updated, # which currently only happens Thread.current[:format_locale_key] = - AbstractController::HashKey.get(self.class, formats, I18n.locale) + AbstractController::HashKey.get(self.class, :formats => formats, :locale => [I18n.locale]) end end diff --git a/actionpack/test/abstract/details_cache_test.rb b/actionpack/test/abstract/details_cache_test.rb new file mode 100644 index 0000000000..ee746c1bb0 --- /dev/null +++ b/actionpack/test/abstract/details_cache_test.rb @@ -0,0 +1,57 @@ +require 'abstract_unit' + +module AbstractController + module Testing + + class CachedController < AbstractController::Base + include AbstractController::Rendering + include AbstractController::DetailsCache + + self.view_paths = [ActionView::FixtureResolver.new( + "default.erb" => "With Default", + "template.erb" => "With Template", + "some/file.erb" => "With File", + "template_name.erb" => "With Template Name" + )] + end + + class TestLocalizedCache < ActiveSupport::TestCase + + def setup + @controller = CachedController.new + CachedController.clear_template_caches! + end + + def test_templates_are_cached + @controller.render :template => "default.erb" + assert_equal "With Default", @controller.response_body + + cached = @controller.class.template_cache + assert_equal 1, cached.size + assert_kind_of ActionView::Template, cached.values.first["default.erb"] + end + + def test_cache_is_used + CachedController.new.render :template => "default.erb" + + @controller.expects(:find_template).never + @controller.render :template => "default.erb" + + assert_equal 1, @controller.class.template_cache.size + end + + def test_cache_changes_with_locale + CachedController.new.render :template => "default.erb" + + I18n.locale = :es + @controller.render :template => "default.erb" + + assert_equal 2, @controller.class.template_cache.size + ensure + I18n.locale = :en + end + + end + + end +end diff --git a/actionpack/test/abstract/localized_cache_test.rb b/actionpack/test/abstract/localized_cache_test.rb deleted file mode 100644 index 8b0b0fff03..0000000000 --- a/actionpack/test/abstract/localized_cache_test.rb +++ /dev/null @@ -1,57 +0,0 @@ -require 'abstract_unit' - -module AbstractController - module Testing - - class CachedController < AbstractController::Base - include AbstractController::Rendering - include AbstractController::LocalizedCache - - self.view_paths = [ActionView::FixtureResolver.new( - "default.erb" => "With Default", - "template.erb" => "With Template", - "some/file.erb" => "With File", - "template_name.erb" => "With Template Name" - )] - end - - class TestLocalizedCache < ActiveSupport::TestCase - - def setup - @controller = CachedController.new - CachedController.clear_template_caches! - end - - def test_templates_are_cached - @controller.render :template => "default.erb" - assert_equal "With Default", @controller.response_body - - cached = @controller.class.template_cache - assert_equal 1, cached.size - assert_kind_of ActionView::Template, cached.values.first["default.erb"] - end - - def test_cache_is_used - CachedController.new.render :template => "default.erb" - - @controller.expects(:find_template).never - @controller.render :template => "default.erb" - - assert_equal 1, @controller.class.template_cache.size - end - - def test_cache_changes_with_locale - CachedController.new.render :template => "default.erb" - - I18n.locale = :es - @controller.render :template => "default.erb" - - assert_equal 2, @controller.class.template_cache.size - ensure - I18n.locale = :en - end - - end - - end -end -- cgit v1.2.3 From 529d0f581276f9aad32432ef65421bc1a59b52e8 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Wed, 24 Feb 2010 22:28:40 -0200 Subject: add time_separator for minutes only if minutes aren't hidden Signed-off-by: Jeremy Kemper --- actionpack/lib/action_view/helpers/date_helper.rb | 2 +- actionpack/test/template/date_helper_test.rb | 41 +++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/actionpack/lib/action_view/helpers/date_helper.rb b/actionpack/lib/action_view/helpers/date_helper.rb index c2810b3190..89ac682c18 100644 --- a/actionpack/lib/action_view/helpers/date_helper.rb +++ b/actionpack/lib/action_view/helpers/date_helper.rb @@ -907,7 +907,7 @@ module ActionView when :hour (@options[:discard_year] && @options[:discard_day]) ? "" : @options[:datetime_separator] when :minute - @options[:time_separator] + @options[:discard_minute] ? "" : @options[:time_separator] when :second @options[:include_seconds] ? @options[:time_separator] : "" end diff --git a/actionpack/test/template/date_helper_test.rb b/actionpack/test/template/date_helper_test.rb index fb51b67185..7d3075d232 100644 --- a/actionpack/test/template/date_helper_test.rb +++ b/actionpack/test/template/date_helper_test.rb @@ -2173,6 +2173,47 @@ class DateHelperTest < ActionView::TestCase assert_dom_equal expected, datetime_select("post", "updated_at", :discard_year => true, :discard_month => true) end + def test_datetime_select_discard_hour + @post = Post.new + @post.updated_at = Time.local(2004, 6, 15, 15, 16, 35) + + expected = %{\n" + expected << %{\n" + expected << %{\n" + + assert_dom_equal expected, datetime_select("post", "updated_at", :discard_hour => true) + end + + def test_datetime_select_discard_minute + @post = Post.new + @post.updated_at = Time.local(2004, 6, 15, 15, 16, 35) + + expected = %{\n" + expected << %{\n" + expected << %{\n" + + expected << " — " + + expected << %{\n" + expected << %{\n} + + assert_dom_equal expected, datetime_select("post", "updated_at", :discard_minute => true) + end + def test_datetime_select_invalid_order @post = Post.new @post.updated_at = Time.local(2004, 6, 15, 15, 16, 35) -- cgit v1.2.3 From f76eaa4b7c44e5793bb73f10f47989cff6be6ea3 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Wed, 24 Feb 2010 22:28:40 -0200 Subject: add time_separator for minutes only if minutes aren't hidden Signed-off-by: Jeremy Kemper --- actionpack/lib/action_view/helpers/date_helper.rb | 2 +- actionpack/test/template/date_helper_test.rb | 41 +++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/actionpack/lib/action_view/helpers/date_helper.rb b/actionpack/lib/action_view/helpers/date_helper.rb index c2810b3190..89ac682c18 100644 --- a/actionpack/lib/action_view/helpers/date_helper.rb +++ b/actionpack/lib/action_view/helpers/date_helper.rb @@ -907,7 +907,7 @@ module ActionView when :hour (@options[:discard_year] && @options[:discard_day]) ? "" : @options[:datetime_separator] when :minute - @options[:time_separator] + @options[:discard_minute] ? "" : @options[:time_separator] when :second @options[:include_seconds] ? @options[:time_separator] : "" end diff --git a/actionpack/test/template/date_helper_test.rb b/actionpack/test/template/date_helper_test.rb index fb51b67185..7d3075d232 100644 --- a/actionpack/test/template/date_helper_test.rb +++ b/actionpack/test/template/date_helper_test.rb @@ -2173,6 +2173,47 @@ class DateHelperTest < ActionView::TestCase assert_dom_equal expected, datetime_select("post", "updated_at", :discard_year => true, :discard_month => true) end + def test_datetime_select_discard_hour + @post = Post.new + @post.updated_at = Time.local(2004, 6, 15, 15, 16, 35) + + expected = %{\n" + expected << %{\n" + expected << %{\n" + + assert_dom_equal expected, datetime_select("post", "updated_at", :discard_hour => true) + end + + def test_datetime_select_discard_minute + @post = Post.new + @post.updated_at = Time.local(2004, 6, 15, 15, 16, 35) + + expected = %{\n" + expected << %{\n" + expected << %{\n" + + expected << " — " + + expected << %{\n" + expected << %{\n} + + assert_dom_equal expected, datetime_select("post", "updated_at", :discard_minute => true) + end + def test_datetime_select_invalid_order @post = Post.new @post.updated_at = Time.local(2004, 6, 15, 15, 16, 35) -- cgit v1.2.3 From bf0f14579aa793f2ab29ec092c517d04e702dbe3 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Thu, 25 Feb 2010 08:32:37 -0800 Subject: let the rails command recurse upwards looking for script/rails, and exec ruby on it for better portability [Xavier Noria] (Closes #4008) --- railties/bin/rails | 37 ++++++++++++++++++++++++++++--------- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/railties/bin/rails b/railties/bin/rails index 72c47b533f..173f122445 100755 --- a/railties/bin/rails +++ b/railties/bin/rails @@ -1,11 +1,30 @@ -if File.exists?(Dir.getwd + '/script/rails') - exec(Dir.getwd + '/script/rails', *ARGV) -else - railties_path = File.expand_path('../../lib', __FILE__) - $:.unshift(railties_path) if File.directory?(railties_path) && !$:.include?(railties_path) +require 'rbconfig' - require 'rails/ruby_version_check' - Signal.trap("INT") { puts; exit } +module Rails + module ScriptRailsLoader + RUBY = File.join(*RbConfig::CONFIG.values_at("bindir", "ruby_install_name")) + RbConfig::CONFIG["EXEEXT"] + SCRIPT_RAILS = File.join('script', 'rails') - require 'rails/commands/application' -end \ No newline at end of file + def self.exec_script_rails! + cwd = Dir.pwd + exec RUBY, SCRIPT_RAILS, *ARGV if File.exists?(SCRIPT_RAILS) + Dir.chdir("..") do + # Recurse in a chdir block: if the search fails we want to be sure + # the application is generated in the original working directory. + exec_script_rails! unless cwd == Dir.pwd + end + rescue SystemCallError + # could not chdir, no problem just return + end + end +end + +Rails::ScriptRailsLoader.exec_script_rails! + +railties_path = File.expand_path('../../lib', __FILE__) +$:.unshift(railties_path) if File.directory?(railties_path) && !$:.include?(railties_path) + +require 'rails/ruby_version_check' +Signal.trap("INT") { puts; exit } + +require 'rails/commands/application' -- cgit v1.2.3 From 6b12d74026808a3014f1dff34481006a96e0f18f Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Thu, 25 Feb 2010 09:28:18 -0800 Subject: Commented metaprogramming turned out to be noisier not clearer --- activesupport/lib/active_support/core_ext/proc.rb | 6 +++--- .../lib/active_support/deprecation/method_wrappers.rb | 18 +++++++++--------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/activesupport/lib/active_support/core_ext/proc.rb b/activesupport/lib/active_support/core_ext/proc.rb index d50076a01e..71b413a88a 100644 --- a/activesupport/lib/active_support/core_ext/proc.rb +++ b/activesupport/lib/active_support/core_ext/proc.rb @@ -5,9 +5,9 @@ class Proc #:nodoc: block, time = self, Time.now object.class_eval do method_name = "__bind_#{time.to_i}_#{time.usec}" - define_method(method_name, &block) # define_method("__bind_1230458026_720454", &block) - method = instance_method(method_name) # method = instance_method("__bind_1230458026_720454") - remove_method(method_name) # remove_method("__bind_1230458026_720454") + define_method(method_name, &block) + method = instance_method(method_name) + remove_method(method_name) method end.bind(object) end diff --git a/activesupport/lib/active_support/deprecation/method_wrappers.rb b/activesupport/lib/active_support/deprecation/method_wrappers.rb index cec8024b17..d0d8b577b3 100644 --- a/activesupport/lib/active_support/deprecation/method_wrappers.rb +++ b/activesupport/lib/active_support/deprecation/method_wrappers.rb @@ -12,15 +12,15 @@ module ActiveSupport method_names.each do |method_name| target_module.alias_method_chain(method_name, :deprecation) do |target, punctuation| target_module.module_eval(<<-end_eval, __FILE__, __LINE__ + 1) - def #{target}_with_deprecation#{punctuation}(*args, &block) # def generate_secret_with_deprecation(*args, &block) - ::ActiveSupport::Deprecation.warn( # ::ActiveSupport::Deprecation.warn( - ::ActiveSupport::Deprecation.deprecated_method_warning( # ::ActiveSupport::Deprecation.deprecated_method_warning( - :#{method_name}, # :generate_secret, - #{options[method_name].inspect}), # "You should use ActiveSupport::SecureRandom.hex(64)"), - caller # caller - ) # ) - send(:#{target}_without_deprecation#{punctuation}, *args, &block) # send(:generate_secret_without_deprecation, *args, &block) - end # end + def #{target}_with_deprecation#{punctuation}(*args, &block) + ::ActiveSupport::Deprecation.warn( + ::ActiveSupport::Deprecation.deprecated_method_warning( + :#{method_name}, + #{options[method_name].inspect}), + caller + ) + send(:#{target}_without_deprecation#{punctuation}, *args, &block) + end end_eval end end -- cgit v1.2.3 From f7b0a857e97304a5daeb47313759b9bf0d7e2fc9 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Thu, 25 Feb 2010 09:32:29 -0800 Subject: Use Object#singleton_class instead of #metaclass. Prefer Ruby's choice. --- actionpack/lib/action_dispatch/testing/integration.rb | 4 ++-- activemodel/lib/active_model/attribute_methods.rb | 2 +- activerecord/lib/active_record/base.rb | 2 +- activerecord/lib/active_record/migration.rb | 4 ++-- activerecord/lib/active_record/named_scope.rb | 4 ++-- activesupport/CHANGELOG | 2 ++ activesupport/lib/active_support/callbacks.rb | 4 ++-- .../lib/active_support/core_ext/class/attribute.rb | 11 ++++++----- .../core_ext/class/delegating_attributes.rb | 12 ++++++------ activesupport/lib/active_support/core_ext/object.rb | 1 + .../lib/active_support/core_ext/object/metaclass.rb | 11 ++++++----- activesupport/lib/active_support/memoizable.rb | 2 +- activesupport/test/core_ext/object_and_class_ext_test.rb | 16 ++++++++++------ railties/lib/rails/generators.rb | 4 ++-- 14 files changed, 44 insertions(+), 35 deletions(-) diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index f93059759b..14c7ff642b 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -1,6 +1,6 @@ require 'stringio' require 'uri' -require 'active_support/core_ext/object/metaclass' +require 'active_support/core_ext/object/singleton_class' require 'rack/test' module ActionDispatch @@ -187,7 +187,7 @@ module ActionDispatch unless defined? @named_routes_configured # install the named routes in this session instance. - klass = metaclass + klass = singleton_class ActionDispatch::Routing::Routes.install_helpers(klass) # the helpers are made protected by default--we make them public for diff --git a/activemodel/lib/active_model/attribute_methods.rb b/activemodel/lib/active_model/attribute_methods.rb index 200a6afbf0..143eb87f54 100644 --- a/activemodel/lib/active_model/attribute_methods.rb +++ b/activemodel/lib/active_model/attribute_methods.rb @@ -86,7 +86,7 @@ module ActiveModel # AttributePerson.inheritance_column # # => 'address_id' def define_attr_method(name, value=nil, &block) - sing = metaclass + sing = singleton_class sing.send :alias_method, "original_#{name}", name if block_given? sing.send :define_method, name, &block diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index ef5a7d5787..83f0b58e8a 100755 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -11,7 +11,7 @@ require 'active_support/core_ext/hash/deep_merge' require 'active_support/core_ext/hash/indifferent_access' require 'active_support/core_ext/hash/slice' require 'active_support/core_ext/string/behavior' -require 'active_support/core_ext/object/metaclass' +require 'active_support/core_ext/object/singleton_class' require 'active_support/core_ext/module/delegation' module ActiveRecord #:nodoc: diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb index 068d2a25b2..fd5ffc6d77 100644 --- a/activerecord/lib/active_record/migration.rb +++ b/activerecord/lib/active_record/migration.rb @@ -1,4 +1,4 @@ -require 'active_support/core_ext/object/metaclass' +require 'active_support/core_ext/object/singleton_class' module ActiveRecord # Exception that can be raised to stop migrations from going backwards. @@ -303,7 +303,7 @@ module ActiveRecord case sym when :up, :down - metaclass.send(:alias_method_chain, sym, "benchmarks") + singleton_class.send(:alias_method_chain, sym, "benchmarks") end ensure @ignore_new_methods = false diff --git a/activerecord/lib/active_record/named_scope.rb b/activerecord/lib/active_record/named_scope.rb index ff6c041ef4..f1f56850ae 100644 --- a/activerecord/lib/active_record/named_scope.rb +++ b/activerecord/lib/active_record/named_scope.rb @@ -1,6 +1,6 @@ require 'active_support/core_ext/array' require 'active_support/core_ext/hash/except' -require 'active_support/core_ext/object/metaclass' +require 'active_support/core_ext/object/singleton_class' module ActiveRecord module NamedScope @@ -112,7 +112,7 @@ module ActiveRecord options.call(*args) end, &block) end - metaclass.instance_eval do + singleton_class.instance_eval do define_method name do |*args| scopes[name].call(self, *args) end diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG index 8ec903e376..56c81cf63b 100644 --- a/activesupport/CHANGELOG +++ b/activesupport/CHANGELOG @@ -1,5 +1,7 @@ *Rails 3.0 (pending)* +* Use Object#singleton_class instead of #metaclass. Prefer Ruby's choice. [Jeremy Kemper] + * JSON backend for YAJL. Preferred if available. #2666 [Brian Lopez] diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb index 6727eda811..b230bb8a40 100644 --- a/activesupport/lib/active_support/callbacks.rb +++ b/activesupport/lib/active_support/callbacks.rb @@ -1,7 +1,7 @@ require 'active_support/core_ext/array/wrap' require 'active_support/core_ext/class/inheritable_attributes' require 'active_support/core_ext/kernel/reporting' -require 'active_support/core_ext/object/metaclass' +require 'active_support/core_ext/object/singleton_class' module ActiveSupport # Callbacks are hooks into the lifecycle of an object that allow you to trigger logic @@ -312,7 +312,7 @@ module ActiveSupport def _normalize_legacy_filter(kind, filter) if !filter.respond_to?(kind) && filter.respond_to?(:filter) - filter.metaclass.class_eval( + filter.singleton_class.class_eval( "def #{kind}(context, &block) filter(context, &block) end", __FILE__, __LINE__ - 1) elsif filter.respond_to?(:before) && filter.respond_to?(:after) && kind == :around diff --git a/activesupport/lib/active_support/core_ext/class/attribute.rb b/activesupport/lib/active_support/core_ext/class/attribute.rb index d74219cb93..1bd39a9349 100644 --- a/activesupport/lib/active_support/core_ext/class/attribute.rb +++ b/activesupport/lib/active_support/core_ext/class/attribute.rb @@ -1,4 +1,4 @@ -require 'active_support/core_ext/object/metaclass' +require 'active_support/core_ext/object/singleton_class' require 'active_support/core_ext/module/delegation' class Class @@ -25,11 +25,12 @@ class Class # # Subclass.setting? # => false def class_attribute(*attrs) + s = singleton_class attrs.each do |attr| - metaclass.send(:define_method, attr) { } - metaclass.send(:define_method, "#{attr}?") { !!send(attr) } - metaclass.send(:define_method, "#{attr}=") do |value| - metaclass.send(:define_method, attr) { value } + s.send(:define_method, attr) { } + s.send(:define_method, "#{attr}?") { !!send(attr) } + s.send(:define_method, "#{attr}=") do |value| + singleton_class.send(:define_method, attr) { value } end end end diff --git a/activesupport/lib/active_support/core_ext/class/delegating_attributes.rb b/activesupport/lib/active_support/core_ext/class/delegating_attributes.rb index 19382abb76..b5785bdcd3 100644 --- a/activesupport/lib/active_support/core_ext/class/delegating_attributes.rb +++ b/activesupport/lib/active_support/core_ext/class/delegating_attributes.rb @@ -1,6 +1,6 @@ require 'active_support/core_ext/object/blank' require 'active_support/core_ext/array/extract_options' -require 'active_support/core_ext/object/metaclass' +require 'active_support/core_ext/object/singleton_class' class Class def superclass_delegating_accessor(name, options = {}) @@ -11,9 +11,9 @@ class Class # Generate the public methods name, name=, and name? # These methods dispatch to the private _name, and _name= methods, making them # overridable - metaclass.send(:define_method, name) { send("_#{name}") } - metaclass.send(:define_method, "#{name}?") { !!send("_#{name}") } - metaclass.send(:define_method, "#{name}=") { |value| send("_#{name}=", value) } + singleton_class.send(:define_method, name) { send("_#{name}") } + singleton_class.send(:define_method, "#{name}?") { !!send("_#{name}") } + singleton_class.send(:define_method, "#{name}=") { |value| send("_#{name}=", value) } # If an instance_reader is needed, generate methods for name and name= on the # class itself, so instances will be able to see them @@ -27,12 +27,12 @@ private # inheritance behavior, without having to store the object in an instance # variable and look up the superclass chain manually. def _stash_object_in_method(object, method, instance_reader = true) - metaclass.send(:define_method, method) { object } + singleton_class.send(:define_method, method) { object } define_method(method) { object } if instance_reader end def _superclass_delegating_accessor(name, options = {}) - metaclass.send(:define_method, "#{name}=") do |value| + singleton_class.send(:define_method, "#{name}=") do |value| _stash_object_in_method(value, name, options[:instance_reader] != false) end self.send("#{name}=", nil) diff --git a/activesupport/lib/active_support/core_ext/object.rb b/activesupport/lib/active_support/core_ext/object.rb index db2dac1472..9dc6ca66a4 100644 --- a/activesupport/lib/active_support/core_ext/object.rb +++ b/activesupport/lib/active_support/core_ext/object.rb @@ -6,6 +6,7 @@ require 'active_support/core_ext/object/try' require 'active_support/core_ext/object/conversions' require 'active_support/core_ext/object/instance_variables' require 'active_support/core_ext/object/metaclass' +require 'active_support/core_ext/object/singleton_class' require 'active_support/core_ext/object/misc' require 'active_support/core_ext/object/extending' diff --git a/activesupport/lib/active_support/core_ext/object/metaclass.rb b/activesupport/lib/active_support/core_ext/object/metaclass.rb index 93fb0ad594..4b36a243c9 100644 --- a/activesupport/lib/active_support/core_ext/object/metaclass.rb +++ b/activesupport/lib/active_support/core_ext/object/metaclass.rb @@ -1,13 +1,14 @@ +require 'active_support/deprecation' + class Object - # Get object's meta (ghost, eigenclass, singleton) class + # Get object's meta (ghost, eigenclass, singleton) class. + # + # Deprecated in favor of Object#singleton_class. def metaclass class << self self end end - # If class_eval is called on an object, add those methods to its metaclass - def class_eval(*args, &block) - metaclass.class_eval(*args, &block) - end + deprecate :metaclass => :singleton_class end diff --git a/activesupport/lib/active_support/memoizable.rb b/activesupport/lib/active_support/memoizable.rb index f810f53029..ca1cfedae3 100644 --- a/activesupport/lib/active_support/memoizable.rb +++ b/activesupport/lib/active_support/memoizable.rb @@ -1,4 +1,4 @@ -require 'active_support/core_ext/object/metaclass' +require 'active_support/core_ext/object/singleton_class' require 'active_support/core_ext/module/aliasing' module ActiveSupport diff --git a/activesupport/test/core_ext/object_and_class_ext_test.rb b/activesupport/test/core_ext/object_and_class_ext_test.rb index f31e7774e9..00c59d84b8 100644 --- a/activesupport/test/core_ext/object_and_class_ext_test.rb +++ b/activesupport/test/core_ext/object_and_class_ext_test.rb @@ -89,7 +89,7 @@ class ClassExtTest < Test::Unit::TestCase end end -class ObjectTests < Test::Unit::TestCase +class ObjectTests < ActiveSupport::TestCase class DuckTime def acts_like_time? true @@ -119,12 +119,16 @@ class ObjectTests < Test::Unit::TestCase assert !duck.acts_like?(:date) end - def test_metaclass - string = "Hello" - string.metaclass.instance_eval do - define_method(:foo) { "bar" } + def test_singleton_class + o = Object.new + assert_equal class << o; self end, o.singleton_class + end + + def test_metaclass_deprecated + o = Object.new + assert_deprecated /use singleton_class instead/ do + assert_equal o.singleton_class, o.metaclass end - assert_equal "bar", string.foo end end diff --git a/railties/lib/rails/generators.rb b/railties/lib/rails/generators.rb index c01018aab2..f24dc620de 100644 --- a/railties/lib/rails/generators.rb +++ b/railties/lib/rails/generators.rb @@ -3,7 +3,7 @@ $:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.inc require 'active_support' require 'active_support/core_ext/object/blank' -require 'active_support/core_ext/object/metaclass' +require 'active_support/core_ext/object/singleton_class' require 'active_support/core_ext/array/extract_options' require 'active_support/core_ext/hash/deep_merge' require 'active_support/core_ext/module/attribute_accessors' @@ -291,4 +291,4 @@ end # If the application was already defined, configure generators, # otherwise you have to configure it by hand. -Rails::Generators.configure! if Rails.respond_to?(:application) && Rails.application \ No newline at end of file +Rails::Generators.configure! if Rails.respond_to?(:application) && Rails.application -- cgit v1.2.3 From 45ceacd6ded0d3fc4c567c17cc45c6979c34cc2a Mon Sep 17 00:00:00 2001 From: "Thomas R. Koll" Date: Fri, 12 Feb 2010 11:06:30 +0100 Subject: load_path is expecting a String in the application.rb generator Signed-off-by: Jeremy Kemper --- railties/lib/generators/rails/app/templates/config/application.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/railties/lib/generators/rails/app/templates/config/application.rb b/railties/lib/generators/rails/app/templates/config/application.rb index 7c555c2542..dc20ffb2fa 100644 --- a/railties/lib/generators/rails/app/templates/config/application.rb +++ b/railties/lib/generators/rails/app/templates/config/application.rb @@ -35,7 +35,7 @@ module <%= app_const_base %> # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. - # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')] + # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Configure generators values. Many other options are available, be sure to check the documentation. -- cgit v1.2.3 From c7f9e8c06cb60aef33cf0a03cb3c1b927eb8c1cf Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Thu, 25 Feb 2010 10:46:29 -0800 Subject: Fix test on 1.8.8. Broken by inherited hook now running before Class.new block. --- railties/test/generators_test.rb | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb index 33cc27bd84..844497c8e3 100644 --- a/railties/test/generators_test.rb +++ b/railties/test/generators_test.rb @@ -147,12 +147,13 @@ class GeneratorsTest < Rails::Generators::TestCase def test_developer_options_are_overwriten_by_user_options Rails::Generators.options[:new_generator] = { :generate => false } - klass = Class.new(Rails::Generators::Base) do - def self.name() 'NewGenerator' end - class_option :generate, :default => true - end + self.class.class_eval <<-end_eval + class NewGenerator < Rails::Generators::Base + class_option :generate, :default => true + end + end_eval - assert_equal false, klass.class_options[:generate].default + assert_equal false, NewGenerator.class_options[:generate].default ensure Rails::Generators.subclasses.delete(klass) end -- cgit v1.2.3 From 0b87d114bde73cddb9401d061acc1f2f4b3e1dfc Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Thu, 25 Feb 2010 10:57:29 -0800 Subject: Missed singleton_class --- .../lib/active_support/core_ext/object/singleton_class.rb | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 activesupport/lib/active_support/core_ext/object/singleton_class.rb diff --git a/activesupport/lib/active_support/core_ext/object/singleton_class.rb b/activesupport/lib/active_support/core_ext/object/singleton_class.rb new file mode 100644 index 0000000000..8dee54e71b --- /dev/null +++ b/activesupport/lib/active_support/core_ext/object/singleton_class.rb @@ -0,0 +1,13 @@ +class Object + # Returns the object's singleton class. + def singleton_class + class << self + self + end + end unless respond_to?(:singleton_class) + + # class_eval on an object acts like singleton_class_eval. + def class_eval(*args, &block) + singleton_class.class_eval(*args, &block) + end +end -- cgit v1.2.3 From ffc45f3e7128f0ef1efca0f39d4717447c15f5b8 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Thu, 25 Feb 2010 11:01:15 -0800 Subject: Fix dangling klass reference --- railties/test/generators_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb index 844497c8e3..07bc92c55c 100644 --- a/railties/test/generators_test.rb +++ b/railties/test/generators_test.rb @@ -155,7 +155,7 @@ class GeneratorsTest < Rails::Generators::TestCase assert_equal false, NewGenerator.class_options[:generate].default ensure - Rails::Generators.subclasses.delete(klass) + Rails::Generators.subclasses.delete(NewGenerator) end def test_load_generators_from_railties -- cgit v1.2.3 From 763f32ab47b96289a4d7b7107411a83164bf69de Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Thu, 25 Feb 2010 11:12:27 -0800 Subject: metaclass deprecated in 2.3.6 --- activesupport/lib/active_support/core_ext/object.rb | 1 - .../lib/active_support/core_ext/object/metaclass.rb | 14 -------------- activesupport/test/core_ext/object_and_class_ext_test.rb | 7 ------- 3 files changed, 22 deletions(-) delete mode 100644 activesupport/lib/active_support/core_ext/object/metaclass.rb diff --git a/activesupport/lib/active_support/core_ext/object.rb b/activesupport/lib/active_support/core_ext/object.rb index 9dc6ca66a4..4f86d9d605 100644 --- a/activesupport/lib/active_support/core_ext/object.rb +++ b/activesupport/lib/active_support/core_ext/object.rb @@ -5,7 +5,6 @@ require 'active_support/core_ext/object/try' require 'active_support/core_ext/object/conversions' require 'active_support/core_ext/object/instance_variables' -require 'active_support/core_ext/object/metaclass' require 'active_support/core_ext/object/singleton_class' require 'active_support/core_ext/object/misc' require 'active_support/core_ext/object/extending' diff --git a/activesupport/lib/active_support/core_ext/object/metaclass.rb b/activesupport/lib/active_support/core_ext/object/metaclass.rb deleted file mode 100644 index 4b36a243c9..0000000000 --- a/activesupport/lib/active_support/core_ext/object/metaclass.rb +++ /dev/null @@ -1,14 +0,0 @@ -require 'active_support/deprecation' - -class Object - # Get object's meta (ghost, eigenclass, singleton) class. - # - # Deprecated in favor of Object#singleton_class. - def metaclass - class << self - self - end - end - - deprecate :metaclass => :singleton_class -end diff --git a/activesupport/test/core_ext/object_and_class_ext_test.rb b/activesupport/test/core_ext/object_and_class_ext_test.rb index 00c59d84b8..437bb78a4e 100644 --- a/activesupport/test/core_ext/object_and_class_ext_test.rb +++ b/activesupport/test/core_ext/object_and_class_ext_test.rb @@ -123,13 +123,6 @@ class ObjectTests < ActiveSupport::TestCase o = Object.new assert_equal class << o; self end, o.singleton_class end - - def test_metaclass_deprecated - o = Object.new - assert_deprecated /use singleton_class instead/ do - assert_equal o.singleton_class, o.metaclass - end - end end class ObjectInstanceVariableTest < Test::Unit::TestCase -- cgit v1.2.3 From 2ba604950603302fd78bcefecfe043efaa8169dc Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Thu, 25 Feb 2010 13:07:48 -0800 Subject: Accept array of attributes as arg also, like 2.3 --- activemodel/lib/active_model/validations.rb | 2 +- .../cases/validations/presence_validation_test.rb | 26 +++++++++++++--------- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/activemodel/lib/active_model/validations.rb b/activemodel/lib/active_model/validations.rb index 7f6748a660..ba8648f8c9 100644 --- a/activemodel/lib/active_model/validations.rb +++ b/activemodel/lib/active_model/validations.rb @@ -137,7 +137,7 @@ module ActiveModel def _merge_attributes(attr_names) options = attr_names.extract_options! - options.merge(:attributes => attr_names) + options.merge(:attributes => attr_names.flatten) end end diff --git a/activemodel/test/cases/validations/presence_validation_test.rb b/activemodel/test/cases/validations/presence_validation_test.rb index 8b9795a90c..c4d787dadb 100644 --- a/activemodel/test/cases/validations/presence_validation_test.rb +++ b/activemodel/test/cases/validations/presence_validation_test.rb @@ -10,6 +10,12 @@ require 'models/custom_reader' class PresenceValidationTest < ActiveModel::TestCase include ActiveModel::TestsDatabase + teardown do + Topic.reset_callbacks(:validate) + Person.reset_callbacks(:validate) + CustomReader.reset_callbacks(:validate) + end + def test_validate_presences Topic.validates_presence_of(:title, :content) @@ -27,17 +33,21 @@ class PresenceValidationTest < ActiveModel::TestCase t.content = "like stuff" assert t.save - ensure - Topic.reset_callbacks(:validate) + end + + test 'accepts array arguments' do + Topic.validates_presence_of %w(title content) + t = Topic.new + assert !t.valid? + assert_equal ["can't be blank"], t.errors[:title] + assert_equal ["can't be blank"], t.errors[:content] end def test_validates_acceptance_of_with_custom_error_using_quotes - Person.validates_presence_of :karma, :message=> "This string contains 'single' and \"double\" quotes" + Person.validates_presence_of :karma, :message => "This string contains 'single' and \"double\" quotes" p = Person.new assert !p.valid? assert_equal "This string contains 'single' and \"double\" quotes", p.errors[:karma].last - ensure - Person.reset_callbacks(:validate) end def test_validates_presence_of_for_ruby_class @@ -50,10 +60,8 @@ class PresenceValidationTest < ActiveModel::TestCase p.karma = "Cold" assert p.valid? - ensure - Person.reset_callbacks(:validate) end - + def test_validates_presence_of_for_ruby_class_with_custom_reader CustomReader.validates_presence_of :karma @@ -64,7 +72,5 @@ class PresenceValidationTest < ActiveModel::TestCase p[:karma] = "Cold" assert p.valid? - ensure - CustomReader.reset_callbacks(:validate) end end -- cgit v1.2.3 From 66d537852b6c0357f391069c6d3b0b62c0722283 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Thu, 25 Feb 2010 15:06:11 -0800 Subject: Bump i18n for new public I18n.normalize_keys --- actionpack/lib/action_view/helpers/translation_helper.rb | 2 +- activesupport/activesupport.gemspec | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/actionpack/lib/action_view/helpers/translation_helper.rb b/actionpack/lib/action_view/helpers/translation_helper.rb index 7d954b3a2f..8a89ee58a0 100644 --- a/actionpack/lib/action_view/helpers/translation_helper.rb +++ b/actionpack/lib/action_view/helpers/translation_helper.rb @@ -15,7 +15,7 @@ module ActionView translation = I18n.translate(scope_key_by_partial(key), options) translation.is_a?(Array) ? translation.map { |entry| entry.html_safe } : translation.html_safe rescue I18n::MissingTranslationData => e - keys = I18n.send(:normalize_translation_keys, e.locale, e.key, e.options[:scope]) + keys = I18n.normalize_keys(e.locale, e.key, e.options[:scope]) content_tag('span', keys.join(', '), :class => 'translation_missing') end alias :t :translate diff --git a/activesupport/activesupport.gemspec b/activesupport/activesupport.gemspec index d0557230aa..90d68a215a 100644 --- a/activesupport/activesupport.gemspec +++ b/activesupport/activesupport.gemspec @@ -16,7 +16,7 @@ Gem::Specification.new do |s| s.has_rdoc = true - s.add_dependency('i18n', '~> 0.3.0') + s.add_dependency('i18n', '~> 0.3.4') s.add_dependency('tzinfo', '~> 0.3.16') s.add_dependency('builder', '~> 2.1.2') s.add_dependency('memcache-client', '~> 1.7.5') -- cgit v1.2.3 From e2795383cfaafe5c1e38f47d520419662433ffca Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Thu, 25 Feb 2010 16:32:24 -0800 Subject: Update plugin tasks dirs deprecation warning --- railties/lib/rails/plugin.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/railties/lib/rails/plugin.rb b/railties/lib/rails/plugin.rb index 882f2dc28e..c1a2c5c87b 100644 --- a/railties/lib/rails/plugin.rb +++ b/railties/lib/rails/plugin.rb @@ -1,4 +1,5 @@ require 'rails/engine' +require 'active_support/core_ext/array/conversions' module Rails class Plugin < Engine @@ -28,8 +29,7 @@ module Rails extra_tasks = Dir["#{root}/{tasks,rails/tasks}/**/*.rake"] unless extra_tasks.empty? - ActiveSupport::Deprecation.warn "Having rake tasks in PLUGIN_PATH/tasks or " << - "PLUGIN_PATH/rails/tasks is deprecated. Use PLUGIN_PATH/lib/tasks instead" + ActiveSupport::Deprecation.warn "Rake tasks in #{extra_tasks.to_sentence} are deprecated. Use lib/tasks instead." extra_tasks.sort.each { |ext| load(ext) } end end -- cgit v1.2.3 From 6e78fdbef06e0fc7135dac5bc71cdcb4b81911c6 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Thu, 25 Feb 2010 16:45:59 -0800 Subject: Remove doubled period --- railties/lib/rails/plugin.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/railties/lib/rails/plugin.rb b/railties/lib/rails/plugin.rb index c1a2c5c87b..0bc3991b33 100644 --- a/railties/lib/rails/plugin.rb +++ b/railties/lib/rails/plugin.rb @@ -29,7 +29,7 @@ module Rails extra_tasks = Dir["#{root}/{tasks,rails/tasks}/**/*.rake"] unless extra_tasks.empty? - ActiveSupport::Deprecation.warn "Rake tasks in #{extra_tasks.to_sentence} are deprecated. Use lib/tasks instead." + ActiveSupport::Deprecation.warn "Rake tasks in #{extra_tasks.to_sentence} are deprecated. Use lib/tasks instead" extra_tasks.sort.each { |ext| load(ext) } end end -- cgit v1.2.3 From 1ff7e566fdd09675877753063487b0589be53aac Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Thu, 25 Feb 2010 16:46:13 -0800 Subject: Bump to Bundler 0.9.8. Remark on RubyGems 1.3.6 fix. --- ci/ci_build.rb | 2 +- rails.gemspec | 2 +- rails3b.gemspec | 5 ++--- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/ci/ci_build.rb b/ci/ci_build.rb index d0895dc35d..e9fb91a6fd 100755 --- a/ci/ci_build.rb +++ b/ci/ci_build.rb @@ -19,7 +19,7 @@ puts "[CruiseControl] Rails build" build_results = {} # Install required version of bundler. -bundler_install_cmd = "gem install bundler -v 0.9.6 --no-ri --no-rdoc" +bundler_install_cmd = "gem install bundler -v 0.9.8 --no-ri --no-rdoc" puts "Running command: #{bundler_install_cmd}" build_results[:install_bundler] = system bundler_install_cmd diff --git a/rails.gemspec b/rails.gemspec index 1460dd5688..4ebbd8061f 100644 --- a/rails.gemspec +++ b/rails.gemspec @@ -20,5 +20,5 @@ Gem::Specification.new do |s| s.add_dependency('activeresource', '= 3.0.0.beta1') s.add_dependency('actionmailer', '= 3.0.0.beta1') s.add_dependency('railties', '= 3.0.0.beta1') - s.add_dependency('bundler', '>= 0.9.3') + s.add_dependency('bundler', '>= 0.9.8') end diff --git a/rails3b.gemspec b/rails3b.gemspec index d67d20b884..613a248ef7 100644 --- a/rails3b.gemspec +++ b/rails3b.gemspec @@ -2,8 +2,7 @@ Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'rails3b' s.version = '3.0.1' - s.summary = 'Just the Rails 3 beta dependencies. Works around prerelease RubyGems bug.' - s.description = 'My kingdom for working dependencies.' + s.summary = 'Just the Rails 3 beta dependencies. Works around prerelease RubyGems bug in versions before 1.3.6.' s.required_ruby_version = '>= 1.8.7' s.author = 'Jeremy Kemper' @@ -22,7 +21,7 @@ Gem::Specification.new do |s| s.add_dependency('tzinfo', '~> 0.3.16') s.add_dependency('builder', '~> 2.1.2') s.add_dependency('memcache-client', '~> 1.7.5') - s.add_dependency('bundler', '>= 0.9.2') + s.add_dependency('bundler', '>= 0.9.8') s.add_dependency('rake', '>= 0.8.3') s.add_dependency('thor', '~> 0.13') end -- cgit v1.2.3 From 76237f163ff7ad2a64af926030e3449c547cafa2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Fri, 26 Feb 2010 02:35:14 +0100 Subject: Application detection should also allow dots in the path. --- railties/lib/rails/engine.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb index 1696bb7b86..479d753614 100644 --- a/railties/lib/rails/engine.rb +++ b/railties/lib/rails/engine.rb @@ -17,7 +17,7 @@ module Rails base.called_from = begin # Remove the line number from backtraces making sure we don't leave anything behind call_stack = caller.map { |p| p.split(':')[0..-2].join(':') } - File.dirname(call_stack.detect { |p| p !~ %r[railties[\w\-]*/lib/rails|rack[\w\-]*/lib/rack] }) + File.dirname(call_stack.detect { |p| p !~ %r[railties[\w\-\.]*/lib/rails|rack[\w\-\.]*/lib/rack] }) end end -- cgit v1.2.3 From 226dfc2681c98deaf14e4ae82e973d1d5caedd68 Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Wed, 24 Feb 2010 16:01:03 -0800 Subject: WIP: Remove the global router --- actionpack/lib/action_controller.rb | 2 +- actionpack/lib/action_controller/base.rb | 2 +- actionpack/lib/action_controller/deprecated.rb | 3 +- actionpack/lib/action_controller/metal/head.rb | 4 +- .../lib/action_controller/metal/redirecting.rb | 4 +- actionpack/lib/action_controller/metal/url_for.rb | 165 -------------------- actionpack/lib/action_controller/test_case.rb | 10 +- actionpack/lib/action_controller/url_rewriter.rb | 9 +- actionpack/lib/action_dispatch/routing.rb | 1 + .../lib/action_dispatch/routing/route_set.rb | 30 ++++ actionpack/lib/action_dispatch/routing/routes.rb | 2 +- actionpack/lib/action_dispatch/routing/url_for.rb | 167 +++++++++++++++++++++ .../action_dispatch/testing/assertions/routing.rb | 27 ++-- .../lib/action_dispatch/testing/integration.rb | 10 +- actionpack/lib/action_view/test_case.rb | 3 +- actionpack/test/abstract_unit.rb | 71 ++++++--- .../test/controller/action_pack_assertions_test.rb | 9 +- actionpack/test/controller/base_test.rb | 4 +- actionpack/test/controller/integration_test.rb | 11 +- actionpack/test/controller/rescue_test.rb | 4 +- actionpack/test/controller/resources_test.rb | 13 +- actionpack/test/controller/test_test.rb | 8 +- actionpack/test/controller/url_for_test.rb | 2 +- actionpack/test/controller/url_rewriter_test.rb | 32 ++-- actionpack/test/dispatch/routing_test.rb | 10 +- actionpack/test/template/test_case_test.rb | 2 +- 26 files changed, 342 insertions(+), 263 deletions(-) delete mode 100644 actionpack/lib/action_controller/metal/url_for.rb create mode 100644 actionpack/lib/action_dispatch/routing/url_for.rb diff --git a/actionpack/lib/action_controller.rb b/actionpack/lib/action_controller.rb index 759e52b135..93d8fb612f 100644 --- a/actionpack/lib/action_controller.rb +++ b/actionpack/lib/action_controller.rb @@ -32,7 +32,7 @@ module ActionController autoload :SessionManagement autoload :Streaming autoload :Testing - autoload :UrlFor + # ROUTES TODO: Proxy UrlFor to Rails.application.routes.url_helpers autoload :Verification end diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb index 7f1aa95f6f..0777d9dc16 100644 --- a/actionpack/lib/action_controller/base.rb +++ b/actionpack/lib/action_controller/base.rb @@ -9,7 +9,7 @@ module ActionController include ActionController::Helpers include ActionController::HideActions - include ActionController::UrlFor + # include ActionController::UrlFor include ActionController::Redirecting include ActionController::Rendering include ActionController::Renderers::All diff --git a/actionpack/lib/action_controller/deprecated.rb b/actionpack/lib/action_controller/deprecated.rb index 50c4058845..6088d97abe 100644 --- a/actionpack/lib/action_controller/deprecated.rb +++ b/actionpack/lib/action_controller/deprecated.rb @@ -1,4 +1,5 @@ ActionController::AbstractRequest = ActionController::Request = ActionDispatch::Request ActionController::AbstractResponse = ActionController::Response = ActionDispatch::Response ActionController::Routing = ActionDispatch::Routing -ActionController::UrlWriter = ActionController::UrlFor +# ROUTES TODO: Figure out how to deprecate this. +# ActionController::UrlWriter = ActionController::UrlFor diff --git a/actionpack/lib/action_controller/metal/head.rb b/actionpack/lib/action_controller/metal/head.rb index 37be8b3999..fe6e6186a5 100644 --- a/actionpack/lib/action_controller/metal/head.rb +++ b/actionpack/lib/action_controller/metal/head.rb @@ -1,7 +1,6 @@ module ActionController module Head extend ActiveSupport::Concern - include ActionController::UrlFor # Return a response that has no content (merely headers). The options # argument is interpreted to be a hash of header names and values. @@ -25,6 +24,9 @@ module ActionController end self.status = status + # ROUTES TODO: Figure out how to rescue from a no method error + # This is needed only if you wire up a controller yourself, and + # this not working would be baffling without a better error self.location = url_for(location) if location self.content_type = Mime[formats.first] self.response_body = " " diff --git a/actionpack/lib/action_controller/metal/redirecting.rb b/actionpack/lib/action_controller/metal/redirecting.rb index 25e4e18493..de40ea77b1 100644 --- a/actionpack/lib/action_controller/metal/redirecting.rb +++ b/actionpack/lib/action_controller/metal/redirecting.rb @@ -12,7 +12,6 @@ module ActionController include AbstractController::Logger include ActionController::RackDelegation - include ActionController::UrlFor # Redirects the browser to the target specified in +options+. This parameter can take one of three forms: # @@ -84,6 +83,9 @@ module ActionController raise RedirectBackError unless refer = request.headers["Referer"] refer else + # ROUTES TODO: Figure out how to rescue from a no method error + # This is needed only if you wire up a controller yourself, and + # this not working would be baffling without a better error url_for(options) end.gsub(/[\r\n]/, '') end diff --git a/actionpack/lib/action_controller/metal/url_for.rb b/actionpack/lib/action_controller/metal/url_for.rb deleted file mode 100644 index 0a9ea7fe1a..0000000000 --- a/actionpack/lib/action_controller/metal/url_for.rb +++ /dev/null @@ -1,165 +0,0 @@ -require 'active_support/core_ext/class/attribute' -require 'active_support/core_ext/module/attribute_accessors' - -module ActionController - # In routes.rb one defines URL-to-controller mappings, but the reverse - # is also possible: an URL can be generated from one of your routing definitions. - # URL generation functionality is centralized in this module. - # - # See ActionDispatch::Routing and ActionController::Resources for general - # information about routing and routes.rb. - # - # Tip: If you need to generate URLs from your models or some other place, - # then ActionController::UrlFor is what you're looking for. Read on for - # an introduction. - # - # == URL generation from parameters - # - # As you may know, some functions - such as ActionController::Base#url_for - # and ActionView::Helpers::UrlHelper#link_to, can generate URLs given a set - # of parameters. For example, you've probably had the chance to write code - # like this in one of your views: - # - # <%= link_to('Click here', :controller => 'users', - # :action => 'new', :message => 'Welcome!') %> - # - # #=> Generates a link to: /users/new?message=Welcome%21 - # - # link_to, and all other functions that require URL generation functionality, - # actually use ActionController::UrlFor under the hood. And in particular, - # they use the ActionController::UrlFor#url_for method. One can generate - # the same path as the above example by using the following code: - # - # include UrlFor - # url_for(:controller => 'users', - # :action => 'new', - # :message => 'Welcome!', - # :only_path => true) - # # => "/users/new?message=Welcome%21" - # - # Notice the :only_path => true part. This is because UrlFor has no - # information about the website hostname that your Rails app is serving. So if you - # want to include the hostname as well, then you must also pass the :host - # argument: - # - # include UrlFor - # url_for(:controller => 'users', - # :action => 'new', - # :message => 'Welcome!', - # :host => 'www.example.com') # Changed this. - # # => "http://www.example.com/users/new?message=Welcome%21" - # - # By default, all controllers and views have access to a special version of url_for, - # that already knows what the current hostname is. So if you use url_for in your - # controllers or your views, then you don't need to explicitly pass the :host - # argument. - # - # For convenience reasons, mailers provide a shortcut for ActionController::UrlFor#url_for. - # So within mailers, you only have to type 'url_for' instead of 'ActionController::UrlFor#url_for' - # in full. However, mailers don't have hostname information, and what's why you'll still - # have to specify the :host argument when generating URLs in mailers. - # - # - # == URL generation for named routes - # - # UrlFor also allows one to access methods that have been auto-generated from - # named routes. For example, suppose that you have a 'users' resource in your - # routes.rb: - # - # map.resources :users - # - # This generates, among other things, the method users_path. By default, - # this method is accessible from your controllers, views and mailers. If you need - # to access this auto-generated method from other places (such as a model), then - # you can do that by including ActionController::UrlFor in your class: - # - # class User < ActiveRecord::Base - # include ActionController::UrlFor - # - # def base_uri - # user_path(self) - # end - # end - # - # User.find(1).base_uri # => "/users/1" - # - module UrlFor - extend ActiveSupport::Concern - - included do - ActionDispatch::Routing::Routes.install_helpers(self) - - # Including in a class uses an inheritable hash. Modules get a plain hash. - if respond_to?(:class_attribute) - class_attribute :default_url_options - else - mattr_accessor :default_url_options - end - - self.default_url_options = {} - end - - # Overwrite to implement a number of default options that all url_for-based methods will use. The default options should come in - # the form of a hash, just like the one you would use for url_for directly. Example: - # - # def default_url_options(options) - # { :project => @project.active? ? @project.url_name : "unknown" } - # end - # - # As you can infer from the example, this is mostly useful for situations where you want to centralize dynamic decisions about the - # urls as they stem from the business domain. Please note that any individual url_for call can always override the defaults set - # by this method. - def default_url_options(options = nil) - self.class.default_url_options - end - - def rewrite_options(options) #:nodoc: - if options.delete(:use_defaults) != false && (defaults = default_url_options(options)) - defaults.merge(options) - else - options - end - end - - # Generate a url based on the options provided, default_url_options and the - # routes defined in routes.rb. The following options are supported: - # - # * :only_path - If true, the relative url is returned. Defaults to +false+. - # * :protocol - The protocol to connect to. Defaults to 'http'. - # * :host - Specifies the host the link should be targeted at. - # If :only_path is false, this option must be - # provided either explicitly, or via +default_url_options+. - # * :port - Optionally specify the port to connect to. - # * :anchor - An anchor name to be appended to the path. - # * :skip_relative_url_root - If true, the url is not constructed using the - # +relative_url_root+ set in ActionController::Base.relative_url_root. - # * :trailing_slash - If true, adds a trailing slash, as in "/archive/2009/" - # - # Any other key (:controller, :action, etc.) given to - # +url_for+ is forwarded to the Routes module. - # - # Examples: - # - # url_for :controller => 'tasks', :action => 'testing', :host=>'somehost.org', :port=>'8080' # => 'http://somehost.org:8080/tasks/testing' - # url_for :controller => 'tasks', :action => 'testing', :host=>'somehost.org', :anchor => 'ok', :only_path => true # => '/tasks/testing#ok' - # url_for :controller => 'tasks', :action => 'testing', :trailing_slash=>true # => 'http://somehost.org/tasks/testing/' - # url_for :controller => 'tasks', :action => 'testing', :host=>'somehost.org', :number => '33' # => 'http://somehost.org/tasks/testing?number=33' - def url_for(options = {}) - options ||= {} - case options - when String - options - when Hash - _url_rewriter.rewrite(rewrite_options(options)) - else - polymorphic_url(options) - end - end - - protected - - def _url_rewriter - ActionController::UrlRewriter - end - end -end diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb index 99924205dd..5f8bc6f325 100644 --- a/actionpack/lib/action_controller/test_case.rb +++ b/actionpack/lib/action_controller/test_case.rb @@ -17,9 +17,9 @@ module ActionController end end - def assign_parameters(controller_path, action, parameters = {}) + def assign_parameters(router, controller_path, action, parameters = {}) parameters = parameters.symbolize_keys.merge(:controller => controller_path, :action => action) - extra_keys = ActionDispatch::Routing::Routes.extra_keys(parameters) + extra_keys = router.extra_keys(parameters) non_path_parameters = get? ? query_parameters : request_parameters parameters.each do |key, value| if value.is_a? Fixnum @@ -220,7 +220,7 @@ module ActionController def process(action, parameters = nil, session = nil, flash = nil, http_method = 'GET') # Sanity check for required instance variables so we can give an # understandable error message. - %w(@controller @request @response).each do |iv_name| + %w(@router @controller @request @response).each do |iv_name| if !(instance_variable_names.include?(iv_name) || instance_variable_names.include?(iv_name.to_sym)) || instance_variable_get(iv_name).nil? raise "#{iv_name} is nil: make sure you set it in your test's setup method." end @@ -236,7 +236,7 @@ module ActionController @request.env['REQUEST_METHOD'] = http_method parameters ||= {} - @request.assign_parameters(@controller.class.name.underscore.sub(/_controller$/, ''), action.to_s, parameters) + @request.assign_parameters(@router, @controller.class.name.underscore.sub(/_controller$/, ''), action.to_s, parameters) @request.session = ActionController::TestSession.new(session) unless session.nil? @request.session["flash"] = @request.flash.update(flash || {}) @@ -340,7 +340,7 @@ module ActionController options.update(:only_path => true, :action => action) url = ActionController::UrlRewriter.new(@request, parameters) - @request.request_uri = url.rewrite(options) + @request.request_uri = url.rewrite(@router, options) end end end diff --git a/actionpack/lib/action_controller/url_rewriter.rb b/actionpack/lib/action_controller/url_rewriter.rb index 933a1fa8f9..272465d4f5 100644 --- a/actionpack/lib/action_controller/url_rewriter.rb +++ b/actionpack/lib/action_controller/url_rewriter.rb @@ -9,11 +9,11 @@ module ActionController @request, @parameters = request, parameters end - def rewrite(options = {}) + def rewrite(router, options = {}) options[:host] ||= @request.host_with_port options[:protocol] ||= @request.protocol - self.class.rewrite(options, @request.symbolized_path_parameters) do |options| + self.class.rewrite(router, options, @request.symbolized_path_parameters) do |options| process_path_options(options) end end @@ -24,7 +24,8 @@ module ActionController alias_method :to_s, :to_str - def self.rewrite(options, path_segments=nil) + # ROUTES TODO: Class method code smell + def self.rewrite(router, options, path_segments=nil) rewritten_url = "" unless options[:only_path] @@ -40,7 +41,7 @@ module ActionController path_options = options.except(*RESERVED_OPTIONS) path_options = yield(path_options) if block_given? - path = Routing::Routes.generate(path_options, path_segments || {}) + path = router.generate(path_options, path_segments || {}) rewritten_url << ActionController::Base.relative_url_root.to_s unless options[:skip_relative_url_root] rewritten_url << (options[:trailing_slash] ? path.sub(/\?|\z/) { "/" + $& } : path) diff --git a/actionpack/lib/action_dispatch/routing.rb b/actionpack/lib/action_dispatch/routing.rb index 325d2f7f04..2cc7fe5344 100644 --- a/actionpack/lib/action_dispatch/routing.rb +++ b/actionpack/lib/action_dispatch/routing.rb @@ -206,6 +206,7 @@ module ActionDispatch autoload :Route, 'action_dispatch/routing/route' autoload :Routes, 'action_dispatch/routing/routes' autoload :RouteSet, 'action_dispatch/routing/route_set' + autoload :UrlFor, 'action_dispatch/routing/url_for' SEPARATORS = %w( / . ? ) HTTP_METHODS = [:get, :head, :post, :put, :delete, :options] diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 8778fd2932..8b761d393f 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -272,6 +272,36 @@ module ActionDispatch named_routes.install(destinations, regenerate_code) end + # ROUTES TODO: Revisit the name of these methods + def url_helpers + @url_helpers ||= begin + router = self + Module.new do + extend ActiveSupport::Concern + include UrlFor + + define_method(:_router) { router } + end + end + end + + def named_url_helpers + @named_url_helpers ||= begin + router = self + + Module.new do + extend ActiveSupport::Concern + include router.url_helpers + + # ROUTES TODO: install_helpers isn't great... can we make a module with the stuff that + # we can include? + included do + router.install_helpers(self) + end + end + end + end + def empty? routes.empty? end diff --git a/actionpack/lib/action_dispatch/routing/routes.rb b/actionpack/lib/action_dispatch/routing/routes.rb index 4714556d36..34afada9c9 100644 --- a/actionpack/lib/action_dispatch/routing/routes.rb +++ b/actionpack/lib/action_dispatch/routing/routes.rb @@ -1,5 +1,5 @@ # A singleton that stores the current route set -ActionDispatch::Routing::Routes = ActionDispatch::Routing::RouteSet.new +# ActionDispatch::Routing::Routes = ActionDispatch::Routing::RouteSet.new # To preserve compatibility with pre-3.0 Rails action_controller/deprecated.rb # defines ActionDispatch::Routing::Routes as an alias diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb new file mode 100644 index 0000000000..64c695fe13 --- /dev/null +++ b/actionpack/lib/action_dispatch/routing/url_for.rb @@ -0,0 +1,167 @@ +module ActionDispatch + module Routing + # In routes.rb one defines URL-to-controller mappings, but the reverse + # is also possible: an URL can be generated from one of your routing definitions. + # URL generation functionality is centralized in this module. + # + # See ActionDispatch::Routing and ActionController::Resources for general + # information about routing and routes.rb. + # + # Tip: If you need to generate URLs from your models or some other place, + # then ActionController::UrlFor is what you're looking for. Read on for + # an introduction. + # + # == URL generation from parameters + # + # As you may know, some functions - such as ActionController::Base#url_for + # and ActionView::Helpers::UrlHelper#link_to, can generate URLs given a set + # of parameters. For example, you've probably had the chance to write code + # like this in one of your views: + # + # <%= link_to('Click here', :controller => 'users', + # :action => 'new', :message => 'Welcome!') %> + # + # #=> Generates a link to: /users/new?message=Welcome%21 + # + # link_to, and all other functions that require URL generation functionality, + # actually use ActionController::UrlFor under the hood. And in particular, + # they use the ActionController::UrlFor#url_for method. One can generate + # the same path as the above example by using the following code: + # + # include UrlFor + # url_for(:controller => 'users', + # :action => 'new', + # :message => 'Welcome!', + # :only_path => true) + # # => "/users/new?message=Welcome%21" + # + # Notice the :only_path => true part. This is because UrlFor has no + # information about the website hostname that your Rails app is serving. So if you + # want to include the hostname as well, then you must also pass the :host + # argument: + # + # include UrlFor + # url_for(:controller => 'users', + # :action => 'new', + # :message => 'Welcome!', + # :host => 'www.example.com') # Changed this. + # # => "http://www.example.com/users/new?message=Welcome%21" + # + # By default, all controllers and views have access to a special version of url_for, + # that already knows what the current hostname is. So if you use url_for in your + # controllers or your views, then you don't need to explicitly pass the :host + # argument. + # + # For convenience reasons, mailers provide a shortcut for ActionController::UrlFor#url_for. + # So within mailers, you only have to type 'url_for' instead of 'ActionController::UrlFor#url_for' + # in full. However, mailers don't have hostname information, and what's why you'll still + # have to specify the :host argument when generating URLs in mailers. + # + # + # == URL generation for named routes + # + # UrlFor also allows one to access methods that have been auto-generated from + # named routes. For example, suppose that you have a 'users' resource in your + # routes.rb: + # + # map.resources :users + # + # This generates, among other things, the method users_path. By default, + # this method is accessible from your controllers, views and mailers. If you need + # to access this auto-generated method from other places (such as a model), then + # you can do that by including ActionController::UrlFor in your class: + # + # class User < ActiveRecord::Base + # include ActionController::UrlFor + # + # def base_uri + # user_path(self) + # end + # end + # + # User.find(1).base_uri # => "/users/1" + # + module UrlFor + extend ActiveSupport::Concern + + included do + # ActionDispatch::Routing::Routes.install_helpers(self) + + # Including in a class uses an inheritable hash. Modules get a plain hash. + if respond_to?(:class_attribute) + class_attribute :default_url_options + else + mattr_accessor :default_url_options + end + + self.default_url_options = {} + end + + # Overwrite to implement a number of default options that all url_for-based methods will use. The default options should come in + # the form of a hash, just like the one you would use for url_for directly. Example: + # + # def default_url_options(options) + # { :project => @project.active? ? @project.url_name : "unknown" } + # end + # + # As you can infer from the example, this is mostly useful for situations where you want to centralize dynamic decisions about the + # urls as they stem from the business domain. Please note that any individual url_for call can always override the defaults set + # by this method. + def default_url_options(options = nil) + # ROUTES TODO: This should probably be an instance method + self.class.default_url_options + end + + def rewrite_options(options) #:nodoc: + if options.delete(:use_defaults) != false && (defaults = default_url_options(options)) + defaults.merge(options) + else + options + end + end + + # Generate a url based on the options provided, default_url_options and the + # routes defined in routes.rb. The following options are supported: + # + # * :only_path - If true, the relative url is returned. Defaults to +false+. + # * :protocol - The protocol to connect to. Defaults to 'http'. + # * :host - Specifies the host the link should be targeted at. + # If :only_path is false, this option must be + # provided either explicitly, or via +default_url_options+. + # * :port - Optionally specify the port to connect to. + # * :anchor - An anchor name to be appended to the path. + # * :skip_relative_url_root - If true, the url is not constructed using the + # +relative_url_root+ set in ActionController::Base.relative_url_root. + # * :trailing_slash - If true, adds a trailing slash, as in "/archive/2009/" + # + # Any other key (:controller, :action, etc.) given to + # +url_for+ is forwarded to the Routes module. + # + # Examples: + # + # url_for :controller => 'tasks', :action => 'testing', :host=>'somehost.org', :port=>'8080' # => 'http://somehost.org:8080/tasks/testing' + # url_for :controller => 'tasks', :action => 'testing', :host=>'somehost.org', :anchor => 'ok', :only_path => true # => '/tasks/testing#ok' + # url_for :controller => 'tasks', :action => 'testing', :trailing_slash=>true # => 'http://somehost.org/tasks/testing/' + # url_for :controller => 'tasks', :action => 'testing', :host=>'somehost.org', :number => '33' # => 'http://somehost.org/tasks/testing?number=33' + def url_for(options = {}) + options ||= {} + case options + when String + options + when Hash + _url_rewriter.rewrite(_router, rewrite_options(options)) + else + polymorphic_url(options) + end + end + + protected + + # ROUTES TODO: Figure out why _url_rewriter is sometimes the class and + # sometimes an instance. + def _url_rewriter + ActionController::UrlRewriter + end + end + end +end \ No newline at end of file diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb index ada749bfe2..f281febbc5 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb @@ -80,7 +80,7 @@ module ActionDispatch expected_path = "/#{expected_path}" unless expected_path[0] == ?/ # Load routes.rb if it hasn't been loaded. - generated_path, extra_keys = ActionDispatch::Routing::Routes.generate_extras(options, defaults) + generated_path, extra_keys = @router.generate_extras(options, defaults) found_extras = options.reject {|k, v| ! extra_keys.include? k} msg = build_message(message, "found extras , not ", found_extras, extras) @@ -142,22 +142,21 @@ module ActionDispatch # end # def with_routing - real_routes = ActionDispatch::Routing::Routes - ActionDispatch::Routing.module_eval { remove_const :Routes } - - temporary_routes = ActionDispatch::Routing::RouteSet.new - ActionDispatch::Routing.module_eval { const_set :Routes, temporary_routes } - - yield temporary_routes + old_routes, @router = @router, ActionDispatch::Routing::RouteSet.new + old_controller, @controller = @controller, @controller.clone if @controller + # ROUTES TODO: Figure out this insanity + silence_warnings { ::ActionController.const_set(:UrlFor, @router.named_url_helpers) } + _router = @router + @controller.metaclass.send(:send, :include, @router.named_url_helpers) if @controller + yield @router ensure - if ActionDispatch::Routing.const_defined? :Routes - ActionDispatch::Routing.module_eval { remove_const :Routes } - end - ActionDispatch::Routing.const_set(:Routes, real_routes) if real_routes + @router = old_routes + @controller = old_controller if @controller + silence_warnings { ::ActionController.const_set(:UrlFor, @router.named_url_helpers) } if @router end def method_missing(selector, *args, &block) - if @controller && ActionDispatch::Routing::Routes.named_routes.helpers.include?(selector) + if @controller && @router.named_routes.helpers.include?(selector) @controller.send(selector, *args, &block) else super @@ -174,7 +173,7 @@ module ActionDispatch request.env["REQUEST_METHOD"] = request_method.to_s.upcase if request_method request.path = path - params = ActionDispatch::Routing::Routes.recognize_path(path, { :method => request.method }) + params = @router.recognize_path(path, { :method => request.method }) request.path_parameters = params.with_indifferent_access request diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index 14c7ff642b..3b9d8b0318 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -188,11 +188,11 @@ module ActionDispatch unless defined? @named_routes_configured # install the named routes in this session instance. klass = singleton_class - ActionDispatch::Routing::Routes.install_helpers(klass) + # ActionDispatch::Routing::Routes.install_helpers(klass) # the helpers are made protected by default--we make them public for # easier access during testing and troubleshooting. - klass.module_eval { public *ActionDispatch::Routing::Routes.named_routes.helpers } + # klass.module_eval { public *ActionDispatch::Routing::Routes.named_routes.helpers } @named_routes_configured = true end end @@ -224,9 +224,13 @@ module ActionDispatch # Returns the URL for the given options, according to the rules specified # in the application's routes. def url_for(options) + # ROUTES TODO: @app.router is not guaranteed to exist, so a generic Rack + # application will not work here. This means that a generic Rack application + # integration test cannot call url_for, since the application will not have + # #router on it. controller ? controller.url_for(options) : - generic_url_rewriter.rewrite(options) + generic_url_rewriter.rewrite(SharedTestRoutes, options) end private diff --git a/actionpack/lib/action_view/test_case.rb b/actionpack/lib/action_view/test_case.rb index af2ed33f3f..f6f4e18a4a 100644 --- a/actionpack/lib/action_view/test_case.rb +++ b/actionpack/lib/action_view/test_case.rb @@ -53,6 +53,7 @@ module ActionView setup :setup_with_controller def setup_with_controller @controller = TestController.new + @router = SharedTestRoutes @output_buffer = ActiveSupport::SafeBuffer.new @rendered = '' @@ -152,7 +153,7 @@ module ActionView end def method_missing(selector, *args) - if ActionDispatch::Routing::Routes.named_routes.helpers.include?(selector) + if @router.named_routes.helpers.include?(selector) @controller.__send__(selector, *args) else super diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb index 8be212c8ab..846ac5f0d7 100644 --- a/actionpack/test/abstract_unit.rb +++ b/actionpack/test/abstract_unit.rb @@ -64,29 +64,50 @@ module SetupOnce end end -class ActiveSupport::TestCase - include SetupOnce - - # Hold off drawing routes until all the possible controller classes - # have been loaded. - setup_once do - ActionDispatch::Routing::Routes.draw do |map| - match ':controller(/:action(/:id))' +SharedTestRoutes = ActionDispatch::Routing::RouteSet.new + +module ActiveSupport + class TestCase + include SetupOnce + # Hold off drawing routes until all the possible controller classes + # have been loaded. + setup_once do + SharedTestRoutes.draw do |map| + match ':controller(/:action(/:id))' + end + + # ROUTES TODO: Don't do this here + # brodel :'( + ActionController::IntegrationTest.app.router.draw do + match ':controller(/:action(/:id))' + end end end end +class RoutedRackApp + attr_reader :router + + def initialize(router, &blk) + @router = router + @stack = ActionDispatch::MiddlewareStack.new(&blk).build(@router) + end + + def call(env) + @stack.call(env) + end +end + class ActionController::IntegrationTest < ActiveSupport::TestCase def self.build_app(routes = nil) - ActionDispatch::Flash - ActionDispatch::MiddlewareStack.new { |middleware| + RoutedRackApp.new(routes || ActionDispatch::Routing::RouteSet.new) do |middleware| middleware.use "ActionDispatch::ShowExceptions" middleware.use "ActionDispatch::Callbacks" middleware.use "ActionDispatch::ParamsParser" middleware.use "ActionDispatch::Cookies" middleware.use "ActionDispatch::Flash" middleware.use "ActionDispatch::Head" - }.build(routes || ActionDispatch::Routing::Routes) + end end self.app = build_app @@ -112,20 +133,15 @@ class ActionController::IntegrationTest < ActiveSupport::TestCase end def with_routing(&block) - real_routes = ActionDispatch::Routing::Routes - ActionDispatch::Routing.module_eval { remove_const :Routes } - temporary_routes = ActionDispatch::Routing::RouteSet.new - self.class.app = self.class.build_app(temporary_routes) - ActionDispatch::Routing.module_eval { const_set :Routes, temporary_routes } + old_app, self.class.app = self.class.app, self.class.build_app(temporary_routes) + old_routes = SharedTestRoutes + silence_warnings { Object.const_set(:SharedTestRoutes, temporary_routes) } yield temporary_routes ensure - if ActionDispatch::Routing.const_defined? :Routes - ActionDispatch::Routing.module_eval { remove_const :Routes } - end - ActionDispatch::Routing.const_set(:Routes, real_routes) if real_routes - self.class.app = self.class.build_app + self.class.app = old_app + silence_warnings { Object.const_set(:SharedTestRoutes, old_routes) } end end @@ -190,6 +206,11 @@ module ActionController class TestCase include ActionDispatch::TestProcess + setup do + # ROUTES TODO: The router object should come from somewhere sane + @router = SharedTestRoutes + end + def assert_template(options = {}, message = nil) validate_request! @@ -232,3 +253,11 @@ module ActionController end end end + +# ROUTES TODO: Cleaner way to do this? +module ActionController + UrlFor = SharedTestRoutes.named_url_helpers + class Base + include UrlFor + end +end \ No newline at end of file diff --git a/actionpack/test/controller/action_pack_assertions_test.rb b/actionpack/test/controller/action_pack_assertions_test.rb index d54be9bdc0..7c83a91f4d 100644 --- a/actionpack/test/controller/action_pack_assertions_test.rb +++ b/actionpack/test/controller/action_pack_assertions_test.rb @@ -253,12 +253,13 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase end def test_assert_redirect_to_nested_named_route + @controller = Admin::InnerModuleController.new + with_routing do |set| set.draw do |map| match 'admin/inner_module', :to => 'admin/inner_module#index', :as => :admin_inner_module match ':controller/:action' end - @controller = Admin::InnerModuleController.new process :redirect_to_index # redirection is <{"action"=>"index", "controller"=>"admin/admin/inner_module"}> assert_redirected_to admin_inner_module_path @@ -266,12 +267,13 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase end def test_assert_redirected_to_top_level_named_route_from_nested_controller + @controller = Admin::InnerModuleController.new + with_routing do |set| set.draw do |map| match '/action_pack_assertions/:id', :to => 'action_pack_assertions#index', :as => :top_level match ':controller/:action' end - @controller = Admin::InnerModuleController.new process :redirect_to_top_level_named_route # assert_redirected_to "http://test.host/action_pack_assertions/foo" would pass because of exact match early return assert_redirected_to "/action_pack_assertions/foo" @@ -279,13 +281,14 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase end def test_assert_redirected_to_top_level_named_route_with_same_controller_name_in_both_namespaces + @controller = Admin::InnerModuleController.new + with_routing do |set| set.draw do |map| # this controller exists in the admin namespace as well which is the only difference from previous test match '/user/:id', :to => 'user#index', :as => :top_level match ':controller/:action' end - @controller = Admin::InnerModuleController.new process :redirect_to_top_level_named_route # assert_redirected_to top_level_url('foo') would pass because of exact match early return assert_redirected_to top_level_path('foo') diff --git a/actionpack/test/controller/base_test.rb b/actionpack/test/controller/base_test.rb index 4fcfbacf4e..25006dda76 100644 --- a/actionpack/test/controller/base_test.rb +++ b/actionpack/test/controller/base_test.rb @@ -219,12 +219,14 @@ class EmptyUrlOptionsTest < ActionController::TestCase end def test_named_routes_with_path_without_doing_a_request_first + @controller = EmptyController.new + with_routing do |set| set.draw do |map| resources :things end - assert_equal '/things', EmptyController.new.send(:things_path) + assert_equal '/things', @controller.send(:things_path) end end end diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb index 683ab5236c..29531d237a 100644 --- a/actionpack/test/controller/integration_test.rb +++ b/actionpack/test/controller/integration_test.rb @@ -86,7 +86,7 @@ class SessionTest < Test::Unit::TestCase def test_url_for_without_controller options = {:action => 'show'} mock_rewriter = mock() - mock_rewriter.expects(:rewrite).with(options).returns('/show') + mock_rewriter.expects(:rewrite).with(SharedTestRoutes, options).returns('/show') @session.stubs(:generic_url_rewriter).returns(mock_rewriter) @session.stubs(:controller).returns(nil) assert_equal '/show', @session.url_for(options) @@ -401,9 +401,14 @@ class IntegrationProcessTest < ActionController::IntegrationTest private def with_test_route_set with_routing do |set| + controller = ::IntegrationProcessTest::IntegrationController.clone + controller.class_eval do + include set.named_url_helpers + end + set.draw do |map| - match ':action', :to => ::IntegrationProcessTest::IntegrationController - get 'get/:action', :to => ::IntegrationProcessTest::IntegrationController + match ':action', :to => controller + get 'get/:action', :to => controller end yield end diff --git a/actionpack/test/controller/rescue_test.rb b/actionpack/test/controller/rescue_test.rb index 118b563a72..dd991898a8 100644 --- a/actionpack/test/controller/rescue_test.rb +++ b/actionpack/test/controller/rescue_test.rb @@ -326,7 +326,7 @@ class RescueTest < ActionController::IntegrationTest end test 'rescue routing exceptions' do - @app = ActionDispatch::Rescue.new(ActionDispatch::Routing::Routes) do + @app = ActionDispatch::Rescue.new(SharedTestRoutes) do rescue_from ActionController::RoutingError, lambda { |env| [200, {"Content-Type" => "text/html"}, ["Gotcha!"]] } end @@ -335,7 +335,7 @@ class RescueTest < ActionController::IntegrationTest end test 'unrescued exception' do - @app = ActionDispatch::Rescue.new(ActionDispatch::Routing::Routes) + @app = ActionDispatch::Rescue.new(SharedTestRoutes) assert_raise(ActionController::RoutingError) { get '/b00m' } end diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb index cce98ac482..6f3c16f588 100644 --- a/actionpack/test/controller/resources_test.rb +++ b/actionpack/test/controller/resources_test.rb @@ -125,7 +125,7 @@ class ResourcesTest < ActionController::TestCase def test_with_custom_conditions with_restful_routing :messages, :conditions => { :subdomain => 'app' } do - assert ActionDispatch::Routing::Routes.recognize_path("/messages", :method => :get, :subdomain => 'app') + assert @router.recognize_path("/messages", :method => :get, :subdomain => 'app') end end @@ -394,7 +394,7 @@ class ResourcesTest < ActionController::TestCase assert_restful_routes_for :messages do |options| assert_recognizes(options.merge(:action => "new"), :path => "/messages/new", :method => :get) assert_raise(ActionController::RoutingError) do - ActionDispatch::Routing::Routes.recognize_path("/messages/new", :method => :post) + @router.recognize_path("/messages/new", :method => :post) end end end @@ -504,7 +504,7 @@ class ResourcesTest < ActionController::TestCase def test_restful_routes_dont_generate_duplicates with_restful_routing :messages do - routes = ActionDispatch::Routing::Routes.routes + routes = @router.routes routes.each do |route| routes.each do |r| next if route === r # skip the comparison instance @@ -1162,8 +1162,8 @@ class ResourcesTest < ActionController::TestCase options[:shallow_options] = options[:options] end - new_action = ActionDispatch::Routing::Routes.resources_path_names[:new] || "new" - edit_action = ActionDispatch::Routing::Routes.resources_path_names[:edit] || "edit" + new_action = @router.resources_path_names[:new] || "new" + edit_action = @router.resources_path_names[:edit] || "edit" if options[:path_names] new_action = options[:path_names][:new] if options[:path_names][:new] @@ -1230,6 +1230,8 @@ class ResourcesTest < ActionController::TestCase end @controller = "#{options[:options][:controller].camelize}Controller".constantize.new + # ROUTES TODO: Figure out a way to not extend the routing helpers here + @controller.metaclass.send(:include, @router.named_url_helpers) @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new get :index, options[:options] @@ -1299,6 +1301,7 @@ class ResourcesTest < ActionController::TestCase def assert_singleton_named_routes_for(singleton_name, options = {}) (options[:options] ||= {})[:controller] ||= singleton_name.to_s.pluralize @controller = "#{options[:options][:controller].camelize}Controller".constantize.new + @controller.metaclass.send(:include, @router.named_url_helpers) @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new get :show, options[:options] diff --git a/actionpack/test/controller/test_test.rb b/actionpack/test/controller/test_test.rb index 3f5d60540f..d716dc2661 100644 --- a/actionpack/test/controller/test_test.rb +++ b/actionpack/test/controller/test_test.rb @@ -476,8 +476,8 @@ XML end def test_with_routing_places_routes_back - assert ActionDispatch::Routing::Routes - routes_id = ActionDispatch::Routing::Routes.object_id + assert @router + routes_id = @router.object_id begin with_routing { raise 'fail' } @@ -485,8 +485,8 @@ XML rescue RuntimeError end - assert ActionDispatch::Routing::Routes - assert_equal routes_id, ActionDispatch::Routing::Routes.object_id + assert @router + assert_equal routes_id, @router.object_id end def test_remote_addr diff --git a/actionpack/test/controller/url_for_test.rb b/actionpack/test/controller/url_for_test.rb index 749fa5861f..43e2f91693 100644 --- a/actionpack/test/controller/url_for_test.rb +++ b/actionpack/test/controller/url_for_test.rb @@ -5,7 +5,7 @@ module AbstractController class UrlForTests < ActionController::TestCase class W - include ActionController::UrlFor + include SharedTestRoutes.url_helpers end def teardown diff --git a/actionpack/test/controller/url_rewriter_test.rb b/actionpack/test/controller/url_rewriter_test.rb index c2b8cd85d8..199b824a7a 100644 --- a/actionpack/test/controller/url_rewriter_test.rb +++ b/actionpack/test/controller/url_rewriter_test.rb @@ -12,52 +12,52 @@ class UrlRewriterTests < ActionController::TestCase def test_port assert_equal('http://test.host:1271/c/a/i', - @rewriter.rewrite(:controller => 'c', :action => 'a', :id => 'i', :port => 1271) + @rewriter.rewrite(@router, :controller => 'c', :action => 'a', :id => 'i', :port => 1271) ) end def test_protocol_with_and_without_separator assert_equal('https://test.host/c/a/i', - @rewriter.rewrite(:protocol => 'https', :controller => 'c', :action => 'a', :id => 'i') + @rewriter.rewrite(@router, :protocol => 'https', :controller => 'c', :action => 'a', :id => 'i') ) assert_equal('https://test.host/c/a/i', - @rewriter.rewrite(:protocol => 'https://', :controller => 'c', :action => 'a', :id => 'i') + @rewriter.rewrite(@router, :protocol => 'https://', :controller => 'c', :action => 'a', :id => 'i') ) end def test_user_name_and_password assert_equal( 'http://david:secret@test.host/c/a/i', - @rewriter.rewrite(:user => "david", :password => "secret", :controller => 'c', :action => 'a', :id => 'i') + @rewriter.rewrite(@router, :user => "david", :password => "secret", :controller => 'c', :action => 'a', :id => 'i') ) end def test_user_name_and_password_with_escape_codes assert_equal( 'http://openid.aol.com%2Fnextangler:one+two%3F@test.host/c/a/i', - @rewriter.rewrite(:user => "openid.aol.com/nextangler", :password => "one two?", :controller => 'c', :action => 'a', :id => 'i') + @rewriter.rewrite(@router, :user => "openid.aol.com/nextangler", :password => "one two?", :controller => 'c', :action => 'a', :id => 'i') ) end def test_anchor assert_equal( 'http://test.host/c/a/i#anchor', - @rewriter.rewrite(:controller => 'c', :action => 'a', :id => 'i', :anchor => 'anchor') + @rewriter.rewrite(@router, :controller => 'c', :action => 'a', :id => 'i', :anchor => 'anchor') ) end def test_anchor_should_call_to_param assert_equal( 'http://test.host/c/a/i#anchor', - @rewriter.rewrite(:controller => 'c', :action => 'a', :id => 'i', :anchor => Struct.new(:to_param).new('anchor')) + @rewriter.rewrite(@router, :controller => 'c', :action => 'a', :id => 'i', :anchor => Struct.new(:to_param).new('anchor')) ) end def test_anchor_should_be_cgi_escaped assert_equal( 'http://test.host/c/a/i#anc%2Fhor', - @rewriter.rewrite(:controller => 'c', :action => 'a', :id => 'i', :anchor => Struct.new(:to_param).new('anc/hor')) + @rewriter.rewrite(@router, :controller => 'c', :action => 'a', :id => 'i', :anchor => Struct.new(:to_param).new('anc/hor')) ) end @@ -66,8 +66,8 @@ class UrlRewriterTests < ActionController::TestCase @params[:action] = 'bye' @params[:id] = '2' - assert_equal '/hi/hi/2', @rewriter.rewrite(:only_path => true, :overwrite_params => {:action => 'hi'}) - u = @rewriter.rewrite(:only_path => false, :overwrite_params => {:action => 'hi'}) + assert_equal '/hi/hi/2', @rewriter.rewrite(@router, :only_path => true, :overwrite_params => {:action => 'hi'}) + u = @rewriter.rewrite(@router, :only_path => false, :overwrite_params => {:action => 'hi'}) assert_match %r(/hi/hi/2$), u end @@ -76,8 +76,8 @@ class UrlRewriterTests < ActionController::TestCase @params[:action] = 'list' @params[:list_page] = 1 - assert_equal '/search/list?list_page=2', @rewriter.rewrite(:only_path => true, :overwrite_params => {"list_page" => 2}) - u = @rewriter.rewrite(:only_path => false, :overwrite_params => {:list_page => 2}) + assert_equal '/search/list?list_page=2', @rewriter.rewrite(@router, :only_path => true, :overwrite_params => {"list_page" => 2}) + u = @rewriter.rewrite(@router, :only_path => false, :overwrite_params => {:list_page => 2}) assert_equal 'http://test.host/search/list?list_page=2', u end @@ -91,12 +91,12 @@ class UrlRewriterTests < ActionController::TestCase def test_trailing_slash options = {:controller => 'foo', :action => 'bar', :id => '3', :only_path => true} - assert_equal '/foo/bar/3', @rewriter.rewrite(options) - assert_equal '/foo/bar/3?query=string', @rewriter.rewrite(options.merge({:query => 'string'})) + assert_equal '/foo/bar/3', @rewriter.rewrite(@router, options) + assert_equal '/foo/bar/3?query=string', @rewriter.rewrite(@router, options.merge({:query => 'string'})) options.update({:trailing_slash => true}) - assert_equal '/foo/bar/3/', @rewriter.rewrite(options) + assert_equal '/foo/bar/3/', @rewriter.rewrite(@router, options) options.update({:query => 'string'}) - assert_equal '/foo/bar/3/?query=string', @rewriter.rewrite(options) + assert_equal '/foo/bar/3/?query=string', @rewriter.rewrite(@router, options) end end diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb index e29127f78f..7cfc6ef3d7 100644 --- a/actionpack/test/dispatch/routing_test.rb +++ b/actionpack/test/dispatch/routing_test.rb @@ -164,6 +164,8 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest Routes end + include Routes.named_url_helpers + def test_logout with_test_routes do delete '/logout' @@ -728,14 +730,6 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest private def with_test_routes - real_routes, temp_routes = ActionDispatch::Routing::Routes, Routes - - ActionDispatch::Routing.module_eval { remove_const :Routes } - ActionDispatch::Routing.module_eval { const_set :Routes, temp_routes } - yield - ensure - ActionDispatch::Routing.module_eval { remove_const :Routes } - ActionDispatch::Routing.const_set(:Routes, real_routes) end end diff --git a/actionpack/test/template/test_case_test.rb b/actionpack/test/template/test_case_test.rb index be2c6b3108..12807baaa7 100644 --- a/actionpack/test/template/test_case_test.rb +++ b/actionpack/test/template/test_case_test.rb @@ -107,7 +107,7 @@ module ActionView end test "is able to use routes" do - controller.request.assign_parameters('foo', 'index') + controller.request.assign_parameters(@router, 'foo', 'index') assert_equal '/foo', url_for assert_equal '/bar', url_for(:controller => 'bar') end -- cgit v1.2.3 From 4b038f638d8c8969b2bccac82d0d7a370381680b Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Wed, 24 Feb 2010 16:01:32 -0800 Subject: Merge branch 'master' of github.com:rails/rails --- actionpack/test/controller/webservice_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actionpack/test/controller/webservice_test.rb b/actionpack/test/controller/webservice_test.rb index ede48017cf..05545395fb 100644 --- a/actionpack/test/controller/webservice_test.rb +++ b/actionpack/test/controller/webservice_test.rb @@ -245,7 +245,7 @@ class WebServiceTest < ActionController::IntegrationTest private def with_params_parsers(parsers = {}) old_session = @integration_session - @app = ActionDispatch::ParamsParser.new(ActionDispatch::Routing::Routes, parsers) + @app = ActionDispatch::ParamsParser.new(app.router, parsers) reset! yield ensure -- cgit v1.2.3 From a278f2331007411b190d65577082d2710ad9a996 Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Wed, 24 Feb 2010 16:17:04 -0800 Subject: Fix all of AP's tests with the non global router --- actionpack/test/activerecord/polymorphic_routes_test.rb | 6 +++--- actionpack/test/controller/caching_test.rb | 6 ++++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/actionpack/test/activerecord/polymorphic_routes_test.rb b/actionpack/test/activerecord/polymorphic_routes_test.rb index 7be2ef7e29..a10bb4473e 100644 --- a/actionpack/test/activerecord/polymorphic_routes_test.rb +++ b/actionpack/test/activerecord/polymorphic_routes_test.rb @@ -400,7 +400,7 @@ class PolymorphicRoutesTest < ActionController::TestCase map.resources :series end - ActionDispatch::Routing::Routes.install_helpers(self.class) + self.class.send(:include, @router.named_url_helpers) yield end end @@ -422,7 +422,7 @@ class PolymorphicRoutesTest < ActionController::TestCase end end - ActionDispatch::Routing::Routes.install_helpers(self.class) + self.class.send(:include, @router.named_url_helpers) yield end end @@ -441,7 +441,7 @@ class PolymorphicRoutesTest < ActionController::TestCase end end - ActionDispatch::Routing::Routes.install_helpers(self.class) + self.class.send(:include, @router.named_url_helpers) yield end end diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb index de92fc56fd..9c9d886f5d 100644 --- a/actionpack/test/controller/caching_test.rb +++ b/actionpack/test/controller/caching_test.rb @@ -74,9 +74,9 @@ class PageCachingTest < ActionController::TestCase match '/', :to => 'posts#index', :as => :main end @params[:format] = 'rss' - assert_equal '/posts.rss', @rewriter.rewrite(@params) + assert_equal '/posts.rss', @rewriter.rewrite(@router, @params) @params[:format] = nil - assert_equal '/', @rewriter.rewrite(@params) + assert_equal '/', @rewriter.rewrite(@router, @params) end end @@ -511,6 +511,8 @@ class ActionCacheTest < ActionController::TestCase @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new @controller = ActionCachingTestController.new + # ROUTES TODO: It seems bad to explicitly remix in the class + @controller.metaclass.send(:include, @router.named_url_helpers) @request.host = 'hostname.com' end -- cgit v1.2.3 From 1fb2c6f63527408c8dbb00d6483ee6cf677db2df Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Wed, 24 Feb 2010 16:21:21 -0800 Subject: Get ActionMailer's tests passing with the non global router --- actionmailer/test/old_base/url_test.rb | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/actionmailer/test/old_base/url_test.rb b/actionmailer/test/old_base/url_test.rb index 53664480ff..0e8917b427 100644 --- a/actionmailer/test/old_base/url_test.rb +++ b/actionmailer/test/old_base/url_test.rb @@ -4,8 +4,10 @@ require 'action_controller' class WelcomeController < ActionController::Base end +AppRoutes = ActionDispatch::Routing::RouteSet.new + class ActionMailer::Base - include ActionController::UrlFor + include AppRoutes.named_url_helpers end class TestMailer < ActionMailer::Base @@ -61,7 +63,7 @@ class ActionMailerUrlTest < Test::Unit::TestCase def test_signed_up_with_url TestMailer.delivery_method = :test - ActionDispatch::Routing::Routes.draw do |map| + AppRoutes.draw do |map| map.connect ':controller/:action/:id' map.welcome 'welcome', :controller=>"foo", :action=>"bar" end -- cgit v1.2.3 From 9a5be2e5a80ab9e74294f32cfef58fbbcd9b637c Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Wed, 24 Feb 2010 16:47:43 -0800 Subject: Get Railties tests passing --- actionmailer/lib/action_mailer/railtie.rb | 2 +- railties/lib/rails/application.rb | 2 +- railties/test/rails_info_controller_test.rb | 3 +++ 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/actionmailer/lib/action_mailer/railtie.rb b/actionmailer/lib/action_mailer/railtie.rb index 4c48d2bed6..7622a90b17 100644 --- a/actionmailer/lib/action_mailer/railtie.rb +++ b/actionmailer/lib/action_mailer/railtie.rb @@ -6,7 +6,7 @@ module ActionMailer railtie_name :action_mailer initializer "action_mailer.url_for", :before => :load_environment_config do |app| - ActionMailer::Base.send(:include, ActionController::UrlFor) if defined?(ActionController) + ActionMailer::Base.send(:include, app.routes.named_url_helpers) end require "action_mailer/railties/log_subscriber" diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb index 67094392ee..a74550b302 100644 --- a/railties/lib/rails/application.rb +++ b/railties/lib/rails/application.rb @@ -48,7 +48,7 @@ module Rails end def routes - ::ActionDispatch::Routing::Routes + @routes ||= ActionDispatch::Routing::RouteSet.new end def railties diff --git a/railties/test/rails_info_controller_test.rb b/railties/test/rails_info_controller_test.rb index a6fc23d95b..017e51326c 100644 --- a/railties/test/rails_info_controller_test.rb +++ b/railties/test/rails_info_controller_test.rb @@ -18,6 +18,9 @@ class InfoControllerTest < ActionController::TestCase match ':controller/:action' end @controller.stubs(:consider_all_requests_local? => false, :local_request? => true) + @router = Rails.application.routes + + Rails::InfoController.send(:include, @router.named_url_helpers) end test "info controller does not allow remote requests" do -- cgit v1.2.3 From 36fd9efb5e4bfc9ac3acd4189d4dc457dea8102a Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Thu, 25 Feb 2010 15:05:10 -0800 Subject: Continued effort to deglobalize the router --- actionpack/lib/action_controller.rb | 2 +- actionpack/lib/action_controller/base.rb | 9 +----- actionpack/lib/action_controller/metal/url_for.rb | 21 +++++++++++++ actionpack/lib/action_controller/railtie.rb | 1 + actionpack/lib/action_controller/test_case.rb | 2 +- actionpack/lib/action_controller/url_rewriter.rb | 21 +++++++++++++ .../lib/action_dispatch/routing/route_set.rb | 23 ++++----------- actionpack/lib/action_dispatch/routing/url_for.rb | 31 +++++--------------- actionpack/test/controller/base_test.rb | 1 + actionpack/test/controller/routing_test.rb | 34 +++++----------------- 10 files changed, 66 insertions(+), 79 deletions(-) create mode 100644 actionpack/lib/action_controller/metal/url_for.rb diff --git a/actionpack/lib/action_controller.rb b/actionpack/lib/action_controller.rb index 93d8fb612f..759e52b135 100644 --- a/actionpack/lib/action_controller.rb +++ b/actionpack/lib/action_controller.rb @@ -32,7 +32,7 @@ module ActionController autoload :SessionManagement autoload :Streaming autoload :Testing - # ROUTES TODO: Proxy UrlFor to Rails.application.routes.url_helpers + autoload :UrlFor autoload :Verification end diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb index 0777d9dc16..f8ddc8da09 100644 --- a/actionpack/lib/action_controller/base.rb +++ b/actionpack/lib/action_controller/base.rb @@ -9,7 +9,7 @@ module ActionController include ActionController::Helpers include ActionController::HideActions - # include ActionController::UrlFor + include ActionController::UrlFor include ActionController::Redirecting include ActionController::Rendering include ActionController::Renderers::All @@ -82,12 +82,5 @@ module ActionController filter end - protected - - # Overwrite url rewriter to use request. - def _url_rewriter - return ActionController::UrlRewriter unless request - @_url_rewriter ||= ActionController::UrlRewriter.new(request, params) - end end end diff --git a/actionpack/lib/action_controller/metal/url_for.rb b/actionpack/lib/action_controller/metal/url_for.rb new file mode 100644 index 0000000000..013834ddee --- /dev/null +++ b/actionpack/lib/action_controller/metal/url_for.rb @@ -0,0 +1,21 @@ +module ActionController + module UrlFor + extend ActiveSupport::Concern + + include ActionDispatch::Routing::UrlFor + include ActionController::RackDelegation + + def merge_options(options) + super.reverse_merge( + :host => request.host_with_port, + :protocol => request.protocol, + :_path_segments => request.symbolized_path_parameters + ) + end + + def _router + raise "In order to use #url_for, you must include the helpers of a particular " \ + "router. For instance, `include Rails.application.router.named_url_helpers" + end + end +end \ No newline at end of file diff --git a/actionpack/lib/action_controller/railtie.rb b/actionpack/lib/action_controller/railtie.rb index 015a8212c4..5a16d82e49 100644 --- a/actionpack/lib/action_controller/railtie.rb +++ b/actionpack/lib/action_controller/railtie.rb @@ -1,6 +1,7 @@ require "action_controller" require "rails" require "action_view/railtie" +require "active_support/core_ext/class/subclasses" module ActionController class Railtie < Rails::Railtie diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb index 5f8bc6f325..0fa2a8b90c 100644 --- a/actionpack/lib/action_controller/test_case.rb +++ b/actionpack/lib/action_controller/test_case.rb @@ -336,7 +336,7 @@ module ActionController private def build_request_uri(action, parameters) unless @request.env['REQUEST_URI'] - options = @controller.__send__(:rewrite_options, parameters) + options = @controller.__send__(:merge_options, parameters) options.update(:only_path => true, :action => action) url = ActionController::UrlRewriter.new(@request, parameters) diff --git a/actionpack/lib/action_controller/url_rewriter.rb b/actionpack/lib/action_controller/url_rewriter.rb index 272465d4f5..807b21cd0e 100644 --- a/actionpack/lib/action_controller/url_rewriter.rb +++ b/actionpack/lib/action_controller/url_rewriter.rb @@ -26,8 +26,14 @@ module ActionController # ROUTES TODO: Class method code smell def self.rewrite(router, options, path_segments=nil) + handle_positional_args(options) + rewritten_url = "" + # ROUTES TODO: Fix the tests + segments = options.delete(:_path_segments) + path_segments = path_segments ? path_segments.merge(segments || {}) : segments + unless options[:only_path] rewritten_url << (options[:protocol] || "http") rewritten_url << "://" unless rewritten_url.match("://") @@ -52,6 +58,21 @@ module ActionController protected + def self.handle_positional_args(options) + return unless args = options.delete(:_positional_args) + + keys = options.delete(:_positional_keys) + keys -= options.keys if args.size < keys.size - 1 # take format into account + + args = args.zip(keys).inject({}) do |h, (v, k)| + h[k] = v + h + end + + # Tell url_for to skip default_url_options + options.merge!(args) + end + def self.rewrite_authentication(options) if options[:user] && options[:password] "#{Rack::Utils.escape(options.delete(:user))}:#{Rack::Utils.escape(options.delete(:password))}@" diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 8b761d393f..7bfe4fa2bf 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -194,24 +194,11 @@ module ActionDispatch # end @module.module_eval <<-END_EVAL, __FILE__, __LINE__ + 1 def #{selector}(*args) - if args.empty? || Hash === args.first - options = #{hash_access_method}(args.first || {}) - else - options = #{hash_access_method}(args.extract_options!) - default = default_url_options(options) if self.respond_to?(:default_url_options, true) - options = (default ||= {}).merge(options) - - keys = #{route.segment_keys.inspect} - keys -= options.keys if args.size < keys.size - 1 # take format into account - - args = args.zip(keys).inject({}) do |h, (v, k)| - h[k] = v - h - end - - # Tell url_for to skip default_url_options - options[:use_defaults] = false - options.merge!(args) + options = #{hash_access_method}(args.extract_options!) + + if args.any? + options[:_positional_args] = args + options[:_positional_keys] = #{route.segment_keys.inspect} end url_for(options) diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb index 64c695fe13..1d6da817ed 100644 --- a/actionpack/lib/action_dispatch/routing/url_for.rb +++ b/actionpack/lib/action_dispatch/routing/url_for.rb @@ -85,8 +85,6 @@ module ActionDispatch extend ActiveSupport::Concern included do - # ActionDispatch::Routing::Routes.install_helpers(self) - # Including in a class uses an inheritable hash. Modules get a plain hash. if respond_to?(:class_attribute) class_attribute :default_url_options @@ -97,23 +95,16 @@ module ActionDispatch self.default_url_options = {} end - # Overwrite to implement a number of default options that all url_for-based methods will use. The default options should come in - # the form of a hash, just like the one you would use for url_for directly. Example: - # - # def default_url_options(options) - # { :project => @project.active? ? @project.url_name : "unknown" } - # end - # - # As you can infer from the example, this is mostly useful for situations where you want to centralize dynamic decisions about the - # urls as they stem from the business domain. Please note that any individual url_for call can always override the defaults set - # by this method. def default_url_options(options = nil) - # ROUTES TODO: This should probably be an instance method self.class.default_url_options end - def rewrite_options(options) #:nodoc: - if options.delete(:use_defaults) != false && (defaults = default_url_options(options)) + def url_options + self.class.default_url_options.merge + end + + def merge_options(options) #:nodoc: + if options.delete(:use_defaults) != false && respond_to?(:default_url_options) && (defaults = default_url_options(options)) defaults.merge(options) else options @@ -149,19 +140,11 @@ module ActionDispatch when String options when Hash - _url_rewriter.rewrite(_router, rewrite_options(options)) + ActionController::UrlRewriter.rewrite(_router, merge_options(options)) else polymorphic_url(options) end end - - protected - - # ROUTES TODO: Figure out why _url_rewriter is sometimes the class and - # sometimes an instance. - def _url_rewriter - ActionController::UrlRewriter - end end end end \ No newline at end of file diff --git a/actionpack/test/controller/base_test.rb b/actionpack/test/controller/base_test.rb index 25006dda76..436ee212c8 100644 --- a/actionpack/test/controller/base_test.rb +++ b/actionpack/test/controller/base_test.rb @@ -220,6 +220,7 @@ class EmptyUrlOptionsTest < ActionController::TestCase def test_named_routes_with_path_without_doing_a_request_first @controller = EmptyController.new + @controller.request = @request with_routing do |set| set.draw do |map| diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb index f390bbdc89..f2fccfbcfc 100644 --- a/actionpack/test/controller/routing_test.rb +++ b/actionpack/test/controller/routing_test.rb @@ -52,29 +52,11 @@ class UriReservedCharactersRoutingTest < Test::Unit::TestCase end class MockController - attr_accessor :routes - - def initialize(routes) - self.routes = routes - end - def url_for(options) - only_path = options.delete(:only_path) - - port = options.delete(:port) || 80 - port_string = port == 80 ? '' : ":#{port}" - - protocol = options.delete(:protocol) || "http" - host = options.delete(:host) || "test.host" - anchor = "##{options.delete(:anchor)}" if options.key?(:anchor) + options[:protocol] ||= "http" + options[:host] ||= "test.host" - path = routes.generate(options) - - only_path ? "#{path}#{anchor}" : "#{protocol}://#{host}#{port_string}#{path}#{anchor}" - end - - def request - @request ||= ActionController::TestRequest.new + super(options) end end @@ -268,9 +250,9 @@ class LegacyRouteSetTests < Test::Unit::TestCase end def setup_for_named_route - klass = Class.new(MockController) - rs.install_helpers(klass) - klass.new(rs) + inst = MockController.clone.new + inst.class.send(:include, rs.named_url_helpers) + inst end def test_named_route_without_hash @@ -759,9 +741,7 @@ class RouteSetTest < ActiveSupport::TestCase map.users '/admin/users', :controller => 'admin/users', :action => 'index' end - klass = Class.new(MockController) - set.install_helpers(klass) - klass.new(set) + MockController.clone.new.tap { |inst| inst.class.send(:include, set.named_url_helpers)} end def test_named_route_hash_access_method -- cgit v1.2.3 From fc4582fb6684ce72f5628629ea7d061659b790f8 Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Thu, 25 Feb 2010 16:48:36 -0800 Subject: Final pass at removing the router from a global constant --- actionpack/lib/action_controller/railtie.rb | 10 ++++-- .../lib/action_controller/railties/url_helpers.rb | 14 ++++++++ actionpack/lib/action_dispatch/routing.rb | 1 - actionpack/lib/action_dispatch/routing/routes.rb | 5 --- .../action_dispatch/testing/assertions/routing.rb | 2 +- .../lib/action_dispatch/testing/integration.rb | 2 -- .../lib/action_view/helpers/atom_feed_helper.rb | 2 +- railties/lib/rails/test_help.rb | 6 ++++ railties/test/application/url_generation_test.rb | 42 ++++++++++++++++++++++ 9 files changed, 72 insertions(+), 12 deletions(-) create mode 100644 actionpack/lib/action_controller/railties/url_helpers.rb delete mode 100644 actionpack/lib/action_dispatch/routing/routes.rb create mode 100644 railties/test/application/url_generation_test.rb diff --git a/actionpack/lib/action_controller/railtie.rb b/actionpack/lib/action_controller/railtie.rb index 5a16d82e49..3df70d4a4d 100644 --- a/actionpack/lib/action_controller/railtie.rb +++ b/actionpack/lib/action_controller/railtie.rb @@ -1,5 +1,5 @@ -require "action_controller" require "rails" +require "action_controller" require "action_view/railtie" require "active_support/core_ext/class/subclasses" @@ -8,6 +8,8 @@ module ActionController railtie_name :action_controller require "action_controller/railties/log_subscriber" + require "action_controller/railties/url_helpers" + log_subscriber ActionController::Railties::LogSubscriber.new initializer "action_controller.logger" do @@ -27,5 +29,9 @@ module ActionController initializer "action_controller.set_helpers_path" do |app| ActionController::Base.helpers_path = app.config.paths.app.helpers.to_a end + + initializer "action_controller.url_helpers" do |app| + ActionController::Base.extend ::ActionController::Railtie::UrlHelpers.with(app.routes) + end end -end +end \ No newline at end of file diff --git a/actionpack/lib/action_controller/railties/url_helpers.rb b/actionpack/lib/action_controller/railties/url_helpers.rb new file mode 100644 index 0000000000..354d3fa898 --- /dev/null +++ b/actionpack/lib/action_controller/railties/url_helpers.rb @@ -0,0 +1,14 @@ +module ActionController + class Railtie + module UrlHelpers + def self.with(router) + Module.new do + define_method(:inherited) do |klass| + super + klass.send(:include, router.named_url_helpers) + end + end + end + end + end +end \ No newline at end of file diff --git a/actionpack/lib/action_dispatch/routing.rb b/actionpack/lib/action_dispatch/routing.rb index 2cc7fe5344..5bc3205c51 100644 --- a/actionpack/lib/action_dispatch/routing.rb +++ b/actionpack/lib/action_dispatch/routing.rb @@ -204,7 +204,6 @@ module ActionDispatch autoload :DeprecatedMapper, 'action_dispatch/routing/deprecated_mapper' autoload :Mapper, 'action_dispatch/routing/mapper' autoload :Route, 'action_dispatch/routing/route' - autoload :Routes, 'action_dispatch/routing/routes' autoload :RouteSet, 'action_dispatch/routing/route_set' autoload :UrlFor, 'action_dispatch/routing/url_for' diff --git a/actionpack/lib/action_dispatch/routing/routes.rb b/actionpack/lib/action_dispatch/routing/routes.rb deleted file mode 100644 index 34afada9c9..0000000000 --- a/actionpack/lib/action_dispatch/routing/routes.rb +++ /dev/null @@ -1,5 +0,0 @@ -# A singleton that stores the current route set -# ActionDispatch::Routing::Routes = ActionDispatch::Routing::RouteSet.new - -# To preserve compatibility with pre-3.0 Rails action_controller/deprecated.rb -# defines ActionDispatch::Routing::Routes as an alias diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb index f281febbc5..17caa2e030 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb @@ -125,7 +125,7 @@ module ActionDispatch end # A helper to make it easier to test different route configurations. - # This method temporarily replaces ActionDispatch::Routing::Routes + # This method temporarily replaces @router # with a new RouteSet instance. # # The new instance is yielded to the passed block. Typically the block diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index 3b9d8b0318..3bd9502e91 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -188,11 +188,9 @@ module ActionDispatch unless defined? @named_routes_configured # install the named routes in this session instance. klass = singleton_class - # ActionDispatch::Routing::Routes.install_helpers(klass) # the helpers are made protected by default--we make them public for # easier access during testing and troubleshooting. - # klass.module_eval { public *ActionDispatch::Routing::Routes.named_routes.helpers } @named_routes_configured = true end end diff --git a/actionpack/lib/action_view/helpers/atom_feed_helper.rb b/actionpack/lib/action_view/helpers/atom_feed_helper.rb index 4305a0d5f5..a26a8c9b4b 100644 --- a/actionpack/lib/action_view/helpers/atom_feed_helper.rb +++ b/actionpack/lib/action_view/helpers/atom_feed_helper.rb @@ -8,7 +8,7 @@ module ActionView # Full usage example: # # config/routes.rb: - # ActionDispatch::Routing::Routes.draw do |map| + # Basecamp::Application.routes.draw do |map| # map.resources :posts # map.root :controller => "posts" # end diff --git a/railties/lib/rails/test_help.rb b/railties/lib/rails/test_help.rb index f9aa018cab..dbb1b76b95 100644 --- a/railties/lib/rails/test_help.rb +++ b/railties/lib/rails/test_help.rb @@ -24,6 +24,12 @@ if defined?(ActiveRecord) end end +class ActionController::TestCase + setup do + @router = Rails.application.routes + end +end + begin require_library_or_gem 'ruby-debug' Debugger.start diff --git a/railties/test/application/url_generation_test.rb b/railties/test/application/url_generation_test.rb new file mode 100644 index 0000000000..a0d9ff7a3a --- /dev/null +++ b/railties/test/application/url_generation_test.rb @@ -0,0 +1,42 @@ +require 'isolation/abstract_unit' + +module ApplicationTests + class UrlGenerationTest < Test::Unit::TestCase + include ActiveSupport::Testing::Isolation + + def app + Rails.application + end + + test "it works" do + boot_rails + require "rails" + require "action_controller/railtie" + + class MyApp < Rails::Application + config.action_controller.session = { :key => "_myapp_session", :secret => "3b7cd727ee24e8444053437c36cc66c4" } + end + + MyApp.initialize! + + class ::ApplicationController < ActionController::Base + end + + class ::OmgController < ::ApplicationController + def index + render :text => omg_path + end + end + + MyApp.routes.draw do + match "/" => "omg#index", :as => :omg + end + + require 'rack/test' + extend Rack::Test::Methods + + get "/" + assert_equal "/", last_response.body + end + end +end -- cgit v1.2.3 From 8760add31a0415b4635059cf7fadabc26946c0c2 Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Thu, 25 Feb 2010 17:51:56 -0800 Subject: Get URL helpers working again in integration tests. --- actionpack/lib/action_controller/railtie.rb | 2 + .../lib/action_dispatch/testing/integration.rb | 48 +++++++++++----------- actionpack/test/controller/integration_test.rb | 24 ++++------- railties/lib/rails/test_help.rb | 4 ++ 4 files changed, 37 insertions(+), 41 deletions(-) diff --git a/actionpack/lib/action_controller/railtie.rb b/actionpack/lib/action_controller/railtie.rb index 3df70d4a4d..268301da64 100644 --- a/actionpack/lib/action_controller/railtie.rb +++ b/actionpack/lib/action_controller/railtie.rb @@ -32,6 +32,8 @@ module ActionController initializer "action_controller.url_helpers" do |app| ActionController::Base.extend ::ActionController::Railtie::UrlHelpers.with(app.routes) + ActionController::Routing::Routes = app.routes + ::SharedTestRoutes = app.routes end end end \ No newline at end of file diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index 3bd9502e91..fb067601c8 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -219,17 +219,17 @@ module ActionDispatch @host = name end - # Returns the URL for the given options, according to the rules specified - # in the application's routes. - def url_for(options) - # ROUTES TODO: @app.router is not guaranteed to exist, so a generic Rack - # application will not work here. This means that a generic Rack application - # integration test cannot call url_for, since the application will not have - # #router on it. - controller ? - controller.url_for(options) : - generic_url_rewriter.rewrite(SharedTestRoutes, options) - end + # # Returns the URL for the given options, according to the rules specified + # # in the application's routes. + # def url_for(options) + # # ROUTES TODO: @app.router is not guaranteed to exist, so a generic Rack + # # application will not work here. This means that a generic Rack application + # # integration test cannot call url_for, since the application will not have + # # #router on it. + # controller ? + # controller.url_for(options) : + # generic_url_rewriter.rewrite(SharedTestRoutes, options) + # end private @@ -283,19 +283,6 @@ module ActionDispatch return response.status end - - # Get a temporary URL writer object - def generic_url_rewriter - env = { - 'REQUEST_METHOD' => "GET", - 'QUERY_STRING' => "", - "REQUEST_URI" => "/", - "HTTP_HOST" => host, - "SERVER_PORT" => https? ? "443" : "80", - "HTTPS" => https? ? "on" : "off" - } - ActionController::UrlRewriter.new(ActionDispatch::Request.new(env), {}) - end end module Runner @@ -367,6 +354,19 @@ module ActionDispatch end end + extend ActiveSupport::Concern + include ActionDispatch::Routing::UrlFor + + def merge_options(options) + opts = super.reverse_merge( + :host => host, + :protocol => https? ? "https" : "http" + ) + + opts.merge!(:port => 443) if !opts.key?(:port) && https? + opts + end + # Delegate unhandled messages to the current session instance. def method_missing(sym, *args, &block) reset! unless @integration_session diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb index 29531d237a..1611a549fd 100644 --- a/actionpack/test/controller/integration_test.rb +++ b/actionpack/test/controller/integration_test.rb @@ -75,23 +75,6 @@ class SessionTest < Test::Unit::TestCase @session.delete_via_redirect(path, args, headers) end - def test_url_for_with_controller - options = {:action => 'show'} - mock_controller = mock() - mock_controller.expects(:url_for).with(options).returns('/show') - @session.stubs(:controller).returns(mock_controller) - assert_equal '/show', @session.url_for(options) - end - - def test_url_for_without_controller - options = {:action => 'show'} - mock_rewriter = mock() - mock_rewriter.expects(:rewrite).with(SharedTestRoutes, options).returns('/show') - @session.stubs(:generic_url_rewriter).returns(mock_rewriter) - @session.stubs(:controller).returns(nil) - assert_equal '/show', @session.url_for(options) - end - def test_get path = "/index"; params = "blah"; headers = {:location => 'blah'} @session.expects(:process).with(:get,path,params,headers) @@ -238,6 +221,8 @@ class IntegrationTestUsesCorrectClass < ActionController::IntegrationTest end class IntegrationProcessTest < ActionController::IntegrationTest + include SharedTestRoutes.named_url_helpers + class IntegrationController < ActionController::Base def get respond_to do |format| @@ -410,12 +395,17 @@ class IntegrationProcessTest < ActionController::IntegrationTest match ':action', :to => controller get 'get/:action', :to => controller end + + self.metaclass.send(:include, set.named_url_helpers) + yield end end end class MetalIntegrationTest < ActionController::IntegrationTest + include SharedTestRoutes.named_url_helpers + class Poller def self.call(env) if env["PATH_INFO"] =~ /^\/success/ diff --git a/railties/lib/rails/test_help.rb b/railties/lib/rails/test_help.rb index dbb1b76b95..5b5ce1dd7b 100644 --- a/railties/lib/rails/test_help.rb +++ b/railties/lib/rails/test_help.rb @@ -30,6 +30,10 @@ class ActionController::TestCase end end +class ActionDispatch::IntegrationTest + include Rails.application.routes.named_url_helpers +end + begin require_library_or_gem 'ruby-debug' Debugger.start -- cgit v1.2.3 From f863045c45fbbe5972f557c02b729441ffe81502 Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Thu, 25 Feb 2010 17:56:58 -0800 Subject: Rename metaclass to singleton_class --- actionpack/lib/action_dispatch/testing/assertions/routing.rb | 2 +- actionpack/test/controller/caching_test.rb | 2 +- actionpack/test/controller/integration_test.rb | 2 +- actionpack/test/controller/resources_test.rb | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb index 17caa2e030..5a3ff5a04c 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb @@ -147,7 +147,7 @@ module ActionDispatch # ROUTES TODO: Figure out this insanity silence_warnings { ::ActionController.const_set(:UrlFor, @router.named_url_helpers) } _router = @router - @controller.metaclass.send(:send, :include, @router.named_url_helpers) if @controller + @controller.singleton_class.send(:send, :include, @router.named_url_helpers) if @controller yield @router ensure @router = old_routes diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb index 9c9d886f5d..98cea945a7 100644 --- a/actionpack/test/controller/caching_test.rb +++ b/actionpack/test/controller/caching_test.rb @@ -512,7 +512,7 @@ class ActionCacheTest < ActionController::TestCase @response = ActionController::TestResponse.new @controller = ActionCachingTestController.new # ROUTES TODO: It seems bad to explicitly remix in the class - @controller.metaclass.send(:include, @router.named_url_helpers) + @controller.singleton_class.send(:include, @router.named_url_helpers) @request.host = 'hostname.com' end diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb index 1611a549fd..437d26e4ed 100644 --- a/actionpack/test/controller/integration_test.rb +++ b/actionpack/test/controller/integration_test.rb @@ -396,7 +396,7 @@ class IntegrationProcessTest < ActionController::IntegrationTest get 'get/:action', :to => controller end - self.metaclass.send(:include, set.named_url_helpers) + self.singleton_class.send(:include, set.named_url_helpers) yield end diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb index 6f3c16f588..b377e5bbbc 100644 --- a/actionpack/test/controller/resources_test.rb +++ b/actionpack/test/controller/resources_test.rb @@ -1231,7 +1231,7 @@ class ResourcesTest < ActionController::TestCase @controller = "#{options[:options][:controller].camelize}Controller".constantize.new # ROUTES TODO: Figure out a way to not extend the routing helpers here - @controller.metaclass.send(:include, @router.named_url_helpers) + @controller.singleton_class.send(:include, @router.named_url_helpers) @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new get :index, options[:options] @@ -1301,7 +1301,7 @@ class ResourcesTest < ActionController::TestCase def assert_singleton_named_routes_for(singleton_name, options = {}) (options[:options] ||= {})[:controller] ||= singleton_name.to_s.pluralize @controller = "#{options[:options][:controller].camelize}Controller".constantize.new - @controller.metaclass.send(:include, @router.named_url_helpers) + @controller.singleton_class.send(:include, @router.named_url_helpers) @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new get :show, options[:options] -- cgit v1.2.3 From b48beb6986ee3c533ccae6d54d70f3c28a80a942 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Fri, 26 Feb 2010 10:27:06 +0100 Subject: Add missing require on abstract_controller/collector [#4061 status:resolved] --- actionpack/lib/abstract_controller/collector.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/actionpack/lib/abstract_controller/collector.rb b/actionpack/lib/abstract_controller/collector.rb index d429333661..81fb514770 100644 --- a/actionpack/lib/abstract_controller/collector.rb +++ b/actionpack/lib/abstract_controller/collector.rb @@ -1,3 +1,5 @@ +require "action_dispatch/http/mime_type" + module AbstractController module Collector def self.generate_method_for_mime(mime) -- cgit v1.2.3 From 5893baa683e9b3c85c07d2811656be03765ebad7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Fri, 26 Feb 2010 10:44:53 +0100 Subject: Add autoload to generators modules and fix failing test. --- railties/lib/rails/generators.rb | 8 +++++++- railties/test/generators_test.rb | 8 ++++---- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/railties/lib/rails/generators.rb b/railties/lib/rails/generators.rb index f24dc620de..3c902ce0d4 100644 --- a/railties/lib/rails/generators.rb +++ b/railties/lib/rails/generators.rb @@ -10,10 +10,16 @@ require 'active_support/core_ext/module/attribute_accessors' require 'active_support/core_ext/string/inflections' require 'rails/generators/base' -require 'rails/generators/named_base' module Rails module Generators + autoload :Actions, 'rails/generators/actions' + autoload :ActiveModel, 'rails/generators/active_model' + autoload :Migration, 'rails/generators/migration' + autoload :NamedBase, 'rails/generators/named_base' + autoload :ResourceHelpers, 'rails/generators/resource_helpers' + autoload :TestCase, 'rails/generators/test_case' + DEFAULT_ALIASES = { :rails => { :actions => '-a', diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb index 07bc92c55c..dd17f8f756 100644 --- a/railties/test/generators_test.rb +++ b/railties/test/generators_test.rb @@ -145,17 +145,17 @@ class GeneratorsTest < Rails::Generators::TestCase end def test_developer_options_are_overwriten_by_user_options - Rails::Generators.options[:new_generator] = { :generate => false } + Rails::Generators.options[:with_options] = { :generate => false } self.class.class_eval <<-end_eval - class NewGenerator < Rails::Generators::Base + class WithOptionsGenerator < Rails::Generators::Base class_option :generate, :default => true end end_eval - assert_equal false, NewGenerator.class_options[:generate].default + assert_equal false, WithOptionsGenerator.class_options[:generate].default ensure - Rails::Generators.subclasses.delete(NewGenerator) + Rails::Generators.subclasses.delete(WithOptionsGenerator) end def test_load_generators_from_railties -- cgit v1.2.3 From 36a234609da3955464adf529e2b9dfb3bc572427 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Fri, 26 Feb 2010 10:51:13 +0100 Subject: Update thor dependency. --- railties/railties.gemspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/railties/railties.gemspec b/railties/railties.gemspec index 44475b82cf..c43bb7e1e9 100644 --- a/railties/railties.gemspec +++ b/railties/railties.gemspec @@ -21,7 +21,7 @@ Gem::Specification.new do |s| s.has_rdoc = false s.add_dependency('rake', '>= 0.8.3') - s.add_dependency('thor', '~> 0.13.3') + s.add_dependency('thor', '~> 0.13.4') s.add_dependency('activesupport', '= 3.0.0.beta1') s.add_dependency('actionpack', '= 3.0.0.beta1') end -- cgit v1.2.3 From 79c47abe6ce0bdcc81c35aa30da8a05c3650d04d Mon Sep 17 00:00:00 2001 From: Ramon Soares Date: Sun, 21 Feb 2010 20:49:54 -0300 Subject: the folder public/javascripts should be created by default [#4027 status:resolved] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- railties/lib/generators/rails/app/app_generator.rb | 7 +++++-- railties/test/generators/app_generator_test.rb | 1 + 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/railties/lib/generators/rails/app/app_generator.rb b/railties/lib/generators/rails/app/app_generator.rb index ea1930a966..92e0d37436 100644 --- a/railties/lib/generators/rails/app/app_generator.rb +++ b/railties/lib/generators/rails/app/app_generator.rb @@ -138,8 +138,11 @@ module Rails::Generators end def create_prototype_files - return if options[:skip_prototype] - directory "public/javascripts" + unless options[:skip_prototype] + directory "public/javascripts" + else + empty_directory_with_gitkeep "public/javascripts" + end end def create_script_files diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb index 01d643cd8c..412034029e 100644 --- a/railties/test/generators/app_generator_test.rb +++ b/railties/test/generators/app_generator_test.rb @@ -107,6 +107,7 @@ class AppGeneratorTest < Rails::Generators::TestCase def test_prototype_and_test_unit_are_skipped_if_required run_generator [destination_root, "--skip-prototype", "--skip-testunit"] assert_no_file "public/javascripts/prototype.js" + assert_file "public/javascripts" assert_no_file "test" end -- cgit v1.2.3 From bf9a0ae12b701cba7a8aac2955ce243866ac7bf6 Mon Sep 17 00:00:00 2001 From: Henry Hsu Date: Fri, 26 Feb 2010 11:06:55 +0100 Subject: Fix a bug where default_scope was overriding attributes given on model initialization [#3218 status:resolved] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- activerecord/lib/active_record/base.rb | 2 +- activerecord/test/cases/method_scoping_test.rb | 10 ++++++++++ activerecord/test/models/developer.rb | 5 +++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index 83f0b58e8a..c1c49c3d84 100755 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -1669,12 +1669,12 @@ module ActiveRecord #:nodoc: @attributes_cache = {} @new_record = true ensure_proper_type - self.attributes = attributes unless attributes.nil? if scope = self.class.send(:current_scoped_methods) create_with = scope.scope_for_create create_with.each { |att,value| self.send("#{att}=", value) } if create_with end + self.attributes = attributes unless attributes.nil? result = yield self if block_given? _run_initialize_callbacks diff --git a/activerecord/test/cases/method_scoping_test.rb b/activerecord/test/cases/method_scoping_test.rb index 1081aa40a9..3151457440 100644 --- a/activerecord/test/cases/method_scoping_test.rb +++ b/activerecord/test/cases/method_scoping_test.rb @@ -663,6 +663,16 @@ class DefaultScopingTest < ActiveRecord::TestCase assert_equal 2, posts.count assert_equal posts(:thinking), posts.first end + + def test_create_attribute_overwrites_default_scoping + assert_equal 'David', PoorDeveloperCalledJamis.create!(:name => 'David').name + assert_equal 200000, PoorDeveloperCalledJamis.create!(:name => 'David', :salary => 200000).salary + end + + def test_create_attribute_overwrites_default_values + assert_equal nil, PoorDeveloperCalledJamis.create!(:salary => nil).salary + assert_equal 50000, PoorDeveloperCalledJamis.create!(:name => 'David').salary + end end =begin diff --git a/activerecord/test/models/developer.rb b/activerecord/test/models/developer.rb index e7a1e110d7..e35de3b9b0 100644 --- a/activerecord/test/models/developer.rb +++ b/activerecord/test/models/developer.rb @@ -99,3 +99,8 @@ class DeveloperCalledJamis < ActiveRecord::Base self.table_name = 'developers' default_scope :conditions => { :name => 'Jamis' } end + +class PoorDeveloperCalledJamis < ActiveRecord::Base + self.table_name = 'developers' + default_scope :conditions => { :name => 'Jamis', :salary => 50000 } +end \ No newline at end of file -- cgit v1.2.3 From b56b9ee7d6807d8ea9e1575afb7a28e89980b348 Mon Sep 17 00:00:00 2001 From: Dr Nic Williams Date: Mon, 22 Feb 2010 22:43:54 +1000 Subject: #add_source: Fixed docco + added required newline to line added to Gemfile MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- railties/lib/rails/generators/actions.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/railties/lib/rails/generators/actions.rb b/railties/lib/rails/generators/actions.rb index e39fa3ff11..7dec4d446a 100644 --- a/railties/lib/rails/generators/actions.rb +++ b/railties/lib/rails/generators/actions.rb @@ -89,12 +89,12 @@ module Rails # # ==== Example # - # source "http://gems.github.com/" + # add_source "http://gems.github.com/" def add_source(source, options={}) log :source, source in_root do - prepend_file "Gemfile", "source #{source.inspect}", :verbose => false + prepend_file "Gemfile", "source #{source.inspect}\n", :verbose => false end end -- cgit v1.2.3 From 4db72b702f7faca7da30a64e45daeee13733762a Mon Sep 17 00:00:00 2001 From: Tobias Bielohlawek Date: Tue, 8 Sep 2009 15:51:56 +0200 Subject: fixed a 'RecordNotFound' bug when calling 'reload' on a object which doesn't met the default_scope conditions, added test [#3166 status:resolved] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The reload method didn't made use of 'with_exclusive_scope' when reloading the object. This lead to a RecordNotFound exception, in case the object doesn't met the default_scope condition (anymore) - which is obviously a bug. This quick fix makes use of with_exclusive_scope in the reload method as well. See test for full example. Signed-off-by: José Valim --- activerecord/lib/active_record/base.rb | 2 +- activerecord/test/cases/base_test.rb | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index c1c49c3d84..cd67490573 100755 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -1932,7 +1932,7 @@ module ActiveRecord #:nodoc: def reload(options = nil) clear_aggregation_cache clear_association_cache - @attributes.update(self.class.find(self.id, options).instance_variable_get('@attributes')) + @attributes.update(self.class.send(:with_exclusive_scope) { self.class.find(self.id, options) }.instance_variable_get('@attributes')) @attributes_cache = {} self end diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 2c4e1a3c0f..e3047fe873 100755 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -1723,6 +1723,12 @@ class BasicsTest < ActiveRecord::TestCase assert_equal t1.title, t2.title end + def test_reload_with_exclusive_scope + dev = DeveloperCalledDavid.first + dev.update_attributes!( :name => "NotDavid" ) + assert_equal dev, dev.reload + end + def test_define_attr_method_with_value k = Class.new( ActiveRecord::Base ) k.send(:define_attr_method, :table_name, "foo") -- cgit v1.2.3 From bd36418c512acb62c5515a6cbde79ce59dd67b46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Fri, 26 Feb 2010 11:51:21 +0100 Subject: Fix controller_path returnsing an empty string in Ruby 1.8.7 [#4036 status:resolved] --- actionpack/lib/abstract_controller.rb | 2 ++ actionpack/lib/abstract_controller/base.rb | 2 +- actionpack/lib/abstract_controller/helpers.rb | 3 --- actionpack/lib/abstract_controller/layouts.rb | 3 --- actionpack/lib/abstract_controller/logger.rb | 4 ++-- actionpack/lib/abstract_controller/rendering.rb | 4 +--- actionpack/test/controller/base_test.rb | 9 +++++++++ 7 files changed, 15 insertions(+), 12 deletions(-) diff --git a/actionpack/lib/abstract_controller.rb b/actionpack/lib/abstract_controller.rb index 1944e42ef1..c1b035306b 100644 --- a/actionpack/lib/abstract_controller.rb +++ b/actionpack/lib/abstract_controller.rb @@ -3,8 +3,10 @@ $:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.inc require 'active_support/ruby/shim' require 'active_support/dependencies/autoload' +require 'active_support/core_ext/class/attribute' require 'active_support/core_ext/module/attr_internal' require 'active_support/core_ext/module/delegation' +require 'active_support/core_ext/module/anonymous' module AbstractController extend ActiveSupport::Autoload diff --git a/actionpack/lib/abstract_controller/base.rb b/actionpack/lib/abstract_controller/base.rb index 3119ee498b..e14818e464 100644 --- a/actionpack/lib/abstract_controller/base.rb +++ b/actionpack/lib/abstract_controller/base.rb @@ -84,7 +84,7 @@ module AbstractController # ==== Returns # String def controller_path - @controller_path ||= name && name.sub(/Controller$/, '').underscore + @controller_path ||= name.sub(/Controller$/, '').underscore unless anonymous? end end diff --git a/actionpack/lib/abstract_controller/helpers.rb b/actionpack/lib/abstract_controller/helpers.rb index ca3a7550e5..f875213afb 100644 --- a/actionpack/lib/abstract_controller/helpers.rb +++ b/actionpack/lib/abstract_controller/helpers.rb @@ -1,7 +1,4 @@ require 'active_support/dependencies' -require 'active_support/core_ext/class/attribute' -require 'active_support/core_ext/module/delegation' -require 'active_support/core_ext/module/anonymous' module AbstractController module Helpers diff --git a/actionpack/lib/abstract_controller/layouts.rb b/actionpack/lib/abstract_controller/layouts.rb index 0d214396aa..beda4e633e 100644 --- a/actionpack/lib/abstract_controller/layouts.rb +++ b/actionpack/lib/abstract_controller/layouts.rb @@ -1,6 +1,3 @@ -require 'active_support/core_ext/class/attribute' -require 'active_support/core_ext/module/delegation' - module AbstractController # Layouts reverse the common pattern of including shared headers and footers in many templates to isolate changes in # repeated setups. The inclusion pattern has pages that look like this: diff --git a/actionpack/lib/abstract_controller/logger.rb b/actionpack/lib/abstract_controller/logger.rb index a23a13e1d6..9318f5e369 100644 --- a/actionpack/lib/abstract_controller/logger.rb +++ b/actionpack/lib/abstract_controller/logger.rb @@ -1,5 +1,5 @@ -require 'active_support/core_ext/logger' -require 'active_support/benchmarkable' +require "active_support/core_ext/logger" +require "active_support/benchmarkable" module AbstractController module Logger diff --git a/actionpack/lib/abstract_controller/rendering.rb b/actionpack/lib/abstract_controller/rendering.rb index 14f51ae1bf..32fdf821a7 100644 --- a/actionpack/lib/abstract_controller/rendering.rb +++ b/actionpack/lib/abstract_controller/rendering.rb @@ -1,7 +1,5 @@ require "abstract_controller/base" -require 'active_support/core_ext/class/attribute' -require 'active_support/core_ext/module/delegation' -require 'active_support/core_ext/array/wrap' +require "active_support/core_ext/array/wrap" module AbstractController class DoubleRenderError < Error diff --git a/actionpack/test/controller/base_test.rb b/actionpack/test/controller/base_test.rb index 436ee212c8..207dc63d57 100644 --- a/actionpack/test/controller/base_test.rb +++ b/actionpack/test/controller/base_test.rb @@ -113,6 +113,15 @@ class ControllerInstanceTests < Test::Unit::TestCase assert_equal Set.new(%w(public_action)), c.class.__send__(:action_methods), "#{c.controller_path} should not be empty!" end end + + def test_temporary_anonymous_controllers + name = 'ExamplesController' + klass = Class.new(ActionController::Base) + Object.const_set(name, klass) + + controller = klass.new + assert_equal "examples", controller.controller_path + end end class PerformActionTest < ActionController::TestCase -- cgit v1.2.3 From e6dffb70e6c1d524eeb5a40e1f8e01b067781143 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Fri, 26 Feb 2010 12:09:39 +0100 Subject: reload! on console now works as expected. [#3822 status:resolved] --- railties/lib/rails/console/app.rb | 2 +- railties/test/application/console_test.rb | 32 ++++++++++++++++++++++++++++--- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/railties/lib/rails/console/app.rb b/railties/lib/rails/console/app.rb index 7e8fd027e6..4524aca809 100644 --- a/railties/lib/rails/console/app.rb +++ b/railties/lib/rails/console/app.rb @@ -26,7 +26,7 @@ end # reloads the environment def reload!(print=true) puts "Reloading..." if print - ActionDispatch::Callbacks.new(lambda {}, false) + ActionDispatch::Callbacks.new(lambda {}, false).call({}) true end diff --git a/railties/test/application/console_test.rb b/railties/test/application/console_test.rb index 22ab60f4a0..8ff69f0208 100644 --- a/railties/test/application/console_test.rb +++ b/railties/test/application/console_test.rb @@ -6,7 +6,9 @@ class ConsoleTest < Test::Unit::TestCase def setup build_app boot_rails + end + def load_environment # Load steps taken from rails/commands/console.rb require "#{rails_root}/config/environment" require 'rails/console/app' @@ -14,18 +16,21 @@ class ConsoleTest < Test::Unit::TestCase end def test_app_method_should_return_integration_session + load_environment console_session = app assert_not_nil console_session assert_instance_of ActionController::Integration::Session, console_session end def test_new_session_should_return_integration_session + load_environment session = new_session assert_not_nil session assert_instance_of ActionController::Integration::Session, session end def test_reload_should_fire_preparation_callbacks + load_environment a = b = c = nil # TODO: These should be defined on the initializer @@ -34,16 +39,37 @@ class ConsoleTest < Test::Unit::TestCase ActionDispatch::Callbacks.to_prepare { c = 3 } # Hide Reloading... output - silence_stream(STDOUT) do - reload! - end + silence_stream(STDOUT) { reload! } assert_equal 1, a assert_equal 2, b assert_equal 3, c end + def test_reload_should_reload_constants + app_file "app/models/user.rb", <<-MODEL + class User + attr_accessor :name + end + MODEL + + load_environment + assert User.new.respond_to?(:name) + assert !User.new.respond_to?(:age) + + app_file "app/models/user.rb", <<-MODEL + class User + attr_accessor :name, :age + end + MODEL + + assert !User.new.respond_to?(:age) + silence_stream(STDOUT) { reload! } + assert User.new.respond_to?(:age) + end + def test_access_to_helpers + load_environment assert_not_nil helper assert_instance_of ActionView::Base, helper assert_equal 'Once upon a time in a world...', -- cgit v1.2.3 From e1daf3fb73bc2989397e6fbd52e7e526c13efb36 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Fri, 26 Feb 2010 08:09:09 -0800 Subject: Remove bin dir from .gitignore --- .gitignore | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index 9480b47d15..9d68f4860f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ +*.gem +pkg +.bundle debug.log doc/rdoc activemodel/doc @@ -16,7 +19,3 @@ railties/doc/guides/html/images railties/doc/guides/html/stylesheets railties/guides/output railties/tmp -bin -.bundle -pkg -*.gem \ No newline at end of file -- cgit v1.2.3 From 47260598bea29bd9c383f66d14c01505dff47d1b Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Fri, 26 Feb 2010 09:14:12 -0800 Subject: CI: restore sudo for bundler gem install --- ci/ci_build.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ci/ci_build.rb b/ci/ci_build.rb index e9fb91a6fd..a2df8e698d 100755 --- a/ci/ci_build.rb +++ b/ci/ci_build.rb @@ -19,7 +19,7 @@ puts "[CruiseControl] Rails build" build_results = {} # Install required version of bundler. -bundler_install_cmd = "gem install bundler -v 0.9.8 --no-ri --no-rdoc" +bundler_install_cmd = "sudo gem install bundler -v 0.9.8 --no-ri --no-rdoc" puts "Running command: #{bundler_install_cmd}" build_results[:install_bundler] = system bundler_install_cmd -- cgit v1.2.3 From 1e95f019bb0b2f1f37c5897562da691eb72c0f1c Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Fri, 26 Feb 2010 14:31:29 -0800 Subject: Fix 1.9 issue --- actionpack/lib/action_controller/railties/url_helpers.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actionpack/lib/action_controller/railties/url_helpers.rb b/actionpack/lib/action_controller/railties/url_helpers.rb index 354d3fa898..e726535a4f 100644 --- a/actionpack/lib/action_controller/railties/url_helpers.rb +++ b/actionpack/lib/action_controller/railties/url_helpers.rb @@ -4,7 +4,7 @@ module ActionController def self.with(router) Module.new do define_method(:inherited) do |klass| - super + super(klass) klass.send(:include, router.named_url_helpers) end end -- cgit v1.2.3 From b4b158ee100b88c84178095082959a07c2621870 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Fri, 26 Feb 2010 20:31:19 -0200 Subject: no more interpreted as grouped expression warnings on array_ext_test --- activesupport/test/core_ext/array_ext_test.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/activesupport/test/core_ext/array_ext_test.rb b/activesupport/test/core_ext/array_ext_test.rb index d4cd5ddbde..b374eca370 100644 --- a/activesupport/test/core_ext/array_ext_test.rb +++ b/activesupport/test/core_ext/array_ext_test.rb @@ -306,7 +306,7 @@ class ArrayUniqByTests < Test::Unit::TestCase def test_uniq_by assert_equal [1,2], [1,2,3,4].uniq_by { |i| i.odd? } assert_equal [1,2], [1,2,3,4].uniq_by(&:even?) - assert_equal (-5..0).to_a, (-5..5).to_a.uniq_by{ |i| i**2 } + assert_equal((-5..0).to_a, (-5..5).to_a.uniq_by{ |i| i**2 }) end def test_uniq_by! @@ -320,7 +320,7 @@ class ArrayUniqByTests < Test::Unit::TestCase a = (-5..5).to_a a.uniq_by! { |i| i**2 } - assert_equal (-5..0).to_a, a + assert_equal((-5..0).to_a, a) end end -- cgit v1.2.3 From b25c41e6d884372f7d70801f832e24dbff3e9077 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Fri, 26 Feb 2010 20:37:26 -0200 Subject: no more warning interpreted as argument prefix on association_preload.rb --- activerecord/lib/active_record/association_preload.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/association_preload.rb b/activerecord/lib/active_record/association_preload.rb index a5b06460fe..6725d4e88b 100644 --- a/activerecord/lib/active_record/association_preload.rb +++ b/activerecord/lib/active_record/association_preload.rb @@ -126,7 +126,7 @@ module ActiveRecord parent_records.each do |parent_record| association_proxy = parent_record.send(reflection_name) association_proxy.loaded - association_proxy.target.push *Array.wrap(associated_record) + association_proxy.target.push(*Array.wrap(associated_record)) association_proxy.__send__(:set_inverse_instance, associated_record, parent_record) end -- cgit v1.2.3 From f10a019452d6864420dd15830073d93dd90de0f1 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Fri, 26 Feb 2010 20:45:01 -0200 Subject: no more warning ambiguous first argument; put parentheses or even spaces on log_subscriber_test --- activeresource/test/cases/log_subscriber_test.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/activeresource/test/cases/log_subscriber_test.rb b/activeresource/test/cases/log_subscriber_test.rb index c25dd4ebc5..5df2cad599 100644 --- a/activeresource/test/cases/log_subscriber_test.rb +++ b/activeresource/test/cases/log_subscriber_test.rb @@ -27,6 +27,6 @@ class LogSubscriberTest < ActiveSupport::TestCase wait assert_equal 2, @logger.logged(:info).size assert_equal "GET http://37s.sunrise.i:3000/people/1.xml", @logger.logged(:info)[0] - assert_match /\-\-\> 200 200 106/, @logger.logged(:info)[1] + assert_match(/\-\-\> 200 200 106/, @logger.logged(:info)[1]) end -end \ No newline at end of file +end -- cgit v1.2.3 From 98f77e08278658ec47c9eb2e8f819d781c1eaebf Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Fri, 26 Feb 2010 15:00:33 -0800 Subject: Rename named_url_helpers to url_helpers and url_helpers to url_for --- actionmailer/lib/action_mailer/railtie.rb | 2 +- actionmailer/test/old_base/url_test.rb | 2 +- actionpack/lib/action_controller/metal/url_for.rb | 2 +- actionpack/lib/action_controller/railties/url_helpers.rb | 2 +- actionpack/lib/action_dispatch/routing/route_set.rb | 11 +++++------ actionpack/lib/action_dispatch/testing/assertions/routing.rb | 6 +++--- actionpack/test/abstract_unit.rb | 2 +- actionpack/test/activerecord/polymorphic_routes_test.rb | 6 +++--- actionpack/test/controller/caching_test.rb | 2 +- actionpack/test/controller/integration_test.rb | 8 ++++---- actionpack/test/controller/resources_test.rb | 4 ++-- actionpack/test/controller/routing_test.rb | 4 ++-- actionpack/test/dispatch/routing_test.rb | 2 +- railties/lib/rails/test_help.rb | 2 +- railties/test/rails_info_controller_test.rb | 2 +- 15 files changed, 28 insertions(+), 29 deletions(-) diff --git a/actionmailer/lib/action_mailer/railtie.rb b/actionmailer/lib/action_mailer/railtie.rb index 7622a90b17..c5f18c7911 100644 --- a/actionmailer/lib/action_mailer/railtie.rb +++ b/actionmailer/lib/action_mailer/railtie.rb @@ -6,7 +6,7 @@ module ActionMailer railtie_name :action_mailer initializer "action_mailer.url_for", :before => :load_environment_config do |app| - ActionMailer::Base.send(:include, app.routes.named_url_helpers) + ActionMailer::Base.send(:include, app.routes.url_helpers) end require "action_mailer/railties/log_subscriber" diff --git a/actionmailer/test/old_base/url_test.rb b/actionmailer/test/old_base/url_test.rb index 0e8917b427..a719248599 100644 --- a/actionmailer/test/old_base/url_test.rb +++ b/actionmailer/test/old_base/url_test.rb @@ -7,7 +7,7 @@ end AppRoutes = ActionDispatch::Routing::RouteSet.new class ActionMailer::Base - include AppRoutes.named_url_helpers + include AppRoutes.url_helpers end class TestMailer < ActionMailer::Base diff --git a/actionpack/lib/action_controller/metal/url_for.rb b/actionpack/lib/action_controller/metal/url_for.rb index 013834ddee..6748cb7bd4 100644 --- a/actionpack/lib/action_controller/metal/url_for.rb +++ b/actionpack/lib/action_controller/metal/url_for.rb @@ -15,7 +15,7 @@ module ActionController def _router raise "In order to use #url_for, you must include the helpers of a particular " \ - "router. For instance, `include Rails.application.router.named_url_helpers" + "router. For instance, `include Rails.application.routes.url_helpers" end end end \ No newline at end of file diff --git a/actionpack/lib/action_controller/railties/url_helpers.rb b/actionpack/lib/action_controller/railties/url_helpers.rb index e726535a4f..ad2a8d4ef3 100644 --- a/actionpack/lib/action_controller/railties/url_helpers.rb +++ b/actionpack/lib/action_controller/railties/url_helpers.rb @@ -5,7 +5,7 @@ module ActionController Module.new do define_method(:inherited) do |klass| super(klass) - klass.send(:include, router.named_url_helpers) + klass.send(:include, router.url_helpers) end end end diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 7bfe4fa2bf..47320883ac 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -259,9 +259,8 @@ module ActionDispatch named_routes.install(destinations, regenerate_code) end - # ROUTES TODO: Revisit the name of these methods - def url_helpers - @url_helpers ||= begin + def url_for + @url_for ||= begin router = self Module.new do extend ActiveSupport::Concern @@ -272,13 +271,13 @@ module ActionDispatch end end - def named_url_helpers - @named_url_helpers ||= begin + def url_helpers + @url_helpers ||= begin router = self Module.new do extend ActiveSupport::Concern - include router.url_helpers + include router.url_for # ROUTES TODO: install_helpers isn't great... can we make a module with the stuff that # we can include? diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb index 5a3ff5a04c..5a9a20cc5b 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb @@ -145,14 +145,14 @@ module ActionDispatch old_routes, @router = @router, ActionDispatch::Routing::RouteSet.new old_controller, @controller = @controller, @controller.clone if @controller # ROUTES TODO: Figure out this insanity - silence_warnings { ::ActionController.const_set(:UrlFor, @router.named_url_helpers) } + silence_warnings { ::ActionController.const_set(:UrlFor, @router.url_helpers) } _router = @router - @controller.singleton_class.send(:send, :include, @router.named_url_helpers) if @controller + @controller.singleton_class.send(:send, :include, @router.url_helpers) if @controller yield @router ensure @router = old_routes @controller = old_controller if @controller - silence_warnings { ::ActionController.const_set(:UrlFor, @router.named_url_helpers) } if @router + silence_warnings { ::ActionController.const_set(:UrlFor, @router.url_helpers) } if @router end def method_missing(selector, *args, &block) diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb index 846ac5f0d7..9960f7af87 100644 --- a/actionpack/test/abstract_unit.rb +++ b/actionpack/test/abstract_unit.rb @@ -256,7 +256,7 @@ end # ROUTES TODO: Cleaner way to do this? module ActionController - UrlFor = SharedTestRoutes.named_url_helpers + UrlFor = SharedTestRoutes.url_helpers class Base include UrlFor end diff --git a/actionpack/test/activerecord/polymorphic_routes_test.rb b/actionpack/test/activerecord/polymorphic_routes_test.rb index a10bb4473e..6e406ecd15 100644 --- a/actionpack/test/activerecord/polymorphic_routes_test.rb +++ b/actionpack/test/activerecord/polymorphic_routes_test.rb @@ -400,7 +400,7 @@ class PolymorphicRoutesTest < ActionController::TestCase map.resources :series end - self.class.send(:include, @router.named_url_helpers) + self.class.send(:include, @router.url_helpers) yield end end @@ -422,7 +422,7 @@ class PolymorphicRoutesTest < ActionController::TestCase end end - self.class.send(:include, @router.named_url_helpers) + self.class.send(:include, @router.url_helpers) yield end end @@ -441,7 +441,7 @@ class PolymorphicRoutesTest < ActionController::TestCase end end - self.class.send(:include, @router.named_url_helpers) + self.class.send(:include, @router.url_helpers) yield end end diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb index 98cea945a7..67b6a1d858 100644 --- a/actionpack/test/controller/caching_test.rb +++ b/actionpack/test/controller/caching_test.rb @@ -512,7 +512,7 @@ class ActionCacheTest < ActionController::TestCase @response = ActionController::TestResponse.new @controller = ActionCachingTestController.new # ROUTES TODO: It seems bad to explicitly remix in the class - @controller.singleton_class.send(:include, @router.named_url_helpers) + @controller.singleton_class.send(:include, @router.url_helpers) @request.host = 'hostname.com' end diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb index 437d26e4ed..5352243734 100644 --- a/actionpack/test/controller/integration_test.rb +++ b/actionpack/test/controller/integration_test.rb @@ -221,7 +221,7 @@ class IntegrationTestUsesCorrectClass < ActionController::IntegrationTest end class IntegrationProcessTest < ActionController::IntegrationTest - include SharedTestRoutes.named_url_helpers + include SharedTestRoutes.url_helpers class IntegrationController < ActionController::Base def get @@ -388,7 +388,7 @@ class IntegrationProcessTest < ActionController::IntegrationTest with_routing do |set| controller = ::IntegrationProcessTest::IntegrationController.clone controller.class_eval do - include set.named_url_helpers + include set.url_helpers end set.draw do |map| @@ -396,7 +396,7 @@ class IntegrationProcessTest < ActionController::IntegrationTest get 'get/:action', :to => controller end - self.singleton_class.send(:include, set.named_url_helpers) + self.singleton_class.send(:include, set.url_helpers) yield end @@ -404,7 +404,7 @@ class IntegrationProcessTest < ActionController::IntegrationTest end class MetalIntegrationTest < ActionController::IntegrationTest - include SharedTestRoutes.named_url_helpers + include SharedTestRoutes.url_helpers class Poller def self.call(env) diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb index b377e5bbbc..cf0cab3690 100644 --- a/actionpack/test/controller/resources_test.rb +++ b/actionpack/test/controller/resources_test.rb @@ -1231,7 +1231,7 @@ class ResourcesTest < ActionController::TestCase @controller = "#{options[:options][:controller].camelize}Controller".constantize.new # ROUTES TODO: Figure out a way to not extend the routing helpers here - @controller.singleton_class.send(:include, @router.named_url_helpers) + @controller.singleton_class.send(:include, @router.url_helpers) @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new get :index, options[:options] @@ -1301,7 +1301,7 @@ class ResourcesTest < ActionController::TestCase def assert_singleton_named_routes_for(singleton_name, options = {}) (options[:options] ||= {})[:controller] ||= singleton_name.to_s.pluralize @controller = "#{options[:options][:controller].camelize}Controller".constantize.new - @controller.singleton_class.send(:include, @router.named_url_helpers) + @controller.singleton_class.send(:include, @router.url_helpers) @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new get :show, options[:options] diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb index f2fccfbcfc..31f86d2dde 100644 --- a/actionpack/test/controller/routing_test.rb +++ b/actionpack/test/controller/routing_test.rb @@ -251,7 +251,7 @@ class LegacyRouteSetTests < Test::Unit::TestCase def setup_for_named_route inst = MockController.clone.new - inst.class.send(:include, rs.named_url_helpers) + inst.class.send(:include, rs.url_helpers) inst end @@ -741,7 +741,7 @@ class RouteSetTest < ActiveSupport::TestCase map.users '/admin/users', :controller => 'admin/users', :action => 'index' end - MockController.clone.new.tap { |inst| inst.class.send(:include, set.named_url_helpers)} + MockController.clone.new.tap { |inst| inst.class.send(:include, set.url_helpers)} end def test_named_route_hash_access_method diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb index 7cfc6ef3d7..37c2f1421b 100644 --- a/actionpack/test/dispatch/routing_test.rb +++ b/actionpack/test/dispatch/routing_test.rb @@ -164,7 +164,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest Routes end - include Routes.named_url_helpers + include Routes.url_helpers def test_logout with_test_routes do diff --git a/railties/lib/rails/test_help.rb b/railties/lib/rails/test_help.rb index 5b5ce1dd7b..06270f6c43 100644 --- a/railties/lib/rails/test_help.rb +++ b/railties/lib/rails/test_help.rb @@ -31,7 +31,7 @@ class ActionController::TestCase end class ActionDispatch::IntegrationTest - include Rails.application.routes.named_url_helpers + include Rails.application.routes.url_helpers end begin diff --git a/railties/test/rails_info_controller_test.rb b/railties/test/rails_info_controller_test.rb index 017e51326c..7275755130 100644 --- a/railties/test/rails_info_controller_test.rb +++ b/railties/test/rails_info_controller_test.rb @@ -20,7 +20,7 @@ class InfoControllerTest < ActionController::TestCase @controller.stubs(:consider_all_requests_local? => false, :local_request? => true) @router = Rails.application.routes - Rails::InfoController.send(:include, @router.named_url_helpers) + Rails::InfoController.send(:include, @router.url_helpers) end test "info controller does not allow remote requests" do -- cgit v1.2.3 From 224c0318bdbaea354bc5ab5c70b267b2a9c3d1c9 Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Fri, 26 Feb 2010 15:04:34 -0800 Subject: Remove the :use_defaults check in UrlFor#merge options --- actionpack/lib/action_dispatch/routing/url_for.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb index 1d6da817ed..7004c1aab3 100644 --- a/actionpack/lib/action_dispatch/routing/url_for.rb +++ b/actionpack/lib/action_dispatch/routing/url_for.rb @@ -104,7 +104,7 @@ module ActionDispatch end def merge_options(options) #:nodoc: - if options.delete(:use_defaults) != false && respond_to?(:default_url_options) && (defaults = default_url_options(options)) + if respond_to?(:default_url_options) && (defaults = default_url_options(options)) defaults.merge(options) else options -- cgit v1.2.3 From bae691f61ab8cf4a59adaee6406855e11d009c74 Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Fri, 26 Feb 2010 15:20:41 -0800 Subject: Change the API for setting global options for #url_for to self.url_options = { ... } This attr_accessor can be set in a before filter or in the action itself. Overwriting default_url_options still works but will output a deprecation notice. --- actionpack/lib/action_controller/metal/url_for.rb | 2 +- actionpack/lib/action_controller/test_case.rb | 2 +- actionpack/lib/action_dispatch/routing/url_for.rb | 34 +++++++++++++++------- .../lib/action_dispatch/testing/integration.rb | 2 +- 4 files changed, 26 insertions(+), 14 deletions(-) diff --git a/actionpack/lib/action_controller/metal/url_for.rb b/actionpack/lib/action_controller/metal/url_for.rb index 6748cb7bd4..8a06f34d23 100644 --- a/actionpack/lib/action_controller/metal/url_for.rb +++ b/actionpack/lib/action_controller/metal/url_for.rb @@ -5,7 +5,7 @@ module ActionController include ActionDispatch::Routing::UrlFor include ActionController::RackDelegation - def merge_options(options) + def url_options super.reverse_merge( :host => request.host_with_port, :protocol => request.protocol, diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb index 0fa2a8b90c..64d9bdab2a 100644 --- a/actionpack/lib/action_controller/test_case.rb +++ b/actionpack/lib/action_controller/test_case.rb @@ -336,7 +336,7 @@ module ActionController private def build_request_uri(action, parameters) unless @request.env['REQUEST_URI'] - options = @controller.__send__(:merge_options, parameters) + options = @controller.__send__(:url_options).merge(parameters) options.update(:only_path => true, :action => action) url = ActionController::UrlRewriter.new(@request, parameters) diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb index 7004c1aab3..d467929561 100644 --- a/actionpack/lib/action_dispatch/routing/url_for.rb +++ b/actionpack/lib/action_dispatch/routing/url_for.rb @@ -95,22 +95,26 @@ module ActionDispatch self.default_url_options = {} end - def default_url_options(options = nil) - self.class.default_url_options - end + # def default_url_options(options = nil) + # self.class.default_url_options + # end def url_options - self.class.default_url_options.merge + self.class.default_url_options.merge(@url_options || {}) end - def merge_options(options) #:nodoc: - if respond_to?(:default_url_options) && (defaults = default_url_options(options)) - defaults.merge(options) - else - options - end + def url_options=(options) + @url_options = options end + # def merge_options(options) #:nodoc: + # if respond_to?(:default_url_options) && (defaults = default_url_options(options)) + # defaults.merge(options) + # else + # options + # end + # end + # Generate a url based on the options provided, default_url_options and the # routes defined in routes.rb. The following options are supported: # @@ -140,7 +144,15 @@ module ActionDispatch when String options when Hash - ActionController::UrlRewriter.rewrite(_router, merge_options(options)) + # Handle the deprecated instance level default_url_options + if respond_to?(:default_url_options, true) + ActiveSupport::Deprecation.warn "Overwriting #default_url_options is deprecated. Please set url options with self.url_options = { ... }" + if defaults = default_url_options(options) + options = defaults.merge(options) + end + end + + ActionController::UrlRewriter.rewrite(_router, url_options.merge(options)) else polymorphic_url(options) end diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index fb067601c8..0bad9c37d6 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -357,7 +357,7 @@ module ActionDispatch extend ActiveSupport::Concern include ActionDispatch::Routing::UrlFor - def merge_options(options) + def url_options opts = super.reverse_merge( :host => host, :protocol => https? ? "https" : "http" -- cgit v1.2.3 From 47fe14bfcc553acfd4c44434636529f25054a751 Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Fri, 26 Feb 2010 15:34:12 -0800 Subject: Silence test deprecation warnings --- actionpack/test/controller/base_test.rb | 71 ++++++++++++++++++++++------- actionpack/test/template/url_helper_test.rb | 2 +- 2 files changed, 56 insertions(+), 17 deletions(-) diff --git a/actionpack/test/controller/base_test.rb b/actionpack/test/controller/base_test.rb index 207dc63d57..ade9a7fcba 100644 --- a/actionpack/test/controller/base_test.rb +++ b/actionpack/test/controller/base_test.rb @@ -66,6 +66,16 @@ class DefaultUrlOptionsController < ActionController::Base end end +class UrlOptionsController < ActionController::Base + def from_view + render :inline => "<%= #{params[:route]} %>" + end + + def url_options + super.merge(:host => 'www.override.com', :action => 'new', :locale => 'en') + end +end + class ControllerClassTests < ActiveSupport::TestCase def test_controller_path assert_equal 'empty', EmptyController.controller_path @@ -162,8 +172,8 @@ class PerformActionTest < ActionController::TestCase end end -class DefaultUrlOptionsTest < ActionController::TestCase - tests DefaultUrlOptionsController +class UrlOptionsTest < ActionController::TestCase + tests UrlOptionsController def setup super @@ -174,7 +184,7 @@ class DefaultUrlOptionsTest < ActionController::TestCase def test_default_url_options_are_used_if_set with_routing do |set| set.draw do |map| - match 'from_view', :to => 'default_url_options#from_view', :as => :from_view + match 'from_view', :to => 'url_options#from_view', :as => :from_view match ':controller/:action' end @@ -184,6 +194,33 @@ class DefaultUrlOptionsTest < ActionController::TestCase assert_equal 'http://www.override.com/from_view?locale=en', @controller.send(:from_view_url) assert_equal 'http://www.override.com/default_url_options/new?locale=en', @controller.url_for(:controller => 'default_url_options') end + end +end + +class DefaultUrlOptionsTest < ActionController::TestCase + tests DefaultUrlOptionsController + + def setup + super + @request.host = 'www.example.com' + rescue_action_in_public! + end + + def test_default_url_options_are_used_if_set + with_routing do |set| + set.draw do |map| + match 'from_view', :to => 'default_url_options#from_view', :as => :from_view + match ':controller/:action' + end + + assert_deprecated do + get :from_view, :route => "from_view_url" + + assert_equal 'http://www.override.com/from_view?locale=en', @response.body + assert_equal 'http://www.override.com/from_view?locale=en', @controller.send(:from_view_url) + assert_equal 'http://www.override.com/default_url_options/new?locale=en', @controller.url_for(:controller => 'default_url_options') + end + end end def test_default_url_options_are_used_in_non_positional_parameters @@ -195,19 +232,21 @@ class DefaultUrlOptionsTest < ActionController::TestCase match ':controller/:action' end - get :from_view, :route => "description_path(1)" - - assert_equal '/en/descriptions/1', @response.body - assert_equal '/en/descriptions', @controller.send(:descriptions_path) - assert_equal '/pl/descriptions', @controller.send(:descriptions_path, "pl") - assert_equal '/pl/descriptions', @controller.send(:descriptions_path, :locale => "pl") - assert_equal '/pl/descriptions.xml', @controller.send(:descriptions_path, "pl", "xml") - assert_equal '/en/descriptions.xml', @controller.send(:descriptions_path, :format => "xml") - assert_equal '/en/descriptions/1', @controller.send(:description_path, 1) - assert_equal '/pl/descriptions/1', @controller.send(:description_path, "pl", 1) - assert_equal '/pl/descriptions/1', @controller.send(:description_path, 1, :locale => "pl") - assert_equal '/pl/descriptions/1.xml', @controller.send(:description_path, "pl", 1, "xml") - assert_equal '/en/descriptions/1.xml', @controller.send(:description_path, 1, :format => "xml") + assert_deprecated do + get :from_view, :route => "description_path(1)" + + assert_equal '/en/descriptions/1', @response.body + assert_equal '/en/descriptions', @controller.send(:descriptions_path) + assert_equal '/pl/descriptions', @controller.send(:descriptions_path, "pl") + assert_equal '/pl/descriptions', @controller.send(:descriptions_path, :locale => "pl") + assert_equal '/pl/descriptions.xml', @controller.send(:descriptions_path, "pl", "xml") + assert_equal '/en/descriptions.xml', @controller.send(:descriptions_path, :format => "xml") + assert_equal '/en/descriptions/1', @controller.send(:description_path, 1) + assert_equal '/pl/descriptions/1', @controller.send(:description_path, "pl", 1) + assert_equal '/pl/descriptions/1', @controller.send(:description_path, 1, :locale => "pl") + assert_equal '/pl/descriptions/1.xml', @controller.send(:description_path, "pl", 1, "xml") + assert_equal '/en/descriptions/1.xml', @controller.send(:description_path, 1, :format => "xml") + end end end diff --git a/actionpack/test/template/url_helper_test.rb b/actionpack/test/template/url_helper_test.rb index c917ca9d2b..b047466aaf 100644 --- a/actionpack/test/template/url_helper_test.rb +++ b/actionpack/test/template/url_helper_test.rb @@ -426,7 +426,7 @@ class UrlHelperControllerTest < ActionController::TestCase end with_url_helper_routing do - get :show_named_route, :kind => 'url' + assert_deprecated { get :show_named_route, :kind => 'url' } assert_equal 'http://testtwo.host/url_helper_controller_test/url_helper/show_named_route', @response.body end end -- cgit v1.2.3 From 5797575bac580037e4a9ee686a8bcb7e56b65235 Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Fri, 26 Feb 2010 15:40:36 -0800 Subject: Stop setting UrlFor using SharedTestHelpers --- actionpack/test/abstract_unit.rb | 6 +++--- actionpack/test/activerecord/polymorphic_routes_test.rb | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb index 9960f7af87..e0acbdd430 100644 --- a/actionpack/test/abstract_unit.rb +++ b/actionpack/test/abstract_unit.rb @@ -254,10 +254,10 @@ module ActionController end end -# ROUTES TODO: Cleaner way to do this? +# This stub emulates the Railtie including the URL helpers from a Rails application module ActionController - UrlFor = SharedTestRoutes.url_helpers class Base - include UrlFor + # ROUTES TODO: Rename SharedTestRoutes to something that reflects it's a standin for Rails.application + include SharedTestRoutes.url_helpers end end \ No newline at end of file diff --git a/actionpack/test/activerecord/polymorphic_routes_test.rb b/actionpack/test/activerecord/polymorphic_routes_test.rb index 6e406ecd15..5643ad5ad6 100644 --- a/actionpack/test/activerecord/polymorphic_routes_test.rb +++ b/actionpack/test/activerecord/polymorphic_routes_test.rb @@ -26,7 +26,7 @@ class Series < ActiveRecord::Base end class PolymorphicRoutesTest < ActionController::TestCase - include ActionController::UrlFor + include SharedTestRoutes.url_helpers self.default_url_options[:host] = 'example.com' def setup -- cgit v1.2.3 From 3bad24c85d973295df55a04272a4e1829eab4685 Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Fri, 26 Feb 2010 15:44:22 -0800 Subject: Remove traces of SharedTestRoutes from user code; leave it as a standin for Rails.application.routes in Rails internal tests --- actionpack/lib/action_controller/railtie.rb | 1 - actionpack/lib/action_dispatch/testing/integration.rb | 12 ------------ actionpack/test/abstract_unit.rb | 1 - 3 files changed, 14 deletions(-) diff --git a/actionpack/lib/action_controller/railtie.rb b/actionpack/lib/action_controller/railtie.rb index 268301da64..69ee4b04ec 100644 --- a/actionpack/lib/action_controller/railtie.rb +++ b/actionpack/lib/action_controller/railtie.rb @@ -33,7 +33,6 @@ module ActionController initializer "action_controller.url_helpers" do |app| ActionController::Base.extend ::ActionController::Railtie::UrlHelpers.with(app.routes) ActionController::Routing::Routes = app.routes - ::SharedTestRoutes = app.routes end end end \ No newline at end of file diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index 0bad9c37d6..88667d3570 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -219,18 +219,6 @@ module ActionDispatch @host = name end - # # Returns the URL for the given options, according to the rules specified - # # in the application's routes. - # def url_for(options) - # # ROUTES TODO: @app.router is not guaranteed to exist, so a generic Rack - # # application will not work here. This means that a generic Rack application - # # integration test cannot call url_for, since the application will not have - # # #router on it. - # controller ? - # controller.url_for(options) : - # generic_url_rewriter.rewrite(SharedTestRoutes, options) - # end - private # Performs the actual request. diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb index e0acbdd430..1213c9d99f 100644 --- a/actionpack/test/abstract_unit.rb +++ b/actionpack/test/abstract_unit.rb @@ -257,7 +257,6 @@ end # This stub emulates the Railtie including the URL helpers from a Rails application module ActionController class Base - # ROUTES TODO: Rename SharedTestRoutes to something that reflects it's a standin for Rails.application include SharedTestRoutes.url_helpers end end \ No newline at end of file -- cgit v1.2.3 From dae109a4632af702b8556ecf029a27d91476848b Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Fri, 26 Feb 2010 15:56:17 -0800 Subject: Including UrlFor in Redirecting and Head will warn usefully if a controller is wired up without a router included (and still support redirect_to "omg") --- actionpack/lib/action_controller/metal/head.rb | 5 ++--- actionpack/lib/action_controller/metal/redirecting.rb | 4 +--- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/actionpack/lib/action_controller/metal/head.rb b/actionpack/lib/action_controller/metal/head.rb index fe6e6186a5..a5c9910d68 100644 --- a/actionpack/lib/action_controller/metal/head.rb +++ b/actionpack/lib/action_controller/metal/head.rb @@ -2,6 +2,8 @@ module ActionController module Head extend ActiveSupport::Concern + include ActionController::UrlFor + # Return a response that has no content (merely headers). The options # argument is interpreted to be a hash of header names and values. # This allows you to easily return a response that consists only of @@ -24,9 +26,6 @@ module ActionController end self.status = status - # ROUTES TODO: Figure out how to rescue from a no method error - # This is needed only if you wire up a controller yourself, and - # this not working would be baffling without a better error self.location = url_for(location) if location self.content_type = Mime[formats.first] self.response_body = " " diff --git a/actionpack/lib/action_controller/metal/redirecting.rb b/actionpack/lib/action_controller/metal/redirecting.rb index de40ea77b1..25e4e18493 100644 --- a/actionpack/lib/action_controller/metal/redirecting.rb +++ b/actionpack/lib/action_controller/metal/redirecting.rb @@ -12,6 +12,7 @@ module ActionController include AbstractController::Logger include ActionController::RackDelegation + include ActionController::UrlFor # Redirects the browser to the target specified in +options+. This parameter can take one of three forms: # @@ -83,9 +84,6 @@ module ActionController raise RedirectBackError unless refer = request.headers["Referer"] refer else - # ROUTES TODO: Figure out how to rescue from a no method error - # This is needed only if you wire up a controller yourself, and - # this not working would be baffling without a better error url_for(options) end.gsub(/[\r\n]/, '') end -- cgit v1.2.3 From ab0cc7286fdaed96ff03bf8a160ccc75c3a2916d Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Fri, 26 Feb 2010 15:56:38 -0800 Subject: Setting UrlFor in with_routing is no longer needed now that it's not global --- actionpack/lib/action_dispatch/testing/assertions/routing.rb | 3 --- actionpack/test/controller/url_for_test.rb | 9 +++++---- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb index 5a9a20cc5b..726da2ee07 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb @@ -144,15 +144,12 @@ module ActionDispatch def with_routing old_routes, @router = @router, ActionDispatch::Routing::RouteSet.new old_controller, @controller = @controller, @controller.clone if @controller - # ROUTES TODO: Figure out this insanity - silence_warnings { ::ActionController.const_set(:UrlFor, @router.url_helpers) } _router = @router @controller.singleton_class.send(:send, :include, @router.url_helpers) if @controller yield @router ensure @router = old_routes @controller = old_controller if @controller - silence_warnings { ::ActionController.const_set(:UrlFor, @router.url_helpers) } if @router end def method_missing(selector, *args, &block) diff --git a/actionpack/test/controller/url_for_test.rb b/actionpack/test/controller/url_for_test.rb index 43e2f91693..a7b77edc6e 100644 --- a/actionpack/test/controller/url_for_test.rb +++ b/actionpack/test/controller/url_for_test.rb @@ -132,7 +132,8 @@ module AbstractController end # We need to create a new class in order to install the new named route. - kls = Class.new { include ActionController::UrlFor } + kls = Class.new { include set.url_helpers } + controller = kls.new assert controller.respond_to?(:home_url) assert_equal 'http://www.basecamphq.com/home/sweet/home/again', @@ -153,7 +154,7 @@ module AbstractController match '/home/sweet/home/:user', :to => 'home#index', :as => :home end - kls = Class.new { include ActionController::UrlFor } + kls = Class.new { include set.url_helpers } controller = kls.new assert_equal 'http://www.basecamphq.com/subdir/home/sweet/home/again', @@ -171,7 +172,7 @@ module AbstractController end # We need to create a new class in order to install the new named route. - kls = Class.new { include ActionController::UrlFor } + kls = Class.new { include set.url_helpers } controller = kls.new assert controller.respond_to?(:home_url) assert_equal '/brave/new/world', @@ -239,7 +240,7 @@ module AbstractController end # We need to create a new class in order to install the new named route. - kls = Class.new { include ActionController::UrlFor } + kls = Class.new { include set.url_helpers } kls.default_url_options[:host] = 'www.basecamphq.com' controller = kls.new -- cgit v1.2.3 From 74df7795a836862df503aa23eda403c15b22ca3b Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Fri, 26 Feb 2010 15:58:24 -0800 Subject: Relatively speaking, it's not actually that bad... --- actionpack/test/abstract_unit.rb | 2 -- 1 file changed, 2 deletions(-) diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb index 1213c9d99f..b09980cbba 100644 --- a/actionpack/test/abstract_unit.rb +++ b/actionpack/test/abstract_unit.rb @@ -76,8 +76,6 @@ module ActiveSupport match ':controller(/:action(/:id))' end - # ROUTES TODO: Don't do this here - # brodel :'( ActionController::IntegrationTest.app.router.draw do match ':controller(/:action(/:id))' end -- cgit v1.2.3 From be0bf10a3cf5783f8859f73659c5fe3c16bd1ccd Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Fri, 26 Feb 2010 16:06:54 -0800 Subject: Upon further reflection, we realized that SharedTestRoutes is not really a hack, but is instead a standin (in the Rails tests) for Rails.application.routes. * In a real application, action_controller/railties.rb does AC::Base.include(app.routes.url_helpers) * ActionController itself does not know about Rails.application, but instead can have named routes for any router * SharedTestRoutes are created in abstract_unit to stand in for Rails.application.routes, and is used in internal functional tests --- actionpack/test/abstract_unit.rb | 1 - 1 file changed, 1 deletion(-) diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb index b09980cbba..c95673d97e 100644 --- a/actionpack/test/abstract_unit.rb +++ b/actionpack/test/abstract_unit.rb @@ -205,7 +205,6 @@ module ActionController include ActionDispatch::TestProcess setup do - # ROUTES TODO: The router object should come from somewhere sane @router = SharedTestRoutes end -- cgit v1.2.3 From 6324eeefd7d1dd7b628afdcf436649062d12bbab Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Fri, 26 Feb 2010 13:29:44 -0800 Subject: plugin rails/init.rb deprecation message --- railties/lib/rails/engine.rb | 6 +++--- railties/lib/rails/plugin.rb | 26 ++++++++++++++------------ 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb index 479d753614..b6ac48768d 100644 --- a/railties/lib/rails/engine.rb +++ b/railties/lib/rails/engine.rb @@ -95,8 +95,8 @@ module Rails initializer :add_view_paths do views = paths.app.views.to_a - ActionController::Base.view_paths.unshift(*views) if defined?(ActionController) - ActionMailer::Base.view_paths.unshift(*views) if defined?(ActionMailer) + ActionController::Base.prepend_view_path(views) if defined?(ActionController) + ActionMailer::Base.prepend_view_path(views) if defined?(ActionMailer) end initializer :add_metals do |app| @@ -132,4 +132,4 @@ module Rails app.config.reload_engines end end -end \ No newline at end of file +end diff --git a/railties/lib/rails/plugin.rb b/railties/lib/rails/plugin.rb index 0bc3991b33..98f329cc17 100644 --- a/railties/lib/rails/plugin.rb +++ b/railties/lib/rails/plugin.rb @@ -26,11 +26,14 @@ module Rails def load_tasks super - extra_tasks = Dir["#{root}/{tasks,rails/tasks}/**/*.rake"] + load_deprecated_tasks + end - unless extra_tasks.empty? - ActiveSupport::Deprecation.warn "Rake tasks in #{extra_tasks.to_sentence} are deprecated. Use lib/tasks instead" - extra_tasks.sort.each { |ext| load(ext) } + def load_deprecated_tasks + tasks = Dir["#{root}/{tasks,rails/tasks}/**/*.rake"].sort + if tasks.any? + ActiveSupport::Deprecation.warn "Rake tasks in #{tasks.to_sentence} are deprecated. Use lib/tasks instead" + tasks.each { |ext| load(ext) } end end @@ -44,15 +47,14 @@ module Rails end initializer :load_init_rb, :before => :load_application_initializers do |app| - if File.file?(file = File.expand_path("rails/init.rb", root)) - ActiveSupport::Deprecation.warn "PLUGIN_PATH/rails/init.rb in plugins is deprecated. " << - "Use PLUGIN_PATH/init.rb instead" - else - file = File.expand_path("init.rb", root) + files = %w(rails/init.rb init.rb).map { |path| File.expand_path path, root } + if initrb = files.find { |path| File.file? path } + if initrb == files.first + ActiveSupport::Deprecation.warn "Use toplevel init.rb; rails/init.rb is deprecated: #{initrb}" + end + config = app.config + eval(File.read(initrb), binding, initrb) end - - config = app.config - eval(File.read(file), binding, file) if file && File.file?(file) end initializer :sanity_check_railties_collision do -- cgit v1.2.3 From 050831803a9e553ba392a73732b00528dfa8c6ad Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Fri, 26 Feb 2010 17:18:29 -0800 Subject: If IntegrationSession is initialized with an objects that responds to #routes, automatically extend the URL helpers from the RouteSet onto it --- .../lib/action_dispatch/routing/route_set.rb | 1 - .../lib/action_dispatch/testing/integration.rb | 28 ++++++++++++++++------ actionpack/test/abstract_unit.rb | 1 + actionpack/test/controller/caching_test.rb | 1 - actionpack/test/controller/integration_test.rb | 6 ++--- actionpack/test/controller/resources_test.rb | 1 - 6 files changed, 24 insertions(+), 14 deletions(-) diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 47320883ac..6bc4303be3 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -203,7 +203,6 @@ module ActionDispatch url_for(options) end - protected :#{selector} END_EVAL helpers << selector end diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index 88667d3570..0aff4250c1 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -162,12 +162,31 @@ module ActionDispatch # A running counter of the number of requests processed. attr_accessor :request_count + include ActionDispatch::Routing::UrlFor + # Create and initialize a new Session instance. def initialize(app) @app = app + + # If the app is a Rails app, make url_helpers available on the session + # This makes app.url_for and app.foo_path available in the console + if app.respond_to?(:routes) && app.routes.respond_to?(:url_helpers) + singleton_class.class_eval { include app.routes.url_helpers } + end + reset! end + def url_options + opts = super.reverse_merge( + :host => host, + :protocol => https? ? "https" : "http" + ) + + opts.merge!(:port => 443) if !opts.key?(:port) && https? + opts + end + # Resets the instance. This can be used to reset the state information # in an existing session instance, so it can be used from a clean-slate # condition. @@ -346,13 +365,8 @@ module ActionDispatch include ActionDispatch::Routing::UrlFor def url_options - opts = super.reverse_merge( - :host => host, - :protocol => https? ? "https" : "http" - ) - - opts.merge!(:port => 443) if !opts.key?(:port) && https? - opts + reset! unless @integration_session + @integration_session.url_options end # Delegate unhandled messages to the current session instance. diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb index c95673d97e..c178dc481c 100644 --- a/actionpack/test/abstract_unit.rb +++ b/actionpack/test/abstract_unit.rb @@ -85,6 +85,7 @@ end class RoutedRackApp attr_reader :router + alias routes router def initialize(router, &blk) @router = router diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb index 67b6a1d858..80c968cc04 100644 --- a/actionpack/test/controller/caching_test.rb +++ b/actionpack/test/controller/caching_test.rb @@ -511,7 +511,6 @@ class ActionCacheTest < ActionController::TestCase @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new @controller = ActionCachingTestController.new - # ROUTES TODO: It seems bad to explicitly remix in the class @controller.singleton_class.send(:include, @router.url_helpers) @request.host = 'hostname.com' end diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb index 5352243734..c38348fa68 100644 --- a/actionpack/test/controller/integration_test.rb +++ b/actionpack/test/controller/integration_test.rb @@ -178,8 +178,8 @@ class IntegrationTestTest < Test::Unit::TestCase session1 = @test.open_session { |sess| } session2 = @test.open_session # implicit session - assert_equal ::ActionController::Integration::Session, session1.class - assert_equal ::ActionController::Integration::Session, session2.class + assert_kind_of ::ActionController::Integration::Session, session1 + assert_kind_of ::ActionController::Integration::Session, session2 assert_not_equal session1, session2 end @@ -221,8 +221,6 @@ class IntegrationTestUsesCorrectClass < ActionController::IntegrationTest end class IntegrationProcessTest < ActionController::IntegrationTest - include SharedTestRoutes.url_helpers - class IntegrationController < ActionController::Base def get respond_to do |format| diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb index cf0cab3690..f60045bba6 100644 --- a/actionpack/test/controller/resources_test.rb +++ b/actionpack/test/controller/resources_test.rb @@ -1230,7 +1230,6 @@ class ResourcesTest < ActionController::TestCase end @controller = "#{options[:options][:controller].camelize}Controller".constantize.new - # ROUTES TODO: Figure out a way to not extend the routing helpers here @controller.singleton_class.send(:include, @router.url_helpers) @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new -- cgit v1.2.3 From 8689989a52fb673650c45322f060093678c6b91e Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Fri, 26 Feb 2010 17:31:32 -0800 Subject: Make ActionController::Routing::Routes a DeprecatedProxy --- actionpack/lib/action_controller/deprecated.rb | 2 -- actionpack/lib/action_controller/railtie.rb | 8 +++++++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/actionpack/lib/action_controller/deprecated.rb b/actionpack/lib/action_controller/deprecated.rb index 6088d97abe..9f2de57033 100644 --- a/actionpack/lib/action_controller/deprecated.rb +++ b/actionpack/lib/action_controller/deprecated.rb @@ -1,5 +1,3 @@ ActionController::AbstractRequest = ActionController::Request = ActionDispatch::Request ActionController::AbstractResponse = ActionController::Response = ActionDispatch::Response ActionController::Routing = ActionDispatch::Routing -# ROUTES TODO: Figure out how to deprecate this. -# ActionController::UrlWriter = ActionController::UrlFor diff --git a/actionpack/lib/action_controller/railtie.rb b/actionpack/lib/action_controller/railtie.rb index 69ee4b04ec..07c6b8f2b6 100644 --- a/actionpack/lib/action_controller/railtie.rb +++ b/actionpack/lib/action_controller/railtie.rb @@ -2,6 +2,7 @@ require "rails" require "action_controller" require "action_view/railtie" require "active_support/core_ext/class/subclasses" +require "active_support/deprecation/proxy_wrappers" module ActionController class Railtie < Rails::Railtie @@ -32,7 +33,12 @@ module ActionController initializer "action_controller.url_helpers" do |app| ActionController::Base.extend ::ActionController::Railtie::UrlHelpers.with(app.routes) - ActionController::Routing::Routes = app.routes + + message = "ActionController::Routing::Routes is deprecated. " \ + "Instead, use Rails.application.routes" + + proxy = ActiveSupport::Deprecation::DeprecatedObjectProxy.new(app.routes, message) + ActionController::Routing::Routes = proxy end end end \ No newline at end of file -- cgit v1.2.3 From faf3c2f827e786bc06ea143b80bb98c9a1e18304 Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Fri, 26 Feb 2010 18:24:55 -0800 Subject: Set the body using the accessor for AD::Response introspection mode so it gets wrapped in a [] --- actionpack/lib/action_dispatch/http/response.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb index e6ed28742f..9cfe5a5ea9 100644 --- a/actionpack/lib/action_dispatch/http/response.rb +++ b/actionpack/lib/action_dispatch/http/response.rb @@ -43,7 +43,8 @@ module ActionDispatch # :nodoc: @block = nil @length = 0 - @status, @header, @body = status, header, body + @status, @header = status, header + self.body = body @cookie = [] @sending_file = false -- cgit v1.2.3 From 4bdc783d37b82b739c5ddcc828d3a253873f6629 Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Fri, 26 Feb 2010 18:25:56 -0800 Subject: 1.9 seems to have a bug involving cloned classes and super. Fix it by not cloning (and instead creating classes on demand). The 1.9 bug should be investigated. --- actionpack/test/controller/routing_test.rb | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb index 31f86d2dde..fc85b01394 100644 --- a/actionpack/test/controller/routing_test.rb +++ b/actionpack/test/controller/routing_test.rb @@ -52,11 +52,17 @@ class UriReservedCharactersRoutingTest < Test::Unit::TestCase end class MockController - def url_for(options) - options[:protocol] ||= "http" - options[:host] ||= "test.host" + def self.build(helpers) + Class.new do + def url_for(options) + options[:protocol] ||= "http" + options[:host] ||= "test.host" - super(options) + super(options) + end + + include helpers + end end end @@ -250,9 +256,7 @@ class LegacyRouteSetTests < Test::Unit::TestCase end def setup_for_named_route - inst = MockController.clone.new - inst.class.send(:include, rs.url_helpers) - inst + MockController.build(rs.url_helpers).new end def test_named_route_without_hash @@ -741,7 +745,7 @@ class RouteSetTest < ActiveSupport::TestCase map.users '/admin/users', :controller => 'admin/users', :action => 'index' end - MockController.clone.new.tap { |inst| inst.class.send(:include, set.url_helpers)} + MockController.build(set.url_helpers).new end def test_named_route_hash_access_method -- cgit v1.2.3 From 3f0ed205e721008759297909f1f224ebd58c6673 Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Fri, 26 Feb 2010 22:47:36 -0800 Subject: Remind us that RoutingAssertions should work in an integration context --- actionpack/lib/action_dispatch/testing/assertions/routing.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb index 726da2ee07..1d7e8090e4 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb @@ -152,6 +152,7 @@ module ActionDispatch @controller = old_controller if @controller end + # ROUTES TODO: These assertions should really work in an integration context def method_missing(selector, *args, &block) if @controller && @router.named_routes.helpers.include?(selector) @controller.send(selector, *args, &block) -- cgit v1.2.3 From 8247bd9d3e1c2772f2f1e0e7ee30ff7f19ddd0de Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Sat, 27 Feb 2010 00:18:16 -0800 Subject: The instance_reader of default_url_options needs to not exist. --- actionpack/lib/action_dispatch/routing/url_for.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb index d467929561..7f2c9a5c12 100644 --- a/actionpack/lib/action_dispatch/routing/url_for.rb +++ b/actionpack/lib/action_dispatch/routing/url_for.rb @@ -90,6 +90,7 @@ module ActionDispatch class_attribute :default_url_options else mattr_accessor :default_url_options + remove_method :default_url_options end self.default_url_options = {} -- cgit v1.2.3 From d8acaf2b66be431ccd594cb90afc4ef2dc470b34 Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Sat, 27 Feb 2010 11:51:19 -0800 Subject: Remove the noisy lines involving AS::Dependencies from the NameError stack trace if a constant cannot be found. --- activesupport/lib/active_support/dependencies.rb | 3 +++ 1 file changed, 3 insertions(+) diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb index 96478ee947..2d7aa7e1e6 100644 --- a/activesupport/lib/active_support/dependencies.rb +++ b/activesupport/lib/active_support/dependencies.rb @@ -441,7 +441,10 @@ module ActiveSupport #:nodoc: qualified_name = qualified_name_for from_mod, const_name path_suffix = qualified_name.underscore + + trace = caller.reject {|l| l =~ %r{#{__FILE__}}} name_error = NameError.new("uninitialized constant #{qualified_name}") + name_error.set_backtrace(trace) file_path = search_for_file(path_suffix) -- cgit v1.2.3 From 1c9de08734f5305f5cff560a192f7f58d3f3fc11 Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Sat, 27 Feb 2010 12:18:28 -0800 Subject: Escape the file name (who knows when a "(" might appear in a filename!) --- activesupport/lib/active_support/dependencies.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb index 2d7aa7e1e6..9c4412c28c 100644 --- a/activesupport/lib/active_support/dependencies.rb +++ b/activesupport/lib/active_support/dependencies.rb @@ -442,7 +442,7 @@ module ActiveSupport #:nodoc: qualified_name = qualified_name_for from_mod, const_name path_suffix = qualified_name.underscore - trace = caller.reject {|l| l =~ %r{#{__FILE__}}} + trace = caller.reject {|l| l =~ %r{#{Regexp.escape(__FILE__)}}} name_error = NameError.new("uninitialized constant #{qualified_name}") name_error.set_backtrace(trace) -- cgit v1.2.3 From 09cb0977d47c7f5fe0797645a011f43b01121bd3 Mon Sep 17 00:00:00 2001 From: "S. Christoffer Eliesen" Date: Mon, 15 Feb 2010 12:18:44 +0100 Subject: Print database.rake errors to stderr. Signed-off-by: Jeremy Kemper --- activerecord/lib/active_record/railties/databases.rake | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake index ed7d2a045e..fa6caa4910 100644 --- a/activerecord/lib/active_record/railties/databases.rake +++ b/activerecord/lib/active_record/railties/databases.rake @@ -109,7 +109,7 @@ namespace :db do # Only connect to local databases local_database?(config) { drop_database(config) } rescue Exception => e - puts "Couldn't drop #{config['database']} : #{e.inspect}" + $stderr.puts "Couldn't drop #{config['database']} : #{e.inspect}" end end end @@ -121,7 +121,7 @@ namespace :db do begin drop_database(config) rescue Exception => e - puts "Couldn't drop #{config['database']} : #{e.inspect}" + $stderr.puts "Couldn't drop #{config['database']} : #{e.inspect}" end end @@ -129,7 +129,7 @@ namespace :db do if %w( 127.0.0.1 localhost ).include?(config['host']) || config['host'].blank? yield else - puts "This task only modifies local databases. #{config['database']} is on a remote host." + $stderr.puts "This task only modifies local databases. #{config['database']} is on a remote host." end end @@ -204,7 +204,7 @@ namespace :db do ActiveRecord::Base.establish_connection(config) puts ActiveRecord::Base.connection.encoding else - puts 'sorry, your database adapter is not supported yet, feel free to submit a patch' + $stderr.puts 'sorry, your database adapter is not supported yet, feel free to submit a patch' end end @@ -216,7 +216,7 @@ namespace :db do ActiveRecord::Base.establish_connection(config) puts ActiveRecord::Base.connection.collation else - puts 'sorry, your database adapter is not supported yet, feel free to submit a patch' + $stderr.puts 'sorry, your database adapter is not supported yet, feel free to submit a patch' end end -- cgit v1.2.3 From 6189480b1878cdadb092fdfa32ba156a91e6a0e1 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sat, 27 Feb 2010 16:59:18 -0800 Subject: Revert "Application detection should also allow dots in the path." Ruby 1.9 regression. This reverts commit 76237f163ff7ad2a64af926030e3449c547cafa2. --- railties/lib/rails/engine.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb index b6ac48768d..a259edc826 100644 --- a/railties/lib/rails/engine.rb +++ b/railties/lib/rails/engine.rb @@ -17,7 +17,7 @@ module Rails base.called_from = begin # Remove the line number from backtraces making sure we don't leave anything behind call_stack = caller.map { |p| p.split(':')[0..-2].join(':') } - File.dirname(call_stack.detect { |p| p !~ %r[railties[\w\-\.]*/lib/rails|rack[\w\-\.]*/lib/rack] }) + File.dirname(call_stack.detect { |p| p !~ %r[railties[\w\-]*/lib/rails|rack[\w\-]*/lib/rack] }) end end -- cgit v1.2.3 From b1b922d6ea96bca0d0406032b02b1cd4b6e7f6c7 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sat, 27 Feb 2010 17:10:04 -0800 Subject: Revert "Revert "Application detection should also allow dots in the path."" Works after all. Culprit was 226dfc2. This reverts commit 6189480b1878cdadb092fdfa32ba156a91e6a0e1. --- railties/lib/rails/engine.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb index a259edc826..b6ac48768d 100644 --- a/railties/lib/rails/engine.rb +++ b/railties/lib/rails/engine.rb @@ -17,7 +17,7 @@ module Rails base.called_from = begin # Remove the line number from backtraces making sure we don't leave anything behind call_stack = caller.map { |p| p.split(':')[0..-2].join(':') } - File.dirname(call_stack.detect { |p| p !~ %r[railties[\w\-]*/lib/rails|rack[\w\-]*/lib/rack] }) + File.dirname(call_stack.detect { |p| p !~ %r[railties[\w\-\.]*/lib/rails|rack[\w\-\.]*/lib/rack] }) end end -- cgit v1.2.3 From b51c0d4d2521ef5e21f767d741252836e5fc5a30 Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Sat, 27 Feb 2010 17:28:29 -0800 Subject: 1.9 doesn't like lambda {} being called with arguments --- railties/lib/rails/console/app.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/railties/lib/rails/console/app.rb b/railties/lib/rails/console/app.rb index 4524aca809..f62d1c14ba 100644 --- a/railties/lib/rails/console/app.rb +++ b/railties/lib/rails/console/app.rb @@ -26,7 +26,7 @@ end # reloads the environment def reload!(print=true) puts "Reloading..." if print - ActionDispatch::Callbacks.new(lambda {}, false).call({}) + ActionDispatch::Callbacks.new(Proc.new {}, false).call({}) true end -- cgit v1.2.3 From 6ffc8364dc7cc40312364f2e5978021c3e7d8ab9 Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Sat, 27 Feb 2010 17:29:28 -0800 Subject: Explain why we're calling an empty callback --- railties/lib/rails/console/app.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/railties/lib/rails/console/app.rb b/railties/lib/rails/console/app.rb index f62d1c14ba..4959e18e33 100644 --- a/railties/lib/rails/console/app.rb +++ b/railties/lib/rails/console/app.rb @@ -26,6 +26,7 @@ end # reloads the environment def reload!(print=true) puts "Reloading..." if print + # This triggers the to_prepare callbacks ActionDispatch::Callbacks.new(Proc.new {}, false).call({}) true end -- cgit v1.2.3 From 32afcdcb889e651b13e161a04c4d6d2ea78a652f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Sun, 28 Feb 2010 11:39:39 +0100 Subject: ActiveModel::Lint should not require our models to respond to id. --- activemodel/lib/active_model/lint.rb | 2 -- 1 file changed, 2 deletions(-) diff --git a/activemodel/lib/active_model/lint.rb b/activemodel/lib/active_model/lint.rb index 0e62e131a3..13ddb622d1 100644 --- a/activemodel/lib/active_model/lint.rb +++ b/activemodel/lib/active_model/lint.rb @@ -22,8 +22,6 @@ module ActiveModel assert model.respond_to?(:to_key), "The model should respond to to_key" def model.persisted?() false end assert model.to_key.nil? - def model.persisted?() true end - assert model.to_key.respond_to?(:each) end # == Responds to to_param -- cgit v1.2.3 From ae8070e21be405331a1ad97f59c4e43d45f10eb3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Sun, 28 Feb 2010 11:43:13 +0100 Subject: Add missing information about attributes method. --- activemodel/lib/active_model/attribute_methods.rb | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/activemodel/lib/active_model/attribute_methods.rb b/activemodel/lib/active_model/attribute_methods.rb index 143eb87f54..588976f1d4 100644 --- a/activemodel/lib/active_model/attribute_methods.rb +++ b/activemodel/lib/active_model/attribute_methods.rb @@ -21,7 +21,6 @@ module ActiveModel # A minimal implementation could be: # # class Person - # # include ActiveModel::AttributeMethods # # attribute_method_affix :prefix => 'reset_', :suffix => '_to_default!' @@ -44,9 +43,13 @@ module ActiveModel # def reset_attribute_to_default!(attr) # send("#{attr}=", "Default Name") # end - # # end - # + # + # Please notice that whenever you include ActiveModel::AtributeMethods in your class, + # it requires you to implement a attributes methods which returns a hash with + # each attribute name in your model as hash key and the attribute value as hash value. + # Hash keys must be a string. + # module AttributeMethods extend ActiveSupport::Concern -- cgit v1.2.3 From f3839b2b9996f84be6599e940a38e43237f35367 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Sun, 28 Feb 2010 11:53:48 +0100 Subject: ActiveRecord should raise an error on invalid migration types. --- .../connection_adapters/abstract/schema_definitions.rb | 11 +++++++---- activerecord/test/cases/ar_schema_test.rb | 10 ++++++++++ 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb index 520f3c8c0c..64faaef4a0 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb @@ -319,16 +319,19 @@ module ActiveRecord def method_missing(symbol, *args) if symbol.to_s == 'xml' xml_column_fallback(args) + else + super end end def xml_column_fallback(*args) case @base.adapter_name.downcase - when 'sqlite', 'mysql' - options = args.extract_options! - column(args[0], :text, options) - end + when 'sqlite', 'mysql' + options = args.extract_options! + column(args[0], :text, options) end + end + # Appends a primary key definition to the table definition. # Can be called multiple times, but this is probably not a good idea. def primary_key(name) diff --git a/activerecord/test/cases/ar_schema_test.rb b/activerecord/test/cases/ar_schema_test.rb index 4c1589d965..665c387d5d 100644 --- a/activerecord/test/cases/ar_schema_test.rb +++ b/activerecord/test/cases/ar_schema_test.rb @@ -27,6 +27,16 @@ if ActiveRecord::Base.connection.supports_migrations? assert_nothing_raised { @connection.select_all "SELECT * FROM schema_migrations" } assert_equal 7, ActiveRecord::Migrator::current_version end + + def test_schema_raises_an_error_for_invalid_column_ntype + assert_raise NoMethodError do + ActiveRecord::Schema.define(:version => 8) do + create_table :vegetables do |t| + t.unknown :color + end + end + end + end end end -- cgit v1.2.3 From 020fdb28ee1d1bdb2dd1aa182869eb2e7c6115cb Mon Sep 17 00:00:00 2001 From: Joao Carlos Date: Wed, 24 Feb 2010 18:41:02 +0000 Subject: #exit accepts an integer, not a string MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- railties/lib/rails/test_help.rb | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/railties/lib/rails/test_help.rb b/railties/lib/rails/test_help.rb index 06270f6c43..c6d67bfc19 100644 --- a/railties/lib/rails/test_help.rb +++ b/railties/lib/rails/test_help.rb @@ -1,6 +1,9 @@ # Make double-sure the RAILS_ENV is set to test, # so fixtures are loaded to the right database -exit("Abort testing: Your Rails environment is not running in test mode!") unless Rails.env.test? +unless Rails.env.test? + puts "Abort testing: Your Rails environment is not running in test mode!" + exit +end require 'test/unit' require 'active_support/core_ext/kernel/requires' -- cgit v1.2.3 From 7317d9ef4c1361219671dc4405a02ed3896f1742 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Sun, 28 Feb 2010 16:39:01 -0600 Subject: Remove implicit controller namespacing from new dsl --- .../action_dispatch/routing/deprecated_mapper.rb | 25 ++++++++++++++++++++++ actionpack/lib/action_dispatch/routing/mapper.rb | 1 - .../lib/action_dispatch/routing/route_set.rb | 24 ++------------------- actionpack/test/abstract_unit.rb | 8 ++++--- .../test/controller/action_pack_assertions_test.rb | 9 +++++--- actionpack/test/controller/render_xml_test.rb | 3 ++- railties/lib/rails/engine.rb | 3 ++- 7 files changed, 42 insertions(+), 31 deletions(-) diff --git a/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb b/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb index 1417a9d8c0..dd650e83d9 100644 --- a/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb +++ b/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb @@ -1,5 +1,30 @@ module ActionDispatch module Routing + class RouteSet + attr_accessor :controller_namespaces + + CONTROLLER_REGEXP = /[_a-zA-Z0-9]+/ + + def controller_constraints + @controller_constraints ||= begin + namespaces = controller_namespaces + in_memory_controller_namespaces + source = namespaces.map { |ns| "#{Regexp.escape(ns)}/#{CONTROLLER_REGEXP.source}" } + source << CONTROLLER_REGEXP.source + Regexp.compile(source.sort.reverse.join('|')) + end + end + + def in_memory_controller_namespaces + namespaces = Set.new + ActionController::Base.subclasses.each do |klass| + controller_name = klass.underscore + namespaces << controller_name.split('/')[0...-1].join('/') + end + namespaces.delete('') + namespaces + end + end + # Mapper instances are used to build routes. The object passed to the draw # block in config/routes.rb is a Mapper instance. # diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index bead321c9c..52e7b0e77d 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -88,7 +88,6 @@ module ActionDispatch @requirements ||= returning(@options[:constraints] || {}) do |requirements| requirements.reverse_merge!(@scope[:constraints]) if @scope[:constraints] @options.each { |k, v| requirements[k] = v if v.is_a?(Regexp) } - requirements[:controller] ||= @set.controller_constraints end end diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 6bc4303be3..99436e3cb0 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -1,5 +1,6 @@ require 'rack/mount' require 'forwardable' +require 'action_dispatch/routing/deprecated_mapper' module ActionDispatch module Routing @@ -208,7 +209,7 @@ module ActionDispatch end end - attr_accessor :routes, :named_routes, :controller_namespaces + attr_accessor :routes, :named_routes attr_accessor :disable_clear_and_finalize, :resources_path_names def self.default_resources_path_names @@ -291,27 +292,6 @@ module ActionDispatch routes.empty? end - CONTROLLER_REGEXP = /[_a-zA-Z0-9]+/ - - def controller_constraints - @controller_constraints ||= begin - namespaces = controller_namespaces + in_memory_controller_namespaces - source = namespaces.map { |ns| "#{Regexp.escape(ns)}/#{CONTROLLER_REGEXP.source}" } - source << CONTROLLER_REGEXP.source - Regexp.compile(source.sort.reverse.join('|')) - end - end - - def in_memory_controller_namespaces - namespaces = Set.new - ActionController::Base.subclasses.each do |klass| - controller_name = klass.underscore - namespaces << controller_name.split('/')[0...-1].join('/') - end - namespaces.delete('') - namespaces - end - def add_route(app, conditions = {}, requirements = {}, defaults = {}, name = nil) route = Route.new(app, conditions, requirements, defaults, name) @set.add_route(*route) diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb index c178dc481c..7bcaf0a5eb 100644 --- a/actionpack/test/abstract_unit.rb +++ b/actionpack/test/abstract_unit.rb @@ -73,11 +73,13 @@ module ActiveSupport # have been loaded. setup_once do SharedTestRoutes.draw do |map| - match ':controller(/:action(/:id))' + # FIXME: match ':controller(/:action(/:id))' + map.connect ':controller/:action/:id' end - ActionController::IntegrationTest.app.router.draw do - match ':controller(/:action(/:id))' + ActionController::IntegrationTest.app.router.draw do |map| + # FIXME: match ':controller(/:action(/:id))' + map.connect ':controller/:action/:id' end end end diff --git a/actionpack/test/controller/action_pack_assertions_test.rb b/actionpack/test/controller/action_pack_assertions_test.rb index 7c83a91f4d..6906dc97e8 100644 --- a/actionpack/test/controller/action_pack_assertions_test.rb +++ b/actionpack/test/controller/action_pack_assertions_test.rb @@ -258,7 +258,8 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase with_routing do |set| set.draw do |map| match 'admin/inner_module', :to => 'admin/inner_module#index', :as => :admin_inner_module - match ':controller/:action' + # match ':controller/:action' + map.connect ':controller/:action/:id' end process :redirect_to_index # redirection is <{"action"=>"index", "controller"=>"admin/admin/inner_module"}> @@ -272,7 +273,8 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase with_routing do |set| set.draw do |map| match '/action_pack_assertions/:id', :to => 'action_pack_assertions#index', :as => :top_level - match ':controller/:action' + # match ':controller/:action' + map.connect ':controller/:action/:id' end process :redirect_to_top_level_named_route # assert_redirected_to "http://test.host/action_pack_assertions/foo" would pass because of exact match early return @@ -287,7 +289,8 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase set.draw do |map| # this controller exists in the admin namespace as well which is the only difference from previous test match '/user/:id', :to => 'user#index', :as => :top_level - match ':controller/:action' + # match ':controller/:action' + map.connect ':controller/:action/:id' end process :redirect_to_top_level_named_route # assert_redirected_to top_level_url('foo') would pass because of exact match early return diff --git a/actionpack/test/controller/render_xml_test.rb b/actionpack/test/controller/render_xml_test.rb index b5b0d0b9d5..4da6c954cf 100644 --- a/actionpack/test/controller/render_xml_test.rb +++ b/actionpack/test/controller/render_xml_test.rb @@ -62,7 +62,8 @@ class RenderXmlTest < ActionController::TestCase with_routing do |set| set.draw do |map| resources :customers - match ':controller/:action' + # match ':controller/:action' + map.connect ':controller/:action/:id' end get :render_with_object_location diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb index b6ac48768d..af47227510 100644 --- a/railties/lib/rails/engine.rb +++ b/railties/lib/rails/engine.rb @@ -43,7 +43,7 @@ module Rails delegate :middleware, :paths, :root, :to => :config def load_tasks - super + super config.paths.lib.tasks.to_a.sort.each { |ext| load(ext) } end @@ -77,6 +77,7 @@ module Rails end end + # DEPRECATED: Remove in 3.1 initializer :add_routing_namespaces do |app| paths.app.controllers.to_a.each do |load_path| load_path = File.expand_path(load_path) -- cgit v1.2.3 From fef7a77386b0e738f3b5c25fd9ab0350a6e56d6c Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Sun, 28 Feb 2010 17:16:34 -0600 Subject: Request#subdomain returns a string version of Request#subdomains --- actionpack/lib/action_dispatch/http/url.rb | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb index 40ceb5a9b6..42ad19044d 100644 --- a/actionpack/lib/action_dispatch/http/url.rb +++ b/actionpack/lib/action_dispatch/http/url.rb @@ -81,6 +81,10 @@ module ActionDispatch parts[0..-(tld_length+2)] end + def subdomain(tld_length = 1) + subdomains(tld_length).join('.') + end + # Returns the query string, accounting for server idiosyncrasies. def query_string @env['QUERY_STRING'].present? ? @env['QUERY_STRING'] : (@env['REQUEST_URI'].to_s.split('?', 2)[1] || '') -- cgit v1.2.3 From 6c8d852056c0445def1622d06e007ee7831e14a3 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Sun, 28 Feb 2010 18:16:57 -0600 Subject: fix up activesupport test load paths --- activesupport/test/abstract_unit.rb | 3 +++ 1 file changed, 3 insertions(+) diff --git a/activesupport/test/abstract_unit.rb b/activesupport/test/abstract_unit.rb index 33be6f65bf..da338a2a26 100644 --- a/activesupport/test/abstract_unit.rb +++ b/activesupport/test/abstract_unit.rb @@ -1,5 +1,8 @@ require File.expand_path('../../../load_paths', __FILE__) +lib = File.expand_path("#{File.dirname(__FILE__)}/../lib") +$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) + require 'test/unit' require 'mocha' -- cgit v1.2.3 From f0fe555d842e7b81b323ed3acfd551f0659c5faa Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Sun, 28 Feb 2010 18:18:21 -0600 Subject: fix up actionmailer load path --- actionmailer/test/abstract_unit.rb | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/actionmailer/test/abstract_unit.rb b/actionmailer/test/abstract_unit.rb index f6baa4a9e8..16fef3a9a4 100644 --- a/actionmailer/test/abstract_unit.rb +++ b/actionmailer/test/abstract_unit.rb @@ -1,5 +1,8 @@ require File.expand_path('../../../load_paths', __FILE__) +lib = File.expand_path("#{File.dirname(__FILE__)}/../lib") +$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) + require 'test/unit' require 'action_mailer' require 'action_mailer/test_case' @@ -14,7 +17,7 @@ ActionView::Template.register_template_handler :bak, lambda { |template| "Lame b FIXTURE_LOAD_PATH = File.expand_path('fixtures', File.dirname(__FILE__)) ActionMailer::Base.view_paths = FIXTURE_LOAD_PATH -class MockSMTP +class MockSMTP def self.deliveries @@deliveries end -- cgit v1.2.3 From cbefcc88b38f0ec3c885b450962623017f4cc64c Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Sun, 28 Feb 2010 18:25:02 -0600 Subject: add activesupport and activemodel load paths to actionpack tests --- actionpack/test/abstract_unit.rb | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb index 7bcaf0a5eb..660cabc554 100644 --- a/actionpack/test/abstract_unit.rb +++ b/actionpack/test/abstract_unit.rb @@ -1,5 +1,11 @@ require File.expand_path('../../../load_paths', __FILE__) +lib = File.expand_path("#{File.dirname(__FILE__)}/../lib") +$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) + +activemodel_path = File.expand_path('../../../activemodel/lib', __FILE__) +$:.unshift(activemodel_path) if File.directory?(activemodel_path) && !$:.include?(activemodel_path) + $:.unshift(File.dirname(__FILE__) + '/lib') $:.unshift(File.dirname(__FILE__) + '/fixtures/helpers') $:.unshift(File.dirname(__FILE__) + '/fixtures/alternate_helpers') -- cgit v1.2.3 From 1a2fba1b6bcb3fdc5268760f67ab0e4a20fa1059 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Sun, 28 Feb 2010 18:26:00 -0600 Subject: don't expand test path --- activemodel/Rakefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activemodel/Rakefile b/activemodel/Rakefile index 14c02f183f..556ea2ec0b 100755 --- a/activemodel/Rakefile +++ b/activemodel/Rakefile @@ -13,7 +13,7 @@ require 'rake/testtask' task :default => :test Rake::TestTask.new do |t| - t.libs << "#{dir}/test" + t.libs << "test" t.test_files = Dir.glob("#{dir}/test/cases/**/*_test.rb").sort t.warning = true end -- cgit v1.2.3 From 4377deed35daead6d120207dd94f89d136025c1d Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Sun, 28 Feb 2010 18:27:00 -0600 Subject: ensure activemodel lib is setup correctly --- activemodel/test/cases/helper.rb | 3 +++ 1 file changed, 3 insertions(+) diff --git a/activemodel/test/cases/helper.rb b/activemodel/test/cases/helper.rb index 8bcbe54651..8578ab7dbd 100644 --- a/activemodel/test/cases/helper.rb +++ b/activemodel/test/cases/helper.rb @@ -1,5 +1,8 @@ require File.expand_path('../../../../load_paths', __FILE__) +lib = File.expand_path("#{File.dirname(__FILE__)}/../../lib") +$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) + require 'config' require 'active_model' -- cgit v1.2.3 From 5cc17da8946abbaa86a4d9c91dcd4b05a289493f Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Sun, 28 Feb 2010 18:28:25 -0600 Subject: activerecord test load paths --- activerecord/test/cases/helper.rb | 3 +++ 1 file changed, 3 insertions(+) diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb index 9e8bfbbee8..f77dc801dc 100644 --- a/activerecord/test/cases/helper.rb +++ b/activerecord/test/cases/helper.rb @@ -1,5 +1,8 @@ require File.expand_path('../../../../load_paths', __FILE__) +lib = File.expand_path("#{File.dirname(__FILE__)}/../../lib") +$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) + require 'config' require 'test/unit' -- cgit v1.2.3 From 30446f7b29b1803ea24f9c6d9ed93b16dcbf7431 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Sun, 28 Feb 2010 18:29:34 -0600 Subject: correct activeresource load path --- activeresource/test/abstract_unit.rb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/activeresource/test/abstract_unit.rb b/activeresource/test/abstract_unit.rb index 1af535e811..fcb770d612 100644 --- a/activeresource/test/abstract_unit.rb +++ b/activeresource/test/abstract_unit.rb @@ -1,12 +1,14 @@ require File.expand_path('../../../load_paths', __FILE__) +lib = File.expand_path("#{File.dirname(__FILE__)}/../lib") +$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) + require 'rubygems' require 'test/unit' require 'active_resource' require 'active_support' require 'active_support/test_case' -$:.unshift "#{File.dirname(__FILE__)}/../test" require 'setter_trap' require 'logger' -- cgit v1.2.3 From a5da48d231bf1e4041e149a8d052d8450e41a4e9 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Sun, 28 Feb 2010 18:32:46 -0600 Subject: vendor/rails doesn't work anymore, remove it from the blank slate suggestion --- railties/lib/generators/rails/app/templates/config/boot.rb | 9 --------- 1 file changed, 9 deletions(-) diff --git a/railties/lib/generators/rails/app/templates/config/boot.rb b/railties/lib/generators/rails/app/templates/config/boot.rb index 29c9d506e5..3cb561d41f 100644 --- a/railties/lib/generators/rails/app/templates/config/boot.rb +++ b/railties/lib/generators/rails/app/templates/config/boot.rb @@ -5,13 +5,4 @@ rescue LoadError require 'rubygems' require 'bundler' Bundler.setup - - # To use 2.x style vendor/rails and RubyGems - # - # vendor_rails = File.expand_path('../../vendor/rails', __FILE__) - # if File.exist?(vendor_rails) - # Dir["#{vendor_rails}/*/lib"].each { |path| $:.unshift(path) } - # end - # - # require 'rubygems' end -- cgit v1.2.3 From 2ce3085e3ceabe688b30f55373b21278c4dca416 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Sun, 28 Feb 2010 18:34:57 -0600 Subject: Define Bundler constant stub if bundler gem is not installed --- load_paths.rb | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/load_paths.rb b/load_paths.rb index d5f2ca0734..b87e0d7235 100644 --- a/load_paths.rb +++ b/load_paths.rb @@ -6,6 +6,11 @@ rescue LoadError require 'bundler' Bundler.setup rescue LoadError + module Bundler + def self.require(*args, &block); end + def self.method_missing(*args, &block); end + end + %w( actionmailer actionpack -- cgit v1.2.3 From 82deaf5f052caf0a906ed0e83c6efd00c057b5ba Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Sun, 28 Feb 2010 18:43:20 -0600 Subject: nested controllers need to be explicitly declared with the new mapper --- railties/test/application/routing_test.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/railties/test/application/routing_test.rb b/railties/test/application/routing_test.rb index b93e349a46..dcac1a87d9 100644 --- a/railties/test/application/routing_test.rb +++ b/railties/test/application/routing_test.rb @@ -120,7 +120,8 @@ module ApplicationTests app_file 'config/routes.rb', <<-RUBY AppTemplate::Application.routes.draw do |map| - match ':controller(/:action)' + match 'admin/foo', :to => 'admin/foo#index' + match 'foo', :to => 'foo#index' end RUBY -- cgit v1.2.3 From 2060977b767061a42eb8db2d5c3a30d205a94123 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lourens=20Naud=C3=A9?= Date: Mon, 8 Feb 2010 00:05:33 +0000 Subject: Hash#symbolize_keys(!) optimizations [#3891 state:committed] Signed-off-by: Jeremy Kemper --- activesupport/lib/active_support/core_ext/hash/keys.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activesupport/lib/active_support/core_ext/hash/keys.rb b/activesupport/lib/active_support/core_ext/hash/keys.rb index 045a6944fa..e4d429fc2b 100644 --- a/activesupport/lib/active_support/core_ext/hash/keys.rb +++ b/activesupport/lib/active_support/core_ext/hash/keys.rb @@ -22,7 +22,7 @@ class Hash # to +to_sym+. def symbolize_keys! keys.each do |key| - self[(key.to_sym rescue key) || key] = delete(key) + self[(key.to_sym rescue key)] = delete(key) if key.respond_to?(:to_sym) && !key.is_a?(Fixnum) end self end -- cgit v1.2.3 From 8fbbdda52634991b047b7567fe3a8ec7c9a6c558 Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Mon, 1 Mar 2010 14:10:53 -0800 Subject: Delegate formats to the controller --- actionpack/lib/action_view/base.rb | 25 ++++++++++++++++++++-- .../lib/action_view/helpers/prototype_helper.rb | 4 ++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb index a61017ae11..2d2b53a6ce 100644 --- a/actionpack/lib/action_view/base.rb +++ b/actionpack/lib/action_view/base.rb @@ -186,12 +186,21 @@ module ActionView #:nodoc: extend ActiveSupport::Memoizable - attr_accessor :base_path, :assigns, :template_extension, :formats + attr_accessor :base_path, :assigns, :template_extension attr_internal :captures def reset_formats(formats) - @formats = formats + old_formats, self.formats = self.formats, formats + reset_hash_key + yield if block_given? + ensure + if block_given? + self.formats = old_formats + reset_hash_key + end + end + def reset_hash_key if defined?(AbstractController::HashKey) # This is expensive, but we need to reset this when the format is updated, # which currently only happens @@ -200,6 +209,18 @@ module ActionView #:nodoc: end end + def formats + controller ? controller.formats : @formats + end + + def formats=(val) + if controller + controller.formats = val + else + @formats = val + end + end + class << self delegate :erb_trim_mode=, :to => 'ActionView::Template::Handlers::ERB' delegate :logger, :to => 'ActionController::Base', :allow_nil => true diff --git a/actionpack/lib/action_view/helpers/prototype_helper.rb b/actionpack/lib/action_view/helpers/prototype_helper.rb index 7eb6bceca0..3c4511d931 100644 --- a/actionpack/lib/action_view/helpers/prototype_helper.rb +++ b/actionpack/lib/action_view/helpers/prototype_helper.rb @@ -182,10 +182,14 @@ module ActionView def initialize(context, &block) #:nodoc: context._evaluate_assigns_and_ivars @context, @lines = context, [] + old_formats = @context.formats + @context.reset_formats([:js, :html]) if @context include_helpers_from_context @context.with_output_buffer(@lines) do @context.instance_exec(self, &block) end + ensure + @context.reset_formats(old_formats) if @context end private -- cgit v1.2.3 From b85ea58eb561d0a0fd2b0a3dbae1dc7846961c2d Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Mon, 1 Mar 2010 14:37:05 -0800 Subject: Change AV formats so they can delegate to the controller. Now users (or plugins) can override details_for_render in their controllers and add appropriate additional details. Now if only they could *do* something with those details... --- actionpack/lib/action_controller/base.rb | 2 +- .../lib/action_controller/metal/rendering.rb | 6 +++- .../lib/action_view/helpers/prototype_helper.rb | 32 ++++++++++++---------- actionpack/lib/action_view/render/rendering.rb | 8 ++++-- actionpack/test/template/javascript_helper_test.rb | 1 + actionpack/test/template/prototype_helper_test.rb | 1 + 6 files changed, 31 insertions(+), 19 deletions(-) diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb index f8ddc8da09..13139358c7 100644 --- a/actionpack/lib/action_controller/base.rb +++ b/actionpack/lib/action_controller/base.rb @@ -52,7 +52,7 @@ module ActionController def method_for_action(action_name) super || begin - if view_paths.exists?(action_name.to_s, {:formats => formats}, controller_path) + if view_paths.exists?(action_name.to_s, details_for_render, controller_path) "default_render" end end diff --git a/actionpack/lib/action_controller/metal/rendering.rb b/actionpack/lib/action_controller/metal/rendering.rb index a026289ee5..6e5379745b 100644 --- a/actionpack/lib/action_controller/metal/rendering.rb +++ b/actionpack/lib/action_controller/metal/rendering.rb @@ -23,10 +23,14 @@ module ActionController def _render_partial(options) options[:partial] = action_name if options[:partial] == true - options[:_details] = {:formats => formats} + options[:_details] = details_for_render super end + def details_for_render + {:formats => formats} + end + def format_for_text formats.first end diff --git a/actionpack/lib/action_view/helpers/prototype_helper.rb b/actionpack/lib/action_view/helpers/prototype_helper.rb index 3c4511d931..67a7586699 100644 --- a/actionpack/lib/action_view/helpers/prototype_helper.rb +++ b/actionpack/lib/action_view/helpers/prototype_helper.rb @@ -182,14 +182,12 @@ module ActionView def initialize(context, &block) #:nodoc: context._evaluate_assigns_and_ivars @context, @lines = context, [] - old_formats = @context.formats - @context.reset_formats([:js, :html]) if @context - include_helpers_from_context - @context.with_output_buffer(@lines) do - @context.instance_exec(self, &block) + @context.reset_formats([:js, :html]) do + include_helpers_from_context + @context.with_output_buffer(@lines) do + @context.instance_exec(self, &block) + end end - ensure - @context.reset_formats(old_formats) if @context end private @@ -573,15 +571,19 @@ module ActionView end end - def render(*options_for_render) - old_formats = @context && @context.formats + def render(*options) + with_formats(:html) do + case option = options.first + when Hash + @context.render(*options) + else + option.to_s + end + end + end - @context.reset_formats([:html]) if @context - Hash === options_for_render.first ? - @context.render(*options_for_render) : - options_for_render.first.to_s - ensure - @context.reset_formats(old_formats) if @context + def with_formats(*args) + @context ? @context.reset_formats(args) { yield } : yield end def javascript_object_for(object) diff --git a/actionpack/lib/action_view/render/rendering.rb b/actionpack/lib/action_view/render/rendering.rb index abc7c09991..64cc0caf11 100644 --- a/actionpack/lib/action_view/render/rendering.rb +++ b/actionpack/lib/action_view/render/rendering.rb @@ -25,7 +25,7 @@ module ActionView end template = if options[:file] - find(options[:file], {:formats => formats}) + find(options[:file], details_for_render) elsif options[:inline] handler = Template.handler_class_for_extension(options[:type] || "erb") Template.new(options[:inline], "inline template", handler, {}) @@ -34,7 +34,7 @@ module ActionView end if template - layout = find(layout, {:formats => formats}) if layout + layout = find(layout, details_for_render) if layout _render_template(template, layout, :locals => options[:locals]) end when :update @@ -44,6 +44,10 @@ module ActionView end end + def details_for_render + controller.try(:details_for_render) || {:formats => formats} + end + # You can think of a layout as a method that is called with a block. _layout_for # returns the contents that are yielded to the layout. If the user calls yield # :some_name, the block, by default, returns content_for(:some_name). If the user diff --git a/actionpack/test/template/javascript_helper_test.rb b/actionpack/test/template/javascript_helper_test.rb index b3e7abc387..368a9c2514 100644 --- a/actionpack/test/template/javascript_helper_test.rb +++ b/actionpack/test/template/javascript_helper_test.rb @@ -9,6 +9,7 @@ class JavaScriptHelperTest < ActionView::TestCase def reset_formats(format) @format = format + yield if block_given? end def setup diff --git a/actionpack/test/template/prototype_helper_test.rb b/actionpack/test/template/prototype_helper_test.rb index 45f9d85e32..6811d3aaf3 100644 --- a/actionpack/test/template/prototype_helper_test.rb +++ b/actionpack/test/template/prototype_helper_test.rb @@ -41,6 +41,7 @@ class PrototypeHelperBaseTest < ActionView::TestCase def reset_formats(format) @format = format + yield if block_given? end def setup -- cgit v1.2.3 From 8b5b2413772e05bde96591570c4a105a53b611a2 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 1 Mar 2010 16:19:56 -0800 Subject: Bump pg dep to 0.9.0+ --- Gemfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gemfile b/Gemfile index 928222e2d0..fb0ca6493d 100644 --- a/Gemfile +++ b/Gemfile @@ -14,7 +14,7 @@ end gem "sqlite3-ruby", ">= 1.2.5", :require => 'sqlite3' group :test do - gem "pg", ">= 0.8.0" + gem "pg", ">= 0.9.0" gem "mysql", ">= 2.8.1" end -- cgit v1.2.3 From 300d6b549d020cbfaa10657f07a22ec892d8078f Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Mon, 1 Mar 2010 15:03:51 -0800 Subject: Merge _details_defaults and details_for_render --- actionpack/lib/abstract_controller/details_cache.rb | 2 +- actionpack/lib/abstract_controller/rendering.rb | 4 ++-- actionpack/lib/action_controller/metal/rendering.rb | 4 ---- 3 files changed, 3 insertions(+), 7 deletions(-) diff --git a/actionpack/lib/abstract_controller/details_cache.rb b/actionpack/lib/abstract_controller/details_cache.rb index 5b87b41e7d..be1a1c0f34 100644 --- a/actionpack/lib/abstract_controller/details_cache.rb +++ b/actionpack/lib/abstract_controller/details_cache.rb @@ -34,7 +34,7 @@ module AbstractController end def render_to_body(*args) - Thread.current[:format_locale_key] = HashKey.get(self.class, _details_defaults) + Thread.current[:format_locale_key] = HashKey.get(self.class, details_for_render) super end diff --git a/actionpack/lib/abstract_controller/rendering.rb b/actionpack/lib/abstract_controller/rendering.rb index 32fdf821a7..2ea4f02871 100644 --- a/actionpack/lib/abstract_controller/rendering.rb +++ b/actionpack/lib/abstract_controller/rendering.rb @@ -168,12 +168,12 @@ module AbstractController end end - def _details_defaults + def details_for_render { :formats => formats, :locale => [I18n.locale] } end def _normalize_details(options) - details = _details_defaults + details = details_for_render details[:formats] = Array(options[:format]) if options[:format] details[:locale] = Array(options[:locale]) if options[:locale] details diff --git a/actionpack/lib/action_controller/metal/rendering.rb b/actionpack/lib/action_controller/metal/rendering.rb index 6e5379745b..00a09309bf 100644 --- a/actionpack/lib/action_controller/metal/rendering.rb +++ b/actionpack/lib/action_controller/metal/rendering.rb @@ -27,10 +27,6 @@ module ActionController super end - def details_for_render - {:formats => formats} - end - def format_for_text formats.first end -- cgit v1.2.3 From 048b436f33059f1da7659edf9ca05fb46042b253 Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Mon, 1 Mar 2010 15:54:45 -0800 Subject: AS::Subscriber is not a LogSubscriber --- activesupport/lib/active_support/notifications/fanout.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/activesupport/lib/active_support/notifications/fanout.rb b/activesupport/lib/active_support/notifications/fanout.rb index 05de4946a5..090eb1eac6 100644 --- a/activesupport/lib/active_support/notifications/fanout.rb +++ b/activesupport/lib/active_support/notifications/fanout.rb @@ -12,7 +12,7 @@ module ActiveSupport end def subscribe(pattern = nil, &block) - @log_subscribers << LogSubscriber.new(pattern, &block) + @log_subscribers << Subscriber.new(pattern, &block) end def publish(*args) @@ -41,7 +41,7 @@ module ActiveSupport end end - class LogSubscriber #:nodoc: + class Subscriber #:nodoc: def initialize(pattern, &block) @pattern = pattern @block = block -- cgit v1.2.3 From c88360ef3651702ca8f7f600e15774f51c84698b Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Mon, 1 Mar 2010 16:01:08 -0800 Subject: You can unsubscribe a subscriber --- activesupport/lib/active_support/notifications.rb | 4 ++++ activesupport/lib/active_support/notifications/fanout.rb | 11 ++++++++--- activesupport/test/notifications_test.rb | 14 +++++++++++++- 3 files changed, 25 insertions(+), 4 deletions(-) diff --git a/activesupport/lib/active_support/notifications.rb b/activesupport/lib/active_support/notifications.rb index 06d57765bc..fca2efd969 100644 --- a/activesupport/lib/active_support/notifications.rb +++ b/activesupport/lib/active_support/notifications.rb @@ -69,6 +69,10 @@ module ActiveSupport @queue.bind(pattern).subscribe(&block) end + def unsubscribe(subscriber) + @queue.unsubscribe(subscriber) + end + def wait @queue.wait end diff --git a/activesupport/lib/active_support/notifications/fanout.rb b/activesupport/lib/active_support/notifications/fanout.rb index 090eb1eac6..e08011e23f 100644 --- a/activesupport/lib/active_support/notifications/fanout.rb +++ b/activesupport/lib/active_support/notifications/fanout.rb @@ -4,7 +4,7 @@ module ActiveSupport # just pushes events to all registered log subscribers. class Fanout def initialize - @log_subscribers = [] + @subscribers = [] end def bind(pattern) @@ -12,11 +12,16 @@ module ActiveSupport end def subscribe(pattern = nil, &block) - @log_subscribers << Subscriber.new(pattern, &block) + @subscribers << Subscriber.new(pattern, &block) + @subscribers.last + end + + def unsubscribe(subscriber) + @subscribers.delete(subscriber) end def publish(*args) - @log_subscribers.each { |s| s.publish(*args) } + @subscribers.each { |s| s.publish(*args) } end # This is a sync queue, so there is not waiting. diff --git a/activesupport/test/notifications_test.rb b/activesupport/test/notifications_test.rb index 779771553c..baee779b8a 100644 --- a/activesupport/test/notifications_test.rb +++ b/activesupport/test/notifications_test.rb @@ -6,7 +6,7 @@ module Notifications ActiveSupport::Notifications.notifier = nil @notifier = ActiveSupport::Notifications.notifier @events = [] - @notifier.subscribe { |*args| @events << event(*args) } + @subscription = @notifier.subscribe { |*args| @events << event(*args) } end private @@ -19,6 +19,18 @@ module Notifications end end + class UnsubscribeTest < TestCase + def unsubscribing_removes_a_subscription + @notifier.publish :foo + @notifier.wait + assert_equal [[:foo]], @events + @notifier.unsubscribe(@subscription) + @notifier.publish :bar + @notifier.wait + assert_equal [[:foo]], @events + end + end + class SyncPubSubTest < TestCase def test_events_are_published_to_a_listener @notifier.publish :foo -- cgit v1.2.3 From fc0882ba5a0f18281736859718252042b15614ad Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Mon, 1 Mar 2010 17:33:59 -0800 Subject: Optimize AS::Notifications to remember which subscribers don't match and not run them. This will allow notifications that are only useful in dev or testing to run efficiently in production. --- activesupport/lib/active_support/notifications.rb | 2 +- .../lib/active_support/notifications/fanout.rb | 15 ++++++++--- activesupport/test/notifications_test.rb | 31 ++++++++++++++++++++-- 3 files changed, 42 insertions(+), 6 deletions(-) diff --git a/activesupport/lib/active_support/notifications.rb b/activesupport/lib/active_support/notifications.rb index fca2efd969..3f1fe64e9b 100644 --- a/activesupport/lib/active_support/notifications.rb +++ b/activesupport/lib/active_support/notifications.rb @@ -44,7 +44,7 @@ module ActiveSupport class << self attr_writer :notifier - delegate :publish, :subscribe, :to => :notifier + delegate :publish, :subscribe, :unsubscribe, :to => :notifier delegate :instrument, :to => :instrumenter def notifier diff --git a/activesupport/lib/active_support/notifications/fanout.rb b/activesupport/lib/active_support/notifications/fanout.rb index e08011e23f..cd60054862 100644 --- a/activesupport/lib/active_support/notifications/fanout.rb +++ b/activesupport/lib/active_support/notifications/fanout.rb @@ -5,6 +5,7 @@ module ActiveSupport class Fanout def initialize @subscribers = [] + @listeners_for = {} end def bind(pattern) @@ -12,16 +13,22 @@ module ActiveSupport end def subscribe(pattern = nil, &block) + @listeners_for.clear @subscribers << Subscriber.new(pattern, &block) @subscribers.last end def unsubscribe(subscriber) @subscribers.delete(subscriber) + @listeners_for.clear end - def publish(*args) - @subscribers.each { |s| s.publish(*args) } + def publish(name, *args) + if listeners = @listeners_for[name] + listeners.each { |s| s.publish(name, *args) } + else + @listeners_for[name] = @subscribers.select { |s| s.publish(name, *args) } + end end # This is a sync queue, so there is not waiting. @@ -53,7 +60,9 @@ module ActiveSupport end def publish(*args) - push(*args) if matches?(args.first) + return unless matches?(args.first) + push(*args) + true end def drained? diff --git a/activesupport/test/notifications_test.rb b/activesupport/test/notifications_test.rb index baee779b8a..67c3527e23 100644 --- a/activesupport/test/notifications_test.rb +++ b/activesupport/test/notifications_test.rb @@ -20,15 +20,20 @@ module Notifications end class UnsubscribeTest < TestCase - def unsubscribing_removes_a_subscription + def test_unsubscribing_removes_a_subscription @notifier.publish :foo @notifier.wait assert_equal [[:foo]], @events @notifier.unsubscribe(@subscription) - @notifier.publish :bar + @notifier.publish :foo @notifier.wait assert_equal [[:foo]], @events end + + private + def event(*args) + args + end end class SyncPubSubTest < TestCase @@ -38,6 +43,28 @@ module Notifications assert_equal [[:foo]], @events end + def test_publishing_multiple_times_works + @notifier.publish :foo + @notifier.publish :foo + @notifier.wait + assert_equal [[:foo], [:foo]], @events + end + + def test_publishing_after_a_new_subscribe_works + @notifier.publish :foo + @notifier.publish :foo + + @notifier.subscribe("not_existant") do |*args| + @events << ActiveSupport::Notifications::Event.new(*args) + end + + @notifier.publish :foo + @notifier.publish :foo + @notifier.wait + + assert_equal [[:foo]] * 4, @events + end + def test_log_subscriber_with_pattern events = [] @notifier.subscribe('1') { |*args| events << args } -- cgit v1.2.3 From 8bb162f008bb8e3a66b4a0d98b9f56cad45a4ab3 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 1 Mar 2010 18:52:07 -0800 Subject: Fix unstated usage of inflector --- railties/lib/rails/railtie.rb | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/railties/lib/rails/railtie.rb b/railties/lib/rails/railtie.rb index 67afae5862..37c802fb60 100644 --- a/railties/lib/rails/railtie.rb +++ b/railties/lib/rails/railtie.rb @@ -1,5 +1,6 @@ require 'rails/initializable' require 'rails/configuration' +require 'active_support/inflector' module Rails class Railtie @@ -23,9 +24,8 @@ module Rails end def railtie_name(railtie_name = nil) - @railtie_name ||= name.demodulize.underscore @railtie_name = railtie_name if railtie_name - @railtie_name + @railtie_name ||= default_name end def railtie_names @@ -53,6 +53,10 @@ module Rails def abstract_railtie?(base) ABSTRACT_RAILTIES.include?(base.name) end + + def default_name + ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(name)) + end end def rake_tasks -- cgit v1.2.3 From 11db694e0b825e3077e7545b08c1bf975997021f Mon Sep 17 00:00:00 2001 From: Bryan Helmkamp Date: Mon, 1 Mar 2010 21:55:43 -0500 Subject: Remove cruft in the gem packaging and release code --- Rakefile | 14 ++++++-------- actionmailer/Rakefile | 10 ---------- actionpack/Rakefile | 31 +------------------------------ activemodel/Rakefile | 7 ------- activerecord/Rakefile | 14 -------------- activeresource/Rakefile | 14 -------------- activesupport/Rakefile | 10 ---------- pushgems.rb | 14 -------------- railties/Rakefile | 11 ----------- release.rb | 25 ------------------------- 10 files changed, 7 insertions(+), 143 deletions(-) delete mode 100755 pushgems.rb delete mode 100755 release.rb diff --git a/Rakefile b/Rakefile index c5c548d89c..4b14f8a2f1 100644 --- a/Rakefile +++ b/Rakefile @@ -2,8 +2,6 @@ require 'rake' require 'rake/rdoctask' require 'rake/gempackagetask' -env = %(PKG_BUILD="#{ENV['PKG_BUILD']}") if ENV['PKG_BUILD'] - PROJECTS = %w(activesupport activemodel actionpack actionmailer activeresource activerecord railties) Dir["#{File.dirname(__FILE__)}/*/lib/*/version.rb"].each do |version_path| @@ -13,12 +11,12 @@ end desc 'Run all tests by default' task :default => %w(test test:isolated) -%w(test test:isolated rdoc pgem package gem gemspec).each do |task_name| +%w(test test:isolated rdoc package gem).each do |task_name| desc "Run #{task_name} task for all projects" task task_name do errors = [] PROJECTS.each do |project| - system(%(cd #{project} && #{env} #{$0} #{task_name})) || errors << project + system(%(cd #{project} && #{$0} #{task_name})) || errors << project end fail("Errors in #{errors.join(', ')}") unless errors.empty? end @@ -27,9 +25,9 @@ end desc "Smoke-test all projects" task :smoke do (PROJECTS - %w(activerecord)).each do |project| - system %(cd #{project} && #{env} #{$0} test:isolated) + system %(cd #{project} && #{$0} test:isolated) end - system %(cd activerecord && #{env} #{$0} sqlite3:isolated_test) + system %(cd activerecord && #{$0} sqlite3:isolated_test) end spec = eval(File.read('rails.gemspec')) @@ -48,7 +46,7 @@ desc "Release all components to gemcutter." task :release_projects => :package do errors = [] PROJECTS.each do |project| - system(%(cd #{project} && #{env} #{$0} release)) || errors << project + system(%(cd #{project} && #{$0} release)) || errors << project end fail("Errors in #{errors.join(', ')}") unless errors.empty? end @@ -122,6 +120,6 @@ task :pdoc => :rdoc do require 'rake/contrib/sshpublisher' Rake::SshDirPublisher.new("wrath.rubyonrails.org", "public_html/api", "doc/rdoc").upload PROJECTS.each do |project| - system %(cd #{project} && #{env} #{$0} pdoc) + system %(cd #{project} && #{$0} pdoc) end end diff --git a/actionmailer/Rakefile b/actionmailer/Rakefile index baea591b97..0cc743dfa6 100644 --- a/actionmailer/Rakefile +++ b/actionmailer/Rakefile @@ -6,16 +6,6 @@ require 'rake/packagetask' require 'rake/gempackagetask' require File.join(File.dirname(__FILE__), 'lib', 'action_mailer', 'version') -PKG_BUILD = ENV['PKG_BUILD'] ? '.' + ENV['PKG_BUILD'] : '' -PKG_NAME = 'actionmailer' -PKG_VERSION = ActionMailer::VERSION::STRING + PKG_BUILD -PKG_FILE_NAME = "#{PKG_NAME}-#{PKG_VERSION}" - -RELEASE_NAME = "REL #{PKG_VERSION}" - -RUBY_FORGE_PROJECT = "actionmailer" -RUBY_FORGE_USER = "webster132" - desc "Default Task" task :default => [ :test ] diff --git a/actionpack/Rakefile b/actionpack/Rakefile index c45f88ed04..f099a4613e 100644 --- a/actionpack/Rakefile +++ b/actionpack/Rakefile @@ -6,16 +6,6 @@ require 'rake/packagetask' require 'rake/gempackagetask' require File.join(File.dirname(__FILE__), 'lib', 'action_pack', 'version') -PKG_BUILD = ENV['PKG_BUILD'] ? '.' + ENV['PKG_BUILD'] : '' -PKG_NAME = 'actionpack' -PKG_VERSION = ActionPack::VERSION::STRING + PKG_BUILD -PKG_FILE_NAME = "#{PKG_NAME}-#{PKG_VERSION}" - -RELEASE_NAME = "REL #{PKG_VERSION}" - -RUBY_FORGE_PROJECT = "actionpack" -RUBY_FORGE_USER = "webster132" - desc "Default Task" task :default => :test @@ -114,27 +104,8 @@ task :update_js => [ :update_scriptaculous ] # Publishing ------------------------------------------------------ -desc "Publish the API documentation" -task :pgem => [:package] do - require 'rake/contrib/sshpublisher' - Rake::SshFilePublisher.new("gems.rubyonrails.org", "/u/sites/gems/gems", "pkg", "#{PKG_FILE_NAME}.gem").upload - `ssh gems.rubyonrails.org '/u/sites/gems/gemupdate.sh'` -end - desc "Publish the API documentation" task :pdoc => [:rdoc] do require 'rake/contrib/sshpublisher' Rake::SshDirPublisher.new("wrath.rubyonrails.org", "public_html/ap", "doc").upload -end - -desc "Publish the release files to RubyForge." -task :release => [ :package ] do - require 'rubyforge' - require 'rake/contrib/rubyforgepublisher' - - packages = %w( gem tgz zip ).collect{ |ext| "pkg/#{PKG_NAME}-#{PKG_VERSION}.#{ext}" } - - rubyforge = RubyForge.new - rubyforge.login - rubyforge.add_release(PKG_NAME, PKG_NAME, "REL #{PKG_VERSION}", *packages) -end +end \ No newline at end of file diff --git a/activemodel/Rakefile b/activemodel/Rakefile index 556ea2ec0b..b1ebf07af0 100755 --- a/activemodel/Rakefile +++ b/activemodel/Rakefile @@ -1,13 +1,6 @@ dir = File.dirname(__FILE__) require "#{dir}/lib/active_model/version" -PKG_BUILD = ENV['PKG_BUILD'] ? '.' + ENV['PKG_BUILD'] : '' -PKG_NAME = 'activemodel' -PKG_VERSION = ActiveModel::VERSION::STRING + PKG_BUILD -PKG_FILE_NAME = "#{PKG_NAME}-#{PKG_VERSION}" -RELEASE_NAME = "REL #{PKG_VERSION}" - - require 'rake/testtask' task :default => :test diff --git a/activerecord/Rakefile b/activerecord/Rakefile index 8a414a751b..c53215e75e 100644 --- a/activerecord/Rakefile +++ b/activerecord/Rakefile @@ -8,22 +8,8 @@ require 'rake/gempackagetask' require File.join(File.dirname(__FILE__), 'lib', 'active_record', 'version') require File.expand_path(File.dirname(__FILE__)) + "/test/config" -PKG_BUILD = ENV['PKG_BUILD'] ? '.' + ENV['PKG_BUILD'] : '' -PKG_NAME = 'activerecord' -PKG_VERSION = ActiveRecord::VERSION::STRING + PKG_BUILD -PKG_FILE_NAME = "#{PKG_NAME}-#{PKG_VERSION}" - -RELEASE_NAME = "REL #{PKG_VERSION}" - -RUBY_FORGE_PROJECT = "activerecord" -RUBY_FORGE_USER = "webster132" - MYSQL_DB_USER = 'rails' -PKG_FILES = FileList[ - "lib/**/*", "test/**/*", "examples/**/*", "doc/**/*", "[A-Z]*", "install.rb", "Rakefile" -].exclude(/\bCVS\b|~$/) - def run_without_aborting(*tasks) errors = [] diff --git a/activeresource/Rakefile b/activeresource/Rakefile index 829752516f..a0a8ab19d1 100644 --- a/activeresource/Rakefile +++ b/activeresource/Rakefile @@ -7,20 +7,6 @@ require 'rake/gempackagetask' require File.join(File.dirname(__FILE__), 'lib', 'active_resource', 'version') -PKG_BUILD = ENV['PKG_BUILD'] ? '.' + ENV['PKG_BUILD'] : '' -PKG_NAME = 'activeresource' -PKG_VERSION = ActiveResource::VERSION::STRING + PKG_BUILD -PKG_FILE_NAME = "#{PKG_NAME}-#{PKG_VERSION}" - -RELEASE_NAME = "REL #{PKG_VERSION}" - -RUBY_FORGE_PROJECT = "activerecord" -RUBY_FORGE_USER = "webster132" - -PKG_FILES = FileList[ - "lib/**/*", "test/**/*", "[A-Z]*", "Rakefile" -].exclude(/\bCVS\b|~$/) - desc "Default Task" task :default => [ :test ] diff --git a/activesupport/Rakefile b/activesupport/Rakefile index 357bdca715..64e3111cf8 100644 --- a/activesupport/Rakefile +++ b/activesupport/Rakefile @@ -4,16 +4,6 @@ require 'rake/gempackagetask' require File.join(File.dirname(__FILE__), 'lib', 'active_support', 'version') -PKG_BUILD = ENV['PKG_BUILD'] ? '.' + ENV['PKG_BUILD'] : '' -PKG_NAME = 'activesupport' -PKG_VERSION = ActiveSupport::VERSION::STRING + PKG_BUILD -PKG_FILE_NAME = "#{PKG_NAME}-#{PKG_VERSION}" - -RELEASE_NAME = "REL #{PKG_VERSION}" - -RUBY_FORGE_PROJECT = "activesupport" -RUBY_FORGE_USER = "webster132" - task :default => :test Rake::TestTask.new do |t| t.libs << 'test' diff --git a/pushgems.rb b/pushgems.rb deleted file mode 100755 index 784aa5de68..0000000000 --- a/pushgems.rb +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env ruby - -unless ARGV.first == "no_build" - build_number = Time.now.strftime("%Y%m%d%H%M%S").to_i -end - -%w( activeresource actionmailer actionpack activerecord railties activesupport ).each do |pkg| - puts "Pushing: #{pkg} (#{build_number})" - if build_number - `cd #{pkg} && rm -rf pkg && PKG_BUILD=#{build_number} rake pgem && cd ..` - else - `cd #{pkg} && rm -rf pkg && rake pgem && cd ..` - end -end \ No newline at end of file diff --git a/railties/Rakefile b/railties/Rakefile index f32a794544..d62bfb71eb 100644 --- a/railties/Rakefile +++ b/railties/Rakefile @@ -11,17 +11,6 @@ require 'rbconfig' $LOAD_PATH.unshift "#{File.dirname(__FILE__)}/lib" require 'rails/version' -PKG_BUILD = ENV['PKG_BUILD'] ? '.' + ENV['PKG_BUILD'] : '' -PKG_NAME = 'railties' -PKG_VERSION = Rails::VERSION::STRING + PKG_BUILD -PKG_FILE_NAME = "#{PKG_NAME}-#{PKG_VERSION}" -PKG_DESTINATION = ENV["RAILS_PKG_DESTINATION"] || "../#{PKG_NAME}" - -RELEASE_NAME = "REL #{PKG_VERSION}" - -RUBY_FORGE_PROJECT = "rails" -RUBY_FORGE_USER = "webster132" - task :default => :test task :test => 'test:isolated' diff --git a/release.rb b/release.rb deleted file mode 100755 index e8e6c01c35..0000000000 --- a/release.rb +++ /dev/null @@ -1,25 +0,0 @@ -#!/usr/bin/env ruby - -VERSION = ARGV.first -PACKAGES = %w(activesupport activerecord actionpack actionmailer activeresource) - -# Copy source -`mkdir release` -(PACKAGES + %w(railties)).each do |p| - `cp -R #{p} release/#{p}` -end - -# Create Rails packages -`cd release/railties && rake template=jamis package` - -# Upload documentation -`cd release/rails/doc/api && scp -r * davidhh@wrath.rubyonrails.com:public_html/api` - -# Upload packages -(PACKAGES + %w(railties)).each do |p| - `cd release/#{p} && echo "Releasing #{p}" && rake release` -end - -# Upload rails tgz/zip -`rubyforge add_release rails rails 'REL #{VERSION}' release/rails-#{VERSION}.tgz` -`rubyforge add_release rails rails 'REL #{VERSION}' release/rails-#{VERSION}.zip` \ No newline at end of file -- cgit v1.2.3 From 812136a0b23787aa0e81c28d0bbc71a9ccf0f6ea Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 1 Mar 2010 19:29:12 -0800 Subject: Fix unstated usage of Pathname --- railties/lib/rails/engine.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb index af47227510..07218dcfa8 100644 --- a/railties/lib/rails/engine.rb +++ b/railties/lib/rails/engine.rb @@ -1,5 +1,6 @@ -require 'active_support/core_ext/module/delegation' require 'rails/railtie' +require 'active_support/core_ext/module/delegation' +require 'pathname' module Rails class Engine < Railtie -- cgit v1.2.3 From a0e8eca30bc1f3cf7519bea37456cbfc98b56047 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 1 Mar 2010 21:29:47 -0800 Subject: Fix unstated usage of Action Dispatch --- railties/lib/rails/configuration.rb | 37 +++++++++++++++++++++---------------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/railties/lib/rails/configuration.rb b/railties/lib/rails/configuration.rb index 811c3a9fd9..bcd98c67f8 100644 --- a/railties/lib/rails/configuration.rb +++ b/railties/lib/rails/configuration.rb @@ -6,22 +6,7 @@ module Rails module Configuration module Shared def middleware - @@default_middleware_stack ||= ActionDispatch::MiddlewareStack.new.tap do |middleware| - middleware.use('::ActionDispatch::Static', lambda { Rails.public_path }, :if => lambda { Rails.application.config.serve_static_assets }) - middleware.use('::Rack::Lock', :if => lambda { !Rails.application.config.allow_concurrency }) - middleware.use('::Rack::Runtime') - middleware.use('::Rails::Rack::Logger') - middleware.use('::ActionDispatch::ShowExceptions', lambda { Rails.application.config.consider_all_requests_local }) - middleware.use('::Rack::Sendfile', lambda { Rails.application.config.action_dispatch.x_sendfile_header }) - middleware.use('::ActionDispatch::Callbacks', lambda { !Rails.application.config.cache_classes }) - middleware.use('::ActionDispatch::Cookies') - middleware.use(lambda { ActionController::Base.session_store }, lambda { ActionController::Base.session_options }) - middleware.use('::ActionDispatch::Flash', :if => lambda { ActionController::Base.session_store }) - middleware.use(lambda { Rails.application.metal_loader.build_middleware(Rails.application.config.metals) }, :if => lambda { Rails.application.metal_loader.metals.any? }) - middleware.use('ActionDispatch::ParamsParser') - middleware.use('::Rack::MethodOverride') - middleware.use('::ActionDispatch::Head') - end + @@default_middleware_stack ||= default_middleware end # Holds generators configuration: @@ -86,6 +71,26 @@ module Rails def options @@options ||= Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new } end + + def default_middleware + require 'action_dispatch' + ActionDispatch::MiddlewareStack.new.tap do |middleware| + middleware.use('::ActionDispatch::Static', lambda { Rails.public_path }, :if => lambda { Rails.application.config.serve_static_assets }) + middleware.use('::Rack::Lock', :if => lambda { !Rails.application.config.allow_concurrency }) + middleware.use('::Rack::Runtime') + middleware.use('::Rails::Rack::Logger') + middleware.use('::ActionDispatch::ShowExceptions', lambda { Rails.application.config.consider_all_requests_local }) + middleware.use('::Rack::Sendfile', lambda { Rails.application.config.action_dispatch.x_sendfile_header }) + middleware.use('::ActionDispatch::Callbacks', lambda { !Rails.application.config.cache_classes }) + middleware.use('::ActionDispatch::Cookies') + middleware.use(lambda { ActionController::Base.session_store }, lambda { ActionController::Base.session_options }) + middleware.use('::ActionDispatch::Flash', :if => lambda { ActionController::Base.session_store }) + middleware.use(lambda { Rails.application.metal_loader.build_middleware(Rails.application.config.metals) }, :if => lambda { Rails.application.metal_loader.metals.any? }) + middleware.use('ActionDispatch::ParamsParser') + middleware.use('::Rack::MethodOverride') + middleware.use('::ActionDispatch::Head') + end + end end class Generators #:nodoc: -- cgit v1.2.3 From b1769fe0bd6ea3b7eb7147333754d4b712831b2c Mon Sep 17 00:00:00 2001 From: Bryan Helmkamp Date: Mon, 1 Mar 2010 23:02:55 -0500 Subject: Add `rake update_versions` task at root for quickly updating all components --- Rakefile | 22 ++++++++++++++++++++++ version.rb | 10 ++++++++++ 2 files changed, 32 insertions(+) create mode 100644 version.rb diff --git a/Rakefile b/Rakefile index 4b14f8a2f1..0c1c240410 100644 --- a/Rakefile +++ b/Rakefile @@ -123,3 +123,25 @@ task :pdoc => :rdoc do system %(cd #{project} && #{$0} pdoc) end end + +task :update_versions do + constants = { + "activesupport" => "ActiveSupport", + "activemodel" => "ActiveModel", + "actionpack" => "ActionPack", + "actionmailer" => "ActionMailer", + "activeresource" => "ActiveResource", + "activerecord" => "ActiveRecord", + "railties" => "Rails" + } + + version_file = File.read("version.rb") + + PROJECTS.each do |project| + Dir["#{project}/lib/*/version.rb"].each do |file| + File.open(file, "w") do |f| + f.write version_file.gsub(/Rails/, constants[project]) + end + end + end +end diff --git a/version.rb b/version.rb new file mode 100644 index 0000000000..1dd8fa0ec7 --- /dev/null +++ b/version.rb @@ -0,0 +1,10 @@ +module Rails + module VERSION #:nodoc: + MAJOR = 3 + MINOR = 0 + TINY = 0 + BUILD = "beta1" + + STRING = [MAJOR, MINOR, TINY, BUILD].join('.') + end +end -- cgit v1.2.3 From a4111bbca0884e4a748ab32ba7d7b550ec8d9186 Mon Sep 17 00:00:00 2001 From: Bryan Helmkamp Date: Mon, 1 Mar 2010 23:03:07 -0500 Subject: Update versions of all components to normalize them to new format --- actionmailer/lib/action_mailer/version.rb | 5 +++-- actionpack/lib/action_pack/version.rb | 7 ++++--- activemodel/lib/active_model/version.rb | 5 +++-- activerecord/lib/active_record/version.rb | 5 +++-- activeresource/lib/active_resource/version.rb | 5 +++-- activesupport/lib/active_support/version.rb | 5 +++-- railties/lib/rails/version.rb | 5 +++-- 7 files changed, 22 insertions(+), 15 deletions(-) diff --git a/actionmailer/lib/action_mailer/version.rb b/actionmailer/lib/action_mailer/version.rb index 56af531d01..7328a7dc80 100644 --- a/actionmailer/lib/action_mailer/version.rb +++ b/actionmailer/lib/action_mailer/version.rb @@ -2,8 +2,9 @@ module ActionMailer module VERSION #:nodoc: MAJOR = 3 MINOR = 0 - TINY = "0.beta1" + TINY = 0 + BUILD = "beta1" - STRING = [MAJOR, MINOR, TINY].join('.') + STRING = [MAJOR, MINOR, TINY, BUILD].join('.') end end diff --git a/actionpack/lib/action_pack/version.rb b/actionpack/lib/action_pack/version.rb index 67f89e1627..72a1cd30ad 100644 --- a/actionpack/lib/action_pack/version.rb +++ b/actionpack/lib/action_pack/version.rb @@ -1,9 +1,10 @@ -module ActionPack #:nodoc: +module ActionPack module VERSION #:nodoc: MAJOR = 3 MINOR = 0 - TINY = "0.beta1" + TINY = 0 + BUILD = "beta1" - STRING = [MAJOR, MINOR, TINY].join('.') + STRING = [MAJOR, MINOR, TINY, BUILD].join('.') end end diff --git a/activemodel/lib/active_model/version.rb b/activemodel/lib/active_model/version.rb index d51423ae1b..85d0eed180 100644 --- a/activemodel/lib/active_model/version.rb +++ b/activemodel/lib/active_model/version.rb @@ -2,8 +2,9 @@ module ActiveModel module VERSION #:nodoc: MAJOR = 3 MINOR = 0 - TINY = "0.beta1" + TINY = 0 + BUILD = "beta1" - STRING = [MAJOR, MINOR, TINY].join('.') + STRING = [MAJOR, MINOR, TINY, BUILD].join('.') end end diff --git a/activerecord/lib/active_record/version.rb b/activerecord/lib/active_record/version.rb index 286ecd0289..eaf5dc6545 100644 --- a/activerecord/lib/active_record/version.rb +++ b/activerecord/lib/active_record/version.rb @@ -2,8 +2,9 @@ module ActiveRecord module VERSION #:nodoc: MAJOR = 3 MINOR = 0 - TINY = "0.beta1" + TINY = 0 + BUILD = "beta1" - STRING = [MAJOR, MINOR, TINY].join('.') + STRING = [MAJOR, MINOR, TINY, BUILD].join('.') end end diff --git a/activeresource/lib/active_resource/version.rb b/activeresource/lib/active_resource/version.rb index 461fef5283..bb60954e05 100644 --- a/activeresource/lib/active_resource/version.rb +++ b/activeresource/lib/active_resource/version.rb @@ -2,8 +2,9 @@ module ActiveResource module VERSION #:nodoc: MAJOR = 3 MINOR = 0 - TINY = "0.beta1" + TINY = 0 + BUILD = "beta1" - STRING = [MAJOR, MINOR, TINY].join('.') + STRING = [MAJOR, MINOR, TINY, BUILD].join('.') end end diff --git a/activesupport/lib/active_support/version.rb b/activesupport/lib/active_support/version.rb index 6c6187be29..831204693f 100644 --- a/activesupport/lib/active_support/version.rb +++ b/activesupport/lib/active_support/version.rb @@ -2,8 +2,9 @@ module ActiveSupport module VERSION #:nodoc: MAJOR = 3 MINOR = 0 - TINY = "0.beta1" + TINY = 0 + BUILD = "beta1" - STRING = [MAJOR, MINOR, TINY].join('.') + STRING = [MAJOR, MINOR, TINY, BUILD].join('.') end end diff --git a/railties/lib/rails/version.rb b/railties/lib/rails/version.rb index d0c7cb45db..1dd8fa0ec7 100644 --- a/railties/lib/rails/version.rb +++ b/railties/lib/rails/version.rb @@ -2,8 +2,9 @@ module Rails module VERSION #:nodoc: MAJOR = 3 MINOR = 0 - TINY = "0.beta1" + TINY = 0 + BUILD = "beta1" - STRING = [MAJOR, MINOR, TINY].join('.') + STRING = [MAJOR, MINOR, TINY, BUILD].join('.') end end -- cgit v1.2.3 From f221a6f19f4cee31e2d103ea9a1930f59223fc25 Mon Sep 17 00:00:00 2001 From: Bryan Helmkamp Date: Mon, 1 Mar 2010 23:36:54 -0500 Subject: Leverage VERSION constants from gemspecs to avoid tedious updates when releasing --- Rakefile | 13 +++++++++---- actionmailer/Rakefile | 1 - actionmailer/actionmailer.gemspec | 7 +++++-- actionpack/Rakefile | 1 - actionpack/actionpack.gemspec | 9 ++++++--- activemodel/Rakefile | 1 - activemodel/activemodel.gemspec | 7 +++++-- activerecord/Rakefile | 1 - activerecord/activerecord.gemspec | 9 ++++++--- activeresource/Rakefile | 2 -- activeresource/activeresource.gemspec | 9 ++++++--- activesupport/Rakefile | 2 -- activesupport/activesupport.gemspec | 5 ++++- rails.gemspec | 17 ++++++++++------- railties/Rakefile | 3 --- railties/lib/rails/tasks/documentation.rake | 2 +- railties/railties.gemspec | 9 ++++++--- 17 files changed, 58 insertions(+), 40 deletions(-) diff --git a/Rakefile b/Rakefile index 0c1c240410..50700fdeac 100644 --- a/Rakefile +++ b/Rakefile @@ -3,10 +3,15 @@ require 'rake/rdoctask' require 'rake/gempackagetask' PROJECTS = %w(activesupport activemodel actionpack actionmailer activeresource activerecord railties) - -Dir["#{File.dirname(__FILE__)}/*/lib/*/version.rb"].each do |version_path| - require version_path -end +PROJECTS.each { |project| $:.unshift "#{project}/lib" } + +require "active_support/version" +require "active_model/version" +require "action_pack/version" +require "action_mailer/version" +require "active_resource/version" +require "active_record/version" +require "rails/version" desc 'Run all tests by default' task :default => %w(test test:isolated) diff --git a/actionmailer/Rakefile b/actionmailer/Rakefile index 0cc743dfa6..5b72843f5e 100644 --- a/actionmailer/Rakefile +++ b/actionmailer/Rakefile @@ -4,7 +4,6 @@ require 'rake/testtask' require 'rake/rdoctask' require 'rake/packagetask' require 'rake/gempackagetask' -require File.join(File.dirname(__FILE__), 'lib', 'action_mailer', 'version') desc "Default Task" task :default => [ :test ] diff --git a/actionmailer/actionmailer.gemspec b/actionmailer/actionmailer.gemspec index 13983aa663..c7a363575b 100644 --- a/actionmailer/actionmailer.gemspec +++ b/actionmailer/actionmailer.gemspec @@ -1,7 +1,10 @@ +$:.unshift "lib" +require "action_mailer/version" + Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'actionmailer' - s.version = '3.0.0.beta1' + s.version = ActionMailer::VERSION::STRING s.summary = 'Email composition, delivery, and recieval framework (part of Rails).' s.description = 'Email composition, delivery, and recieval framework (part of Rails).' s.required_ruby_version = '>= 1.8.7' @@ -17,7 +20,7 @@ Gem::Specification.new do |s| s.has_rdoc = true - s.add_dependency('actionpack', '= 3.0.0.beta1') + s.add_dependency('actionpack', "= #{ActionMailer::VERSION::STRING}") s.add_dependency('mail', '~> 2.1.3') s.add_dependency('text-format', '~> 1.0.0') end diff --git a/actionpack/Rakefile b/actionpack/Rakefile index f099a4613e..b9ace8658a 100644 --- a/actionpack/Rakefile +++ b/actionpack/Rakefile @@ -4,7 +4,6 @@ require 'rake/testtask' require 'rake/rdoctask' require 'rake/packagetask' require 'rake/gempackagetask' -require File.join(File.dirname(__FILE__), 'lib', 'action_pack', 'version') desc "Default Task" task :default => :test diff --git a/actionpack/actionpack.gemspec b/actionpack/actionpack.gemspec index 00c4d7de1c..d19649a386 100644 --- a/actionpack/actionpack.gemspec +++ b/actionpack/actionpack.gemspec @@ -1,7 +1,10 @@ +$:.unshift "lib" +require "action_pack/version" + Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'actionpack' - s.version = '3.0.0.beta1' + s.version = ActionPack::VERSION::STRING s.summary = 'Web-flow and rendering framework putting the VC in MVC (part of Rails).' s.description = 'Web-flow and rendering framework putting the VC in MVC (part of Rails).' s.required_ruby_version = '>= 1.8.7' @@ -17,8 +20,8 @@ Gem::Specification.new do |s| s.has_rdoc = true - s.add_dependency('activesupport', '= 3.0.0.beta1') - s.add_dependency('activemodel', '= 3.0.0.beta1') + s.add_dependency('activesupport', "= #{ActionPack::VERSION::STRING}") + s.add_dependency('activemodel', "= #{ActionPack::VERSION::STRING}") s.add_dependency('rack', '~> 1.1.0') s.add_dependency('rack-test', '~> 0.5.0') s.add_dependency('rack-mount', '~> 0.5.1') diff --git a/activemodel/Rakefile b/activemodel/Rakefile index b1ebf07af0..d4a00c5073 100755 --- a/activemodel/Rakefile +++ b/activemodel/Rakefile @@ -1,5 +1,4 @@ dir = File.dirname(__FILE__) -require "#{dir}/lib/active_model/version" require 'rake/testtask' diff --git a/activemodel/activemodel.gemspec b/activemodel/activemodel.gemspec index b4fbe26d97..00e06c35be 100644 --- a/activemodel/activemodel.gemspec +++ b/activemodel/activemodel.gemspec @@ -1,7 +1,10 @@ +$:.unshift "lib" +require "active_model/version" + Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'activemodel' - s.version = '3.0.0.beta1' + s.version = ActiveModel::VERSION::STRING s.summary = "A toolkit for building other modeling frameworks like ActiveRecord" s.description = %q{Extracts common modeling concerns from ActiveRecord to share between similar frameworks like ActiveResource.} s.required_ruby_version = '>= 1.8.7' @@ -13,7 +16,7 @@ Gem::Specification.new do |s| s.has_rdoc = true - s.add_dependency('activesupport', '= 3.0.0.beta1') + s.add_dependency('activesupport', "= #{ActiveModel::VERSION::STRING}") s.require_path = 'lib' s.files = Dir["CHANGELOG", "MIT-LICENSE", "README", "lib/**/*"] diff --git a/activerecord/Rakefile b/activerecord/Rakefile index c53215e75e..e638da0f3e 100644 --- a/activerecord/Rakefile +++ b/activerecord/Rakefile @@ -5,7 +5,6 @@ require 'rake/rdoctask' require 'rake/packagetask' require 'rake/gempackagetask' -require File.join(File.dirname(__FILE__), 'lib', 'active_record', 'version') require File.expand_path(File.dirname(__FILE__)) + "/test/config" MYSQL_DB_USER = 'rails' diff --git a/activerecord/activerecord.gemspec b/activerecord/activerecord.gemspec index aeaafbb694..b269126a86 100644 --- a/activerecord/activerecord.gemspec +++ b/activerecord/activerecord.gemspec @@ -1,7 +1,10 @@ +$:.unshift "lib" +require "active_record/version" + Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'activerecord' - s.version = '3.0.0.beta1' + s.version = ActiveRecord::VERSION::STRING s.summary = 'Object-relational mapper framework (part of Rails).' s.description = 'Object-relational mapper framework (part of Rails).' s.required_ruby_version = '>= 1.8.7' @@ -18,7 +21,7 @@ Gem::Specification.new do |s| s.extra_rdoc_files = %w( README ) s.rdoc_options.concat ['--main', 'README'] - s.add_dependency('activesupport', '= 3.0.0.beta1') - s.add_dependency('activemodel', '= 3.0.0.beta1') + s.add_dependency('activesupport', "= #{ActiveRecord::VERSION::STRING}") + s.add_dependency('activemodel', "= #{ActiveRecord::VERSION::STRING}") s.add_dependency('arel', '~> 0.2.1') end diff --git a/activeresource/Rakefile b/activeresource/Rakefile index a0a8ab19d1..175b379699 100644 --- a/activeresource/Rakefile +++ b/activeresource/Rakefile @@ -5,8 +5,6 @@ require 'rake/rdoctask' require 'rake/packagetask' require 'rake/gempackagetask' -require File.join(File.dirname(__FILE__), 'lib', 'active_resource', 'version') - desc "Default Task" task :default => [ :test ] diff --git a/activeresource/activeresource.gemspec b/activeresource/activeresource.gemspec index 1722ebeb8e..4cee5dbddd 100644 --- a/activeresource/activeresource.gemspec +++ b/activeresource/activeresource.gemspec @@ -1,7 +1,10 @@ +$:.unshift "lib" +require "active_resource/version" + Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'activeresource' - s.version = '3.0.0.beta1' + s.version = ActiveResource::VERSION::STRING s.summary = 'REST-model framework (part of Rails).' s.description = 'REST-model framework (part of Rails).' s.required_ruby_version = '>= 1.8.7' @@ -18,6 +21,6 @@ Gem::Specification.new do |s| s.extra_rdoc_files = %w( README ) s.rdoc_options.concat ['--main', 'README'] - s.add_dependency('activesupport', '= 3.0.0.beta1') - s.add_dependency('activemodel', '= 3.0.0.beta1') + s.add_dependency('activesupport', "= #{ActiveResource::VERSION::STRING}") + s.add_dependency('activemodel', "= #{ActiveResource::VERSION::STRING}") end diff --git a/activesupport/Rakefile b/activesupport/Rakefile index 64e3111cf8..43f4722dbc 100644 --- a/activesupport/Rakefile +++ b/activesupport/Rakefile @@ -2,8 +2,6 @@ require 'rake/testtask' require 'rake/rdoctask' require 'rake/gempackagetask' -require File.join(File.dirname(__FILE__), 'lib', 'active_support', 'version') - task :default => :test Rake::TestTask.new do |t| t.libs << 'test' diff --git a/activesupport/activesupport.gemspec b/activesupport/activesupport.gemspec index 90d68a215a..d76f752457 100644 --- a/activesupport/activesupport.gemspec +++ b/activesupport/activesupport.gemspec @@ -1,7 +1,10 @@ +$:.unshift "lib" +require "active_support/version" + Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'activesupport' - s.version = '3.0.0.beta1' + s.version = ActiveSupport::VERSION::STRING s.summary = 'Support and utility classes used by the Rails framework.' s.description = 'Support and utility classes used by the Rails framework.' s.required_ruby_version = '>= 1.8.7' diff --git a/rails.gemspec b/rails.gemspec index 4ebbd8061f..52d82eee1f 100644 --- a/rails.gemspec +++ b/rails.gemspec @@ -1,7 +1,10 @@ +$:.unshift "railties/lib" +require "rails/version" + Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'rails' - s.version = '3.0.0.beta1' + s.version = Rails::VERSION::STRING s.summary = 'Full-stack web-application framework.' s.description = 'Full-stack web-application framework.' s.required_ruby_version = '>= 1.8.7' @@ -14,11 +17,11 @@ Gem::Specification.new do |s| s.files = [] s.require_path = [] - s.add_dependency('activesupport', '= 3.0.0.beta1') - s.add_dependency('actionpack', '= 3.0.0.beta1') - s.add_dependency('activerecord', '= 3.0.0.beta1') - s.add_dependency('activeresource', '= 3.0.0.beta1') - s.add_dependency('actionmailer', '= 3.0.0.beta1') - s.add_dependency('railties', '= 3.0.0.beta1') + s.add_dependency('activesupport', "= #{Rails::VERSION::STRING}") + s.add_dependency('actionpack', "= #{Rails::VERSION::STRING}") + s.add_dependency('activerecord', "= #{Rails::VERSION::STRING}") + s.add_dependency('activeresource', "= #{Rails::VERSION::STRING}") + s.add_dependency('actionmailer', "= #{Rails::VERSION::STRING}") + s.add_dependency('railties', "= #{Rails::VERSION::STRING}") s.add_dependency('bundler', '>= 0.9.8') end diff --git a/railties/Rakefile b/railties/Rakefile index d62bfb71eb..fe049d565f 100644 --- a/railties/Rakefile +++ b/railties/Rakefile @@ -8,9 +8,6 @@ require 'rake/gempackagetask' require 'date' require 'rbconfig' -$LOAD_PATH.unshift "#{File.dirname(__FILE__)}/lib" -require 'rails/version' - task :default => :test task :test => 'test:isolated' diff --git a/railties/lib/rails/tasks/documentation.rake b/railties/lib/rails/tasks/documentation.rake index f7cc6ff4be..1f4067d29e 100644 --- a/railties/lib/rails/tasks/documentation.rake +++ b/railties/lib/rails/tasks/documentation.rake @@ -14,7 +14,7 @@ namespace :doc do desc 'Generate documentation for the Rails framework. Specify path with PATH="/path/to/rails"' Rake::RDocTask.new("rails") { |rdoc| path = ENV['RAILS_PATH'] || 'vendor/gems/gems' - version = '-3.0.0.beta1' unless ENV['RAILS_PATH'] + version = "-#{Rails::VERSION::STRING}" unless ENV['RAILS_PATH'] rdoc.rdoc_dir = 'doc/api' rdoc.template = "#{ENV['template']}.rb" if ENV['template'] rdoc.title = "Rails Framework Documentation" diff --git a/railties/railties.gemspec b/railties/railties.gemspec index c43bb7e1e9..e2758a84e5 100644 --- a/railties/railties.gemspec +++ b/railties/railties.gemspec @@ -1,7 +1,10 @@ +$:.unshift "lib" +require "rails/version" + Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'railties' - s.version = '3.0.0.beta1' + s.version = Rails::VERSION::STRING s.summary = 'Controls boot-up, rake tasks and generators for the Rails framework.' s.description = 'Controls boot-up, rake tasks and generators for the Rails framework.' s.required_ruby_version = '>= 1.8.7' @@ -22,6 +25,6 @@ Gem::Specification.new do |s| s.add_dependency('rake', '>= 0.8.3') s.add_dependency('thor', '~> 0.13.4') - s.add_dependency('activesupport', '= 3.0.0.beta1') - s.add_dependency('actionpack', '= 3.0.0.beta1') + s.add_dependency('activesupport', "= #{Rails::VERSION::STRING}") + s.add_dependency('actionpack', "= #{Rails::VERSION::STRING}") end -- cgit v1.2.3 From ea4fd64133998ce5d6791e0cd98e42f1463ae301 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 1 Mar 2010 23:22:11 -0800 Subject: Revert orphaned SharedTestRoutes --- actionpack/lib/action_view/test_case.rb | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/actionpack/lib/action_view/test_case.rb b/actionpack/lib/action_view/test_case.rb index f6f4e18a4a..af2ed33f3f 100644 --- a/actionpack/lib/action_view/test_case.rb +++ b/actionpack/lib/action_view/test_case.rb @@ -53,7 +53,6 @@ module ActionView setup :setup_with_controller def setup_with_controller @controller = TestController.new - @router = SharedTestRoutes @output_buffer = ActiveSupport::SafeBuffer.new @rendered = '' @@ -153,7 +152,7 @@ module ActionView end def method_missing(selector, *args) - if @router.named_routes.helpers.include?(selector) + if ActionDispatch::Routing::Routes.named_routes.helpers.include?(selector) @controller.__send__(selector, *args) else super -- cgit v1.2.3 From 56ea20605a54386158e90e290caa6d15e7623ade Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 2 Mar 2010 10:32:09 -0800 Subject: Wordsmith gem descriptions --- actionmailer/actionmailer.gemspec | 4 ++-- actionpack/actionpack.gemspec | 2 +- activemodel/activemodel.gemspec | 5 +++-- activerecord/activerecord.gemspec | 2 +- activeresource/activeresource.gemspec | 4 ++-- activesupport/activesupport.gemspec | 4 ++-- rails.gemspec | 4 ++-- railties/railties.gemspec | 4 ++-- 8 files changed, 15 insertions(+), 14 deletions(-) diff --git a/actionmailer/actionmailer.gemspec b/actionmailer/actionmailer.gemspec index c7a363575b..fc7f3f1e5f 100644 --- a/actionmailer/actionmailer.gemspec +++ b/actionmailer/actionmailer.gemspec @@ -5,8 +5,8 @@ Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'actionmailer' s.version = ActionMailer::VERSION::STRING - s.summary = 'Email composition, delivery, and recieval framework (part of Rails).' - s.description = 'Email composition, delivery, and recieval framework (part of Rails).' + s.summary = 'Email composition, delivery, and receiving framework (part of Rails).' + s.description = 'Email on Rails. Compose, deliver, receive, and test emails using the familiar controller/view pattern. First-class support for multipart email and attachments.' s.required_ruby_version = '>= 1.8.7' s.author = 'David Heinemeier Hansson' diff --git a/actionpack/actionpack.gemspec b/actionpack/actionpack.gemspec index d19649a386..a281df8642 100644 --- a/actionpack/actionpack.gemspec +++ b/actionpack/actionpack.gemspec @@ -6,7 +6,7 @@ Gem::Specification.new do |s| s.name = 'actionpack' s.version = ActionPack::VERSION::STRING s.summary = 'Web-flow and rendering framework putting the VC in MVC (part of Rails).' - s.description = 'Web-flow and rendering framework putting the VC in MVC (part of Rails).' + s.description = 'Web apps on Rails. Simple, battle-tested conventions for building and testing MVC web applications. Works with any Rack-compatible server.' s.required_ruby_version = '>= 1.8.7' s.author = 'David Heinemeier Hansson' diff --git a/activemodel/activemodel.gemspec b/activemodel/activemodel.gemspec index 00e06c35be..80b4461e60 100644 --- a/activemodel/activemodel.gemspec +++ b/activemodel/activemodel.gemspec @@ -5,8 +5,9 @@ Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'activemodel' s.version = ActiveModel::VERSION::STRING - s.summary = "A toolkit for building other modeling frameworks like ActiveRecord" - s.description = %q{Extracts common modeling concerns from ActiveRecord to share between similar frameworks like ActiveResource.} + s.summary = 'A toolkit for building modeling frameworks (part of Rails).' + s.description = 'A toolkit for building modeling frameworks like Active Record and Active Resource. Rich support for attributes, callbacks, validations, observers, serialization, internationalization, and testing.' + to share between similar frameworks like ActiveResource.} s.required_ruby_version = '>= 1.8.7' s.author = "David Heinemeier Hansson" diff --git a/activerecord/activerecord.gemspec b/activerecord/activerecord.gemspec index b269126a86..5d76333950 100644 --- a/activerecord/activerecord.gemspec +++ b/activerecord/activerecord.gemspec @@ -6,7 +6,7 @@ Gem::Specification.new do |s| s.name = 'activerecord' s.version = ActiveRecord::VERSION::STRING s.summary = 'Object-relational mapper framework (part of Rails).' - s.description = 'Object-relational mapper framework (part of Rails).' + s.description = 'Databases on Rails. Build a persistent domain model by mapping database tables to Ruby classes. Strong conventions for associations, validations, aggregations, migrations, and testing come baked-in.' s.required_ruby_version = '>= 1.8.7' s.author = 'David Heinemeier Hansson' diff --git a/activeresource/activeresource.gemspec b/activeresource/activeresource.gemspec index 4cee5dbddd..209364a5dc 100644 --- a/activeresource/activeresource.gemspec +++ b/activeresource/activeresource.gemspec @@ -5,8 +5,8 @@ Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'activeresource' s.version = ActiveResource::VERSION::STRING - s.summary = 'REST-model framework (part of Rails).' - s.description = 'REST-model framework (part of Rails).' + s.summary = 'REST modeling framework (part of Rails).' + s.description = 'REST on Rails. Wrap your RESTful web app with Ruby classes and work with them like Active Record models.' s.required_ruby_version = '>= 1.8.7' s.author = 'David Heinemeier Hansson' diff --git a/activesupport/activesupport.gemspec b/activesupport/activesupport.gemspec index d76f752457..3273d84b27 100644 --- a/activesupport/activesupport.gemspec +++ b/activesupport/activesupport.gemspec @@ -5,8 +5,8 @@ Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'activesupport' s.version = ActiveSupport::VERSION::STRING - s.summary = 'Support and utility classes used by the Rails framework.' - s.description = 'Support and utility classes used by the Rails framework.' + s.summary = 'A toolkit of support libraries and Ruby core extensions extracted from the Rails framework.' + s.summary = 'A toolkit of support libraries and Ruby core extensions extracted from the Rails framework. Rich support for multibyte strings, internationalization, time zones, and testing.' s.required_ruby_version = '>= 1.8.7' s.author = 'David Heinemeier Hansson' diff --git a/rails.gemspec b/rails.gemspec index 52d82eee1f..0cd4540ec3 100644 --- a/rails.gemspec +++ b/rails.gemspec @@ -5,8 +5,8 @@ Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'rails' s.version = Rails::VERSION::STRING - s.summary = 'Full-stack web-application framework.' - s.description = 'Full-stack web-application framework.' + s.summary = 'Full-stack web application framework.' + s.description = 'Ruby on Rails is a full-stack web framework optimized for programmer happiness and sustainable productivity. It encourages beautiful code by favoring convention over configuration.' s.required_ruby_version = '>= 1.8.7' s.author = 'David Heinemeier Hansson' diff --git a/railties/railties.gemspec b/railties/railties.gemspec index e2758a84e5..7b17642667 100644 --- a/railties/railties.gemspec +++ b/railties/railties.gemspec @@ -5,8 +5,8 @@ Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'railties' s.version = Rails::VERSION::STRING - s.summary = 'Controls boot-up, rake tasks and generators for the Rails framework.' - s.description = 'Controls boot-up, rake tasks and generators for the Rails framework.' + s.summary = 'Tools for creating, working with, and running Rails applications.' + s.description = 'Rails internals: application bootup, plugins, generators, and rake tasks.' s.required_ruby_version = '>= 1.8.7' s.author = 'David Heinemeier Hansson' -- cgit v1.2.3 From 5c40c2691d78c5252df415e69d479445318cd740 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 2 Mar 2010 10:44:16 -0800 Subject: Stray line. Typo. --- activemodel/activemodel.gemspec | 1 - activesupport/activesupport.gemspec | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/activemodel/activemodel.gemspec b/activemodel/activemodel.gemspec index 80b4461e60..9183558c7c 100644 --- a/activemodel/activemodel.gemspec +++ b/activemodel/activemodel.gemspec @@ -7,7 +7,6 @@ Gem::Specification.new do |s| s.version = ActiveModel::VERSION::STRING s.summary = 'A toolkit for building modeling frameworks (part of Rails).' s.description = 'A toolkit for building modeling frameworks like Active Record and Active Resource. Rich support for attributes, callbacks, validations, observers, serialization, internationalization, and testing.' - to share between similar frameworks like ActiveResource.} s.required_ruby_version = '>= 1.8.7' s.author = "David Heinemeier Hansson" diff --git a/activesupport/activesupport.gemspec b/activesupport/activesupport.gemspec index 3273d84b27..89e8dca278 100644 --- a/activesupport/activesupport.gemspec +++ b/activesupport/activesupport.gemspec @@ -6,7 +6,7 @@ Gem::Specification.new do |s| s.name = 'activesupport' s.version = ActiveSupport::VERSION::STRING s.summary = 'A toolkit of support libraries and Ruby core extensions extracted from the Rails framework.' - s.summary = 'A toolkit of support libraries and Ruby core extensions extracted from the Rails framework. Rich support for multibyte strings, internationalization, time zones, and testing.' + s.description = 'A toolkit of support libraries and Ruby core extensions extracted from the Rails framework. Rich support for multibyte strings, internationalization, time zones, and testing.' s.required_ruby_version = '>= 1.8.7' s.author = 'David Heinemeier Hansson' -- cgit v1.2.3 From a64fcc1a8d84b274691b5e332257eabf0cb5c2a8 Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Tue, 2 Mar 2010 12:06:40 -0800 Subject: :controller doesn't work for namespaced controllers anymore. --- railties/test/rails_info_controller_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/railties/test/rails_info_controller_test.rb b/railties/test/rails_info_controller_test.rb index 7275755130..d904d7b461 100644 --- a/railties/test/rails_info_controller_test.rb +++ b/railties/test/rails_info_controller_test.rb @@ -15,7 +15,7 @@ class InfoControllerTest < ActionController::TestCase def setup Rails.application.routes.draw do |map| - match ':controller/:action' + match '/rails/info/properties' => "rails/info#properties" end @controller.stubs(:consider_all_requests_local? => false, :local_request? => true) @router = Rails.application.routes -- cgit v1.2.3 From 57bae9764e45ad19dff7a879eeb46d1dffc5ca22 Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Tue, 2 Mar 2010 12:31:29 -0800 Subject: Fix a test that assumes that defined?(ActiveRecord) == defined?(ActiveRecord::Base) --- railties/test/application/initializers/frameworks_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/railties/test/application/initializers/frameworks_test.rb b/railties/test/application/initializers/frameworks_test.rb index 94d3505518..91f31df2e7 100644 --- a/railties/test/application/initializers/frameworks_test.rb +++ b/railties/test/application/initializers/frameworks_test.rb @@ -91,7 +91,7 @@ module ApplicationTests test "database middleware doesn't initialize when activerecord is not in frameworks" do use_frameworks [] require "#{app_path}/config/environment" - assert_nil defined?(ActiveRecord) + assert_nil defined?(ActiveRecord::Base) end end end -- cgit v1.2.3 From b01db07a9f009016186da34c4936a9efb2c224c6 Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Tue, 2 Mar 2010 12:32:31 -0800 Subject: Moved initializers for ActionMailer and ActionController into their own railties --- actionmailer/lib/action_mailer/railtie.rb | 5 +++++ actionpack/lib/action_controller/railtie.rb | 5 +++++ railties/lib/rails/application/bootstrap.rb | 16 ++-------------- 3 files changed, 12 insertions(+), 14 deletions(-) diff --git a/actionmailer/lib/action_mailer/railtie.rb b/actionmailer/lib/action_mailer/railtie.rb index c5f18c7911..779486fc96 100644 --- a/actionmailer/lib/action_mailer/railtie.rb +++ b/actionmailer/lib/action_mailer/railtie.rb @@ -16,6 +16,11 @@ module ActionMailer ActionMailer::Base.logger ||= Rails.logger end + initializer "action_mailer.add_view_paths" do |app| + views = app.config.paths.app.views.to_a + ActionMailer::Base.prepend_view_path(views) + end + initializer "action_mailer.set_configs" do |app| app.config.action_mailer.each do |k,v| ActionMailer::Base.send "#{k}=", v diff --git a/actionpack/lib/action_controller/railtie.rb b/actionpack/lib/action_controller/railtie.rb index 07c6b8f2b6..a18b63fb13 100644 --- a/actionpack/lib/action_controller/railtie.rb +++ b/actionpack/lib/action_controller/railtie.rb @@ -27,6 +27,11 @@ module ActionController ActionController::Base.cache_store ||= RAILS_CACHE end + initializer "action_controller.add_view_paths" do |app| + views = app.config.paths.app.views.to_a + ActionController::Base.prepend_view_path(views) + end + initializer "action_controller.set_helpers_path" do |app| ActionController::Base.helpers_path = app.config.paths.app.helpers.to_a end diff --git a/railties/lib/rails/application/bootstrap.rb b/railties/lib/rails/application/bootstrap.rb index 0714b34b31..06243f2e5e 100644 --- a/railties/lib/rails/application/bootstrap.rb +++ b/railties/lib/rails/application/bootstrap.rb @@ -1,3 +1,5 @@ +require "active_support/notifications" + module Rails class Application module Bootstrap @@ -49,20 +51,6 @@ module Rails end end - # Initialize rails log subscriber on top of notifications. - initializer :initialize_log_subscriber do - require 'active_support/notifications' - - if config.colorize_logging == false - Rails::LogSubscriber.colorize_logging = false - config.generators.colorize_logging = false - end - - ActiveSupport::Notifications.subscribe do |*args| - Rails::LogSubscriber.dispatch(args) - end - end - initializer :set_clear_dependencies_hook do unless config.cache_classes ActionDispatch::Callbacks.after do -- cgit v1.2.3 From d434c5406846fb280b8a9d6ec40247b1f1b464c6 Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Tue, 2 Mar 2010 12:34:26 -0800 Subject: Log Tailer doesn't exist anymore. Removing some traces left over in tests. --- railties/test/log_subscriber_test.rb | 2 -- 1 file changed, 2 deletions(-) diff --git a/railties/test/log_subscriber_test.rb b/railties/test/log_subscriber_test.rb index a4de023e65..49288cfaa8 100644 --- a/railties/test/log_subscriber_test.rb +++ b/railties/test/log_subscriber_test.rb @@ -30,13 +30,11 @@ class SyncLogSubscriberTest < ActiveSupport::TestCase def setup super @log_subscriber = MyLogSubscriber.new - Rails::LogSubscriber.instance_variable_set(:@log_tailer, nil) end def teardown super Rails::LogSubscriber.log_subscribers.clear - Rails::LogSubscriber.instance_variable_set(:@log_tailer, nil) end def instrument(*args, &block) -- cgit v1.2.3 From c2dbc391a9292e6f73cadce2f0ba1be871b29e82 Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Tue, 2 Mar 2010 13:05:25 -0800 Subject: Have log subscribers subscribe to the actual events, so the subscriber doesn't subscribe to *every* event, so we can have events that are slow-ish but are not actually run in production. --- railties/lib/rails/application/configuration.rb | 13 +++++++-- railties/lib/rails/log_subscriber.rb | 34 +++++++++++------------- railties/lib/rails/log_subscriber/test_helper.rb | 1 - 3 files changed, 27 insertions(+), 21 deletions(-) diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb index d6ad045294..a00f9c43ae 100644 --- a/railties/lib/rails/application/configuration.rb +++ b/railties/lib/rails/application/configuration.rb @@ -5,7 +5,7 @@ module Rails class Configuration < ::Rails::Engine::Configuration include ::Rails::Configuration::Deprecated - attr_accessor :allow_concurrency, :cache_classes, :cache_store, :colorize_logging, + attr_accessor :allow_concurrency, :cache_classes, :cache_store, :consider_all_requests_local, :dependency_loading, :filter_parameters, :log_level, :logger, :metals, :plugins, :preload_frameworks, :reload_engines, :reload_plugins, @@ -14,7 +14,6 @@ module Rails def initialize(*) super @allow_concurrency = false - @colorize_logging = true @filter_parameters = [] @dependency_loading = true @serve_static_assets = true @@ -81,6 +80,16 @@ module Rails def log_level @log_level ||= Rails.env.production? ? :info : :debug end + + def colorize_logging + @colorize_logging + end + + def colorize_logging=(val) + @colorize_logging = val + Rails::LogSubscriber.colorize_logging = val + self.generators.colorize_logging = val + end end end end \ No newline at end of file diff --git a/railties/lib/rails/log_subscriber.rb b/railties/lib/rails/log_subscriber.rb index 05cb70690a..0fbc19d89c 100644 --- a/railties/lib/rails/log_subscriber.rb +++ b/railties/lib/rails/log_subscriber.rb @@ -29,7 +29,7 @@ module Rails # This is useful because it avoids spanning several log subscribers just for logging # purposes(which slows down the main thread). Besides of providing a centralized # facility on top of Rails.logger. - # + # # Log subscriber also has some helpers to deal with logging and automatically flushes # all logs when the request finishes (via action_dispatch.callback notification). class LogSubscriber @@ -50,31 +50,29 @@ module Rails CYAN = "\e[36m" WHITE = "\e[37m" - def self.add(namespace, log_subscriber) - log_subscribers[namespace.to_sym] = log_subscriber - end - - def self.log_subscribers - @log_subscribers ||= {} - end + def self.add(namespace, log_subscriber, notifier = ActiveSupport::Notifications) + log_subscribers << log_subscriber - def self.dispatch(args) - namespace, name = args[0].split(".") - return unless namespace && name + log_subscriber.public_methods(false).each do |event| + notifier.subscribe("#{namespace}.#{event}") do |*args| + next if log_subscriber.logger.nil? - log_subscriber = log_subscribers[namespace.to_sym] - if log_subscriber.respond_to?(name) && log_subscriber.logger - begin - log_subscriber.send(name, ActiveSupport::Notifications::Event.new(*args)) - rescue Exception => e - Rails.logger.error "Could not log #{args[0].inspect} event. #{e.class}: #{e.message}" + begin + log_subscriber.send(event, ActiveSupport::Notifications::Event.new(*args)) + rescue Exception => e + Rails.logger.error "Could not log #{args[0].inspect} event. #{e.class}: #{e.message}" + end end end end + def self.log_subscribers + @log_subscribers ||= [] + end + # Flush all log_subscribers' logger. def self.flush_all! - loggers = log_subscribers.values.map(&:logger) + loggers = log_subscribers.map(&:logger) loggers.uniq! loggers.each { |l| l.flush if l.respond_to?(:flush) } end diff --git a/railties/lib/rails/log_subscriber/test_helper.rb b/railties/lib/rails/log_subscriber/test_helper.rb index 9ede56cad4..02f5079462 100644 --- a/railties/lib/rails/log_subscriber/test_helper.rb +++ b/railties/lib/rails/log_subscriber/test_helper.rb @@ -43,7 +43,6 @@ module Rails @notifier = ActiveSupport::Notifications::Notifier.new(queue) Rails::LogSubscriber.colorize_logging = false - @notifier.subscribe { |*args| Rails::LogSubscriber.dispatch(args) } set_logger(@logger) ActiveSupport::Notifications.notifier = @notifier -- cgit v1.2.3 From ecfd6d90eeeeeffb7415b4d9316da4e0bc35743b Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 2 Mar 2010 13:41:02 -0800 Subject: Action Mailer setup obviated by test bundle --- actionpack/test/controller/assert_select_test.rb | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/actionpack/test/controller/assert_select_test.rb b/actionpack/test/controller/assert_select_test.rb index 612827dd41..cb3e848dfa 100644 --- a/actionpack/test/controller/assert_select_test.rb +++ b/actionpack/test/controller/assert_select_test.rb @@ -6,18 +6,7 @@ require 'abstract_unit' require 'controller/fake_controllers' - -unless defined?(ActionMailer) - begin - $:.unshift("#{File.dirname(__FILE__)}/../../../actionmailer/lib") - require 'action_mailer' - rescue LoadError => e - raise unless e.message =~ /action_mailer/ - require 'rubygems' - gem 'actionmailer' - end -end - +require 'action_mailer' ActionMailer::Base.view_paths = FIXTURE_LOAD_PATH class AssertSelectTest < ActionController::TestCase -- cgit v1.2.3 From aa749a74f63547a503772f4489fb60b5e4fbea1a Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Tue, 2 Mar 2010 14:00:17 -0800 Subject: Get the railties tests to pass again. --- actionmailer/lib/action_mailer/railtie.rb | 5 ----- actionpack/lib/action_controller/railtie.rb | 5 ----- railties/lib/rails/engine.rb | 4 ++-- railties/test/railties/railtie_test.rb | 2 +- 4 files changed, 3 insertions(+), 13 deletions(-) diff --git a/actionmailer/lib/action_mailer/railtie.rb b/actionmailer/lib/action_mailer/railtie.rb index 779486fc96..c5f18c7911 100644 --- a/actionmailer/lib/action_mailer/railtie.rb +++ b/actionmailer/lib/action_mailer/railtie.rb @@ -16,11 +16,6 @@ module ActionMailer ActionMailer::Base.logger ||= Rails.logger end - initializer "action_mailer.add_view_paths" do |app| - views = app.config.paths.app.views.to_a - ActionMailer::Base.prepend_view_path(views) - end - initializer "action_mailer.set_configs" do |app| app.config.action_mailer.each do |k,v| ActionMailer::Base.send "#{k}=", v diff --git a/actionpack/lib/action_controller/railtie.rb b/actionpack/lib/action_controller/railtie.rb index a18b63fb13..07c6b8f2b6 100644 --- a/actionpack/lib/action_controller/railtie.rb +++ b/actionpack/lib/action_controller/railtie.rb @@ -27,11 +27,6 @@ module ActionController ActionController::Base.cache_store ||= RAILS_CACHE end - initializer "action_controller.add_view_paths" do |app| - views = app.config.paths.app.views.to_a - ActionController::Base.prepend_view_path(views) - end - initializer "action_controller.set_helpers_path" do |app| ActionController::Base.helpers_path = app.config.paths.app.helpers.to_a end diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb index 07218dcfa8..79183480a3 100644 --- a/railties/lib/rails/engine.rb +++ b/railties/lib/rails/engine.rb @@ -97,8 +97,8 @@ module Rails initializer :add_view_paths do views = paths.app.views.to_a - ActionController::Base.prepend_view_path(views) if defined?(ActionController) - ActionMailer::Base.prepend_view_path(views) if defined?(ActionMailer) + ActionController::Base.prepend_view_path(views) if defined?(ActionController::Base) + ActionMailer::Base.prepend_view_path(views) if defined?(ActionMailer::Base) end initializer :add_metals do |app| diff --git a/railties/test/railties/railtie_test.rb b/railties/test/railties/railtie_test.rb index 9eb4e9993a..9fefb285b4 100644 --- a/railties/test/railties/railtie_test.rb +++ b/railties/test/railties/railtie_test.rb @@ -54,7 +54,7 @@ module RailtiesTest test "railtie can add log subscribers" do begin class Foo < Rails::Railtie ; log_subscriber(Rails::LogSubscriber.new) ; end - assert_kind_of Rails::LogSubscriber, Rails::LogSubscriber.log_subscribers[:foo] + assert_kind_of Rails::LogSubscriber, Rails::LogSubscriber.log_subscribers[0] ensure Rails::LogSubscriber.log_subscribers.clear end -- cgit v1.2.3 From 6d7d03b77c281014ab01177ed47b7e887866e3f9 Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Tue, 2 Mar 2010 14:04:57 -0800 Subject: Fix some tests that relied on hardcoded Exception information (ht: evan) --- actionpack/test/template/render_test.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/actionpack/test/template/render_test.rb b/actionpack/test/template/render_test.rb index fdf3db1cdb..338ada8b0e 100644 --- a/actionpack/test/template/render_test.rb +++ b/actionpack/test/template/render_test.rb @@ -108,7 +108,7 @@ module RenderTestCases @view.render(:partial => "test/raise") flunk "Render did not raise Template::Error" rescue ActionView::Template::Error => e - assert_match "undefined local variable or method `doesnt_exist'", e.message + assert_match %r!method.*doesnt_exist!, e.message assert_equal "", e.sub_template_message assert_equal "1", e.line_number assert_equal File.expand_path("#{FIXTURE_LOAD_PATH}/test/_raise.html.erb"), e.file_name @@ -118,7 +118,7 @@ module RenderTestCases @view.render(:file => "test/sub_template_raise") flunk "Render did not raise Template::Error" rescue ActionView::Template::Error => e - assert_match "undefined local variable or method `doesnt_exist'", e.message + assert_match %r!method.*doesnt_exist!, e.message assert_equal "Trace of template inclusion: #{File.expand_path("#{FIXTURE_LOAD_PATH}/test/sub_template_raise.html.erb")}", e.sub_template_message assert_equal "1", e.line_number assert_equal File.expand_path("#{FIXTURE_LOAD_PATH}/test/_raise.html.erb"), e.file_name -- cgit v1.2.3 From 9f83cdc38e03dc3e65a702b00dc4a3cc0bb44e60 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 2 Mar 2010 14:07:42 -0800 Subject: No longer add missing leading / on path args to assert_redirected_to. Deprecated in 2.3.6. --- .../action_dispatch/testing/assertions/response.rb | 23 +++++++++++++--------- .../test/controller/action_pack_assertions_test.rb | 6 ++++-- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/actionpack/lib/action_dispatch/testing/assertions/response.rb b/actionpack/lib/action_dispatch/testing/assertions/response.rb index c2486d3730..937c9f48d2 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/response.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/response.rb @@ -132,16 +132,21 @@ module ActionDispatch end def normalize_argument_to_redirection(fragment) - after_routing = @controller.url_for(fragment) - if after_routing =~ %r{^\w+://.*} - after_routing - else - # FIXME - this should probably get removed. - if after_routing.first != '/' - after_routing = '/' + after_routing + case fragment + when %r{^\w[\w\d+.-]*:.*} + fragment + when String + if fragment =~ %r{^\w[\w\d+.-]*:.*} + fragment + else + @request.protocol + @request.host_with_port + fragment end - @request.protocol + @request.host_with_port + after_routing - end + when :back + raise RedirectBackError unless refer = @request.headers["Referer"] + refer + else + @controller.url_for(fragment) + end.gsub(/[\r\n]/, '') end def validate_request! diff --git a/actionpack/test/controller/action_pack_assertions_test.rb b/actionpack/test/controller/action_pack_assertions_test.rb index 6906dc97e8..26e0d6d844 100644 --- a/actionpack/test/controller/action_pack_assertions_test.rb +++ b/actionpack/test/controller/action_pack_assertions_test.rb @@ -469,9 +469,11 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase assert_redirected_to '/some/path' end - def test_redirected_to_url_no_leadling_slash + def test_redirected_to_url_no_leading_slash_fails process :redirect_to_path - assert_redirected_to 'some/path' + assert_raise ActiveSupport::TestCase::Assertion do + assert_redirected_to 'some/path' + end end def test_redirected_to_url_full_url -- cgit v1.2.3 From d78e3fe73fccb90ddb25dc04f9643b83cae2b9e3 Mon Sep 17 00:00:00 2001 From: Carlhuda Date: Tue, 2 Mar 2010 14:40:59 -0800 Subject: Fix failing Action Pack tests --- actionpack/lib/action_view/test_case.rb | 2 +- actionpack/test/abstract_unit.rb | 10 ++++++++++ actionpack/test/activerecord/controller_runtime_test.rb | 2 +- actionpack/test/controller/log_subscriber_test.rb | 3 ++- actionpack/test/template/log_subscriber_test.rb | 2 +- 5 files changed, 15 insertions(+), 4 deletions(-) diff --git a/actionpack/lib/action_view/test_case.rb b/actionpack/lib/action_view/test_case.rb index af2ed33f3f..f639700eaf 100644 --- a/actionpack/lib/action_view/test_case.rb +++ b/actionpack/lib/action_view/test_case.rb @@ -152,7 +152,7 @@ module ActionView end def method_missing(selector, *args) - if ActionDispatch::Routing::Routes.named_routes.helpers.include?(selector) + if @controller._router.named_routes.helpers.include?(selector) @controller.__send__(selector, *args) else super diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb index 660cabc554..f1e8779cfa 100644 --- a/actionpack/test/abstract_unit.rb +++ b/actionpack/test/abstract_unit.rb @@ -203,6 +203,16 @@ end class ::ApplicationController < ActionController::Base end +module ActionView + class TestCase + # Must repeat the setup because AV::TestCase is a duplication + # of AC::TestCase + setup do + @router = SharedTestRoutes + end + end +end + module ActionController class Base include ActionController::Testing diff --git a/actionpack/test/activerecord/controller_runtime_test.rb b/actionpack/test/activerecord/controller_runtime_test.rb index d089830857..331f861d8f 100644 --- a/actionpack/test/activerecord/controller_runtime_test.rb +++ b/actionpack/test/activerecord/controller_runtime_test.rb @@ -17,9 +17,9 @@ class ControllerRuntimeLogSubscriberTest < ActionController::TestCase tests LogSubscriberController def setup + super @old_logger = ActionController::Base.logger Rails::LogSubscriber.add(:action_controller, ActionController::Railties::LogSubscriber.new) - super end def teardown diff --git a/actionpack/test/controller/log_subscriber_test.rb b/actionpack/test/controller/log_subscriber_test.rb index 668d6ae5ea..1f8134822c 100644 --- a/actionpack/test/controller/log_subscriber_test.rb +++ b/actionpack/test/controller/log_subscriber_test.rb @@ -40,6 +40,8 @@ class ACLogSubscriberTest < ActionController::TestCase include Rails::LogSubscriber::TestHelper def setup + super + @old_logger = ActionController::Base.logger @cache_path = File.expand_path('../temp/test_cache', File.dirname(__FILE__)) @@ -47,7 +49,6 @@ class ACLogSubscriberTest < ActionController::TestCase ActionController::Base.cache_store = :file_store, @cache_path Rails::LogSubscriber.add(:action_controller, ActionController::Railties::LogSubscriber.new) - super end def teardown diff --git a/actionpack/test/template/log_subscriber_test.rb b/actionpack/test/template/log_subscriber_test.rb index 2eb2484cf5..5076dfa70f 100644 --- a/actionpack/test/template/log_subscriber_test.rb +++ b/actionpack/test/template/log_subscriber_test.rb @@ -7,11 +7,11 @@ class AVLogSubscriberTest < ActiveSupport::TestCase include Rails::LogSubscriber::TestHelper def setup + super @old_logger = ActionController::Base.logger @view = ActionView::Base.new(ActionController::Base.view_paths, {}) Rails.stubs(:root).returns(File.expand_path(FIXTURE_LOAD_PATH)) Rails::LogSubscriber.add(:action_view, ActionView::Railties::LogSubscriber.new) - super end def teardown -- cgit v1.2.3 From 6193be26ce49bc24d67eb97f2f5f49c86f9f6bb7 Mon Sep 17 00:00:00 2001 From: Mikel Lindsaar Date: Wed, 3 Mar 2010 13:39:36 +1100 Subject: Removing prototype and just using vanilla js --- .../rails/app/templates/public/index.html | 34 +++++++++++----------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/railties/lib/generators/rails/app/templates/public/index.html b/railties/lib/generators/rails/app/templates/public/index.html index ef916f9c5a..836da1b689 100644 --- a/railties/lib/generators/rails/app/templates/public/index.html +++ b/railties/lib/generators/rails/app/templates/public/index.html @@ -181,27 +181,27 @@ } - - @@ -210,7 +210,7 @@