aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--actionmailer/CHANGELOG5
-rw-r--r--actionmailer/lib/action_mailer/base.rb2
-rw-r--r--actionmailer/test/abstract_unit.rb12
-rw-r--r--actionmailer/test/mail_service_test.rb5
-rw-r--r--actionpack/CHANGELOG2
-rw-r--r--actionpack/lib/action_controller/layout.rb2
-rw-r--r--actionpack/lib/action_view/helpers/asset_tag_helper.rb3
-rw-r--r--actionpack/lib/action_view/helpers/atom_feed_helper.rb2
-rw-r--r--actionpack/lib/action_view/helpers/form_helper.rb3
-rw-r--r--actionpack/lib/action_view/helpers/url_helper.rb27
-rw-r--r--actionpack/lib/action_view/paths.rb6
-rw-r--r--actionpack/test/abstract_unit.rb6
-rw-r--r--actionpack/test/controller/caching_test.rb24
-rw-r--r--actionpack/test/controller/dispatcher_test.rb4
-rw-r--r--actionpack/test/controller/integration_test.rb4
-rw-r--r--actionpack/test/controller/polymorphic_routes_test.rb306
-rw-r--r--actionpack/test/controller/render_test.rb11
-rw-r--r--actionpack/test/controller/rescue_test.rb3
-rw-r--r--actionpack/test/controller/routing_test.rb2764
-rw-r--r--actionpack/test/fixtures/test/render_implicit_js_template_without_layout.js.erb1
-rw-r--r--actionpack/test/template/active_record_helper_i18n_test.rb64
-rw-r--r--actionpack/test/template/asset_tag_helper_test.rb26
-rw-r--r--actionpack/test/template/compiled_templates_test.rb134
-rw-r--r--actionpack/test/template/date_helper_i18n_test.rb176
-rw-r--r--actionpack/test/template/date_helper_test.rb66
-rw-r--r--actionpack/test/template/form_helper_test.rb9
-rw-r--r--actionpack/test/template/form_options_helper_test.rb1198
-rw-r--r--actionpack/test/template/number_helper_i18n_test.rb108
-rw-r--r--actionpack/test/template/test_test.rb10
-rw-r--r--actionpack/test/template/translation_helper_test.rb36
-rw-r--r--actionpack/test/template/url_helper_test.rb35
-rw-r--r--activerecord/CHANGELOG5
-rw-r--r--activerecord/lib/active_record/attribute_methods.rb1
-rw-r--r--activerecord/lib/active_record/autosave_association.rb12
-rwxr-xr-xactiverecord/lib/active_record/base.rb22
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb1
-rw-r--r--activerecord/lib/active_record/nested_attributes.rb8
-rw-r--r--activerecord/lib/active_record/session_store.rb2
-rw-r--r--activerecord/lib/active_record/validations.rb2
-rw-r--r--activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb10
-rw-r--r--activerecord/test/cases/associations/has_many_associations_test.rb10
-rw-r--r--activerecord/test/cases/associations/has_many_through_associations_test.rb10
-rw-r--r--activerecord/test/cases/associations/join_model_test.rb12
-rw-r--r--activerecord/test/cases/attribute_methods_test.rb12
-rw-r--r--activerecord/test/cases/autosave_association_test.rb24
-rw-r--r--activerecord/test/cases/calculations_test.rb36
-rw-r--r--activerecord/test/cases/datatype_test_postgresql.rb1
-rw-r--r--activerecord/test/cases/finder_test.rb39
-rw-r--r--activerecord/test/cases/fixtures_test.rb30
-rw-r--r--activerecord/test/cases/helper.rb13
-rw-r--r--activerecord/test/cases/migration_test.rb424
-rw-r--r--activerecord/test/cases/nested_attributes_test.rb14
-rw-r--r--activerecord/test/cases/query_cache_test.rb4
-rw-r--r--activerecord/test/cases/transactions_test.rb32
-rw-r--r--activerecord/test/cases/validations_i18n_test.rb580
-rw-r--r--activeresource/test/abstract_unit.rb12
-rw-r--r--activeresource/test/connection_test.rb28
-rw-r--r--activesupport/lib/active_support/inflector.rb2
-rw-r--r--activesupport/lib/active_support/multibyte/chars.rb2
-rw-r--r--activesupport/test/abstract_unit.rb3
-rwxr-xr-xci/ci_build.rb4
-rw-r--r--ci/geminstaller.yml2
-rwxr-xr-xrailties/guides/files/javascripts/code_highlighter.js376
-rwxr-xr-xrailties/guides/files/javascripts/guides.js16
-rw-r--r--railties/guides/files/javascripts/highlighters.js4
-rw-r--r--railties/guides/files/stylesheets/main.css24
-rwxr-xr-xrailties/guides/files/stylesheets/print.css104
-rwxr-xr-xrailties/guides/files/stylesheets/reset.css86
-rwxr-xr-xrailties/guides/files/stylesheets/style.css26
-rw-r--r--railties/guides/files/stylesheets/syntax.css4
-rw-r--r--railties/guides/rails_guides/indexer.rb2
-rw-r--r--railties/guides/source/2_2_release_notes.textile10
-rw-r--r--railties/guides/source/2_3_release_notes.textile84
-rw-r--r--railties/guides/source/action_controller_overview.textile6
-rw-r--r--railties/guides/source/action_mailer_basics.textile28
-rw-r--r--railties/guides/source/active_record_basics.textile8
-rw-r--r--railties/guides/source/activerecord_validations_callbacks.textile98
-rw-r--r--railties/guides/source/association_basics.textile66
-rw-r--r--railties/guides/source/caching_with_rails.textile24
-rw-r--r--railties/guides/source/command_line.textile22
-rw-r--r--railties/guides/source/debugging_rails_applications.textile16
-rw-r--r--railties/guides/source/form_helpers.textile16
-rw-r--r--railties/guides/source/getting_started.textile40
-rw-r--r--railties/guides/source/i18n.textile32
-rw-r--r--railties/guides/source/layout.html.erb6
-rw-r--r--railties/guides/source/layouts_and_rendering.textile20
-rw-r--r--railties/guides/source/migrations.textile22
-rw-r--r--railties/guides/source/performance_testing.textile12
-rw-r--r--railties/guides/source/plugins.textile76
-rw-r--r--railties/guides/source/rails_on_rack.textile4
-rw-r--r--railties/guides/source/routing.textile26
-rw-r--r--railties/guides/source/security.textile10
-rw-r--r--railties/guides/source/testing.textile72
-rw-r--r--railties/lib/commands/server.rb19
-rw-r--r--railties/lib/initializer.rb4
-rw-r--r--railties/lib/rails_generator/generators/components/scaffold/templates/controller.rb2
-rw-r--r--railties/lib/rails_generator/generators/components/scaffold/templates/layout.html.erb2
-rw-r--r--railties/lib/rails_generator/generators/components/scaffold/templates/view_edit.html.erb4
-rw-r--r--railties/lib/rails_generator/generators/components/scaffold/templates/view_index.html.erb4
-rw-r--r--railties/lib/rails_generator/generators/components/scaffold/templates/view_new.html.erb4
-rw-r--r--railties/lib/rails_generator/generators/components/scaffold/templates/view_show.html.erb2
-rw-r--r--railties/lib/tasks/databases.rake1
-rw-r--r--railties/test/abstract_unit.rb12
-rw-r--r--railties/test/boot_test.rb5
-rw-r--r--railties/test/console_app_test.rb22
-rw-r--r--railties/test/gem_dependency_test.rb230
-rw-r--r--railties/test/generators/rails_scaffold_generator_test.rb24
-rw-r--r--railties/test/initializer_test.rb416
-rw-r--r--railties/test/plugin_locator_test.rb107
-rw-r--r--railties/test/plugin_test.rb271
110 files changed, 4472 insertions, 4408 deletions
diff --git a/actionmailer/CHANGELOG b/actionmailer/CHANGELOG
index ecfa25b0a0..457e9aca94 100644
--- a/actionmailer/CHANGELOG
+++ b/actionmailer/CHANGELOG
@@ -1,3 +1,8 @@
+*Edge*
+
+* Fixed that ActionMailer should send correctly formatted Return-Path in MAIL FROM for SMTP #1842 [Matt Jones]
+
+
*2.3.0 [RC1] (February 1st, 2009)*
* Fixed RFC-2045 quoted-printable bug #1421 [squadette]
diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb
index eda5de4e18..f421945763 100644
--- a/actionmailer/lib/action_mailer/base.rb
+++ b/actionmailer/lib/action_mailer/base.rb
@@ -672,7 +672,7 @@ module ActionMailer #:nodoc:
def perform_delivery_smtp(mail)
destinations = mail.destinations
mail.ready_to_send
- sender = mail['return-path'] || mail.from
+ sender = (mail['return-path'] && mail['return-path'].spec) || mail.from
smtp = Net::SMTP.new(smtp_settings[:address], smtp_settings[:port])
smtp.enable_starttls_auto if smtp_settings[:enable_starttls_auto] && smtp.respond_to?(:enable_starttls_auto)
diff --git a/actionmailer/test/abstract_unit.rb b/actionmailer/test/abstract_unit.rb
index a6126d6f7f..51b375fef3 100644
--- a/actionmailer/test/abstract_unit.rb
+++ b/actionmailer/test/abstract_unit.rb
@@ -1,5 +1,9 @@
+require 'rubygems'
require 'test/unit'
+gem 'mocha', '>= 0.9.5'
+require 'mocha'
+
$:.unshift "#{File.dirname(__FILE__)}/../lib"
$:.unshift "#{File.dirname(__FILE__)}/../../activesupport/lib"
$:.unshift "#{File.dirname(__FILE__)}/../../actionpack/lib"
@@ -43,7 +47,6 @@ class Net::SMTP
end
def uses_gem(gem_name, test_name, version = '> 0')
- require 'rubygems'
gem gem_name.to_s, version
require gem_name.to_s
yield
@@ -51,13 +54,6 @@ rescue LoadError
$stderr.puts "Skipping #{test_name} tests. `gem install #{gem_name}` and try again."
end
-# Wrap tests that use Mocha and skip if unavailable.
-unless defined? uses_mocha
- def uses_mocha(test_name, &block)
- uses_gem('mocha', test_name, '>= 0.5.5', &block)
- end
-end
-
def set_delivery_method(delivery_method)
@old_delivery_method = ActionMailer::Base.delivery_method
ActionMailer::Base.delivery_method = delivery_method
diff --git a/actionmailer/test/mail_service_test.rb b/actionmailer/test/mail_service_test.rb
index a886b1143e..1e04531753 100644
--- a/actionmailer/test/mail_service_test.rb
+++ b/actionmailer/test/mail_service_test.rb
@@ -289,8 +289,6 @@ class TestMailer < ActionMailer::Base
end
end
-uses_mocha 'ActionMailerTest' do
-
class ActionMailerTest < Test::Unit::TestCase
include ActionMailer::Quoting
@@ -940,6 +938,7 @@ EOF
ActionMailer::Base.delivery_method = :smtp
TestMailer.deliver_return_path
assert_match %r{^Return-Path: <another@somewhere.test>}, MockSMTP.deliveries[0][0]
+ assert_equal "another@somewhere.test", MockSMTP.deliveries[0][1].to_s
end
def test_body_is_stored_as_an_ivar
@@ -974,8 +973,6 @@ EOF
end
end
-end # uses_mocha
-
class InheritableTemplateRootTest < Test::Unit::TestCase
def test_attr
expected = "#{File.dirname(__FILE__)}/fixtures/path.with.dots"
diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG
index 546311e078..41e3be8b35 100644
--- a/actionpack/CHANGELOG
+++ b/actionpack/CHANGELOG
@@ -1,5 +1,7 @@
*Edge*
+* Fix a syntax error in current_page?() that was prevent matches against URL's with multiple query parameters #1385, #1868 [chris finne/Andrew White]
+
* Added localized rescue template when I18n.locale is set (ex: public/404.da.html) #1835 [José Valim]
diff --git a/actionpack/lib/action_controller/layout.rb b/actionpack/lib/action_controller/layout.rb
index 183d56c2e8..d6bcf7a8c1 100644
--- a/actionpack/lib/action_controller/layout.rb
+++ b/actionpack/lib/action_controller/layout.rb
@@ -173,7 +173,7 @@ module ActionController #:nodoc:
end
def default_layout(format) #:nodoc:
- layout = read_inheritable_attribute(:layout)
+ layout = read_inheritable_attribute(:layout) unless format == :js
return layout unless read_inheritable_attribute(:auto_layout)
find_layout(layout, format)
end
diff --git a/actionpack/lib/action_view/helpers/asset_tag_helper.rb b/actionpack/lib/action_view/helpers/asset_tag_helper.rb
index f6abea38ed..a32beb6100 100644
--- a/actionpack/lib/action_view/helpers/asset_tag_helper.rb
+++ b/actionpack/lib/action_view/helpers/asset_tag_helper.rb
@@ -516,7 +516,8 @@ module ActionView
def compute_public_path(source, dir, ext = nil, include_host = true)
has_request = @controller.respond_to?(:request)
- if ext && (File.extname(source).blank? || File.exist?(File.join(ASSETS_DIR, dir, "#{source}.#{ext}")))
+ source_ext = File.extname(source)[1..-1]
+ if ext && (source_ext.blank? || (ext != source_ext && File.exist?(File.join(ASSETS_DIR, dir, "#{source}.#{ext}"))))
source += ".#{ext}"
end
diff --git a/actionpack/lib/action_view/helpers/atom_feed_helper.rb b/actionpack/lib/action_view/helpers/atom_feed_helper.rb
index cd25684940..dc4497581c 100644
--- a/actionpack/lib/action_view/helpers/atom_feed_helper.rb
+++ b/actionpack/lib/action_view/helpers/atom_feed_helper.rb
@@ -30,7 +30,7 @@ module ActionView
# app/views/posts/index.atom.builder:
# atom_feed do |feed|
# feed.title("My great blog!")
- # feed.updated((@posts.first.created_at))
+ # feed.updated(@posts.first.created_at)
#
# for post in @posts
# feed.entry(post) do |entry|
diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb
index 2ac2427884..0651f75cfb 100644
--- a/actionpack/lib/action_view/helpers/form_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_helper.rb
@@ -971,7 +971,8 @@ module ActionView
@template.fields_for(child_name, child, *args, &block)
end.join
else
- @template.fields_for(name, association, *args, &block)
+ object = args.first.respond_to?(:new_record?) ? args.first : association
+ @template.fields_for(name, object, *args, &block)
end
end
diff --git a/actionpack/lib/action_view/helpers/url_helper.rb b/actionpack/lib/action_view/helpers/url_helper.rb
index 2e0eb8766b..36e0a78e93 100644
--- a/actionpack/lib/action_view/helpers/url_helper.rb
+++ b/actionpack/lib/action_view/helpers/url_helper.rb
@@ -507,7 +507,30 @@ module ActionView
# current_page?(:controller => 'shop', :action => 'checkout')
# # => true
#
- # current_page?(:controller => 'shop', :action => 'checkout', :order => 'asc)
+ # current_page?(:controller => 'shop', :action => 'checkout', :order => 'asc')
+ # # => false
+ #
+ # current_page?(:action => 'checkout')
+ # # => true
+ #
+ # current_page?(:controller => 'library', :action => 'checkout')
+ # # => false
+ #
+ # Let's say we're in the <tt>/shop/checkout?order=desc&page=1</tt> action.
+ #
+ # current_page?(:action => 'process')
+ # # => false
+ #
+ # current_page?(:controller => 'shop', :action => 'checkout')
+ # # => true
+ #
+ # current_page?(:controller => 'shop', :action => 'checkout', :order => 'desc', :page=>'1')
+ # # => true
+ #
+ # current_page?(:controller => 'shop', :action => 'checkout', :order => 'desc', :page=>'2')
+ # # => false
+ #
+ # current_page?(:controller => 'shop', :action => 'checkout', :order => 'desc')
# # => false
#
# current_page?(:action => 'checkout')
@@ -516,7 +539,7 @@ module ActionView
# current_page?(:controller => 'library', :action => 'checkout')
# # => false
def current_page?(options)
- url_string = CGI.escapeHTML(url_for(options))
+ url_string = CGI.unescapeHTML(url_for(options))
request = @controller.request
# We ignore any extra parameters in the request_uri if the
# submitted url doesn't have any either. This lets the function
diff --git a/actionpack/lib/action_view/paths.rb b/actionpack/lib/action_view/paths.rb
index ee26542a07..c7d6fd696a 100644
--- a/actionpack/lib/action_view/paths.rb
+++ b/actionpack/lib/action_view/paths.rb
@@ -2,7 +2,11 @@ module ActionView #:nodoc:
class PathSet < Array #:nodoc:
def self.type_cast(obj)
if obj.is_a?(String)
- Template::EagerPath.new(obj)
+ if !Object.const_defined?(:Rails) || Rails.configuration.cache_classes
+ Template::EagerPath.new(obj)
+ else
+ Template::Path.new(obj)
+ end
else
obj
end
diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb
index 882d2cd6a8..c3717a60b8 100644
--- a/actionpack/test/abstract_unit.rb
+++ b/actionpack/test/abstract_unit.rb
@@ -8,7 +8,7 @@ require 'yaml'
require 'stringio'
require 'test/unit'
-gem 'mocha', '>= 0.9.3'
+gem 'mocha', '>= 0.9.5'
require 'mocha'
begin
@@ -38,7 +38,3 @@ ORIGINAL_LOCALES = I18n.available_locales.map(&:to_s).sort
FIXTURE_LOAD_PATH = File.join(File.dirname(__FILE__), 'fixtures')
ActionController::Base.view_paths = FIXTURE_LOAD_PATH
-
-def uses_mocha(test_name)
- yield
-end
diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb
index 7f8e47ba58..9af1ccc740 100644
--- a/actionpack/test/controller/caching_test.rb
+++ b/actionpack/test/controller/caching_test.rb
@@ -108,13 +108,11 @@ class PageCachingTest < ActionController::TestCase
assert File.exist?("#{FILE_STORE_PATH}/page_caching_test/trailing_slash.html")
end
- uses_mocha("should_cache_ok_at_custom_path") do
- def test_should_cache_ok_at_custom_path
- @request.stubs(:path).returns("/index.html")
- get :ok
- assert_response :ok
- assert File.exist?("#{FILE_STORE_PATH}/index.html")
- end
+ def test_should_cache_ok_at_custom_path
+ @request.stubs(:path).returns("/index.html")
+ get :ok
+ assert_response :ok
+ assert File.exist?("#{FILE_STORE_PATH}/index.html")
end
[:ok, :no_content, :found, :not_found].each do |status|
@@ -291,13 +289,11 @@ class ActionCacheTest < ActionController::TestCase
ActionController::Base.use_accept_header = old_use_accept_header
end
- uses_mocha 'test action cache' do
- def test_action_cache_with_store_options
- MockTime.expects(:now).returns(12345).once
- @controller.expects(:read_fragment).with('hostname.com/action_caching_test', :expires_in => 1.hour).once
- @controller.expects(:write_fragment).with('hostname.com/action_caching_test', '12345.0', :expires_in => 1.hour).once
- get :index
- end
+ def test_action_cache_with_store_options
+ MockTime.expects(:now).returns(12345).once
+ @controller.expects(:read_fragment).with('hostname.com/action_caching_test', :expires_in => 1.hour).once
+ @controller.expects(:write_fragment).with('hostname.com/action_caching_test', '12345.0', :expires_in => 1.hour).once
+ get :index
end
def test_action_cache_with_custom_cache_path
diff --git a/actionpack/test/controller/dispatcher_test.rb b/actionpack/test/controller/dispatcher_test.rb
index 7cd4e71aa1..47226f1fc5 100644
--- a/actionpack/test/controller/dispatcher_test.rb
+++ b/actionpack/test/controller/dispatcher_test.rb
@@ -1,7 +1,5 @@
require 'abstract_unit'
-uses_mocha 'dispatcher tests' do
-
class DispatcherTest < Test::Unit::TestCase
Dispatcher = ActionController::Dispatcher
@@ -100,5 +98,3 @@ class DispatcherTest < Test::Unit::TestCase
assert_equal howmany, klass.subclasses.size, message
end
end
-
-end
diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb
index dc2c6fae49..57517e45a7 100644
--- a/actionpack/test/controller/integration_test.rb
+++ b/actionpack/test/controller/integration_test.rb
@@ -1,7 +1,5 @@
require 'abstract_unit'
-uses_mocha 'integration' do
-
class SessionTest < Test::Unit::TestCase
StubApp = lambda { |env|
[200, {"Content-Type" => "text/html", "Content-Length" => "13"}, "Hello, World!"]
@@ -417,5 +415,3 @@ class MetalTest < ActionController::IntegrationTest
assert_equal '', response.body
end
end
-
-end
diff --git a/actionpack/test/controller/polymorphic_routes_test.rb b/actionpack/test/controller/polymorphic_routes_test.rb
index 09c7f74617..53295522ae 100644
--- a/actionpack/test/controller/polymorphic_routes_test.rb
+++ b/actionpack/test/controller/polymorphic_routes_test.rb
@@ -21,190 +21,188 @@ end
# TODO: test nested models
class Response::Nested < Response; end
-uses_mocha 'polymorphic URL helpers' do
- class PolymorphicRoutesTest < ActiveSupport::TestCase
- include ActionController::PolymorphicRoutes
+class PolymorphicRoutesTest < ActiveSupport::TestCase
+ include ActionController::PolymorphicRoutes
- def setup
- @article = Article.new
- @response = Response.new
- end
-
- def test_with_record
- @article.save
- expects(:article_url).with(@article)
- polymorphic_url(@article)
- end
+ def setup
+ @article = Article.new
+ @response = Response.new
+ end
- def test_with_new_record
- expects(:articles_url).with()
- @article.expects(:new_record?).returns(true)
- polymorphic_url(@article)
- end
+ def test_with_record
+ @article.save
+ expects(:article_url).with(@article)
+ polymorphic_url(@article)
+ end
- def test_with_record_and_action
- expects(:new_article_url).with()
- @article.expects(:new_record?).never
- polymorphic_url(@article, :action => 'new')
- end
+ def test_with_new_record
+ expects(:articles_url).with()
+ @article.expects(:new_record?).returns(true)
+ polymorphic_url(@article)
+ end
- def test_url_helper_prefixed_with_new
- expects(:new_article_url).with()
- new_polymorphic_url(@article)
- end
+ def test_with_record_and_action
+ expects(:new_article_url).with()
+ @article.expects(:new_record?).never
+ polymorphic_url(@article, :action => 'new')
+ end
- def test_url_helper_prefixed_with_edit
- @article.save
- expects(:edit_article_url).with(@article)
- edit_polymorphic_url(@article)
- end
+ def test_url_helper_prefixed_with_new
+ expects(:new_article_url).with()
+ new_polymorphic_url(@article)
+ end
- def test_url_helper_prefixed_with_edit_with_url_options
- @article.save
- expects(:edit_article_url).with(@article, :param1 => '10')
- edit_polymorphic_url(@article, :param1 => '10')
- end
+ def test_url_helper_prefixed_with_edit
+ @article.save
+ expects(:edit_article_url).with(@article)
+ edit_polymorphic_url(@article)
+ end
- def test_url_helper_with_url_options
- @article.save
- expects(:article_url).with(@article, :param1 => '10')
- polymorphic_url(@article, :param1 => '10')
- end
+ def test_url_helper_prefixed_with_edit_with_url_options
+ @article.save
+ expects(:edit_article_url).with(@article, :param1 => '10')
+ edit_polymorphic_url(@article, :param1 => '10')
+ end
- def test_formatted_url_helper_is_deprecated
- expects(:articles_url).with(:format => :pdf)
- assert_deprecated do
- formatted_polymorphic_url([@article, :pdf])
- end
- end
+ def test_url_helper_with_url_options
+ @article.save
+ expects(:article_url).with(@article, :param1 => '10')
+ polymorphic_url(@article, :param1 => '10')
+ end
- def test_format_option
- @article.save
- expects(:article_url).with(@article, :format => :pdf)
- polymorphic_url(@article, :format => :pdf)
+ def test_formatted_url_helper_is_deprecated
+ expects(:articles_url).with(:format => :pdf)
+ assert_deprecated do
+ formatted_polymorphic_url([@article, :pdf])
end
+ end
- def test_format_option_with_url_options
- @article.save
- expects(:article_url).with(@article, :format => :pdf, :param1 => '10')
- polymorphic_url(@article, :format => :pdf, :param1 => '10')
- end
+ def test_format_option
+ @article.save
+ expects(:article_url).with(@article, :format => :pdf)
+ polymorphic_url(@article, :format => :pdf)
+ end
- def test_id_and_format_option
- @article.save
- expects(:article_url).with(:id => @article, :format => :pdf)
- polymorphic_url(:id => @article, :format => :pdf)
- end
+ def test_format_option_with_url_options
+ @article.save
+ expects(:article_url).with(@article, :format => :pdf, :param1 => '10')
+ polymorphic_url(@article, :format => :pdf, :param1 => '10')
+ end
- def test_with_nested
- @response.save
- expects(:article_response_url).with(@article, @response)
- polymorphic_url([@article, @response])
- end
+ def test_id_and_format_option
+ @article.save
+ expects(:article_url).with(:id => @article, :format => :pdf)
+ polymorphic_url(:id => @article, :format => :pdf)
+ end
- def test_with_nested_unsaved
- expects(:article_responses_url).with(@article)
- polymorphic_url([@article, @response])
- end
+ def test_with_nested
+ @response.save
+ expects(:article_response_url).with(@article, @response)
+ polymorphic_url([@article, @response])
+ end
- def test_new_with_array_and_namespace
- expects(:new_admin_article_url).with()
- polymorphic_url([:admin, @article], :action => 'new')
- end
+ def test_with_nested_unsaved
+ expects(:article_responses_url).with(@article)
+ polymorphic_url([@article, @response])
+ end
- def test_unsaved_with_array_and_namespace
- expects(:admin_articles_url).with()
- polymorphic_url([:admin, @article])
- end
+ def test_new_with_array_and_namespace
+ expects(:new_admin_article_url).with()
+ polymorphic_url([:admin, @article], :action => 'new')
+ end
- def test_nested_unsaved_with_array_and_namespace
- @article.save
- expects(:admin_article_url).with(@article)
- polymorphic_url([:admin, @article])
- expects(:admin_article_responses_url).with(@article)
- polymorphic_url([:admin, @article, @response])
- end
+ def test_unsaved_with_array_and_namespace
+ expects(:admin_articles_url).with()
+ polymorphic_url([:admin, @article])
+ end
- def test_nested_with_array_and_namespace
- @response.save
- expects(:admin_article_response_url).with(@article, @response)
- polymorphic_url([:admin, @article, @response])
+ def test_nested_unsaved_with_array_and_namespace
+ @article.save
+ expects(:admin_article_url).with(@article)
+ polymorphic_url([:admin, @article])
+ expects(:admin_article_responses_url).with(@article)
+ polymorphic_url([:admin, @article, @response])
+ end
- # a ridiculously long named route tests correct ordering of namespaces and nesting:
- @tag = Tag.new
- @tag.save
- expects(:site_admin_article_response_tag_url).with(@article, @response, @tag)
- polymorphic_url([:site, :admin, @article, @response, @tag])
- end
+ def test_nested_with_array_and_namespace
+ @response.save
+ expects(:admin_article_response_url).with(@article, @response)
+ polymorphic_url([:admin, @article, @response])
- def test_nesting_with_array_ending_in_singleton_resource
- expects(:article_response_url).with(@article)
- polymorphic_url([@article, :response])
- end
+ # a ridiculously long named route tests correct ordering of namespaces and nesting:
+ @tag = Tag.new
+ @tag.save
+ expects(:site_admin_article_response_tag_url).with(@article, @response, @tag)
+ polymorphic_url([:site, :admin, @article, @response, @tag])
+ end
- def test_nesting_with_array_containing_singleton_resource
- @tag = Tag.new
- @tag.save
- expects(:article_response_tag_url).with(@article, @tag)
- polymorphic_url([@article, :response, @tag])
- end
+ def test_nesting_with_array_ending_in_singleton_resource
+ expects(:article_response_url).with(@article)
+ polymorphic_url([@article, :response])
+ end
- def test_nesting_with_array_containing_namespace_and_singleton_resource
- @tag = Tag.new
- @tag.save
- expects(:admin_article_response_tag_url).with(@article, @tag)
- polymorphic_url([:admin, @article, :response, @tag])
- end
+ def test_nesting_with_array_containing_singleton_resource
+ @tag = Tag.new
+ @tag.save
+ expects(:article_response_tag_url).with(@article, @tag)
+ polymorphic_url([@article, :response, @tag])
+ end
- def test_nesting_with_array_containing_singleton_resource_and_format
- @tag = Tag.new
- @tag.save
- expects(:article_response_tag_url).with(@article, @tag, :format => :pdf)
- polymorphic_url([@article, :response, @tag], :format => :pdf)
- end
+ def test_nesting_with_array_containing_namespace_and_singleton_resource
+ @tag = Tag.new
+ @tag.save
+ expects(:admin_article_response_tag_url).with(@article, @tag)
+ polymorphic_url([:admin, @article, :response, @tag])
+ end
- def test_nesting_with_array_containing_singleton_resource_and_format_option
- @tag = Tag.new
- @tag.save
- expects(:article_response_tag_url).with(@article, @tag, :format => :pdf)
- polymorphic_url([@article, :response, @tag], :format => :pdf)
- end
+ def test_nesting_with_array_containing_singleton_resource_and_format
+ @tag = Tag.new
+ @tag.save
+ expects(:article_response_tag_url).with(@article, @tag, :format => :pdf)
+ polymorphic_url([@article, :response, @tag], :format => :pdf)
+ end
- def test_nesting_with_array_containing_nil
- expects(:article_response_url).with(@article)
- polymorphic_url([@article, nil, :response])
- end
+ def test_nesting_with_array_containing_singleton_resource_and_format_option
+ @tag = Tag.new
+ @tag.save
+ expects(:article_response_tag_url).with(@article, @tag, :format => :pdf)
+ polymorphic_url([@article, :response, @tag], :format => :pdf)
+ end
- def test_with_array_containing_single_object
- @article.save
- expects(:article_url).with(@article)
- polymorphic_url([nil, @article])
- end
+ def test_nesting_with_array_containing_nil
+ expects(:article_response_url).with(@article)
+ polymorphic_url([@article, nil, :response])
+ end
- def test_with_array_containing_single_name
- @article.save
- expects(:articles_url)
- polymorphic_url([:articles])
- end
+ def test_with_array_containing_single_object
+ @article.save
+ expects(:article_url).with(@article)
+ polymorphic_url([nil, @article])
+ end
- # TODO: Needs to be updated to correctly know about whether the object is in a hash or not
- def xtest_with_hash
- expects(:article_url).with(@article)
- @article.save
- polymorphic_url(:id => @article)
- end
+ def test_with_array_containing_single_name
+ @article.save
+ expects(:articles_url)
+ polymorphic_url([:articles])
+ end
- def test_polymorphic_path_accepts_options
- expects(:new_article_path).with()
- polymorphic_path(@article, :action => :new)
- end
+ # TODO: Needs to be updated to correctly know about whether the object is in a hash or not
+ def xtest_with_hash
+ expects(:article_url).with(@article)
+ @article.save
+ polymorphic_url(:id => @article)
+ end
+
+ def test_polymorphic_path_accepts_options
+ expects(:new_article_path).with()
+ polymorphic_path(@article, :action => :new)
+ end
- def test_polymorphic_path_does_not_modify_arguments
- expects(:admin_article_responses_url).with(@article)
- path = [:admin, @article, @response]
- assert_no_difference 'path.size' do
- polymorphic_url(path)
- end
+ def test_polymorphic_path_does_not_modify_arguments
+ expects(:admin_article_responses_url).with(@article)
+ path = [:admin, @article, @response]
+ assert_no_difference 'path.size' do
+ polymorphic_url(path)
end
end
end
diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb
index 584b9277c4..e131a735a9 100644
--- a/actionpack/test/controller/render_test.rb
+++ b/actionpack/test/controller/render_test.rb
@@ -277,6 +277,9 @@ class TestController < ActionController::Base
def render_implicit_html_template_from_xhr_request
end
+ def render_implicit_js_template_without_layout
+ end
+
def formatted_html_erb
end
@@ -681,7 +684,8 @@ class TestController < ActionController::Base
"render_with_explicit_string_template",
"render_js_with_explicit_template",
"render_js_with_explicit_action_template",
- "delete_with_js", "update_page", "update_page_with_instance_variables"
+ "delete_with_js", "update_page", "update_page_with_instance_variables",
+ "render_implicit_js_template_without_layout"
"layouts/standard"
when "action_talk_to_layout", "layout_overriding_layout"
@@ -1018,6 +1022,11 @@ class RenderTest < ActionController::TestCase
assert_equal "Hello HTML!", @response.body
end
+ def test_should_implicitly_render_js_template_without_layout
+ get :render_implicit_js_template_without_layout, :format => :js
+ assert_no_match /<html>/, @response.body
+ end
+
def test_should_render_formatted_template
get :formatted_html_erb
assert_equal 'formatted html erb', @response.body
diff --git a/actionpack/test/controller/rescue_test.rb b/actionpack/test/controller/rescue_test.rb
index 85c2a4c1bb..d7c9499157 100644
--- a/actionpack/test/controller/rescue_test.rb
+++ b/actionpack/test/controller/rescue_test.rb
@@ -1,7 +1,5 @@
require 'abstract_unit'
-uses_mocha 'rescue' do
-
class RescueController < ActionController::Base
class NotAuthorized < StandardError
end
@@ -543,4 +541,3 @@ class ControllerInheritanceRescueControllerTest < ActionController::TestCase
assert_response :created
end
end
-end # uses_mocha
diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb
index b981119e1e..d6fc6fddb2 100644
--- a/actionpack/test/controller/routing_test.rb
+++ b/actionpack/test/controller/routing_test.rb
@@ -691,1635 +691,1592 @@ class RoutingTest < Test::Unit::TestCase
end
end
-uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do
- class MockController
- attr_accessor :routes
+class MockController
+ attr_accessor :routes
- def initialize(routes)
- self.routes = routes
- end
+ def initialize(routes)
+ self.routes = routes
+ end
- def url_for(options)
- only_path = options.delete(:only_path)
+ def url_for(options)
+ only_path = options.delete(:only_path)
- port = options.delete(:port) || 80
- port_string = port == 80 ? '' : ":#{port}"
+ 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)
+ protocol = options.delete(:protocol) || "http"
+ host = options.delete(:host) || "test.host"
+ anchor = "##{options.delete(:anchor)}" if options.key?(:anchor)
- path = routes.generate(options)
+ path = routes.generate(options)
- only_path ? "#{path}#{anchor}" : "#{protocol}://#{host}#{port_string}#{path}#{anchor}"
- end
-
- def request
- @request ||= ActionController::TestRequest.new
- end
+ only_path ? "#{path}#{anchor}" : "#{protocol}://#{host}#{port_string}#{path}#{anchor}"
end
- class LegacyRouteSetTests < Test::Unit::TestCase
- attr_reader :rs
+ def request
+ @request ||= ActionController::TestRequest.new
+ end
+end
- def setup
- # These tests assume optimisation is on, so re-enable it.
- ActionController::Base.optimise_named_routes = true
+class LegacyRouteSetTests < Test::Unit::TestCase
+ attr_reader :rs
- @rs = ::ActionController::Routing::RouteSet.new
+ def setup
+ # These tests assume optimisation is on, so re-enable it.
+ ActionController::Base.optimise_named_routes = true
+
+ @rs = ::ActionController::Routing::RouteSet.new
+
+ ActionController::Routing.use_controllers! %w(content admin/user admin/news_feed)
+ end
+
+ def teardown
+ @rs.clear!
+ end
+
+ def test_default_setup
+ @rs.draw {|m| m.connect ':controller/:action/:id' }
+ assert_equal({:controller => "content", :action => 'index'}, rs.recognize_path("/content"))
+ assert_equal({:controller => "content", :action => 'list'}, rs.recognize_path("/content/list"))
+ assert_equal({:controller => "content", :action => 'show', :id => '10'}, rs.recognize_path("/content/show/10"))
+
+ assert_equal({:controller => "admin/user", :action => 'show', :id => '10'}, rs.recognize_path("/admin/user/show/10"))
+
+ assert_equal '/admin/user/show/10', rs.generate(:controller => 'admin/user', :action => 'show', :id => 10)
+
+ assert_equal '/admin/user/show', rs.generate({:action => 'show'}, {:controller => 'admin/user', :action => 'list', :id => '10'})
+ assert_equal '/admin/user/list/10', rs.generate({}, {:controller => 'admin/user', :action => 'list', :id => '10'})
+
+ assert_equal '/admin/stuff', rs.generate({:controller => 'stuff'}, {:controller => 'admin/user', :action => 'list', :id => '10'})
+ assert_equal '/stuff', rs.generate({:controller => '/stuff'}, {:controller => 'admin/user', :action => 'list', :id => '10'})
+ end
+
+ def test_ignores_leading_slash
+ @rs.clear!
+ @rs.draw {|m| m.connect '/:controller/:action/:id'}
+ test_default_setup
+ end
+
+ def test_time_recognition
+ # We create many routes to make situation more realistic
+ @rs = ::ActionController::Routing::RouteSet.new
+ @rs.draw { |map|
+ map.frontpage '', :controller => 'search', :action => 'new'
+ map.resources :videos do |video|
+ video.resources :comments
+ video.resource :file, :controller => 'video_file'
+ video.resource :share, :controller => 'video_shares'
+ video.resource :abuse, :controller => 'video_abuses'
+ end
+ map.resources :abuses, :controller => 'video_abuses'
+ map.resources :video_uploads
+ map.resources :video_visits
+
+ map.resources :users do |user|
+ user.resource :settings
+ user.resources :videos
+ end
+ map.resources :channels do |channel|
+ channel.resources :videos, :controller => 'channel_videos'
+ end
+ map.resource :session
+ map.resource :lost_password
+ map.search 'search', :controller => 'search'
+ map.resources :pages
+ map.connect ':controller/:action/:id'
+ }
+ n = 1000
+ if RunTimeTests
+ GC.start
+ rectime = Benchmark.realtime do
+ n.times do
+ rs.recognize_path("/videos/1234567", {:method => :get})
+ rs.recognize_path("/videos/1234567/abuse", {:method => :get})
+ rs.recognize_path("/users/1234567/settings", {:method => :get})
+ rs.recognize_path("/channels/1234567", {:method => :get})
+ rs.recognize_path("/session/new", {:method => :get})
+ rs.recognize_path("/admin/user/show/10", {:method => :get})
+ end
+ end
+ puts "\n\nRecognition (#{rs.routes.size} routes):"
+ per_url = rectime / (n * 6)
+ puts "#{per_url * 1000} ms/url"
+ puts "#{1 / per_url} url/s\n\n"
+ end
+ end
+
+ def test_time_generation
+ n = 5000
+ if RunTimeTests
+ GC.start
+ pairs = [
+ [{:controller => 'content', :action => 'index'}, {:controller => 'content', :action => 'show'}],
+ [{:controller => 'content'}, {:controller => 'content', :action => 'index'}],
+ [{:controller => 'content', :action => 'list'}, {:controller => 'content', :action => 'index'}],
+ [{:controller => 'content', :action => 'show', :id => '10'}, {:controller => 'content', :action => 'list'}],
+ [{:controller => 'admin/user', :action => 'index'}, {:controller => 'admin/user', :action => 'show'}],
+ [{:controller => 'admin/user'}, {:controller => 'admin/user', :action => 'index'}],
+ [{:controller => 'admin/user', :action => 'list'}, {:controller => 'admin/user', :action => 'index'}],
+ [{:controller => 'admin/user', :action => 'show', :id => '10'}, {:controller => 'admin/user', :action => 'list'}],
+ ]
+ p = nil
+ gentime = Benchmark.realtime do
+ n.times do
+ pairs.each {|(a, b)| rs.generate(a, b)}
+ end
+ end
- ActionController::Routing.use_controllers! %w(content admin/user admin/news_feed)
- end
-
- def teardown
- @rs.clear!
+ puts "\n\nGeneration (RouteSet): (#{(n * 8)} urls)"
+ per_url = gentime / (n * 8)
+ puts "#{per_url * 1000} ms/url"
+ puts "#{1 / per_url} url/s\n\n"
end
+ end
- def test_default_setup
- @rs.draw {|m| m.connect ':controller/:action/:id' }
- assert_equal({:controller => "content", :action => 'index'}, rs.recognize_path("/content"))
- assert_equal({:controller => "content", :action => 'list'}, rs.recognize_path("/content/list"))
- assert_equal({:controller => "content", :action => 'show', :id => '10'}, rs.recognize_path("/content/show/10"))
-
- assert_equal({:controller => "admin/user", :action => 'show', :id => '10'}, rs.recognize_path("/admin/user/show/10"))
-
- assert_equal '/admin/user/show/10', rs.generate(:controller => 'admin/user', :action => 'show', :id => 10)
-
- assert_equal '/admin/user/show', rs.generate({:action => 'show'}, {:controller => 'admin/user', :action => 'list', :id => '10'})
- assert_equal '/admin/user/list/10', rs.generate({}, {:controller => 'admin/user', :action => 'list', :id => '10'})
+ def test_route_with_colon_first
+ rs.draw do |map|
+ map.connect '/:controller/:action/:id', :action => 'index', :id => nil
+ map.connect ':url', :controller => 'tiny_url', :action => 'translate'
+ end
+ end
- assert_equal '/admin/stuff', rs.generate({:controller => 'stuff'}, {:controller => 'admin/user', :action => 'list', :id => '10'})
- assert_equal '/stuff', rs.generate({:controller => '/stuff'}, {:controller => 'admin/user', :action => 'list', :id => '10'})
+ def test_route_with_regexp_for_controller
+ rs.draw do |map|
+ map.connect ':controller/:admintoken/:action/:id', :controller => /admin\/.+/
+ map.connect ':controller/:action/:id'
end
+ assert_equal({:controller => "admin/user", :admintoken => "foo", :action => "index"},
+ rs.recognize_path("/admin/user/foo"))
+ assert_equal({:controller => "content", :action => "foo"}, rs.recognize_path("/content/foo"))
+ assert_equal '/admin/user/foo', rs.generate(:controller => "admin/user", :admintoken => "foo", :action => "index")
+ assert_equal '/content/foo', rs.generate(:controller => "content", :action => "foo")
+ end
- def test_ignores_leading_slash
- @rs.clear!
- @rs.draw {|m| m.connect '/:controller/:action/:id'}
- test_default_setup
+ def test_route_with_regexp_and_dot
+ rs.draw do |map|
+ map.connect ':controller/:action/:file',
+ :controller => /admin|user/,
+ :action => /upload|download/,
+ :defaults => {:file => nil},
+ :requirements => {:file => %r{[^/]+(\.[^/]+)?}}
end
+ # Without a file extension
+ assert_equal '/user/download/file',
+ rs.generate(:controller => "user", :action => "download", :file => "file")
+ assert_equal(
+ {:controller => "user", :action => "download", :file => "file"},
+ rs.recognize_path("/user/download/file"))
- def test_time_recognition
- # We create many routes to make situation more realistic
- @rs = ::ActionController::Routing::RouteSet.new
- @rs.draw { |map|
- map.frontpage '', :controller => 'search', :action => 'new'
- map.resources :videos do |video|
- video.resources :comments
- video.resource :file, :controller => 'video_file'
- video.resource :share, :controller => 'video_shares'
- video.resource :abuse, :controller => 'video_abuses'
- end
- map.resources :abuses, :controller => 'video_abuses'
- map.resources :video_uploads
- map.resources :video_visits
+ # Now, let's try a file with an extension, really a dot (.)
+ assert_equal '/user/download/file.jpg',
+ rs.generate(
+ :controller => "user", :action => "download", :file => "file.jpg")
+ assert_equal(
+ {:controller => "user", :action => "download", :file => "file.jpg"},
+ rs.recognize_path("/user/download/file.jpg"))
+ end
- map.resources :users do |user|
- user.resource :settings
- user.resources :videos
- end
- map.resources :channels do |channel|
- channel.resources :videos, :controller => 'channel_videos'
- end
- map.resource :session
- map.resource :lost_password
- map.search 'search', :controller => 'search'
- map.resources :pages
- map.connect ':controller/:action/:id'
- }
- n = 1000
- if RunTimeTests
- GC.start
- rectime = Benchmark.realtime do
- n.times do
- rs.recognize_path("/videos/1234567", {:method => :get})
- rs.recognize_path("/videos/1234567/abuse", {:method => :get})
- rs.recognize_path("/users/1234567/settings", {:method => :get})
- rs.recognize_path("/channels/1234567", {:method => :get})
- rs.recognize_path("/session/new", {:method => :get})
- rs.recognize_path("/admin/user/show/10", {:method => :get})
- end
- end
- puts "\n\nRecognition (#{rs.routes.size} routes):"
- per_url = rectime / (n * 6)
- puts "#{per_url * 1000} ms/url"
- puts "#{1 / per_url} url/s\n\n"
- end
- end
+ def test_basic_named_route
+ rs.add_named_route :home, '', :controller => 'content', :action => 'list'
+ x = setup_for_named_route
+ assert_equal("http://test.host/",
+ x.send(:home_url))
+ end
- def test_time_generation
- n = 5000
- if RunTimeTests
- GC.start
- pairs = [
- [{:controller => 'content', :action => 'index'}, {:controller => 'content', :action => 'show'}],
- [{:controller => 'content'}, {:controller => 'content', :action => 'index'}],
- [{:controller => 'content', :action => 'list'}, {:controller => 'content', :action => 'index'}],
- [{:controller => 'content', :action => 'show', :id => '10'}, {:controller => 'content', :action => 'list'}],
- [{:controller => 'admin/user', :action => 'index'}, {:controller => 'admin/user', :action => 'show'}],
- [{:controller => 'admin/user'}, {:controller => 'admin/user', :action => 'index'}],
- [{:controller => 'admin/user', :action => 'list'}, {:controller => 'admin/user', :action => 'index'}],
- [{:controller => 'admin/user', :action => 'show', :id => '10'}, {:controller => 'admin/user', :action => 'list'}],
- ]
- p = nil
- gentime = Benchmark.realtime do
- n.times do
- pairs.each {|(a, b)| rs.generate(a, b)}
- end
- end
+ def test_basic_named_route_with_relative_url_root
+ rs.add_named_route :home, '', :controller => 'content', :action => 'list'
+ x = setup_for_named_route
+ ActionController::Base.relative_url_root = "/foo"
+ assert_equal("http://test.host/foo/",
+ x.send(:home_url))
+ assert_equal "/foo/", x.send(:home_path)
+ ActionController::Base.relative_url_root = nil
+ end
- puts "\n\nGeneration (RouteSet): (#{(n * 8)} urls)"
- per_url = gentime / (n * 8)
- puts "#{per_url * 1000} ms/url"
- puts "#{1 / per_url} url/s\n\n"
- end
- end
+ def test_named_route_with_option
+ rs.add_named_route :page, 'page/:title', :controller => 'content', :action => 'show_page'
+ x = setup_for_named_route
+ assert_equal("http://test.host/page/new%20stuff",
+ x.send(:page_url, :title => 'new stuff'))
+ end
- def test_route_with_colon_first
- rs.draw do |map|
- map.connect '/:controller/:action/:id', :action => 'index', :id => nil
- map.connect ':url', :controller => 'tiny_url', :action => 'translate'
- end
- end
+ def test_named_route_with_default
+ rs.add_named_route :page, 'page/:title', :controller => 'content', :action => 'show_page', :title => 'AboutPage'
+ x = setup_for_named_route
+ assert_equal("http://test.host/page/AboutRails",
+ x.send(:page_url, :title => "AboutRails"))
- def test_route_with_regexp_for_controller
- rs.draw do |map|
- map.connect ':controller/:admintoken/:action/:id', :controller => /admin\/.+/
- map.connect ':controller/:action/:id'
- end
- assert_equal({:controller => "admin/user", :admintoken => "foo", :action => "index"},
- rs.recognize_path("/admin/user/foo"))
- assert_equal({:controller => "content", :action => "foo"}, rs.recognize_path("/content/foo"))
- assert_equal '/admin/user/foo', rs.generate(:controller => "admin/user", :admintoken => "foo", :action => "index")
- assert_equal '/content/foo', rs.generate(:controller => "content", :action => "foo")
- end
+ end
- def test_route_with_regexp_and_dot
- rs.draw do |map|
- map.connect ':controller/:action/:file',
- :controller => /admin|user/,
- :action => /upload|download/,
- :defaults => {:file => nil},
- :requirements => {:file => %r{[^/]+(\.[^/]+)?}}
- end
- # Without a file extension
- assert_equal '/user/download/file',
- rs.generate(:controller => "user", :action => "download", :file => "file")
- assert_equal(
- {:controller => "user", :action => "download", :file => "file"},
- rs.recognize_path("/user/download/file"))
+ def test_named_route_with_name_prefix
+ rs.add_named_route :page, 'page', :controller => 'content', :action => 'show_page', :name_prefix => 'my_'
+ x = setup_for_named_route
+ assert_equal("http://test.host/page",
+ x.send(:my_page_url))
+ end
- # Now, let's try a file with an extension, really a dot (.)
- assert_equal '/user/download/file.jpg',
- rs.generate(
- :controller => "user", :action => "download", :file => "file.jpg")
- assert_equal(
- {:controller => "user", :action => "download", :file => "file.jpg"},
- rs.recognize_path("/user/download/file.jpg"))
- end
+ def test_named_route_with_path_prefix
+ rs.add_named_route :page, 'page', :controller => 'content', :action => 'show_page', :path_prefix => 'my'
+ x = setup_for_named_route
+ assert_equal("http://test.host/my/page",
+ x.send(:page_url))
+ end
- def test_basic_named_route
- rs.add_named_route :home, '', :controller => 'content', :action => 'list'
- x = setup_for_named_route
- assert_equal("http://test.host/",
- x.send(:home_url))
- end
+ def test_named_route_with_nested_controller
+ rs.add_named_route :users, 'admin/user', :controller => 'admin/user', :action => 'index'
+ x = setup_for_named_route
+ assert_equal("http://test.host/admin/user",
+ x.send(:users_url))
+ end
- def test_basic_named_route_with_relative_url_root
- rs.add_named_route :home, '', :controller => 'content', :action => 'list'
- x = setup_for_named_route
- ActionController::Base.relative_url_root = "/foo"
- assert_equal("http://test.host/foo/",
- x.send(:home_url))
- assert_equal "/foo/", x.send(:home_path)
- ActionController::Base.relative_url_root = nil
- end
+ def test_optimised_named_route_call_never_uses_url_for
+ rs.add_named_route :users, 'admin/user', :controller => '/admin/user', :action => 'index'
+ rs.add_named_route :user, 'admin/user/:id', :controller=>'/admin/user', :action=>'show'
+ x = setup_for_named_route
+ x.expects(:url_for).never
+ x.send(:users_url)
+ x.send(:users_path)
+ x.send(:user_url, 2, :foo=>"bar")
+ x.send(:user_path, 3, :bar=>"foo")
+ end
- def test_named_route_with_option
- rs.add_named_route :page, 'page/:title', :controller => 'content', :action => 'show_page'
- x = setup_for_named_route
- assert_equal("http://test.host/page/new%20stuff",
- x.send(:page_url, :title => 'new stuff'))
- end
+ def test_optimised_named_route_with_host
+ rs.add_named_route :pages, 'pages', :controller => 'content', :action => 'show_page', :host => 'foo.com'
+ x = setup_for_named_route
+ x.expects(:url_for).with(:host => 'foo.com', :only_path => false, :controller => 'content', :action => 'show_page', :use_route => :pages).once
+ x.send(:pages_url)
+ end
- def test_named_route_with_default
- rs.add_named_route :page, 'page/:title', :controller => 'content', :action => 'show_page', :title => 'AboutPage'
- x = setup_for_named_route
- assert_equal("http://test.host/page/AboutRails",
- x.send(:page_url, :title => "AboutRails"))
+ def setup_for_named_route
+ klass = Class.new(MockController)
+ rs.install_helpers(klass)
+ klass.new(rs)
+ end
+ def test_named_route_without_hash
+ rs.draw do |map|
+ map.normal ':controller/:action/:id'
end
+ end
- def test_named_route_with_name_prefix
- rs.add_named_route :page, 'page', :controller => 'content', :action => 'show_page', :name_prefix => 'my_'
- x = setup_for_named_route
- assert_equal("http://test.host/page",
- x.send(:my_page_url))
+ def test_named_route_root
+ rs.draw do |map|
+ map.root :controller => "hello"
end
+ x = setup_for_named_route
+ assert_equal("http://test.host/", x.send(:root_url))
+ assert_equal("/", x.send(:root_path))
+ end
- def test_named_route_with_path_prefix
- rs.add_named_route :page, 'page', :controller => 'content', :action => 'show_page', :path_prefix => 'my'
- x = setup_for_named_route
- assert_equal("http://test.host/my/page",
- x.send(:page_url))
+ def test_named_route_with_regexps
+ rs.draw do |map|
+ map.article 'page/:year/:month/:day/:title', :controller => 'page', :action => 'show',
+ :year => /\d+/, :month => /\d+/, :day => /\d+/
+ map.connect ':controller/:action/:id'
end
+ x = setup_for_named_route
+ # assert_equal(
+ # {:controller => 'page', :action => 'show', :title => 'hi', :use_route => :article, :only_path => false},
+ # x.send(:article_url, :title => 'hi')
+ # )
+ assert_equal(
+ "http://test.host/page/2005/6/10/hi",
+ x.send(:article_url, :title => 'hi', :day => 10, :year => 2005, :month => 6)
+ )
+ end
- def test_named_route_with_nested_controller
- rs.add_named_route :users, 'admin/user', :controller => 'admin/user', :action => 'index'
- x = setup_for_named_route
- assert_equal("http://test.host/admin/user",
- x.send(:users_url))
- end
+ def test_changing_controller
+ @rs.draw {|m| m.connect ':controller/:action/:id' }
- def test_optimised_named_route_call_never_uses_url_for
- rs.add_named_route :users, 'admin/user', :controller => '/admin/user', :action => 'index'
- rs.add_named_route :user, 'admin/user/:id', :controller=>'/admin/user', :action=>'show'
- x = setup_for_named_route
- x.expects(:url_for).never
- x.send(:users_url)
- x.send(:users_path)
- x.send(:user_url, 2, :foo=>"bar")
- x.send(:user_path, 3, :bar=>"foo")
- end
+ assert_equal '/admin/stuff/show/10', rs.generate(
+ {:controller => 'stuff', :action => 'show', :id => 10},
+ {:controller => 'admin/user', :action => 'index'}
+ )
+ end
- def test_optimised_named_route_with_host
- rs.add_named_route :pages, 'pages', :controller => 'content', :action => 'show_page', :host => 'foo.com'
- x = setup_for_named_route
- x.expects(:url_for).with(:host => 'foo.com', :only_path => false, :controller => 'content', :action => 'show_page', :use_route => :pages).once
- x.send(:pages_url)
+ def test_paths_escaped
+ rs.draw do |map|
+ map.path 'file/*path', :controller => 'content', :action => 'show_file'
+ map.connect ':controller/:action/:id'
end
- def setup_for_named_route
- klass = Class.new(MockController)
- rs.install_helpers(klass)
- klass.new(rs)
- end
+ # No + to space in URI escaping, only for query params.
+ results = rs.recognize_path "/file/hello+world/how+are+you%3F"
+ assert results, "Recognition should have succeeded"
+ assert_equal ['hello+world', 'how+are+you?'], results[:path]
- def test_named_route_without_hash
- rs.draw do |map|
- map.normal ':controller/:action/:id'
- end
- end
+ # Use %20 for space instead.
+ results = rs.recognize_path "/file/hello%20world/how%20are%20you%3F"
+ assert results, "Recognition should have succeeded"
+ assert_equal ['hello world', 'how are you?'], results[:path]
- def test_named_route_root
- rs.draw do |map|
- map.root :controller => "hello"
- end
- x = setup_for_named_route
- assert_equal("http://test.host/", x.send(:root_url))
- assert_equal("/", x.send(:root_path))
- end
+ results = rs.recognize_path "/file"
+ assert results, "Recognition should have succeeded"
+ assert_equal [], results[:path]
+ end
- def test_named_route_with_regexps
- rs.draw do |map|
- map.article 'page/:year/:month/:day/:title', :controller => 'page', :action => 'show',
- :year => /\d+/, :month => /\d+/, :day => /\d+/
- map.connect ':controller/:action/:id'
- end
- x = setup_for_named_route
- # assert_equal(
- # {:controller => 'page', :action => 'show', :title => 'hi', :use_route => :article, :only_path => false},
- # x.send(:article_url, :title => 'hi')
- # )
- assert_equal(
- "http://test.host/page/2005/6/10/hi",
- x.send(:article_url, :title => 'hi', :day => 10, :year => 2005, :month => 6)
- )
- end
+ def test_paths_slashes_unescaped_with_ordered_parameters
+ rs.add_named_route :path, '/file/*path', :controller => 'content'
- def test_changing_controller
- @rs.draw {|m| m.connect ':controller/:action/:id' }
+ # No / to %2F in URI, only for query params.
+ x = setup_for_named_route
+ assert_equal("/file/hello/world", x.send(:path_path, 'hello/world'))
+ end
- assert_equal '/admin/stuff/show/10', rs.generate(
- {:controller => 'stuff', :action => 'show', :id => 10},
- {:controller => 'admin/user', :action => 'index'}
- )
+ def test_non_controllers_cannot_be_matched
+ rs.draw do |map|
+ map.connect ':controller/:action/:id'
end
+ assert_raises(ActionController::RoutingError) { rs.recognize_path("/not_a/show/10") }
+ end
- def test_paths_escaped
+ def test_paths_do_not_accept_defaults
+ assert_raises(ActionController::RoutingError) do
rs.draw do |map|
- map.path 'file/*path', :controller => 'content', :action => 'show_file'
+ map.path 'file/*path', :controller => 'content', :action => 'show_file', :path => %w(fake default)
map.connect ':controller/:action/:id'
end
-
- # No + to space in URI escaping, only for query params.
- results = rs.recognize_path "/file/hello+world/how+are+you%3F"
- assert results, "Recognition should have succeeded"
- assert_equal ['hello+world', 'how+are+you?'], results[:path]
-
- # Use %20 for space instead.
- results = rs.recognize_path "/file/hello%20world/how%20are%20you%3F"
- assert results, "Recognition should have succeeded"
- assert_equal ['hello world', 'how are you?'], results[:path]
-
- results = rs.recognize_path "/file"
- assert results, "Recognition should have succeeded"
- assert_equal [], results[:path]
end
- def test_paths_slashes_unescaped_with_ordered_parameters
- rs.add_named_route :path, '/file/*path', :controller => 'content'
-
- # No / to %2F in URI, only for query params.
- x = setup_for_named_route
- assert_equal("/file/hello/world", x.send(:path_path, 'hello/world'))
+ rs.draw do |map|
+ map.path 'file/*path', :controller => 'content', :action => 'show_file', :path => []
+ map.connect ':controller/:action/:id'
end
+ end
- def test_non_controllers_cannot_be_matched
- rs.draw do |map|
- map.connect ':controller/:action/:id'
- end
- assert_raises(ActionController::RoutingError) { rs.recognize_path("/not_a/show/10") }
+ def test_should_list_options_diff_when_routing_requirements_dont_match
+ rs.draw do |map|
+ map.post 'post/:id', :controller=> 'post', :action=> 'show', :requirements => {:id => /\d+/}
end
+ exception = assert_raise(ActionController::RoutingError) { rs.generate(:controller => 'post', :action => 'show', :bad_param => "foo", :use_route => "post") }
+ assert_match /^post_url failed to generate/, exception.message
+ from_match = exception.message.match(/from \{[^\}]+\}/).to_s
+ assert_match /:bad_param=>"foo"/, from_match
+ assert_match /:action=>"show"/, from_match
+ assert_match /:controller=>"post"/, from_match
- def test_paths_do_not_accept_defaults
- assert_raises(ActionController::RoutingError) do
- rs.draw do |map|
- map.path 'file/*path', :controller => 'content', :action => 'show_file', :path => %w(fake default)
- map.connect ':controller/:action/:id'
- end
- end
+ expected_match = exception.message.match(/expected: \{[^\}]+\}/).to_s
+ assert_no_match /:bad_param=>"foo"/, expected_match
+ assert_match /:action=>"show"/, expected_match
+ assert_match /:controller=>"post"/, expected_match
- rs.draw do |map|
- map.path 'file/*path', :controller => 'content', :action => 'show_file', :path => []
- map.connect ':controller/:action/:id'
- end
+ diff_match = exception.message.match(/diff: \{[^\}]+\}/).to_s
+ assert_match /:bad_param=>"foo"/, diff_match
+ assert_no_match /:action=>"show"/, diff_match
+ assert_no_match /:controller=>"post"/, diff_match
+ end
+
+ # this specifies the case where your formerly would get a very confusing error message with an empty diff
+ def test_should_have_better_error_message_when_options_diff_is_empty
+ rs.draw do |map|
+ map.content '/content/:query', :controller => 'content', :action => 'show'
end
- def test_should_list_options_diff_when_routing_requirements_dont_match
- rs.draw do |map|
- map.post 'post/:id', :controller=> 'post', :action=> 'show', :requirements => {:id => /\d+/}
- end
- exception = assert_raise(ActionController::RoutingError) { rs.generate(:controller => 'post', :action => 'show', :bad_param => "foo", :use_route => "post") }
- assert_match /^post_url failed to generate/, exception.message
- from_match = exception.message.match(/from \{[^\}]+\}/).to_s
- assert_match /:bad_param=>"foo"/, from_match
- assert_match /:action=>"show"/, from_match
- assert_match /:controller=>"post"/, from_match
-
- expected_match = exception.message.match(/expected: \{[^\}]+\}/).to_s
- assert_no_match /:bad_param=>"foo"/, expected_match
- assert_match /:action=>"show"/, expected_match
- assert_match /:controller=>"post"/, expected_match
-
- diff_match = exception.message.match(/diff: \{[^\}]+\}/).to_s
- assert_match /:bad_param=>"foo"/, diff_match
- assert_no_match /:action=>"show"/, diff_match
- assert_no_match /:controller=>"post"/, diff_match
- end
-
- # this specifies the case where your formerly would get a very confusing error message with an empty diff
- def test_should_have_better_error_message_when_options_diff_is_empty
- rs.draw do |map|
- map.content '/content/:query', :controller => 'content', :action => 'show'
- end
+ exception = assert_raise(ActionController::RoutingError) { rs.generate(:controller => 'content', :action => 'show', :use_route => "content") }
+ assert_match %r[:action=>"show"], exception.message
+ assert_match %r[:controller=>"content"], exception.message
+ assert_match %r[you may have ambiguous routes, or you may need to supply additional parameters for this route], exception.message
+ assert_match %r[content_url has the following required parameters: \["content", :query\] - are they all satisfied?], exception.message
+ end
- exception = assert_raise(ActionController::RoutingError) { rs.generate(:controller => 'content', :action => 'show', :use_route => "content") }
- assert_match %r[:action=>"show"], exception.message
- assert_match %r[:controller=>"content"], exception.message
- assert_match %r[you may have ambiguous routes, or you may need to supply additional parameters for this route], exception.message
- assert_match %r[content_url has the following required parameters: \["content", :query\] - are they all satisfied?], exception.message
+ def test_dynamic_path_allowed
+ rs.draw do |map|
+ map.connect '*path', :controller => 'content', :action => 'show_file'
end
- def test_dynamic_path_allowed
- rs.draw do |map|
- map.connect '*path', :controller => 'content', :action => 'show_file'
- end
+ assert_equal '/pages/boo', rs.generate(:controller => 'content', :action => 'show_file', :path => %w(pages boo))
+ end
- assert_equal '/pages/boo', rs.generate(:controller => 'content', :action => 'show_file', :path => %w(pages boo))
+ def test_dynamic_recall_paths_allowed
+ rs.draw do |map|
+ map.connect '*path', :controller => 'content', :action => 'show_file'
end
- def test_dynamic_recall_paths_allowed
- rs.draw do |map|
- map.connect '*path', :controller => 'content', :action => 'show_file'
- end
+ recall_path = ActionController::Routing::PathSegment::Result.new(%w(pages boo))
+ assert_equal '/pages/boo', rs.generate({}, :controller => 'content', :action => 'show_file', :path => recall_path)
+ end
- recall_path = ActionController::Routing::PathSegment::Result.new(%w(pages boo))
- assert_equal '/pages/boo', rs.generate({}, :controller => 'content', :action => 'show_file', :path => recall_path)
+ def test_backwards
+ rs.draw do |map|
+ map.connect 'page/:id/:action', :controller => 'pages', :action => 'show'
+ map.connect ':controller/:action/:id'
end
- def test_backwards
- rs.draw do |map|
- map.connect 'page/:id/:action', :controller => 'pages', :action => 'show'
- map.connect ':controller/:action/:id'
- end
+ assert_equal '/page/20', rs.generate({:id => 20}, {:controller => 'pages', :action => 'show'})
+ assert_equal '/page/20', rs.generate(:controller => 'pages', :id => 20, :action => 'show')
+ assert_equal '/pages/boo', rs.generate(:controller => 'pages', :action => 'boo')
+ end
- assert_equal '/page/20', rs.generate({:id => 20}, {:controller => 'pages', :action => 'show'})
- assert_equal '/page/20', rs.generate(:controller => 'pages', :id => 20, :action => 'show')
- assert_equal '/pages/boo', rs.generate(:controller => 'pages', :action => 'boo')
+ def test_route_with_fixnum_default
+ rs.draw do |map|
+ map.connect 'page/:id', :controller => 'content', :action => 'show_page', :id => 1
+ map.connect ':controller/:action/:id'
end
- def test_route_with_fixnum_default
- rs.draw do |map|
- map.connect 'page/:id', :controller => 'content', :action => 'show_page', :id => 1
- map.connect ':controller/:action/:id'
- end
+ assert_equal '/page', rs.generate(:controller => 'content', :action => 'show_page')
+ assert_equal '/page', rs.generate(:controller => 'content', :action => 'show_page', :id => 1)
+ assert_equal '/page', rs.generate(:controller => 'content', :action => 'show_page', :id => '1')
+ assert_equal '/page/10', rs.generate(:controller => 'content', :action => 'show_page', :id => 10)
- assert_equal '/page', rs.generate(:controller => 'content', :action => 'show_page')
- assert_equal '/page', rs.generate(:controller => 'content', :action => 'show_page', :id => 1)
- assert_equal '/page', rs.generate(:controller => 'content', :action => 'show_page', :id => '1')
- assert_equal '/page/10', rs.generate(:controller => 'content', :action => 'show_page', :id => 10)
+ assert_equal({:controller => "content", :action => 'show_page', :id => '1'}, rs.recognize_path("/page"))
+ assert_equal({:controller => "content", :action => 'show_page', :id => '1'}, rs.recognize_path("/page/1"))
+ assert_equal({:controller => "content", :action => 'show_page', :id => '10'}, rs.recognize_path("/page/10"))
+ end
- assert_equal({:controller => "content", :action => 'show_page', :id => '1'}, rs.recognize_path("/page"))
- assert_equal({:controller => "content", :action => 'show_page', :id => '1'}, rs.recognize_path("/page/1"))
- assert_equal({:controller => "content", :action => 'show_page', :id => '10'}, rs.recognize_path("/page/10"))
+ # For newer revision
+ def test_route_with_text_default
+ rs.draw do |map|
+ map.connect 'page/:id', :controller => 'content', :action => 'show_page', :id => 1
+ map.connect ':controller/:action/:id'
end
- # For newer revision
- def test_route_with_text_default
- rs.draw do |map|
- map.connect 'page/:id', :controller => 'content', :action => 'show_page', :id => 1
- map.connect ':controller/:action/:id'
- end
+ assert_equal '/page/foo', rs.generate(:controller => 'content', :action => 'show_page', :id => 'foo')
+ assert_equal({:controller => "content", :action => 'show_page', :id => 'foo'}, rs.recognize_path("/page/foo"))
- assert_equal '/page/foo', rs.generate(:controller => 'content', :action => 'show_page', :id => 'foo')
- assert_equal({:controller => "content", :action => 'show_page', :id => 'foo'}, rs.recognize_path("/page/foo"))
+ token = "\321\202\320\265\320\272\321\201\321\202" # 'text' in russian
+ escaped_token = CGI::escape(token)
- token = "\321\202\320\265\320\272\321\201\321\202" # 'text' in russian
- escaped_token = CGI::escape(token)
+ assert_equal '/page/' + escaped_token, rs.generate(:controller => 'content', :action => 'show_page', :id => token)
+ assert_equal({:controller => "content", :action => 'show_page', :id => token}, rs.recognize_path("/page/#{escaped_token}"))
+ end
- assert_equal '/page/' + escaped_token, rs.generate(:controller => 'content', :action => 'show_page', :id => token)
- assert_equal({:controller => "content", :action => 'show_page', :id => token}, rs.recognize_path("/page/#{escaped_token}"))
- end
+ def test_action_expiry
+ @rs.draw {|m| m.connect ':controller/:action/:id' }
+ assert_equal '/content', rs.generate({:controller => 'content'}, {:controller => 'content', :action => 'show'})
+ end
- def test_action_expiry
- @rs.draw {|m| m.connect ':controller/:action/:id' }
- assert_equal '/content', rs.generate({:controller => 'content'}, {:controller => 'content', :action => 'show'})
- end
+ def test_recognition_with_uppercase_controller_name
+ @rs.draw {|m| m.connect ':controller/:action/:id' }
+ assert_equal({:controller => "content", :action => 'index'}, rs.recognize_path("/Content"))
+ assert_equal({:controller => "content", :action => 'list'}, rs.recognize_path("/ConTent/list"))
+ assert_equal({:controller => "content", :action => 'show', :id => '10'}, rs.recognize_path("/CONTENT/show/10"))
- def test_recognition_with_uppercase_controller_name
- @rs.draw {|m| m.connect ':controller/:action/:id' }
- assert_equal({:controller => "content", :action => 'index'}, rs.recognize_path("/Content"))
- assert_equal({:controller => "content", :action => 'list'}, rs.recognize_path("/ConTent/list"))
- assert_equal({:controller => "content", :action => 'show', :id => '10'}, rs.recognize_path("/CONTENT/show/10"))
+ # these used to work, before the routes rewrite, but support for this was pulled in the new version...
+ #assert_equal({'controller' => "admin/news_feed", 'action' => 'index'}, rs.recognize_path("Admin/NewsFeed"))
+ #assert_equal({'controller' => "admin/news_feed", 'action' => 'index'}, rs.recognize_path("Admin/News_Feed"))
+ end
- # these used to work, before the routes rewrite, but support for this was pulled in the new version...
- #assert_equal({'controller' => "admin/news_feed", 'action' => 'index'}, rs.recognize_path("Admin/NewsFeed"))
- #assert_equal({'controller' => "admin/news_feed", 'action' => 'index'}, rs.recognize_path("Admin/News_Feed"))
+ def test_requirement_should_prevent_optional_id
+ rs.draw do |map|
+ map.post 'post/:id', :controller=> 'post', :action=> 'show', :requirements => {:id => /\d+/}
end
- def test_requirement_should_prevent_optional_id
- rs.draw do |map|
- map.post 'post/:id', :controller=> 'post', :action=> 'show', :requirements => {:id => /\d+/}
- end
+ assert_equal '/post/10', rs.generate(:controller => 'post', :action => 'show', :id => 10)
- assert_equal '/post/10', rs.generate(:controller => 'post', :action => 'show', :id => 10)
+ assert_raises ActionController::RoutingError do
+ rs.generate(:controller => 'post', :action => 'show')
+ end
+ end
- assert_raises ActionController::RoutingError do
- rs.generate(:controller => 'post', :action => 'show')
- end
+ def test_both_requirement_and_optional
+ rs.draw do |map|
+ map.blog('test/:year', :controller => 'post', :action => 'show',
+ :defaults => { :year => nil },
+ :requirements => { :year => /\d{4}/ }
+ )
+ map.connect ':controller/:action/:id'
end
- def test_both_requirement_and_optional
- rs.draw do |map|
- map.blog('test/:year', :controller => 'post', :action => 'show',
- :defaults => { :year => nil },
- :requirements => { :year => /\d{4}/ }
- )
- map.connect ':controller/:action/:id'
- end
+ assert_equal '/test', rs.generate(:controller => 'post', :action => 'show')
+ assert_equal '/test', rs.generate(:controller => 'post', :action => 'show', :year => nil)
- assert_equal '/test', rs.generate(:controller => 'post', :action => 'show')
- assert_equal '/test', rs.generate(:controller => 'post', :action => 'show', :year => nil)
+ x = setup_for_named_route
+ assert_equal("http://test.host/test",
+ x.send(:blog_url))
+ end
- x = setup_for_named_route
- assert_equal("http://test.host/test",
- x.send(:blog_url))
+ def test_set_to_nil_forgets
+ rs.draw do |map|
+ map.connect 'pages/:year/:month/:day', :controller => 'content', :action => 'list_pages', :month => nil, :day => nil
+ map.connect ':controller/:action/:id'
end
- def test_set_to_nil_forgets
- rs.draw do |map|
- map.connect 'pages/:year/:month/:day', :controller => 'content', :action => 'list_pages', :month => nil, :day => nil
- map.connect ':controller/:action/:id'
- end
+ assert_equal '/pages/2005',
+ rs.generate(:controller => 'content', :action => 'list_pages', :year => 2005)
+ assert_equal '/pages/2005/6',
+ rs.generate(:controller => 'content', :action => 'list_pages', :year => 2005, :month => 6)
+ assert_equal '/pages/2005/6/12',
+ rs.generate(:controller => 'content', :action => 'list_pages', :year => 2005, :month => 6, :day => 12)
- assert_equal '/pages/2005',
- rs.generate(:controller => 'content', :action => 'list_pages', :year => 2005)
- assert_equal '/pages/2005/6',
- rs.generate(:controller => 'content', :action => 'list_pages', :year => 2005, :month => 6)
- assert_equal '/pages/2005/6/12',
- rs.generate(:controller => 'content', :action => 'list_pages', :year => 2005, :month => 6, :day => 12)
+ assert_equal '/pages/2005/6/4',
+ rs.generate({:day => 4}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'})
- assert_equal '/pages/2005/6/4',
- rs.generate({:day => 4}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'})
+ assert_equal '/pages/2005/6',
+ rs.generate({:day => nil}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'})
- assert_equal '/pages/2005/6',
- rs.generate({:day => nil}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'})
+ assert_equal '/pages/2005',
+ rs.generate({:day => nil, :month => nil}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'})
+ end
- assert_equal '/pages/2005',
- rs.generate({:day => nil, :month => nil}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'})
+ def test_url_with_no_action_specified
+ rs.draw do |map|
+ map.connect '', :controller => 'content'
+ map.connect ':controller/:action/:id'
end
- def test_url_with_no_action_specified
- rs.draw do |map|
- map.connect '', :controller => 'content'
- map.connect ':controller/:action/:id'
- end
+ assert_equal '/', rs.generate(:controller => 'content', :action => 'index')
+ assert_equal '/', rs.generate(:controller => 'content')
+ end
- assert_equal '/', rs.generate(:controller => 'content', :action => 'index')
- assert_equal '/', rs.generate(:controller => 'content')
+ def test_named_url_with_no_action_specified
+ rs.draw do |map|
+ map.home '', :controller => 'content'
+ map.connect ':controller/:action/:id'
end
- def test_named_url_with_no_action_specified
+ assert_equal '/', rs.generate(:controller => 'content', :action => 'index')
+ assert_equal '/', rs.generate(:controller => 'content')
+
+ x = setup_for_named_route
+ assert_equal("http://test.host/",
+ x.send(:home_url))
+ end
+
+ def test_url_generated_when_forgetting_action
+ [{:controller => 'content', :action => 'index'}, {:controller => 'content'}].each do |hash|
rs.draw do |map|
- map.home '', :controller => 'content'
+ map.home '', hash
map.connect ':controller/:action/:id'
end
-
- assert_equal '/', rs.generate(:controller => 'content', :action => 'index')
- assert_equal '/', rs.generate(:controller => 'content')
-
- x = setup_for_named_route
- assert_equal("http://test.host/",
- x.send(:home_url))
+ assert_equal '/', rs.generate({:action => nil}, {:controller => 'content', :action => 'hello'})
+ assert_equal '/', rs.generate({:controller => 'content'})
+ assert_equal '/content/hi', rs.generate({:controller => 'content', :action => 'hi'})
end
+ end
- def test_url_generated_when_forgetting_action
- [{:controller => 'content', :action => 'index'}, {:controller => 'content'}].each do |hash|
- rs.draw do |map|
- map.home '', hash
- map.connect ':controller/:action/:id'
- end
- assert_equal '/', rs.generate({:action => nil}, {:controller => 'content', :action => 'hello'})
- assert_equal '/', rs.generate({:controller => 'content'})
- assert_equal '/content/hi', rs.generate({:controller => 'content', :action => 'hi'})
- end
+ def test_named_route_method
+ rs.draw do |map|
+ map.categories 'categories', :controller => 'content', :action => 'categories'
+ map.connect ':controller/:action/:id'
end
- def test_named_route_method
- rs.draw do |map|
- map.categories 'categories', :controller => 'content', :action => 'categories'
- map.connect ':controller/:action/:id'
- end
+ assert_equal '/categories', rs.generate(:controller => 'content', :action => 'categories')
+ assert_equal '/content/hi', rs.generate({:controller => 'content', :action => 'hi'})
+ end
- assert_equal '/categories', rs.generate(:controller => 'content', :action => 'categories')
- assert_equal '/content/hi', rs.generate({:controller => 'content', :action => 'hi'})
- end
+ def test_named_routes_array
+ test_named_route_method
+ assert_equal [:categories], rs.named_routes.names
+ end
- def test_named_routes_array
- test_named_route_method
- assert_equal [:categories], rs.named_routes.names
+ def test_nil_defaults
+ rs.draw do |map|
+ map.connect 'journal',
+ :controller => 'content',
+ :action => 'list_journal',
+ :date => nil, :user_id => nil
+ map.connect ':controller/:action/:id'
end
- def test_nil_defaults
- rs.draw do |map|
- map.connect 'journal',
- :controller => 'content',
- :action => 'list_journal',
- :date => nil, :user_id => nil
- map.connect ':controller/:action/:id'
- end
+ assert_equal '/journal', rs.generate(:controller => 'content', :action => 'list_journal', :date => nil, :user_id => nil)
+ end
- assert_equal '/journal', rs.generate(:controller => 'content', :action => 'list_journal', :date => nil, :user_id => nil)
+ def setup_request_method_routes_for(method)
+ @request = ActionController::TestRequest.new
+ @request.env["REQUEST_METHOD"] = method
+ @request.request_uri = "/match"
+
+ rs.draw do |r|
+ r.connect '/match', :controller => 'books', :action => 'get', :conditions => { :method => :get }
+ r.connect '/match', :controller => 'books', :action => 'post', :conditions => { :method => :post }
+ r.connect '/match', :controller => 'books', :action => 'put', :conditions => { :method => :put }
+ r.connect '/match', :controller => 'books', :action => 'delete', :conditions => { :method => :delete }
end
+ end
+
+ %w(GET POST PUT DELETE).each do |request_method|
+ define_method("test_request_method_recognized_with_#{request_method}") do
+ begin
+ Object.const_set(:BooksController, Class.new(ActionController::Base))
- def setup_request_method_routes_for(method)
- @request = ActionController::TestRequest.new
- @request.env["REQUEST_METHOD"] = method
- @request.request_uri = "/match"
+ setup_request_method_routes_for(request_method)
- rs.draw do |r|
- r.connect '/match', :controller => 'books', :action => 'get', :conditions => { :method => :get }
- r.connect '/match', :controller => 'books', :action => 'post', :conditions => { :method => :post }
- r.connect '/match', :controller => 'books', :action => 'put', :conditions => { :method => :put }
- r.connect '/match', :controller => 'books', :action => 'delete', :conditions => { :method => :delete }
+ assert_nothing_raised { rs.recognize(@request) }
+ assert_equal request_method.downcase, @request.path_parameters[:action]
+ ensure
+ Object.send(:remove_const, :BooksController) rescue nil
end
end
+ end
- %w(GET POST PUT DELETE).each do |request_method|
- define_method("test_request_method_recognized_with_#{request_method}") do
- begin
- Object.const_set(:BooksController, Class.new(ActionController::Base))
+ def test_recognize_array_of_methods
+ Object.const_set(:BooksController, Class.new(ActionController::Base))
+ rs.draw do |r|
+ r.connect '/match', :controller => 'books', :action => 'get_or_post', :conditions => { :method => [:get, :post] }
+ r.connect '/match', :controller => 'books', :action => 'not_get_or_post'
+ end
- setup_request_method_routes_for(request_method)
+ @request = ActionController::TestRequest.new
+ @request.env["REQUEST_METHOD"] = 'POST'
+ @request.request_uri = "/match"
+ assert_nothing_raised { rs.recognize(@request) }
+ assert_equal 'get_or_post', @request.path_parameters[:action]
- assert_nothing_raised { rs.recognize(@request) }
- assert_equal request_method.downcase, @request.path_parameters[:action]
- ensure
- Object.send(:remove_const, :BooksController) rescue nil
- end
- end
+ # have to recreate or else the RouteSet uses a cached version:
+ @request = ActionController::TestRequest.new
+ @request.env["REQUEST_METHOD"] = 'PUT'
+ @request.request_uri = "/match"
+ assert_nothing_raised { rs.recognize(@request) }
+ assert_equal 'not_get_or_post', @request.path_parameters[:action]
+ ensure
+ Object.send(:remove_const, :BooksController) rescue nil
+ end
+
+ def test_subpath_recognized
+ Object.const_set(:SubpathBooksController, Class.new(ActionController::Base))
+
+ rs.draw do |r|
+ r.connect '/books/:id/edit', :controller => 'subpath_books', :action => 'edit'
+ r.connect '/items/:id/:action', :controller => 'subpath_books'
+ r.connect '/posts/new/:action', :controller => 'subpath_books'
+ r.connect '/posts/:id', :controller => 'subpath_books', :action => "show"
end
- def test_recognize_array_of_methods
- Object.const_set(:BooksController, Class.new(ActionController::Base))
- rs.draw do |r|
- r.connect '/match', :controller => 'books', :action => 'get_or_post', :conditions => { :method => [:get, :post] }
- r.connect '/match', :controller => 'books', :action => 'not_get_or_post'
- end
+ hash = rs.recognize_path "/books/17/edit"
+ assert_not_nil hash
+ assert_equal %w(subpath_books 17 edit), [hash[:controller], hash[:id], hash[:action]]
- @request = ActionController::TestRequest.new
- @request.env["REQUEST_METHOD"] = 'POST'
- @request.request_uri = "/match"
- assert_nothing_raised { rs.recognize(@request) }
- assert_equal 'get_or_post', @request.path_parameters[:action]
-
- # have to recreate or else the RouteSet uses a cached version:
- @request = ActionController::TestRequest.new
- @request.env["REQUEST_METHOD"] = 'PUT'
- @request.request_uri = "/match"
- assert_nothing_raised { rs.recognize(@request) }
- assert_equal 'not_get_or_post', @request.path_parameters[:action]
- ensure
- Object.send(:remove_const, :BooksController) rescue nil
- end
-
- def test_subpath_recognized
- Object.const_set(:SubpathBooksController, Class.new(ActionController::Base))
-
- rs.draw do |r|
- r.connect '/books/:id/edit', :controller => 'subpath_books', :action => 'edit'
- r.connect '/items/:id/:action', :controller => 'subpath_books'
- r.connect '/posts/new/:action', :controller => 'subpath_books'
- r.connect '/posts/:id', :controller => 'subpath_books', :action => "show"
- end
+ hash = rs.recognize_path "/items/3/complete"
+ assert_not_nil hash
+ assert_equal %w(subpath_books 3 complete), [hash[:controller], hash[:id], hash[:action]]
- hash = rs.recognize_path "/books/17/edit"
- assert_not_nil hash
- assert_equal %w(subpath_books 17 edit), [hash[:controller], hash[:id], hash[:action]]
+ hash = rs.recognize_path "/posts/new/preview"
+ assert_not_nil hash
+ assert_equal %w(subpath_books preview), [hash[:controller], hash[:action]]
- hash = rs.recognize_path "/items/3/complete"
- assert_not_nil hash
- assert_equal %w(subpath_books 3 complete), [hash[:controller], hash[:id], hash[:action]]
+ hash = rs.recognize_path "/posts/7"
+ assert_not_nil hash
+ assert_equal %w(subpath_books show 7), [hash[:controller], hash[:action], hash[:id]]
+ ensure
+ Object.send(:remove_const, :SubpathBooksController) rescue nil
+ end
- hash = rs.recognize_path "/posts/new/preview"
- assert_not_nil hash
- assert_equal %w(subpath_books preview), [hash[:controller], hash[:action]]
+ def test_subpath_generated
+ Object.const_set(:SubpathBooksController, Class.new(ActionController::Base))
- hash = rs.recognize_path "/posts/7"
- assert_not_nil hash
- assert_equal %w(subpath_books show 7), [hash[:controller], hash[:action], hash[:id]]
- ensure
- Object.send(:remove_const, :SubpathBooksController) rescue nil
+ rs.draw do |r|
+ r.connect '/books/:id/edit', :controller => 'subpath_books', :action => 'edit'
+ r.connect '/items/:id/:action', :controller => 'subpath_books'
+ r.connect '/posts/new/:action', :controller => 'subpath_books'
end
- def test_subpath_generated
- Object.const_set(:SubpathBooksController, Class.new(ActionController::Base))
-
- rs.draw do |r|
- r.connect '/books/:id/edit', :controller => 'subpath_books', :action => 'edit'
- r.connect '/items/:id/:action', :controller => 'subpath_books'
- r.connect '/posts/new/:action', :controller => 'subpath_books'
- end
+ assert_equal "/books/7/edit", rs.generate(:controller => "subpath_books", :id => 7, :action => "edit")
+ assert_equal "/items/15/complete", rs.generate(:controller => "subpath_books", :id => 15, :action => "complete")
+ assert_equal "/posts/new/preview", rs.generate(:controller => "subpath_books", :action => "preview")
+ ensure
+ Object.send(:remove_const, :SubpathBooksController) rescue nil
+ end
- assert_equal "/books/7/edit", rs.generate(:controller => "subpath_books", :id => 7, :action => "edit")
- assert_equal "/items/15/complete", rs.generate(:controller => "subpath_books", :id => 15, :action => "complete")
- assert_equal "/posts/new/preview", rs.generate(:controller => "subpath_books", :action => "preview")
- ensure
- Object.send(:remove_const, :SubpathBooksController) rescue nil
+ def test_failed_requirements_raises_exception_with_violated_requirements
+ rs.draw do |r|
+ r.foo_with_requirement 'foos/:id', :controller=>'foos', :requirements=>{:id=>/\d+/}
end
- def test_failed_requirements_raises_exception_with_violated_requirements
- rs.draw do |r|
- r.foo_with_requirement 'foos/:id', :controller=>'foos', :requirements=>{:id=>/\d+/}
- end
+ x = setup_for_named_route
+ assert_raises(ActionController::RoutingError) do
+ x.send(:foo_with_requirement_url, "I am Against the requirements")
+ end
+ end
- x = setup_for_named_route
- assert_raises(ActionController::RoutingError) do
- x.send(:foo_with_requirement_url, "I am Against the requirements")
- end
+ def test_routes_changed_correctly_after_clear
+ ActionController::Base.optimise_named_routes = true
+ rs = ::ActionController::Routing::RouteSet.new
+ rs.draw do |r|
+ r.connect 'ca', :controller => 'ca', :action => "aa"
+ r.connect 'cb', :controller => 'cb', :action => "ab"
+ r.connect 'cc', :controller => 'cc', :action => "ac"
+ r.connect ':controller/:action/:id'
+ r.connect ':controller/:action/:id.:format'
end
- def test_routes_changed_correctly_after_clear
- ActionController::Base.optimise_named_routes = true
- rs = ::ActionController::Routing::RouteSet.new
- rs.draw do |r|
- r.connect 'ca', :controller => 'ca', :action => "aa"
- r.connect 'cb', :controller => 'cb', :action => "ab"
- r.connect 'cc', :controller => 'cc', :action => "ac"
- r.connect ':controller/:action/:id'
- r.connect ':controller/:action/:id.:format'
- end
+ hash = rs.recognize_path "/cc"
- hash = rs.recognize_path "/cc"
+ assert_not_nil hash
+ assert_equal %w(cc ac), [hash[:controller], hash[:action]]
- assert_not_nil hash
- assert_equal %w(cc ac), [hash[:controller], hash[:action]]
+ rs.draw do |r|
+ r.connect 'cb', :controller => 'cb', :action => "ab"
+ r.connect 'cc', :controller => 'cc', :action => "ac"
+ r.connect ':controller/:action/:id'
+ r.connect ':controller/:action/:id.:format'
+ end
- rs.draw do |r|
- r.connect 'cb', :controller => 'cb', :action => "ab"
- r.connect 'cc', :controller => 'cc', :action => "ac"
- r.connect ':controller/:action/:id'
- r.connect ':controller/:action/:id.:format'
- end
+ hash = rs.recognize_path "/cc"
- hash = rs.recognize_path "/cc"
+ assert_not_nil hash
+ assert_equal %w(cc ac), [hash[:controller], hash[:action]]
- assert_not_nil hash
- assert_equal %w(cc ac), [hash[:controller], hash[:action]]
+ end
+end
- end
+class RouteTest < Test::Unit::TestCase
+ def setup
+ @route = ROUTING::Route.new
end
- class RouteTest < Test::Unit::TestCase
- def setup
- @route = ROUTING::Route.new
- end
+ def slash_segment(is_optional = false)
+ ROUTING::DividerSegment.new('/', :optional => is_optional)
+ end
- def slash_segment(is_optional = false)
- ROUTING::DividerSegment.new('/', :optional => is_optional)
+ def default_route
+ unless defined?(@default_route)
+ segments = []
+ segments << ROUTING::StaticSegment.new('/', :raw => true)
+ segments << ROUTING::DynamicSegment.new(:controller)
+ segments << slash_segment(:optional)
+ segments << ROUTING::DynamicSegment.new(:action, :default => 'index', :optional => true)
+ segments << slash_segment(:optional)
+ segments << ROUTING::DynamicSegment.new(:id, :optional => true)
+ segments << slash_segment(:optional)
+ @default_route = ROUTING::Route.new(segments).freeze
end
+ @default_route
+ end
- def default_route
- unless defined?(@default_route)
- segments = []
- segments << ROUTING::StaticSegment.new('/', :raw => true)
- segments << ROUTING::DynamicSegment.new(:controller)
- segments << slash_segment(:optional)
- segments << ROUTING::DynamicSegment.new(:action, :default => 'index', :optional => true)
- segments << slash_segment(:optional)
- segments << ROUTING::DynamicSegment.new(:id, :optional => true)
- segments << slash_segment(:optional)
- @default_route = ROUTING::Route.new(segments).freeze
- end
- @default_route
- end
+ def test_default_route_recognition
+ expected = {:controller => 'accounts', :action => 'show', :id => '10'}
+ assert_equal expected, default_route.recognize('/accounts/show/10')
+ assert_equal expected, default_route.recognize('/accounts/show/10/')
- def test_default_route_recognition
- expected = {:controller => 'accounts', :action => 'show', :id => '10'}
- assert_equal expected, default_route.recognize('/accounts/show/10')
- assert_equal expected, default_route.recognize('/accounts/show/10/')
+ expected[:id] = 'jamis'
+ assert_equal expected, default_route.recognize('/accounts/show/jamis/')
- expected[:id] = 'jamis'
- assert_equal expected, default_route.recognize('/accounts/show/jamis/')
+ expected.delete :id
+ assert_equal expected, default_route.recognize('/accounts/show')
+ assert_equal expected, default_route.recognize('/accounts/show/')
- expected.delete :id
- assert_equal expected, default_route.recognize('/accounts/show')
- assert_equal expected, default_route.recognize('/accounts/show/')
+ expected[:action] = 'index'
+ assert_equal expected, default_route.recognize('/accounts/')
+ assert_equal expected, default_route.recognize('/accounts')
- expected[:action] = 'index'
- assert_equal expected, default_route.recognize('/accounts/')
- assert_equal expected, default_route.recognize('/accounts')
+ assert_equal nil, default_route.recognize('/')
+ assert_equal nil, default_route.recognize('/accounts/how/goood/it/is/to/be/free')
+ end
- assert_equal nil, default_route.recognize('/')
- assert_equal nil, default_route.recognize('/accounts/how/goood/it/is/to/be/free')
- end
+ def test_default_route_should_omit_default_action
+ o = {:controller => 'accounts', :action => 'index'}
+ assert_equal '/accounts', default_route.generate(o, o, {})
+ end
- def test_default_route_should_omit_default_action
- o = {:controller => 'accounts', :action => 'index'}
- assert_equal '/accounts', default_route.generate(o, o, {})
- end
+ def test_default_route_should_include_default_action_when_id_present
+ o = {:controller => 'accounts', :action => 'index', :id => '20'}
+ assert_equal '/accounts/index/20', default_route.generate(o, o, {})
+ end
- def test_default_route_should_include_default_action_when_id_present
- o = {:controller => 'accounts', :action => 'index', :id => '20'}
- assert_equal '/accounts/index/20', default_route.generate(o, o, {})
- end
+ def test_default_route_should_work_with_action_but_no_id
+ o = {:controller => 'accounts', :action => 'list_all'}
+ assert_equal '/accounts/list_all', default_route.generate(o, o, {})
+ end
- def test_default_route_should_work_with_action_but_no_id
- o = {:controller => 'accounts', :action => 'list_all'}
- assert_equal '/accounts/list_all', default_route.generate(o, o, {})
- end
+ def test_default_route_should_uri_escape_pluses
+ expected = { :controller => 'accounts', :action => 'show', :id => 'hello world' }
+ assert_equal expected, default_route.recognize('/accounts/show/hello world')
+ assert_equal expected, default_route.recognize('/accounts/show/hello%20world')
+ assert_equal '/accounts/show/hello%20world', default_route.generate(expected, expected, {})
- def test_default_route_should_uri_escape_pluses
- expected = { :controller => 'accounts', :action => 'show', :id => 'hello world' }
- assert_equal expected, default_route.recognize('/accounts/show/hello world')
- assert_equal expected, default_route.recognize('/accounts/show/hello%20world')
- assert_equal '/accounts/show/hello%20world', default_route.generate(expected, expected, {})
+ expected[:id] = 'hello+world'
+ assert_equal expected, default_route.recognize('/accounts/show/hello+world')
+ assert_equal expected, default_route.recognize('/accounts/show/hello%2Bworld')
+ assert_equal '/accounts/show/hello+world', default_route.generate(expected, expected, {})
+ end
- expected[:id] = 'hello+world'
- assert_equal expected, default_route.recognize('/accounts/show/hello+world')
- assert_equal expected, default_route.recognize('/accounts/show/hello%2Bworld')
- assert_equal '/accounts/show/hello+world', default_route.generate(expected, expected, {})
- end
+ def test_matches_controller_and_action
+ # requirement_for should only be called for the action and controller _once_
+ @route.expects(:requirement_for).with(:controller).times(1).returns('pages')
+ @route.expects(:requirement_for).with(:action).times(1).returns('show')
- def test_matches_controller_and_action
- # requirement_for should only be called for the action and controller _once_
- @route.expects(:requirement_for).with(:controller).times(1).returns('pages')
- @route.expects(:requirement_for).with(:action).times(1).returns('show')
+ @route.requirements = {:controller => 'pages', :action => 'show'}
+ assert @route.matches_controller_and_action?('pages', 'show')
+ assert !@route.matches_controller_and_action?('not_pages', 'show')
+ assert !@route.matches_controller_and_action?('pages', 'not_show')
+ end
- @route.requirements = {:controller => 'pages', :action => 'show'}
- assert @route.matches_controller_and_action?('pages', 'show')
- assert !@route.matches_controller_and_action?('not_pages', 'show')
- assert !@route.matches_controller_and_action?('pages', 'not_show')
- end
+ def test_parameter_shell
+ page_url = ROUTING::Route.new
+ page_url.requirements = {:controller => 'pages', :action => 'show', :id => /\d+/}
+ assert_equal({:controller => 'pages', :action => 'show'}, page_url.parameter_shell)
+ end
- def test_parameter_shell
- page_url = ROUTING::Route.new
- page_url.requirements = {:controller => 'pages', :action => 'show', :id => /\d+/}
- assert_equal({:controller => 'pages', :action => 'show'}, page_url.parameter_shell)
- end
+ def test_defaults
+ route = ROUTING::RouteBuilder.new.build '/users/:id.:format', :controller => "users", :action => "show", :format => "html"
+ assert_equal(
+ { :controller => "users", :action => "show", :format => "html" },
+ route.defaults)
+ end
- def test_defaults
- route = ROUTING::RouteBuilder.new.build '/users/:id.:format', :controller => "users", :action => "show", :format => "html"
- assert_equal(
- { :controller => "users", :action => "show", :format => "html" },
- route.defaults)
+ def test_builder_complains_without_controller
+ assert_raises(ArgumentError) do
+ ROUTING::RouteBuilder.new.build '/contact', :contoller => "contact", :action => "index"
end
+ end
- def test_builder_complains_without_controller
- assert_raises(ArgumentError) do
- ROUTING::RouteBuilder.new.build '/contact', :contoller => "contact", :action => "index"
- end
- end
+ def test_significant_keys_for_default_route
+ keys = default_route.significant_keys.sort_by {|k| k.to_s }
+ assert_equal [:action, :controller, :id], keys
+ end
- def test_significant_keys_for_default_route
- keys = default_route.significant_keys.sort_by {|k| k.to_s }
- assert_equal [:action, :controller, :id], keys
- end
+ def test_significant_keys
+ segments = []
+ segments << ROUTING::StaticSegment.new('/', :raw => true)
+ segments << ROUTING::StaticSegment.new('user')
+ segments << ROUTING::StaticSegment.new('/', :raw => true, :optional => true)
+ segments << ROUTING::DynamicSegment.new(:user)
+ segments << ROUTING::StaticSegment.new('/', :raw => true, :optional => true)
- def test_significant_keys
- segments = []
- segments << ROUTING::StaticSegment.new('/', :raw => true)
- segments << ROUTING::StaticSegment.new('user')
- segments << ROUTING::StaticSegment.new('/', :raw => true, :optional => true)
- segments << ROUTING::DynamicSegment.new(:user)
- segments << ROUTING::StaticSegment.new('/', :raw => true, :optional => true)
+ requirements = {:controller => 'users', :action => 'show'}
- requirements = {:controller => 'users', :action => 'show'}
+ user_url = ROUTING::Route.new(segments, requirements)
+ keys = user_url.significant_keys.sort_by { |k| k.to_s }
+ assert_equal [:action, :controller, :user], keys
+ end
- user_url = ROUTING::Route.new(segments, requirements)
- keys = user_url.significant_keys.sort_by { |k| k.to_s }
- assert_equal [:action, :controller, :user], keys
- end
+ def test_build_empty_query_string
+ assert_equal '', @route.build_query_string({})
+ end
- def test_build_empty_query_string
- assert_equal '', @route.build_query_string({})
- end
+ def test_build_query_string_with_nil_value
+ assert_equal '', @route.build_query_string({:x => nil})
+ end
- def test_build_query_string_with_nil_value
- assert_equal '', @route.build_query_string({:x => nil})
- end
+ def test_simple_build_query_string
+ assert_equal '?x=1&y=2', order_query_string(@route.build_query_string(:x => '1', :y => '2'))
+ end
- def test_simple_build_query_string
- assert_equal '?x=1&y=2', order_query_string(@route.build_query_string(:x => '1', :y => '2'))
- end
+ def test_convert_ints_build_query_string
+ assert_equal '?x=1&y=2', order_query_string(@route.build_query_string(:x => 1, :y => 2))
+ end
- def test_convert_ints_build_query_string
- assert_equal '?x=1&y=2', order_query_string(@route.build_query_string(:x => 1, :y => 2))
- end
+ def test_escape_spaces_build_query_string
+ assert_equal '?x=hello+world&y=goodbye+world', order_query_string(@route.build_query_string(:x => 'hello world', :y => 'goodbye world'))
+ end
- def test_escape_spaces_build_query_string
- assert_equal '?x=hello+world&y=goodbye+world', order_query_string(@route.build_query_string(:x => 'hello world', :y => 'goodbye world'))
- end
+ def test_expand_array_build_query_string
+ assert_equal '?x%5B%5D=1&x%5B%5D=2', order_query_string(@route.build_query_string(:x => [1, 2]))
+ end
- def test_expand_array_build_query_string
- assert_equal '?x%5B%5D=1&x%5B%5D=2', order_query_string(@route.build_query_string(:x => [1, 2]))
- end
+ def test_escape_spaces_build_query_string_selected_keys
+ assert_equal '?x=hello+world', order_query_string(@route.build_query_string({:x => 'hello world', :y => 'goodbye world'}, [:x]))
+ end
- def test_escape_spaces_build_query_string_selected_keys
- assert_equal '?x=hello+world', order_query_string(@route.build_query_string({:x => 'hello world', :y => 'goodbye world'}, [:x]))
+ private
+ def order_query_string(qs)
+ '?' + qs[1..-1].split('&').sort.join('&')
end
+end
- private
- def order_query_string(qs)
- '?' + qs[1..-1].split('&').sort.join('&')
- end
+class RouteSetTest < Test::Unit::TestCase
+ def set
+ @set ||= ROUTING::RouteSet.new
end
- class RouteSetTest < Test::Unit::TestCase
- def set
- @set ||= ROUTING::RouteSet.new
- end
+ def request
+ @request ||= ActionController::TestRequest.new
+ end
- def request
- @request ||= ActionController::TestRequest.new
- end
+ def test_generate_extras
+ set.draw { |m| m.connect ':controller/:action/:id' }
+ path, extras = set.generate_extras(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world")
+ assert_equal "/foo/bar/15", path
+ assert_equal %w(that this), extras.map(&:to_s).sort
+ end
- def test_generate_extras
- set.draw { |m| m.connect ':controller/:action/:id' }
- path, extras = set.generate_extras(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world")
- assert_equal "/foo/bar/15", path
- assert_equal %w(that this), extras.map(&:to_s).sort
- end
+ def test_extra_keys
+ set.draw { |m| m.connect ':controller/:action/:id' }
+ extras = set.extra_keys(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world")
+ assert_equal %w(that this), extras.map(&:to_s).sort
+ end
- def test_extra_keys
- set.draw { |m| m.connect ':controller/:action/:id' }
- extras = set.extra_keys(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world")
- assert_equal %w(that this), extras.map(&:to_s).sort
+ def test_generate_extras_not_first
+ set.draw do |map|
+ map.connect ':controller/:action/:id.:format'
+ map.connect ':controller/:action/:id'
end
+ path, extras = set.generate_extras(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world")
+ assert_equal "/foo/bar/15", path
+ assert_equal %w(that this), extras.map(&:to_s).sort
+ end
- def test_generate_extras_not_first
- set.draw do |map|
- map.connect ':controller/:action/:id.:format'
- map.connect ':controller/:action/:id'
- end
- path, extras = set.generate_extras(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world")
- assert_equal "/foo/bar/15", path
- assert_equal %w(that this), extras.map(&:to_s).sort
+ def test_generate_not_first
+ set.draw do |map|
+ map.connect ':controller/:action/:id.:format'
+ map.connect ':controller/:action/:id'
end
+ assert_equal "/foo/bar/15?this=hello", set.generate(:controller => "foo", :action => "bar", :id => 15, :this => "hello")
+ end
- def test_generate_not_first
- set.draw do |map|
- map.connect ':controller/:action/:id.:format'
- map.connect ':controller/:action/:id'
- end
- assert_equal "/foo/bar/15?this=hello", set.generate(:controller => "foo", :action => "bar", :id => 15, :this => "hello")
+ def test_extra_keys_not_first
+ set.draw do |map|
+ map.connect ':controller/:action/:id.:format'
+ map.connect ':controller/:action/:id'
end
+ extras = set.extra_keys(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world")
+ assert_equal %w(that this), extras.map(&:to_s).sort
+ end
- def test_extra_keys_not_first
- set.draw do |map|
- map.connect ':controller/:action/:id.:format'
- map.connect ':controller/:action/:id'
- end
- extras = set.extra_keys(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world")
- assert_equal %w(that this), extras.map(&:to_s).sort
+ def test_draw
+ assert_equal 0, set.routes.size
+ set.draw do |map|
+ map.connect '/hello/world', :controller => 'a', :action => 'b'
end
+ assert_equal 1, set.routes.size
+ end
- def test_draw
- assert_equal 0, set.routes.size
- set.draw do |map|
- map.connect '/hello/world', :controller => 'a', :action => 'b'
- end
- assert_equal 1, set.routes.size
+ def test_named_draw
+ assert_equal 0, set.routes.size
+ set.draw do |map|
+ map.hello '/hello/world', :controller => 'a', :action => 'b'
end
+ assert_equal 1, set.routes.size
+ assert_equal set.routes.first, set.named_routes[:hello]
+ end
- def test_named_draw
- assert_equal 0, set.routes.size
- set.draw do |map|
- map.hello '/hello/world', :controller => 'a', :action => 'b'
- end
- assert_equal 1, set.routes.size
- assert_equal set.routes.first, set.named_routes[:hello]
+ def test_later_named_routes_take_precedence
+ set.draw do |map|
+ map.hello '/hello/world', :controller => 'a', :action => 'b'
+ map.hello '/hello', :controller => 'a', :action => 'b'
end
+ assert_equal set.routes.last, set.named_routes[:hello]
+ end
- def test_later_named_routes_take_precedence
- set.draw do |map|
- map.hello '/hello/world', :controller => 'a', :action => 'b'
- map.hello '/hello', :controller => 'a', :action => 'b'
- end
- assert_equal set.routes.last, set.named_routes[:hello]
+ def setup_named_route_test
+ set.draw do |map|
+ map.show '/people/:id', :controller => 'people', :action => 'show'
+ map.index '/people', :controller => 'people', :action => 'index'
+ map.multi '/people/go/:foo/:bar/joe/:id', :controller => 'people', :action => 'multi'
+ map.users '/admin/users', :controller => 'admin/users', :action => 'index'
end
- def setup_named_route_test
- set.draw do |map|
- map.show '/people/:id', :controller => 'people', :action => 'show'
- map.index '/people', :controller => 'people', :action => 'index'
- map.multi '/people/go/:foo/:bar/joe/:id', :controller => 'people', :action => 'multi'
- map.users '/admin/users', :controller => 'admin/users', :action => 'index'
- end
-
- klass = Class.new(MockController)
- set.install_helpers(klass)
- klass.new(set)
- end
+ klass = Class.new(MockController)
+ set.install_helpers(klass)
+ klass.new(set)
+ end
- def test_named_route_hash_access_method
- controller = setup_named_route_test
+ def test_named_route_hash_access_method
+ controller = setup_named_route_test
- assert_equal(
- { :controller => 'people', :action => 'show', :id => 5, :use_route => :show, :only_path => false },
- controller.send(:hash_for_show_url, :id => 5))
+ assert_equal(
+ { :controller => 'people', :action => 'show', :id => 5, :use_route => :show, :only_path => false },
+ controller.send(:hash_for_show_url, :id => 5))
- assert_equal(
- { :controller => 'people', :action => 'index', :use_route => :index, :only_path => false },
- controller.send(:hash_for_index_url))
+ assert_equal(
+ { :controller => 'people', :action => 'index', :use_route => :index, :only_path => false },
+ controller.send(:hash_for_index_url))
- assert_equal(
- { :controller => 'people', :action => 'show', :id => 5, :use_route => :show, :only_path => true },
- controller.send(:hash_for_show_path, :id => 5)
- )
- end
+ assert_equal(
+ { :controller => 'people', :action => 'show', :id => 5, :use_route => :show, :only_path => true },
+ controller.send(:hash_for_show_path, :id => 5)
+ )
+ end
- def test_named_route_url_method
- controller = setup_named_route_test
+ def test_named_route_url_method
+ controller = setup_named_route_test
- assert_equal "http://test.host/people/5", controller.send(:show_url, :id => 5)
- assert_equal "/people/5", controller.send(:show_path, :id => 5)
+ assert_equal "http://test.host/people/5", controller.send(:show_url, :id => 5)
+ assert_equal "/people/5", controller.send(:show_path, :id => 5)
- assert_equal "http://test.host/people", controller.send(:index_url)
- assert_equal "/people", controller.send(:index_path)
+ assert_equal "http://test.host/people", controller.send(:index_url)
+ assert_equal "/people", controller.send(:index_path)
- assert_equal "http://test.host/admin/users", controller.send(:users_url)
- assert_equal '/admin/users', controller.send(:users_path)
- assert_equal '/admin/users', set.generate(controller.send(:hash_for_users_url), {:controller => 'users', :action => 'index'})
- end
+ assert_equal "http://test.host/admin/users", controller.send(:users_url)
+ assert_equal '/admin/users', controller.send(:users_path)
+ assert_equal '/admin/users', set.generate(controller.send(:hash_for_users_url), {:controller => 'users', :action => 'index'})
+ end
- def test_named_route_url_method_with_anchor
- controller = setup_named_route_test
+ def test_named_route_url_method_with_anchor
+ controller = setup_named_route_test
- assert_equal "http://test.host/people/5#location", controller.send(:show_url, :id => 5, :anchor => 'location')
- assert_equal "/people/5#location", controller.send(:show_path, :id => 5, :anchor => 'location')
+ assert_equal "http://test.host/people/5#location", controller.send(:show_url, :id => 5, :anchor => 'location')
+ assert_equal "/people/5#location", controller.send(:show_path, :id => 5, :anchor => 'location')
- assert_equal "http://test.host/people#location", controller.send(:index_url, :anchor => 'location')
- assert_equal "/people#location", controller.send(:index_path, :anchor => 'location')
+ assert_equal "http://test.host/people#location", controller.send(:index_url, :anchor => 'location')
+ assert_equal "/people#location", controller.send(:index_path, :anchor => 'location')
- assert_equal "http://test.host/admin/users#location", controller.send(:users_url, :anchor => 'location')
- assert_equal '/admin/users#location', controller.send(:users_path, :anchor => 'location')
+ assert_equal "http://test.host/admin/users#location", controller.send(:users_url, :anchor => 'location')
+ assert_equal '/admin/users#location', controller.send(:users_path, :anchor => 'location')
- assert_equal "http://test.host/people/go/7/hello/joe/5#location",
- controller.send(:multi_url, 7, "hello", 5, :anchor => 'location')
+ assert_equal "http://test.host/people/go/7/hello/joe/5#location",
+ controller.send(:multi_url, 7, "hello", 5, :anchor => 'location')
- assert_equal "http://test.host/people/go/7/hello/joe/5?baz=bar#location",
- controller.send(:multi_url, 7, "hello", 5, :baz => "bar", :anchor => 'location')
+ assert_equal "http://test.host/people/go/7/hello/joe/5?baz=bar#location",
+ controller.send(:multi_url, 7, "hello", 5, :baz => "bar", :anchor => 'location')
- assert_equal "http://test.host/people?baz=bar#location",
- controller.send(:index_url, :baz => "bar", :anchor => 'location')
- end
+ assert_equal "http://test.host/people?baz=bar#location",
+ controller.send(:index_url, :baz => "bar", :anchor => 'location')
+ end
- def test_named_route_url_method_with_port
- controller = setup_named_route_test
- assert_equal "http://test.host:8080/people/5", controller.send(:show_url, 5, :port=>8080)
- end
+ def test_named_route_url_method_with_port
+ controller = setup_named_route_test
+ assert_equal "http://test.host:8080/people/5", controller.send(:show_url, 5, :port=>8080)
+ end
- def test_named_route_url_method_with_host
- controller = setup_named_route_test
- assert_equal "http://some.example.com/people/5", controller.send(:show_url, 5, :host=>"some.example.com")
- end
+ def test_named_route_url_method_with_host
+ controller = setup_named_route_test
+ assert_equal "http://some.example.com/people/5", controller.send(:show_url, 5, :host=>"some.example.com")
+ end
- def test_named_route_url_method_with_protocol
- controller = setup_named_route_test
- assert_equal "https://test.host/people/5", controller.send(:show_url, 5, :protocol => "https")
- end
+ def test_named_route_url_method_with_protocol
+ controller = setup_named_route_test
+ assert_equal "https://test.host/people/5", controller.send(:show_url, 5, :protocol => "https")
+ end
- def test_named_route_url_method_with_ordered_parameters
- controller = setup_named_route_test
- assert_equal "http://test.host/people/go/7/hello/joe/5",
- controller.send(:multi_url, 7, "hello", 5)
- end
+ def test_named_route_url_method_with_ordered_parameters
+ controller = setup_named_route_test
+ assert_equal "http://test.host/people/go/7/hello/joe/5",
+ controller.send(:multi_url, 7, "hello", 5)
+ end
- def test_named_route_url_method_with_ordered_parameters_and_hash
- controller = setup_named_route_test
- assert_equal "http://test.host/people/go/7/hello/joe/5?baz=bar",
- controller.send(:multi_url, 7, "hello", 5, :baz => "bar")
- end
+ def test_named_route_url_method_with_ordered_parameters_and_hash
+ controller = setup_named_route_test
+ assert_equal "http://test.host/people/go/7/hello/joe/5?baz=bar",
+ controller.send(:multi_url, 7, "hello", 5, :baz => "bar")
+ end
- def test_named_route_url_method_with_ordered_parameters_and_empty_hash
- controller = setup_named_route_test
- assert_equal "http://test.host/people/go/7/hello/joe/5",
- controller.send(:multi_url, 7, "hello", 5, {})
- end
+ def test_named_route_url_method_with_ordered_parameters_and_empty_hash
+ controller = setup_named_route_test
+ assert_equal "http://test.host/people/go/7/hello/joe/5",
+ controller.send(:multi_url, 7, "hello", 5, {})
+ end
- def test_named_route_url_method_with_no_positional_arguments
- controller = setup_named_route_test
- assert_equal "http://test.host/people?baz=bar",
- controller.send(:index_url, :baz => "bar")
- end
+ def test_named_route_url_method_with_no_positional_arguments
+ controller = setup_named_route_test
+ assert_equal "http://test.host/people?baz=bar",
+ controller.send(:index_url, :baz => "bar")
+ end
- def test_draw_default_route
- ActionController::Routing.with_controllers(['users']) do
- set.draw do |map|
- map.connect '/:controller/:action/:id'
- end
+ def test_draw_default_route
+ ActionController::Routing.with_controllers(['users']) do
+ set.draw do |map|
+ map.connect '/:controller/:action/:id'
+ end
- assert_equal 1, set.routes.size
- route = set.routes.first
+ assert_equal 1, set.routes.size
+ route = set.routes.first
- assert route.segments.last.optional?
+ assert route.segments.last.optional?
- assert_equal '/users/show/10', set.generate(:controller => 'users', :action => 'show', :id => 10)
- assert_equal '/users/index/10', set.generate(:controller => 'users', :id => 10)
+ assert_equal '/users/show/10', set.generate(:controller => 'users', :action => 'show', :id => 10)
+ assert_equal '/users/index/10', set.generate(:controller => 'users', :id => 10)
- assert_equal({:controller => 'users', :action => 'index', :id => '10'}, set.recognize_path('/users/index/10'))
- assert_equal({:controller => 'users', :action => 'index', :id => '10'}, set.recognize_path('/users/index/10/'))
- end
+ assert_equal({:controller => 'users', :action => 'index', :id => '10'}, set.recognize_path('/users/index/10'))
+ assert_equal({:controller => 'users', :action => 'index', :id => '10'}, set.recognize_path('/users/index/10/'))
end
+ end
- def test_draw_default_route_with_default_controller
- ActionController::Routing.with_controllers(['users']) do
- set.draw do |map|
- map.connect '/:controller/:action/:id', :controller => 'users'
- end
- assert_equal({:controller => 'users', :action => 'index'}, set.recognize_path('/'))
+ def test_draw_default_route_with_default_controller
+ ActionController::Routing.with_controllers(['users']) do
+ set.draw do |map|
+ map.connect '/:controller/:action/:id', :controller => 'users'
end
+ assert_equal({:controller => 'users', :action => 'index'}, set.recognize_path('/'))
end
+ end
- def test_route_with_parameter_shell
- ActionController::Routing.with_controllers(['users', 'pages']) do
- set.draw do |map|
- map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+/
- map.connect '/:controller/:action/:id'
- end
+ def test_route_with_parameter_shell
+ ActionController::Routing.with_controllers(['users', 'pages']) do
+ set.draw do |map|
+ map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+/
+ map.connect '/:controller/:action/:id'
+ end
- assert_equal({:controller => 'pages', :action => 'index'}, set.recognize_path('/pages'))
- assert_equal({:controller => 'pages', :action => 'index'}, set.recognize_path('/pages/index'))
- assert_equal({:controller => 'pages', :action => 'list'}, set.recognize_path('/pages/list'))
+ assert_equal({:controller => 'pages', :action => 'index'}, set.recognize_path('/pages'))
+ assert_equal({:controller => 'pages', :action => 'index'}, set.recognize_path('/pages/index'))
+ assert_equal({:controller => 'pages', :action => 'list'}, set.recognize_path('/pages/list'))
- assert_equal({:controller => 'pages', :action => 'show', :id => '10'}, set.recognize_path('/pages/show/10'))
- assert_equal({:controller => 'pages', :action => 'show', :id => '10'}, set.recognize_path('/page/10'))
- end
+ assert_equal({:controller => 'pages', :action => 'show', :id => '10'}, set.recognize_path('/pages/show/10'))
+ assert_equal({:controller => 'pages', :action => 'show', :id => '10'}, set.recognize_path('/page/10'))
end
+ end
- def test_route_requirements_with_anchor_chars_are_invalid
- assert_raises ArgumentError do
- set.draw do |map|
- map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /^\d+/
- end
- end
- assert_raises ArgumentError do
- set.draw do |map|
- map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\A\d+/
- end
- end
- assert_raises ArgumentError do
- set.draw do |map|
- map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+$/
- end
- end
- assert_raises ArgumentError do
- set.draw do |map|
- map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+\Z/
- end
- end
- assert_raises ArgumentError do
- set.draw do |map|
- map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+\z/
- end
+ def test_route_requirements_with_anchor_chars_are_invalid
+ assert_raises ArgumentError do
+ set.draw do |map|
+ map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /^\d+/
end
- assert_nothing_raised do
- set.draw do |map|
- map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+/, :name => /^(david|jamis)/
- end
- assert_raises ActionController::RoutingError do
- set.generate :controller => 'pages', :action => 'show', :id => 10
- end
+ end
+ assert_raises ArgumentError do
+ set.draw do |map|
+ map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\A\d+/
end
end
-
- def test_route_requirements_with_invalid_http_method_is_invalid
- assert_raises ArgumentError do
- set.draw do |map|
- map.connect 'valid/route', :controller => 'pages', :action => 'show', :conditions => {:method => :invalid}
- end
+ assert_raises ArgumentError do
+ set.draw do |map|
+ map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+$/
end
end
-
- def test_route_requirements_with_head_method_condition_is_invalid
- assert_raises ArgumentError do
- set.draw do |map|
- map.connect 'valid/route', :controller => 'pages', :action => 'show', :conditions => {:method => :head}
- end
+ assert_raises ArgumentError do
+ set.draw do |map|
+ map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+\Z/
end
end
-
- def test_non_path_route_requirements_match_all
+ assert_raises ArgumentError do
set.draw do |map|
- map.connect 'page/37s', :controller => 'pages', :action => 'show', :name => /(jamis|david)/
+ map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+\z/
end
- assert_equal '/page/37s', set.generate(:controller => 'pages', :action => 'show', :name => 'jamis')
- assert_raises ActionController::RoutingError do
- set.generate(:controller => 'pages', :action => 'show', :name => 'not_jamis')
+ end
+ assert_nothing_raised do
+ set.draw do |map|
+ map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+/, :name => /^(david|jamis)/
end
assert_raises ActionController::RoutingError do
- set.generate(:controller => 'pages', :action => 'show', :name => 'nor_jamis_and_david')
+ set.generate :controller => 'pages', :action => 'show', :id => 10
end
end
+ end
- def test_recognize_with_encoded_id_and_regex
+ def test_route_requirements_with_invalid_http_method_is_invalid
+ assert_raises ArgumentError do
set.draw do |map|
- map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /[a-zA-Z0-9\+]+/
+ map.connect 'valid/route', :controller => 'pages', :action => 'show', :conditions => {:method => :invalid}
end
-
- assert_equal({:controller => 'pages', :action => 'show', :id => '10'}, set.recognize_path('/page/10'))
- assert_equal({:controller => 'pages', :action => 'show', :id => 'hello+world'}, set.recognize_path('/page/hello+world'))
end
+ end
- def test_recognize_with_conditions
- Object.const_set(:PeopleController, Class.new)
-
+ def test_route_requirements_with_head_method_condition_is_invalid
+ assert_raises ArgumentError do
set.draw do |map|
- map.with_options(:controller => "people") do |people|
- people.people "/people", :action => "index", :conditions => { :method => :get }
- people.connect "/people", :action => "create", :conditions => { :method => :post }
- people.person "/people/:id", :action => "show", :conditions => { :method => :get }
- people.connect "/people/:id", :action => "update", :conditions => { :method => :put }
- people.connect "/people/:id", :action => "destroy", :conditions => { :method => :delete }
- end
+ map.connect 'valid/route', :controller => 'pages', :action => 'show', :conditions => {:method => :head}
end
+ end
+ end
- request.path = "/people"
- request.env["REQUEST_METHOD"] = "GET"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("index", request.path_parameters[:action])
- request.recycle!
+ def test_non_path_route_requirements_match_all
+ set.draw do |map|
+ map.connect 'page/37s', :controller => 'pages', :action => 'show', :name => /(jamis|david)/
+ end
+ assert_equal '/page/37s', set.generate(:controller => 'pages', :action => 'show', :name => 'jamis')
+ assert_raises ActionController::RoutingError do
+ set.generate(:controller => 'pages', :action => 'show', :name => 'not_jamis')
+ end
+ assert_raises ActionController::RoutingError do
+ set.generate(:controller => 'pages', :action => 'show', :name => 'nor_jamis_and_david')
+ end
+ end
- request.env["REQUEST_METHOD"] = "POST"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("create", request.path_parameters[:action])
- request.recycle!
-
- request.env["REQUEST_METHOD"] = "PUT"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("update", request.path_parameters[:action])
- request.recycle!
-
- assert_raises(ActionController::UnknownHttpMethod) {
- request.env["REQUEST_METHOD"] = "BACON"
- set.recognize(request)
- }
- request.recycle!
-
- request.path = "/people/5"
- request.env["REQUEST_METHOD"] = "GET"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("show", request.path_parameters[:action])
- assert_equal("5", request.path_parameters[:id])
- request.recycle!
-
- request.env["REQUEST_METHOD"] = "PUT"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("update", request.path_parameters[:action])
- assert_equal("5", request.path_parameters[:id])
- request.recycle!
-
- request.env["REQUEST_METHOD"] = "DELETE"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("destroy", request.path_parameters[:action])
- assert_equal("5", request.path_parameters[:id])
- request.recycle!
+ def test_recognize_with_encoded_id_and_regex
+ set.draw do |map|
+ map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /[a-zA-Z0-9\+]+/
+ end
- begin
- request.env["REQUEST_METHOD"] = "POST"
- set.recognize(request)
- flunk 'Should have raised MethodNotAllowed'
- rescue ActionController::MethodNotAllowed => e
- assert_equal [:get, :put, :delete], e.allowed_methods
- end
- request.recycle!
+ assert_equal({:controller => 'pages', :action => 'show', :id => '10'}, set.recognize_path('/page/10'))
+ assert_equal({:controller => 'pages', :action => 'show', :id => 'hello+world'}, set.recognize_path('/page/hello+world'))
+ end
- ensure
- Object.send(:remove_const, :PeopleController)
+ def test_recognize_with_conditions
+ Object.const_set(:PeopleController, Class.new)
+
+ set.draw do |map|
+ map.with_options(:controller => "people") do |people|
+ people.people "/people", :action => "index", :conditions => { :method => :get }
+ people.connect "/people", :action => "create", :conditions => { :method => :post }
+ people.person "/people/:id", :action => "show", :conditions => { :method => :get }
+ people.connect "/people/:id", :action => "update", :conditions => { :method => :put }
+ people.connect "/people/:id", :action => "destroy", :conditions => { :method => :delete }
+ end
end
- def test_recognize_with_alias_in_conditions
- Object.const_set(:PeopleController, Class.new)
+ request.path = "/people"
+ request.env["REQUEST_METHOD"] = "GET"
+ assert_nothing_raised { set.recognize(request) }
+ assert_equal("index", request.path_parameters[:action])
+ request.recycle!
- set.draw do |map|
- map.people "/people", :controller => 'people', :action => "index",
- :conditions => { :method => :get }
- map.root :people
- end
+ request.env["REQUEST_METHOD"] = "POST"
+ assert_nothing_raised { set.recognize(request) }
+ assert_equal("create", request.path_parameters[:action])
+ request.recycle!
- request.path = "/people"
- request.env["REQUEST_METHOD"] = "GET"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("people", request.path_parameters[:controller])
- assert_equal("index", request.path_parameters[:action])
+ request.env["REQUEST_METHOD"] = "PUT"
+ assert_nothing_raised { set.recognize(request) }
+ assert_equal("update", request.path_parameters[:action])
+ request.recycle!
- request.path = "/"
- request.env["REQUEST_METHOD"] = "GET"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("people", request.path_parameters[:controller])
- assert_equal("index", request.path_parameters[:action])
- ensure
- Object.send(:remove_const, :PeopleController)
- end
+ assert_raises(ActionController::UnknownHttpMethod) {
+ request.env["REQUEST_METHOD"] = "BACON"
+ set.recognize(request)
+ }
+ request.recycle!
- def test_typo_recognition
- Object.const_set(:ArticlesController, Class.new)
+ request.path = "/people/5"
+ request.env["REQUEST_METHOD"] = "GET"
+ assert_nothing_raised { set.recognize(request) }
+ assert_equal("show", request.path_parameters[:action])
+ assert_equal("5", request.path_parameters[:id])
+ request.recycle!
- set.draw do |map|
- map.connect 'articles/:year/:month/:day/:title',
- :controller => 'articles', :action => 'permalink',
- :year => /\d{4}/, :day => /\d{1,2}/, :month => /\d{1,2}/
- end
+ request.env["REQUEST_METHOD"] = "PUT"
+ assert_nothing_raised { set.recognize(request) }
+ assert_equal("update", request.path_parameters[:action])
+ assert_equal("5", request.path_parameters[:id])
+ request.recycle!
- request.path = "/articles/2005/11/05/a-very-interesting-article"
- request.env["REQUEST_METHOD"] = "GET"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("permalink", request.path_parameters[:action])
- assert_equal("2005", request.path_parameters[:year])
- assert_equal("11", request.path_parameters[:month])
- assert_equal("05", request.path_parameters[:day])
- assert_equal("a-very-interesting-article", request.path_parameters[:title])
+ request.env["REQUEST_METHOD"] = "DELETE"
+ assert_nothing_raised { set.recognize(request) }
+ assert_equal("destroy", request.path_parameters[:action])
+ assert_equal("5", request.path_parameters[:id])
+ request.recycle!
- ensure
- Object.send(:remove_const, :ArticlesController)
+ begin
+ request.env["REQUEST_METHOD"] = "POST"
+ set.recognize(request)
+ flunk 'Should have raised MethodNotAllowed'
+ rescue ActionController::MethodNotAllowed => e
+ assert_equal [:get, :put, :delete], e.allowed_methods
end
+ request.recycle!
- def test_routing_traversal_does_not_load_extra_classes
- assert !Object.const_defined?("Profiler__"), "Profiler should not be loaded"
- set.draw do |map|
- map.connect '/profile', :controller => 'profile'
- end
-
- request.path = '/profile'
+ ensure
+ Object.send(:remove_const, :PeopleController)
+ end
- set.recognize(request) rescue nil
+ def test_recognize_with_alias_in_conditions
+ Object.const_set(:PeopleController, Class.new)
- assert !Object.const_defined?("Profiler__"), "Profiler should not be loaded"
+ set.draw do |map|
+ map.people "/people", :controller => 'people', :action => "index",
+ :conditions => { :method => :get }
+ map.root :people
end
- def test_recognize_with_conditions_and_format
- Object.const_set(:PeopleController, Class.new)
+ request.path = "/people"
+ request.env["REQUEST_METHOD"] = "GET"
+ assert_nothing_raised { set.recognize(request) }
+ assert_equal("people", request.path_parameters[:controller])
+ assert_equal("index", request.path_parameters[:action])
- set.draw do |map|
- map.with_options(:controller => "people") do |people|
- people.person "/people/:id", :action => "show", :conditions => { :method => :get }
- people.connect "/people/:id", :action => "update", :conditions => { :method => :put }
- people.connect "/people/:id.:_format", :action => "show", :conditions => { :method => :get }
- end
- end
+ request.path = "/"
+ request.env["REQUEST_METHOD"] = "GET"
+ assert_nothing_raised { set.recognize(request) }
+ assert_equal("people", request.path_parameters[:controller])
+ assert_equal("index", request.path_parameters[:action])
+ ensure
+ Object.send(:remove_const, :PeopleController)
+ end
- request.path = "/people/5"
- request.env["REQUEST_METHOD"] = "GET"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("show", request.path_parameters[:action])
- assert_equal("5", request.path_parameters[:id])
- request.recycle!
-
- request.env["REQUEST_METHOD"] = "PUT"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("update", request.path_parameters[:action])
- request.recycle!
-
- request.path = "/people/5.png"
- request.env["REQUEST_METHOD"] = "GET"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("show", request.path_parameters[:action])
- assert_equal("5", request.path_parameters[:id])
- assert_equal("png", request.path_parameters[:_format])
- ensure
- Object.send(:remove_const, :PeopleController)
- end
-
- def test_generate_with_default_action
- set.draw do |map|
- map.connect "/people", :controller => "people"
- map.connect "/people/list", :controller => "people", :action => "list"
- end
+ def test_typo_recognition
+ Object.const_set(:ArticlesController, Class.new)
- url = set.generate(:controller => "people", :action => "list")
- assert_equal "/people/list", url
+ set.draw do |map|
+ map.connect 'articles/:year/:month/:day/:title',
+ :controller => 'articles', :action => 'permalink',
+ :year => /\d{4}/, :day => /\d{1,2}/, :month => /\d{1,2}/
end
- def test_root_map
- Object.const_set(:PeopleController, Class.new)
+ request.path = "/articles/2005/11/05/a-very-interesting-article"
+ request.env["REQUEST_METHOD"] = "GET"
+ assert_nothing_raised { set.recognize(request) }
+ assert_equal("permalink", request.path_parameters[:action])
+ assert_equal("2005", request.path_parameters[:year])
+ assert_equal("11", request.path_parameters[:month])
+ assert_equal("05", request.path_parameters[:day])
+ assert_equal("a-very-interesting-article", request.path_parameters[:title])
- set.draw { |map| map.root :controller => "people" }
+ ensure
+ Object.send(:remove_const, :ArticlesController)
+ end
- request.path = ""
- request.env["REQUEST_METHOD"] = "GET"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("people", request.path_parameters[:controller])
- assert_equal("index", request.path_parameters[:action])
- ensure
- Object.send(:remove_const, :PeopleController)
+ def test_routing_traversal_does_not_load_extra_classes
+ assert !Object.const_defined?("Profiler__"), "Profiler should not be loaded"
+ set.draw do |map|
+ map.connect '/profile', :controller => 'profile'
end
- def test_namespace
- Object.const_set(:Api, Module.new { |m| m.const_set(:ProductsController, Class.new) })
+ request.path = '/profile'
- set.draw do |map|
+ set.recognize(request) rescue nil
- map.namespace 'api' do |api|
- api.route 'inventory', :controller => "products", :action => 'inventory'
- end
+ assert !Object.const_defined?("Profiler__"), "Profiler should not be loaded"
+ end
+
+ def test_recognize_with_conditions_and_format
+ Object.const_set(:PeopleController, Class.new)
+ set.draw do |map|
+ map.with_options(:controller => "people") do |people|
+ people.person "/people/:id", :action => "show", :conditions => { :method => :get }
+ people.connect "/people/:id", :action => "update", :conditions => { :method => :put }
+ people.connect "/people/:id.:_format", :action => "show", :conditions => { :method => :get }
end
+ end
+
+ request.path = "/people/5"
+ request.env["REQUEST_METHOD"] = "GET"
+ assert_nothing_raised { set.recognize(request) }
+ assert_equal("show", request.path_parameters[:action])
+ assert_equal("5", request.path_parameters[:id])
+ request.recycle!
- request.path = "/api/inventory"
- request.env["REQUEST_METHOD"] = "GET"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("api/products", request.path_parameters[:controller])
- assert_equal("inventory", request.path_parameters[:action])
- ensure
- Object.send(:remove_const, :Api)
+ request.env["REQUEST_METHOD"] = "PUT"
+ assert_nothing_raised { set.recognize(request) }
+ assert_equal("update", request.path_parameters[:action])
+ request.recycle!
+
+ request.path = "/people/5.png"
+ request.env["REQUEST_METHOD"] = "GET"
+ assert_nothing_raised { set.recognize(request) }
+ assert_equal("show", request.path_parameters[:action])
+ assert_equal("5", request.path_parameters[:id])
+ assert_equal("png", request.path_parameters[:_format])
+ ensure
+ Object.send(:remove_const, :PeopleController)
+ end
+
+ def test_generate_with_default_action
+ set.draw do |map|
+ map.connect "/people", :controller => "people"
+ map.connect "/people/list", :controller => "people", :action => "list"
end
- def test_namespaced_root_map
- Object.const_set(:Api, Module.new { |m| m.const_set(:ProductsController, Class.new) })
+ url = set.generate(:controller => "people", :action => "list")
+ assert_equal "/people/list", url
+ end
- set.draw do |map|
+ def test_root_map
+ Object.const_set(:PeopleController, Class.new)
- map.namespace 'api' do |api|
- api.root :controller => "products"
- end
+ set.draw { |map| map.root :controller => "people" }
+
+ request.path = ""
+ request.env["REQUEST_METHOD"] = "GET"
+ assert_nothing_raised { set.recognize(request) }
+ assert_equal("people", request.path_parameters[:controller])
+ assert_equal("index", request.path_parameters[:action])
+ ensure
+ Object.send(:remove_const, :PeopleController)
+ end
+ def test_namespace
+ Object.const_set(:Api, Module.new { |m| m.const_set(:ProductsController, Class.new) })
+
+ set.draw do |map|
+
+ map.namespace 'api' do |api|
+ api.route 'inventory', :controller => "products", :action => 'inventory'
end
- request.path = "/api"
- request.env["REQUEST_METHOD"] = "GET"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("api/products", request.path_parameters[:controller])
- assert_equal("index", request.path_parameters[:action])
- ensure
- Object.send(:remove_const, :Api)
end
- def test_namespace_with_path_prefix
- Object.const_set(:Api, Module.new { |m| m.const_set(:ProductsController, Class.new) })
+ request.path = "/api/inventory"
+ request.env["REQUEST_METHOD"] = "GET"
+ assert_nothing_raised { set.recognize(request) }
+ assert_equal("api/products", request.path_parameters[:controller])
+ assert_equal("inventory", request.path_parameters[:action])
+ ensure
+ Object.send(:remove_const, :Api)
+ end
- set.draw do |map|
+ def test_namespaced_root_map
+ Object.const_set(:Api, Module.new { |m| m.const_set(:ProductsController, Class.new) })
- map.namespace 'api', :path_prefix => 'prefix' do |api|
- api.route 'inventory', :controller => "products", :action => 'inventory'
- end
+ set.draw do |map|
+ map.namespace 'api' do |api|
+ api.root :controller => "products"
end
- request.path = "/prefix/inventory"
- request.env["REQUEST_METHOD"] = "GET"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("api/products", request.path_parameters[:controller])
- assert_equal("inventory", request.path_parameters[:action])
- ensure
- Object.send(:remove_const, :Api)
end
- def test_generate_finds_best_fit
- set.draw do |map|
- map.connect "/people", :controller => "people", :action => "index"
- map.connect "/ws/people", :controller => "people", :action => "index", :ws => true
- end
+ request.path = "/api"
+ request.env["REQUEST_METHOD"] = "GET"
+ assert_nothing_raised { set.recognize(request) }
+ assert_equal("api/products", request.path_parameters[:controller])
+ assert_equal("index", request.path_parameters[:action])
+ ensure
+ Object.send(:remove_const, :Api)
+ end
- url = set.generate(:controller => "people", :action => "index", :ws => true)
- assert_equal "/ws/people", url
- end
+ def test_namespace_with_path_prefix
+ Object.const_set(:Api, Module.new { |m| m.const_set(:ProductsController, Class.new) })
- def test_generate_changes_controller_module
- set.draw { |map| map.connect ':controller/:action/:id' }
- current = { :controller => "bling/bloop", :action => "bap", :id => 9 }
- url = set.generate({:controller => "foo/bar", :action => "baz", :id => 7}, current)
- assert_equal "/foo/bar/baz/7", url
- end
+ set.draw do |map|
- def test_id_is_not_impossibly_sticky
- set.draw do |map|
- map.connect 'foo/:number', :controller => "people", :action => "index"
- map.connect ':controller/:action/:id'
+ map.namespace 'api', :path_prefix => 'prefix' do |api|
+ api.route 'inventory', :controller => "products", :action => 'inventory'
end
- url = set.generate({:controller => "people", :action => "index", :number => 3},
- {:controller => "people", :action => "index", :id => "21"})
- assert_equal "/foo/3", url
end
- def test_id_is_sticky_when_it_ought_to_be
- set.draw do |map|
- map.connect ':controller/:id/:action'
- end
+ request.path = "/prefix/inventory"
+ request.env["REQUEST_METHOD"] = "GET"
+ assert_nothing_raised { set.recognize(request) }
+ assert_equal("api/products", request.path_parameters[:controller])
+ assert_equal("inventory", request.path_parameters[:action])
+ ensure
+ Object.send(:remove_const, :Api)
+ end
- url = set.generate({:action => "destroy"}, {:controller => "people", :action => "show", :id => "7"})
- assert_equal "/people/7/destroy", url
+ def test_generate_finds_best_fit
+ set.draw do |map|
+ map.connect "/people", :controller => "people", :action => "index"
+ map.connect "/ws/people", :controller => "people", :action => "index", :ws => true
end
- def test_use_static_path_when_possible
- set.draw do |map|
- map.connect 'about', :controller => "welcome", :action => "about"
- map.connect ':controller/:action/:id'
- end
+ url = set.generate(:controller => "people", :action => "index", :ws => true)
+ assert_equal "/ws/people", url
+ end
- url = set.generate({:controller => "welcome", :action => "about"},
- {:controller => "welcome", :action => "get", :id => "7"})
- assert_equal "/about", url
+ def test_generate_changes_controller_module
+ set.draw { |map| map.connect ':controller/:action/:id' }
+ current = { :controller => "bling/bloop", :action => "bap", :id => 9 }
+ url = set.generate({:controller => "foo/bar", :action => "baz", :id => 7}, current)
+ assert_equal "/foo/bar/baz/7", url
+ end
+
+ def test_id_is_not_impossibly_sticky
+ set.draw do |map|
+ map.connect 'foo/:number', :controller => "people", :action => "index"
+ map.connect ':controller/:action/:id'
end
- def test_generate
- set.draw { |map| map.connect ':controller/:action/:id' }
+ url = set.generate({:controller => "people", :action => "index", :number => 3},
+ {:controller => "people", :action => "index", :id => "21"})
+ assert_equal "/foo/3", url
+ end
- args = { :controller => "foo", :action => "bar", :id => "7", :x => "y" }
- assert_equal "/foo/bar/7?x=y", set.generate(args)
- assert_equal ["/foo/bar/7", [:x]], set.generate_extras(args)
- assert_equal [:x], set.extra_keys(args)
+ def test_id_is_sticky_when_it_ought_to_be
+ set.draw do |map|
+ map.connect ':controller/:id/:action'
end
- def test_generate_with_path_prefix
- set.draw { |map| map.connect ':controller/:action/:id', :path_prefix => 'my' }
+ url = set.generate({:action => "destroy"}, {:controller => "people", :action => "show", :id => "7"})
+ assert_equal "/people/7/destroy", url
+ end
- args = { :controller => "foo", :action => "bar", :id => "7", :x => "y" }
- assert_equal "/my/foo/bar/7?x=y", set.generate(args)
+ def test_use_static_path_when_possible
+ set.draw do |map|
+ map.connect 'about', :controller => "welcome", :action => "about"
+ map.connect ':controller/:action/:id'
end
- def test_named_routes_are_never_relative_to_modules
- set.draw do |map|
- map.connect "/connection/manage/:action", :controller => 'connection/manage'
- map.connect "/connection/connection", :controller => "connection/connection"
- map.family_connection "/connection", :controller => "connection"
- end
+ url = set.generate({:controller => "welcome", :action => "about"},
+ {:controller => "welcome", :action => "get", :id => "7"})
+ assert_equal "/about", url
+ end
- url = set.generate({:controller => "connection"}, {:controller => 'connection/manage'})
- assert_equal "/connection/connection", url
+ def test_generate
+ set.draw { |map| map.connect ':controller/:action/:id' }
- url = set.generate({:use_route => :family_connection, :controller => "connection"}, {:controller => 'connection/manage'})
- assert_equal "/connection", url
- end
+ args = { :controller => "foo", :action => "bar", :id => "7", :x => "y" }
+ assert_equal "/foo/bar/7?x=y", set.generate(args)
+ assert_equal ["/foo/bar/7", [:x]], set.generate_extras(args)
+ assert_equal [:x], set.extra_keys(args)
+ end
- def test_action_left_off_when_id_is_recalled
- set.draw do |map|
- map.connect ':controller/:action/:id'
- end
- assert_equal '/post', set.generate(
- {:controller => 'post', :action => 'index'},
- {:controller => 'post', :action => 'show', :id => '10'}
- )
- end
+ def test_generate_with_path_prefix
+ set.draw { |map| map.connect ':controller/:action/:id', :path_prefix => 'my' }
- def test_query_params_will_be_shown_when_recalled
- set.draw do |map|
- map.connect 'show_post/:parameter', :controller => 'post', :action => 'show'
- map.connect ':controller/:action/:id'
- end
- assert_equal '/post/edit?parameter=1', set.generate(
- {:action => 'edit', :parameter => 1},
- {:controller => 'post', :action => 'show', :parameter => 1}
- )
+ args = { :controller => "foo", :action => "bar", :id => "7", :x => "y" }
+ assert_equal "/my/foo/bar/7?x=y", set.generate(args)
+ end
+
+ def test_named_routes_are_never_relative_to_modules
+ set.draw do |map|
+ map.connect "/connection/manage/:action", :controller => 'connection/manage'
+ map.connect "/connection/connection", :controller => "connection/connection"
+ map.family_connection "/connection", :controller => "connection"
end
- def test_expiry_determination_should_consider_values_with_to_param
- set.draw { |map| map.connect 'projects/:project_id/:controller/:action' }
- assert_equal '/projects/1/post/show', set.generate(
- {:action => 'show', :project_id => 1},
- {:controller => 'post', :action => 'show', :project_id => '1'})
+ url = set.generate({:controller => "connection"}, {:controller => 'connection/manage'})
+ assert_equal "/connection/connection", url
+
+ url = set.generate({:use_route => :family_connection, :controller => "connection"}, {:controller => 'connection/manage'})
+ assert_equal "/connection", url
+ end
+
+ def test_action_left_off_when_id_is_recalled
+ set.draw do |map|
+ map.connect ':controller/:action/:id'
end
+ assert_equal '/post', set.generate(
+ {:controller => 'post', :action => 'index'},
+ {:controller => 'post', :action => 'show', :id => '10'}
+ )
+ end
- def test_generate_all
- set.draw do |map|
- map.connect 'show_post/:id', :controller => 'post', :action => 'show'
- map.connect ':controller/:action/:id'
- end
- all = set.generate(
- {:action => 'show', :id => 10, :generate_all => true},
- {:controller => 'post', :action => 'show'}
- )
- assert_equal 2, all.length
- assert_equal '/show_post/10', all.first
- assert_equal '/post/show/10', all.last
+ def test_query_params_will_be_shown_when_recalled
+ set.draw do |map|
+ map.connect 'show_post/:parameter', :controller => 'post', :action => 'show'
+ map.connect ':controller/:action/:id'
end
+ assert_equal '/post/edit?parameter=1', set.generate(
+ {:action => 'edit', :parameter => 1},
+ {:controller => 'post', :action => 'show', :parameter => 1}
+ )
+ end
- def test_named_route_in_nested_resource
- set.draw do |map|
- map.resources :projects do |project|
- project.milestones 'milestones', :controller => 'milestones', :action => 'index'
- end
- end
+ def test_expiry_determination_should_consider_values_with_to_param
+ set.draw { |map| map.connect 'projects/:project_id/:controller/:action' }
+ assert_equal '/projects/1/post/show', set.generate(
+ {:action => 'show', :project_id => 1},
+ {:controller => 'post', :action => 'show', :project_id => '1'})
+ end
- request.path = "/projects/1/milestones"
- request.env["REQUEST_METHOD"] = "GET"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("milestones", request.path_parameters[:controller])
- assert_equal("index", request.path_parameters[:action])
+ def test_generate_all
+ set.draw do |map|
+ map.connect 'show_post/:id', :controller => 'post', :action => 'show'
+ map.connect ':controller/:action/:id'
end
+ all = set.generate(
+ {:action => 'show', :id => 10, :generate_all => true},
+ {:controller => 'post', :action => 'show'}
+ )
+ assert_equal 2, all.length
+ assert_equal '/show_post/10', all.first
+ assert_equal '/post/show/10', all.last
+ end
- def test_setting_root_in_namespace_using_symbol
- assert_nothing_raised do
- set.draw do |map|
- map.namespace :admin do |admin|
- admin.root :controller => 'home'
- end
- end
+ def test_named_route_in_nested_resource
+ set.draw do |map|
+ map.resources :projects do |project|
+ project.milestones 'milestones', :controller => 'milestones', :action => 'index'
end
end
- def test_setting_root_in_namespace_using_string
- assert_nothing_raised do
- set.draw do |map|
- map.namespace 'admin' do |admin|
- admin.root :controller => 'home'
- end
- end
- end
- end
+ request.path = "/projects/1/milestones"
+ request.env["REQUEST_METHOD"] = "GET"
+ assert_nothing_raised { set.recognize(request) }
+ assert_equal("milestones", request.path_parameters[:controller])
+ assert_equal("index", request.path_parameters[:action])
+ end
- def test_route_requirements_with_unsupported_regexp_options_must_error
- assert_raises ArgumentError do
- set.draw do |map|
- map.connect 'page/:name', :controller => 'pages',
- :action => 'show',
- :requirements => {:name => /(david|jamis)/m}
+ def test_setting_root_in_namespace_using_symbol
+ assert_nothing_raised do
+ set.draw do |map|
+ map.namespace :admin do |admin|
+ admin.root :controller => 'home'
end
end
end
+ end
- def test_route_requirements_with_supported_options_must_not_error
- assert_nothing_raised do
- set.draw do |map|
- map.connect 'page/:name', :controller => 'pages',
- :action => 'show',
- :requirements => {:name => /(david|jamis)/i}
- end
- end
- assert_nothing_raised do
- set.draw do |map|
- map.connect 'page/:name', :controller => 'pages',
- :action => 'show',
- :requirements => {:name => / # Desperately overcommented regexp
- ( #Either
- david #The Creator
- | #Or
- jamis #The Deployer
- )/x}
+ def test_setting_root_in_namespace_using_string
+ assert_nothing_raised do
+ set.draw do |map|
+ map.namespace 'admin' do |admin|
+ admin.root :controller => 'home'
end
end
end
+ end
- def test_route_requirement_recognize_with_ignore_case
+ def test_route_requirements_with_unsupported_regexp_options_must_error
+ assert_raises ArgumentError do
set.draw do |map|
map.connect 'page/:name', :controller => 'pages',
:action => 'show',
- :requirements => {:name => /(david|jamis)/i}
- end
- assert_equal({:controller => 'pages', :action => 'show', :name => 'jamis'}, set.recognize_path('/page/jamis'))
- assert_raises ActionController::RoutingError do
- set.recognize_path('/page/davidjamis')
+ :requirements => {:name => /(david|jamis)/m}
end
- assert_equal({:controller => 'pages', :action => 'show', :name => 'DAVID'}, set.recognize_path('/page/DAVID'))
end
+ end
- def test_route_requirement_generate_with_ignore_case
+ def test_route_requirements_with_supported_options_must_not_error
+ assert_nothing_raised do
set.draw do |map|
map.connect 'page/:name', :controller => 'pages',
:action => 'show',
:requirements => {:name => /(david|jamis)/i}
end
- url = set.generate({:controller => 'pages', :action => 'show', :name => 'david'})
- assert_equal "/page/david", url
- assert_raises ActionController::RoutingError do
- url = set.generate({:controller => 'pages', :action => 'show', :name => 'davidjamis'})
- end
- url = set.generate({:controller => 'pages', :action => 'show', :name => 'JAMIS'})
- assert_equal "/page/JAMIS", url
end
-
- def test_route_requirement_recognize_with_extended_syntax
+ assert_nothing_raised do
set.draw do |map|
map.connect 'page/:name', :controller => 'pages',
:action => 'show',
@@ -2330,142 +2287,183 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do
jamis #The Deployer
)/x}
end
- assert_equal({:controller => 'pages', :action => 'show', :name => 'jamis'}, set.recognize_path('/page/jamis'))
- assert_equal({:controller => 'pages', :action => 'show', :name => 'david'}, set.recognize_path('/page/david'))
- assert_raises ActionController::RoutingError do
- set.recognize_path('/page/david #The Creator')
- end
- assert_raises ActionController::RoutingError do
- set.recognize_path('/page/David')
- end
end
+ end
- def test_route_requirement_generate_with_extended_syntax
- set.draw do |map|
- map.connect 'page/:name', :controller => 'pages',
- :action => 'show',
- :requirements => {:name => / # Desperately overcommented regexp
- ( #Either
- david #The Creator
- | #Or
- jamis #The Deployer
- )/x}
- end
- url = set.generate({:controller => 'pages', :action => 'show', :name => 'david'})
- assert_equal "/page/david", url
- assert_raises ActionController::RoutingError do
- url = set.generate({:controller => 'pages', :action => 'show', :name => 'davidjamis'})
- end
- assert_raises ActionController::RoutingError do
- url = set.generate({:controller => 'pages', :action => 'show', :name => 'JAMIS'})
- end
+ def test_route_requirement_recognize_with_ignore_case
+ set.draw do |map|
+ map.connect 'page/:name', :controller => 'pages',
+ :action => 'show',
+ :requirements => {:name => /(david|jamis)/i}
+ end
+ assert_equal({:controller => 'pages', :action => 'show', :name => 'jamis'}, set.recognize_path('/page/jamis'))
+ assert_raises ActionController::RoutingError do
+ set.recognize_path('/page/davidjamis')
end
+ assert_equal({:controller => 'pages', :action => 'show', :name => 'DAVID'}, set.recognize_path('/page/DAVID'))
+ end
- def test_route_requirement_generate_with_xi_modifiers
- set.draw do |map|
- map.connect 'page/:name', :controller => 'pages',
- :action => 'show',
- :requirements => {:name => / # Desperately overcommented regexp
- ( #Either
- david #The Creator
- | #Or
- jamis #The Deployer
- )/xi}
- end
- url = set.generate({:controller => 'pages', :action => 'show', :name => 'JAMIS'})
- assert_equal "/page/JAMIS", url
+ def test_route_requirement_generate_with_ignore_case
+ set.draw do |map|
+ map.connect 'page/:name', :controller => 'pages',
+ :action => 'show',
+ :requirements => {:name => /(david|jamis)/i}
end
+ url = set.generate({:controller => 'pages', :action => 'show', :name => 'david'})
+ assert_equal "/page/david", url
+ assert_raises ActionController::RoutingError do
+ url = set.generate({:controller => 'pages', :action => 'show', :name => 'davidjamis'})
+ end
+ url = set.generate({:controller => 'pages', :action => 'show', :name => 'JAMIS'})
+ assert_equal "/page/JAMIS", url
+ end
- def test_route_requirement_recognize_with_xi_modifiers
- set.draw do |map|
- map.connect 'page/:name', :controller => 'pages',
- :action => 'show',
- :requirements => {:name => / # Desperately overcommented regexp
- ( #Either
- david #The Creator
- | #Or
- jamis #The Deployer
- )/xi}
- end
- assert_equal({:controller => 'pages', :action => 'show', :name => 'JAMIS'}, set.recognize_path('/page/JAMIS'))
+ def test_route_requirement_recognize_with_extended_syntax
+ set.draw do |map|
+ map.connect 'page/:name', :controller => 'pages',
+ :action => 'show',
+ :requirements => {:name => / # Desperately overcommented regexp
+ ( #Either
+ david #The Creator
+ | #Or
+ jamis #The Deployer
+ )/x}
+ end
+ assert_equal({:controller => 'pages', :action => 'show', :name => 'jamis'}, set.recognize_path('/page/jamis'))
+ assert_equal({:controller => 'pages', :action => 'show', :name => 'david'}, set.recognize_path('/page/david'))
+ assert_raises ActionController::RoutingError do
+ set.recognize_path('/page/david #The Creator')
+ end
+ assert_raises ActionController::RoutingError do
+ set.recognize_path('/page/David')
end
end
- class RouteLoadingTest < Test::Unit::TestCase
- def setup
- routes.instance_variable_set '@routes_last_modified', nil
- silence_warnings { Object.const_set :RAILS_ROOT, '.' }
- routes.add_configuration_file(File.join(RAILS_ROOT, 'config', 'routes.rb'))
+ def test_route_requirement_generate_with_extended_syntax
+ set.draw do |map|
+ map.connect 'page/:name', :controller => 'pages',
+ :action => 'show',
+ :requirements => {:name => / # Desperately overcommented regexp
+ ( #Either
+ david #The Creator
+ | #Or
+ jamis #The Deployer
+ )/x}
+ end
+ url = set.generate({:controller => 'pages', :action => 'show', :name => 'david'})
+ assert_equal "/page/david", url
+ assert_raises ActionController::RoutingError do
+ url = set.generate({:controller => 'pages', :action => 'show', :name => 'davidjamis'})
+ end
+ assert_raises ActionController::RoutingError do
+ url = set.generate({:controller => 'pages', :action => 'show', :name => 'JAMIS'})
+ end
+ end
- @stat = stub_everything
+ def test_route_requirement_generate_with_xi_modifiers
+ set.draw do |map|
+ map.connect 'page/:name', :controller => 'pages',
+ :action => 'show',
+ :requirements => {:name => / # Desperately overcommented regexp
+ ( #Either
+ david #The Creator
+ | #Or
+ jamis #The Deployer
+ )/xi}
end
+ url = set.generate({:controller => 'pages', :action => 'show', :name => 'JAMIS'})
+ assert_equal "/page/JAMIS", url
+ end
- def teardown
- ActionController::Routing::Routes.configuration_files.clear
- Object.send :remove_const, :RAILS_ROOT
+ def test_route_requirement_recognize_with_xi_modifiers
+ set.draw do |map|
+ map.connect 'page/:name', :controller => 'pages',
+ :action => 'show',
+ :requirements => {:name => / # Desperately overcommented regexp
+ ( #Either
+ david #The Creator
+ | #Or
+ jamis #The Deployer
+ )/xi}
end
+ assert_equal({:controller => 'pages', :action => 'show', :name => 'JAMIS'}, set.recognize_path('/page/JAMIS'))
+ end
+end
- def test_load
- File.expects(:stat).returns(@stat)
- routes.expects(:load).with(regexp_matches(/routes\.rb$/))
+class RouteLoadingTest < Test::Unit::TestCase
+ def setup
+ routes.instance_variable_set '@routes_last_modified', nil
+ silence_warnings { Object.const_set :RAILS_ROOT, '.' }
+ routes.add_configuration_file(File.join(RAILS_ROOT, 'config', 'routes.rb'))
- routes.reload
- end
+ @stat = stub_everything
+ end
+
+ def teardown
+ ActionController::Routing::Routes.configuration_files.clear
+ Object.send :remove_const, :RAILS_ROOT
+ end
- def test_no_reload_when_not_modified
- @stat.expects(:mtime).times(2).returns(1)
- File.expects(:stat).times(2).returns(@stat)
- routes.expects(:load).with(regexp_matches(/routes\.rb$/)).at_most_once
+ def test_load
+ File.expects(:stat).returns(@stat)
+ routes.expects(:load).with(regexp_matches(/routes\.rb$/))
- 2.times { routes.reload }
- end
+ routes.reload
+ end
- def test_reload_when_modified
- @stat.expects(:mtime).at_least(2).returns(1, 2)
- File.expects(:stat).at_least(2).returns(@stat)
- routes.expects(:load).with(regexp_matches(/routes\.rb$/)).times(2)
+ def test_no_reload_when_not_modified
+ @stat.expects(:mtime).times(2).returns(1)
+ File.expects(:stat).times(2).returns(@stat)
+ routes.expects(:load).with(regexp_matches(/routes\.rb$/)).at_most_once
- 2.times { routes.reload }
- end
+ 2.times { routes.reload }
+ end
- def test_bang_forces_reload
- @stat.expects(:mtime).at_least(2).returns(1)
- File.expects(:stat).at_least(2).returns(@stat)
- routes.expects(:load).with(regexp_matches(/routes\.rb$/)).times(2)
+ def test_reload_when_modified
+ @stat.expects(:mtime).at_least(2).returns(1, 2)
+ File.expects(:stat).at_least(2).returns(@stat)
+ routes.expects(:load).with(regexp_matches(/routes\.rb$/)).times(2)
- 2.times { routes.reload! }
- end
+ 2.times { routes.reload }
+ end
- def test_adding_inflections_forces_reload
- ActiveSupport::Inflector::Inflections.instance.expects(:uncountable).with('equipment')
- routes.expects(:reload!)
+ def test_bang_forces_reload
+ @stat.expects(:mtime).at_least(2).returns(1)
+ File.expects(:stat).at_least(2).returns(@stat)
+ routes.expects(:load).with(regexp_matches(/routes\.rb$/)).times(2)
- ActiveSupport::Inflector.inflections { |inflect| inflect.uncountable('equipment') }
- end
+ 2.times { routes.reload! }
+ end
- def test_load_with_configuration
- routes.configuration_files.clear
- routes.add_configuration_file("foobarbaz")
- File.expects(:stat).returns(@stat)
- routes.expects(:load).with("foobarbaz")
+ def test_adding_inflections_forces_reload
+ ActiveSupport::Inflector::Inflections.instance.expects(:uncountable).with('equipment')
+ routes.expects(:reload!)
- routes.reload
- end
-
- def test_load_multiple_configurations
- routes.add_configuration_file("engines.rb")
-
- File.expects(:stat).at_least_once.returns(@stat)
+ ActiveSupport::Inflector.inflections { |inflect| inflect.uncountable('equipment') }
+ end
- routes.expects(:load).with('./config/routes.rb')
- routes.expects(:load).with('engines.rb')
+ def test_load_with_configuration
+ routes.configuration_files.clear
+ routes.add_configuration_file("foobarbaz")
+ File.expects(:stat).returns(@stat)
+ routes.expects(:load).with("foobarbaz")
- routes.reload
- end
+ routes.reload
+ end
+
+ def test_load_multiple_configurations
+ routes.add_configuration_file("engines.rb")
+
+ File.expects(:stat).at_least_once.returns(@stat)
- private
- def routes
- ActionController::Routing::Routes
- end
+ routes.expects(:load).with('./config/routes.rb')
+ routes.expects(:load).with('engines.rb')
+
+ routes.reload
end
+
+ private
+ def routes
+ ActionController::Routing::Routes
+ end
end
diff --git a/actionpack/test/fixtures/test/render_implicit_js_template_without_layout.js.erb b/actionpack/test/fixtures/test/render_implicit_js_template_without_layout.js.erb
new file mode 100644
index 0000000000..d5b94af505
--- /dev/null
+++ b/actionpack/test/fixtures/test/render_implicit_js_template_without_layout.js.erb
@@ -0,0 +1 @@
+alert('hello');
diff --git a/actionpack/test/template/active_record_helper_i18n_test.rb b/actionpack/test/template/active_record_helper_i18n_test.rb
index 7e6bf70706..4b6e8ddcca 100644
--- a/actionpack/test/template/active_record_helper_i18n_test.rb
+++ b/actionpack/test/template/active_record_helper_i18n_test.rb
@@ -4,43 +4,41 @@ class ActiveRecordHelperI18nTest < Test::Unit::TestCase
include ActionView::Helpers::ActiveRecordHelper
attr_reader :request
- uses_mocha 'active_record_helper_i18n_test' do
- def setup
- @object = stub :errors => stub(:count => 1, :full_messages => ['full_messages'])
- @object_name = 'book'
- stubs(:content_tag).returns 'content_tag'
+ def setup
+ @object = stub :errors => stub(:count => 1, :full_messages => ['full_messages'])
+ @object_name = 'book'
+ stubs(:content_tag).returns 'content_tag'
- I18n.stubs(:t).with(:'header', :locale => 'en', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').returns "1 error prohibited this from being saved"
- I18n.stubs(:t).with(:'body', :locale => 'en', :scope => [:activerecord, :errors, :template]).returns 'There were problems with the following fields:'
- end
+ I18n.stubs(:t).with(:'header', :locale => 'en', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').returns "1 error prohibited this from being saved"
+ I18n.stubs(:t).with(:'body', :locale => 'en', :scope => [:activerecord, :errors, :template]).returns 'There were problems with the following fields:'
+ end
- def test_error_messages_for_given_a_header_option_it_does_not_translate_header_message
- I18n.expects(:translate).with(:'header', :locale => 'en', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').never
- error_messages_for(:object => @object, :header_message => 'header message', :locale => 'en')
- end
+ def test_error_messages_for_given_a_header_option_it_does_not_translate_header_message
+ I18n.expects(:translate).with(:'header', :locale => 'en', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').never
+ error_messages_for(:object => @object, :header_message => 'header message', :locale => 'en')
+ end
- def test_error_messages_for_given_no_header_option_it_translates_header_message
- I18n.expects(:t).with(:'header', :locale => 'en', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').returns 'header message'
- I18n.expects(:t).with('', :default => '', :count => 1, :scope => [:activerecord, :models]).once.returns ''
- error_messages_for(:object => @object, :locale => 'en')
- end
+ def test_error_messages_for_given_no_header_option_it_translates_header_message
+ I18n.expects(:t).with(:'header', :locale => 'en', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').returns 'header message'
+ I18n.expects(:t).with('', :default => '', :count => 1, :scope => [:activerecord, :models]).once.returns ''
+ error_messages_for(:object => @object, :locale => 'en')
+ end
- def test_error_messages_for_given_a_message_option_it_does_not_translate_message
- I18n.expects(:t).with(:'body', :locale => 'en', :scope => [:activerecord, :errors, :template]).never
- I18n.expects(:t).with('', :default => '', :count => 1, :scope => [:activerecord, :models]).once.returns ''
- error_messages_for(:object => @object, :message => 'message', :locale => 'en')
- end
+ def test_error_messages_for_given_a_message_option_it_does_not_translate_message
+ I18n.expects(:t).with(:'body', :locale => 'en', :scope => [:activerecord, :errors, :template]).never
+ I18n.expects(:t).with('', :default => '', :count => 1, :scope => [:activerecord, :models]).once.returns ''
+ error_messages_for(:object => @object, :message => 'message', :locale => 'en')
+ end
- def test_error_messages_for_given_no_message_option_it_translates_message
- I18n.expects(:t).with(:'body', :locale => 'en', :scope => [:activerecord, :errors, :template]).returns 'There were problems with the following fields:'
- I18n.expects(:t).with('', :default => '', :count => 1, :scope => [:activerecord, :models]).once.returns ''
- error_messages_for(:object => @object, :locale => 'en')
- end
-
- def test_error_messages_for_given_object_name_it_translates_object_name
- I18n.expects(:t).with(:header, :locale => 'en', :scope => [:activerecord, :errors, :template], :count => 1, :model => @object_name).returns "1 error prohibited this #{@object_name} from being saved"
- I18n.expects(:t).with(@object_name, :default => @object_name, :count => 1, :scope => [:activerecord, :models]).once.returns @object_name
- error_messages_for(:object => @object, :locale => 'en', :object_name => @object_name)
- end
+ def test_error_messages_for_given_no_message_option_it_translates_message
+ I18n.expects(:t).with(:'body', :locale => 'en', :scope => [:activerecord, :errors, :template]).returns 'There were problems with the following fields:'
+ I18n.expects(:t).with('', :default => '', :count => 1, :scope => [:activerecord, :models]).once.returns ''
+ error_messages_for(:object => @object, :locale => 'en')
+ end
+
+ def test_error_messages_for_given_object_name_it_translates_object_name
+ I18n.expects(:t).with(:header, :locale => 'en', :scope => [:activerecord, :errors, :template], :count => 1, :model => @object_name).returns "1 error prohibited this #{@object_name} from being saved"
+ I18n.expects(:t).with(@object_name, :default => @object_name, :count => 1, :scope => [:activerecord, :models]).once.returns @object_name
+ error_messages_for(:object => @object, :locale => 'en', :object_name => @object_name)
end
end
diff --git a/actionpack/test/template/asset_tag_helper_test.rb b/actionpack/test/template/asset_tag_helper_test.rb
index 5e2fc20167..32ad87c12d 100644
--- a/actionpack/test/template/asset_tag_helper_test.rb
+++ b/actionpack/test/template/asset_tag_helper_test.rb
@@ -228,20 +228,18 @@ class AssetTagHelperTest < ActionView::TestCase
ImageLinkToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
end
- uses_mocha 'test image tag with windows behaviour' do
- def test_image_tag_windows_behaviour
- old_asset_id, ENV["RAILS_ASSET_ID"] = ENV["RAILS_ASSET_ID"], "1"
- # This simulates the behaviour of File#exist? on windows when testing a file ending in "."
- # If the file "rails.png" exists, windows will return true when asked if "rails.png." exists (notice trailing ".")
- # OS X, linux etc will return false in this case.
- File.stubs(:exist?).with('template/../fixtures/public/images/rails.png.').returns(true)
- assert_equal '<img alt="Rails" src="/images/rails.png?1" />', image_tag('rails.png')
- ensure
- if old_asset_id
- ENV["RAILS_ASSET_ID"] = old_asset_id
- else
- ENV.delete("RAILS_ASSET_ID")
- end
+ def test_image_tag_windows_behaviour
+ old_asset_id, ENV["RAILS_ASSET_ID"] = ENV["RAILS_ASSET_ID"], "1"
+ # This simulates the behaviour of File#exist? on windows when testing a file ending in "."
+ # If the file "rails.png" exists, windows will return true when asked if "rails.png." exists (notice trailing ".")
+ # OS X, linux etc will return false in this case.
+ File.stubs(:exist?).with('template/../fixtures/public/images/rails.png.').returns(true)
+ assert_equal '<img alt="Rails" src="/images/rails.png?1" />', image_tag('rails.png')
+ ensure
+ if old_asset_id
+ ENV["RAILS_ASSET_ID"] = old_asset_id
+ else
+ ENV.delete("RAILS_ASSET_ID")
end
end
diff --git a/actionpack/test/template/compiled_templates_test.rb b/actionpack/test/template/compiled_templates_test.rb
index caea1bd643..a7ed13cf57 100644
--- a/actionpack/test/template/compiled_templates_test.rb
+++ b/actionpack/test/template/compiled_templates_test.rb
@@ -1,87 +1,85 @@
require 'abstract_unit'
require 'controller/fake_models'
-uses_mocha 'TestTemplateRecompilation' do
- class CompiledTemplatesTest < Test::Unit::TestCase
- def setup
- @compiled_templates = ActionView::Base::CompiledTemplates
- @compiled_templates.instance_methods.each do |m|
- @compiled_templates.send(:remove_method, m) if m =~ /^_run_/
- end
+class CompiledTemplatesTest < Test::Unit::TestCase
+ def setup
+ @compiled_templates = ActionView::Base::CompiledTemplates
+ @compiled_templates.instance_methods.each do |m|
+ @compiled_templates.send(:remove_method, m) if m =~ /^_run_/
end
+ end
- def test_template_gets_compiled
- assert_equal 0, @compiled_templates.instance_methods.size
- assert_equal "Hello world!", render(:file => "test/hello_world.erb")
- assert_equal 1, @compiled_templates.instance_methods.size
- end
+ def test_template_gets_compiled
+ assert_equal 0, @compiled_templates.instance_methods.size
+ assert_equal "Hello world!", render(:file => "test/hello_world.erb")
+ assert_equal 1, @compiled_templates.instance_methods.size
+ end
- def test_template_gets_recompiled_when_using_different_keys_in_local_assigns
- assert_equal 0, @compiled_templates.instance_methods.size
- assert_equal "Hello world!", render(:file => "test/hello_world.erb")
- assert_equal "Hello world!", render(:file => "test/hello_world.erb", :locals => {:foo => "bar"})
- assert_equal 2, @compiled_templates.instance_methods.size
- end
+ def test_template_gets_recompiled_when_using_different_keys_in_local_assigns
+ assert_equal 0, @compiled_templates.instance_methods.size
+ assert_equal "Hello world!", render(:file => "test/hello_world.erb")
+ assert_equal "Hello world!", render(:file => "test/hello_world.erb", :locals => {:foo => "bar"})
+ assert_equal 2, @compiled_templates.instance_methods.size
+ end
- def test_compiled_template_will_not_be_recompiled_when_rendered_with_identical_local_assigns
- assert_equal 0, @compiled_templates.instance_methods.size
- assert_equal "Hello world!", render(:file => "test/hello_world.erb")
- ActionView::Template.any_instance.expects(:compile!).never
- assert_equal "Hello world!", render(:file => "test/hello_world.erb")
- end
+ def test_compiled_template_will_not_be_recompiled_when_rendered_with_identical_local_assigns
+ assert_equal 0, @compiled_templates.instance_methods.size
+ assert_equal "Hello world!", render(:file => "test/hello_world.erb")
+ ActionView::Template.any_instance.expects(:compile!).never
+ assert_equal "Hello world!", render(:file => "test/hello_world.erb")
+ end
- def test_compiled_template_will_always_be_recompiled_when_template_is_not_cached
- ActionView::Template.any_instance.expects(:recompile?).times(3).returns(true)
- assert_equal 0, @compiled_templates.instance_methods.size
- assert_equal "Hello world!", render(:file => "#{FIXTURE_LOAD_PATH}/test/hello_world.erb")
- ActionView::Template.any_instance.expects(:compile!).times(3)
- 3.times { assert_equal "Hello world!", render(:file => "#{FIXTURE_LOAD_PATH}/test/hello_world.erb") }
- assert_equal 1, @compiled_templates.instance_methods.size
- end
+ def test_compiled_template_will_always_be_recompiled_when_template_is_not_cached
+ ActionView::Template.any_instance.expects(:recompile?).times(3).returns(true)
+ assert_equal 0, @compiled_templates.instance_methods.size
+ assert_equal "Hello world!", render(:file => "#{FIXTURE_LOAD_PATH}/test/hello_world.erb")
+ ActionView::Template.any_instance.expects(:compile!).times(3)
+ 3.times { assert_equal "Hello world!", render(:file => "#{FIXTURE_LOAD_PATH}/test/hello_world.erb") }
+ assert_equal 1, @compiled_templates.instance_methods.size
+ end
- def test_template_changes_are_not_reflected_with_cached_templates
- assert_equal "Hello world!", render(:file => "test/hello_world.erb")
- modify_template "test/hello_world.erb", "Goodbye world!" do
- assert_equal "Hello world!", render(:file => "test/hello_world.erb")
- end
+ def test_template_changes_are_not_reflected_with_cached_templates
+ assert_equal "Hello world!", render(:file => "test/hello_world.erb")
+ modify_template "test/hello_world.erb", "Goodbye world!" do
assert_equal "Hello world!", render(:file => "test/hello_world.erb")
end
+ assert_equal "Hello world!", render(:file => "test/hello_world.erb")
+ end
- def test_template_changes_are_reflected_with_uncached_templates
- assert_equal "Hello world!", render_without_cache(:file => "test/hello_world.erb")
- modify_template "test/hello_world.erb", "Goodbye world!" do
- assert_equal "Goodbye world!", render_without_cache(:file => "test/hello_world.erb")
- end
- assert_equal "Hello world!", render_without_cache(:file => "test/hello_world.erb")
+ def test_template_changes_are_reflected_with_uncached_templates
+ assert_equal "Hello world!", render_without_cache(:file => "test/hello_world.erb")
+ modify_template "test/hello_world.erb", "Goodbye world!" do
+ assert_equal "Goodbye world!", render_without_cache(:file => "test/hello_world.erb")
end
+ assert_equal "Hello world!", render_without_cache(:file => "test/hello_world.erb")
+ end
- private
- def render(*args)
- render_with_cache(*args)
- end
+ private
+ def render(*args)
+ render_with_cache(*args)
+ end
- def render_with_cache(*args)
- view_paths = ActionController::Base.view_paths
- assert_equal ActionView::Template::EagerPath, view_paths.first.class
- ActionView::Base.new(view_paths, {}).render(*args)
- end
+ def render_with_cache(*args)
+ view_paths = ActionController::Base.view_paths
+ assert_equal ActionView::Template::EagerPath, view_paths.first.class
+ ActionView::Base.new(view_paths, {}).render(*args)
+ end
- def render_without_cache(*args)
- path = ActionView::Template::Path.new(FIXTURE_LOAD_PATH)
- view_paths = ActionView::Base.process_view_paths(path)
- assert_equal ActionView::Template::Path, view_paths.first.class
- ActionView::Base.new(view_paths, {}).render(*args)
- end
+ def render_without_cache(*args)
+ path = ActionView::Template::Path.new(FIXTURE_LOAD_PATH)
+ view_paths = ActionView::Base.process_view_paths(path)
+ assert_equal ActionView::Template::Path, view_paths.first.class
+ ActionView::Base.new(view_paths, {}).render(*args)
+ end
- def modify_template(template, content)
- filename = "#{FIXTURE_LOAD_PATH}/#{template}"
- old_content = File.read(filename)
- begin
- File.open(filename, "wb+") { |f| f.write(content) }
- yield
- ensure
- File.open(filename, "wb+") { |f| f.write(old_content) }
- end
+ def modify_template(template, content)
+ filename = "#{FIXTURE_LOAD_PATH}/#{template}"
+ old_content = File.read(filename)
+ begin
+ File.open(filename, "wb+") { |f| f.write(content) }
+ yield
+ ensure
+ File.open(filename, "wb+") { |f| f.write(old_content) }
end
- end
+ end
end
diff --git a/actionpack/test/template/date_helper_i18n_test.rb b/actionpack/test/template/date_helper_i18n_test.rb
index fac30da128..bc011f59b8 100644
--- a/actionpack/test/template/date_helper_i18n_test.rb
+++ b/actionpack/test/template/date_helper_i18n_test.rb
@@ -8,66 +8,64 @@ class DateHelperDistanceOfTimeInWordsI18nTests < Test::Unit::TestCase
@from = Time.mktime(2004, 6, 6, 21, 45, 0)
end
- uses_mocha 'date_helper_distance_of_time_in_words_i18n_test' do
- # distance_of_time_in_words
-
- def test_distance_of_time_in_words_calls_i18n
- { # with include_seconds
- [2.seconds, true] => [:'less_than_x_seconds', 5],
- [9.seconds, true] => [:'less_than_x_seconds', 10],
- [19.seconds, true] => [:'less_than_x_seconds', 20],
- [30.seconds, true] => [:'half_a_minute', nil],
- [59.seconds, true] => [:'less_than_x_minutes', 1],
- [60.seconds, true] => [:'x_minutes', 1],
-
- # without include_seconds
- [29.seconds, false] => [:'less_than_x_minutes', 1],
- [60.seconds, false] => [:'x_minutes', 1],
- [44.minutes, false] => [:'x_minutes', 44],
- [61.minutes, false] => [:'about_x_hours', 1],
- [24.hours, false] => [:'x_days', 1],
- [30.days, false] => [:'about_x_months', 1],
- [60.days, false] => [:'x_months', 2],
- [1.year, false] => [:'about_x_years', 1],
- [3.years, false] => [:'over_x_years', 3]
-
- }.each do |passed, expected|
- assert_distance_of_time_in_words_translates_key passed, expected
- end
+ # distance_of_time_in_words
+
+ def test_distance_of_time_in_words_calls_i18n
+ { # with include_seconds
+ [2.seconds, true] => [:'less_than_x_seconds', 5],
+ [9.seconds, true] => [:'less_than_x_seconds', 10],
+ [19.seconds, true] => [:'less_than_x_seconds', 20],
+ [30.seconds, true] => [:'half_a_minute', nil],
+ [59.seconds, true] => [:'less_than_x_minutes', 1],
+ [60.seconds, true] => [:'x_minutes', 1],
+
+ # without include_seconds
+ [29.seconds, false] => [:'less_than_x_minutes', 1],
+ [60.seconds, false] => [:'x_minutes', 1],
+ [44.minutes, false] => [:'x_minutes', 44],
+ [61.minutes, false] => [:'about_x_hours', 1],
+ [24.hours, false] => [:'x_days', 1],
+ [30.days, false] => [:'about_x_months', 1],
+ [60.days, false] => [:'x_months', 2],
+ [1.year, false] => [:'about_x_years', 1],
+ [3.years, false] => [:'over_x_years', 3]
+
+ }.each do |passed, expected|
+ assert_distance_of_time_in_words_translates_key passed, expected
end
+ end
- def assert_distance_of_time_in_words_translates_key(passed, expected)
- diff, include_seconds = *passed
- key, count = *expected
- to = @from + diff
+ def assert_distance_of_time_in_words_translates_key(passed, expected)
+ diff, include_seconds = *passed
+ key, count = *expected
+ to = @from + diff
- options = {:locale => 'en', :scope => :'datetime.distance_in_words'}
- options[:count] = count if count
+ options = {:locale => 'en', :scope => :'datetime.distance_in_words'}
+ options[:count] = count if count
- I18n.expects(:t).with(key, options)
- distance_of_time_in_words(@from, to, include_seconds, :locale => 'en')
- end
+ I18n.expects(:t).with(key, options)
+ distance_of_time_in_words(@from, to, include_seconds, :locale => 'en')
+ end
- def test_distance_of_time_pluralizations
- { [:'less_than_x_seconds', 1] => 'less than 1 second',
- [:'less_than_x_seconds', 2] => 'less than 2 seconds',
- [:'less_than_x_minutes', 1] => 'less than a minute',
- [:'less_than_x_minutes', 2] => 'less than 2 minutes',
- [:'x_minutes', 1] => '1 minute',
- [:'x_minutes', 2] => '2 minutes',
- [:'about_x_hours', 1] => 'about 1 hour',
- [:'about_x_hours', 2] => 'about 2 hours',
- [:'x_days', 1] => '1 day',
- [:'x_days', 2] => '2 days',
- [:'about_x_years', 1] => 'about 1 year',
- [:'about_x_years', 2] => 'about 2 years',
- [:'over_x_years', 1] => 'over 1 year',
- [:'over_x_years', 2] => 'over 2 years'
-
- }.each do |args, expected|
- key, count = *args
- assert_equal expected, I18n.t(key, :count => count, :scope => 'datetime.distance_in_words')
- end
+ def test_distance_of_time_pluralizations
+ { [:'less_than_x_seconds', 1] => 'less than 1 second',
+ [:'less_than_x_seconds', 2] => 'less than 2 seconds',
+ [:'less_than_x_minutes', 1] => 'less than a minute',
+ [:'less_than_x_minutes', 2] => 'less than 2 minutes',
+ [:'x_minutes', 1] => '1 minute',
+ [:'x_minutes', 2] => '2 minutes',
+ [:'about_x_hours', 1] => 'about 1 hour',
+ [:'about_x_hours', 2] => 'about 2 hours',
+ [:'x_days', 1] => '1 day',
+ [:'x_days', 2] => '2 days',
+ [:'about_x_years', 1] => 'about 1 year',
+ [:'about_x_years', 2] => 'about 2 years',
+ [:'over_x_years', 1] => 'over 1 year',
+ [:'over_x_years', 2] => 'over 2 years'
+
+ }.each do |args, expected|
+ key, count = *args
+ assert_equal expected, I18n.t(key, :count => count, :scope => 'datetime.distance_in_words')
end
end
end
@@ -76,49 +74,47 @@ class DateHelperSelectTagsI18nTests < Test::Unit::TestCase
include ActionView::Helpers::DateHelper
attr_reader :request
- uses_mocha 'date_helper_select_tags_i18n_tests' do
- def setup
- @prompt_defaults = {:year => 'Year', :month => 'Month', :day => 'Day', :hour => 'Hour', :minute => 'Minute', :second => 'Seconds'}
-
- I18n.stubs(:translate).with(:'date.month_names', :locale => 'en').returns Date::MONTHNAMES
- end
+ def setup
+ @prompt_defaults = {:year => 'Year', :month => 'Month', :day => 'Day', :hour => 'Hour', :minute => 'Minute', :second => 'Seconds'}
- # select_month
+ I18n.stubs(:translate).with(:'date.month_names', :locale => 'en').returns Date::MONTHNAMES
+ end
- def test_select_month_given_use_month_names_option_does_not_translate_monthnames
- I18n.expects(:translate).never
- select_month(8, :locale => 'en', :use_month_names => Date::MONTHNAMES)
- end
+ # select_month
- def test_select_month_translates_monthnames
- I18n.expects(:translate).with(:'date.month_names', :locale => 'en').returns Date::MONTHNAMES
- select_month(8, :locale => 'en')
- end
+ def test_select_month_given_use_month_names_option_does_not_translate_monthnames
+ I18n.expects(:translate).never
+ select_month(8, :locale => 'en', :use_month_names => Date::MONTHNAMES)
+ end
- def test_select_month_given_use_short_month_option_translates_abbr_monthnames
- I18n.expects(:translate).with(:'date.abbr_month_names', :locale => 'en').returns Date::ABBR_MONTHNAMES
- select_month(8, :locale => 'en', :use_short_month => true)
- end
+ def test_select_month_translates_monthnames
+ I18n.expects(:translate).with(:'date.month_names', :locale => 'en').returns Date::MONTHNAMES
+ select_month(8, :locale => 'en')
+ end
- def test_date_or_time_select_translates_prompts
- @prompt_defaults.each do |key, prompt|
- I18n.expects(:translate).with(('datetime.prompts.' + key.to_s).to_sym, :locale => 'en').returns prompt
- end
+ def test_select_month_given_use_short_month_option_translates_abbr_monthnames
+ I18n.expects(:translate).with(:'date.abbr_month_names', :locale => 'en').returns Date::ABBR_MONTHNAMES
+ select_month(8, :locale => 'en', :use_short_month => true)
+ end
- I18n.expects(:translate).with(:'date.order', :locale => 'en').returns [:year, :month, :day]
- datetime_select('post', 'updated_at', :locale => 'en', :include_seconds => true, :prompt => true)
+ def test_date_or_time_select_translates_prompts
+ @prompt_defaults.each do |key, prompt|
+ I18n.expects(:translate).with(('datetime.prompts.' + key.to_s).to_sym, :locale => 'en').returns prompt
end
- # date_or_time_select
+ I18n.expects(:translate).with(:'date.order', :locale => 'en').returns [:year, :month, :day]
+ datetime_select('post', 'updated_at', :locale => 'en', :include_seconds => true, :prompt => true)
+ end
- def test_date_or_time_select_given_an_order_options_does_not_translate_order
- I18n.expects(:translate).never
- datetime_select('post', 'updated_at', :order => [:year, :month, :day], :locale => 'en')
- end
+ # date_or_time_select
- def test_date_or_time_select_given_no_order_options_translates_order
- I18n.expects(:translate).with(:'date.order', :locale => 'en').returns [:year, :month, :day]
- datetime_select('post', 'updated_at', :locale => 'en')
- end
+ def test_date_or_time_select_given_an_order_options_does_not_translate_order
+ I18n.expects(:translate).never
+ datetime_select('post', 'updated_at', :order => [:year, :month, :day], :locale => 'en')
+ end
+
+ def test_date_or_time_select_given_no_order_options_translates_order
+ I18n.expects(:translate).with(:'date.order', :locale => 'en').returns [:year, :month, :day]
+ datetime_select('post', 'updated_at', :locale => 'en')
end
-end \ No newline at end of file
+end
diff --git a/actionpack/test/template/date_helper_test.rb b/actionpack/test/template/date_helper_test.rb
index 92cdce2e45..59e921f09b 100644
--- a/actionpack/test/template/date_helper_test.rb
+++ b/actionpack/test/template/date_helper_test.rb
@@ -1726,40 +1726,38 @@ class DateHelperTest < ActionView::TestCase
assert_dom_equal expected, datetime_select("post", "updated_at")
end
- uses_mocha 'TestDatetimeSelectDefaultsToTimeZoneNowWhenConfigTimeZoneIsSet' do
- def test_datetime_select_defaults_to_time_zone_now_when_config_time_zone_is_set
- time = stub(:year => 2004, :month => 6, :day => 15, :hour => 16, :min => 35, :sec => 0)
- time_zone = mock()
- time_zone.expects(:now).returns time
- Time.zone_default = time_zone
- @post = Post.new
-
- expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}
- expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
- expected << "</select>\n"
-
- expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\n}
- expected << %{<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
- expected << "</select>\n"
-
- expected << %{<select id="post_updated_at_3i" name="post[updated_at(3i)]">\n}
- expected << %{<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n}
- expected << "</select>\n"
-
- expected << " &mdash; "
-
- expected << %{<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n}
- expected << %{<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n}
- expected << "</select>\n"
- expected << " : "
- expected << %{<select id="post_updated_at_5i" name="post[updated_at(5i)]">\n}
- expected << %{<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n<option value="32">32</option>\n<option value="33">33</option>\n<option value="34">34</option>\n<option value="35" selected="selected">35</option>\n<option value="36">36</option>\n<option value="37">37</option>\n<option value="38">38</option>\n<option value="39">39</option>\n<option value="40">40</option>\n<option value="41">41</option>\n<option value="42">42</option>\n<option value="43">43</option>\n<option value="44">44</option>\n<option value="45">45</option>\n<option value="46">46</option>\n<option value="47">47</option>\n<option value="48">48</option>\n<option value="49">49</option>\n<option value="50">50</option>\n<option value="51">51</option>\n<option value="52">52</option>\n<option value="53">53</option>\n<option value="54">54</option>\n<option value="55">55</option>\n<option value="56">56</option>\n<option value="57">57</option>\n<option value="58">58</option>\n<option value="59">59</option>\n}
- expected << "</select>\n"
-
- assert_dom_equal expected, datetime_select("post", "updated_at")
- ensure
- Time.zone_default = nil
- end
+ def test_datetime_select_defaults_to_time_zone_now_when_config_time_zone_is_set
+ time = stub(:year => 2004, :month => 6, :day => 15, :hour => 16, :min => 35, :sec => 0)
+ time_zone = mock()
+ time_zone.expects(:now).returns time
+ Time.zone_default = time_zone
+ @post = Post.new
+
+ expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}
+ expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\n}
+ expected << %{<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_updated_at_3i" name="post[updated_at(3i)]">\n}
+ expected << %{<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n}
+ expected << "</select>\n"
+
+ expected << " &mdash; "
+
+ expected << %{<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n}
+ expected << %{<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n}
+ expected << "</select>\n"
+ expected << " : "
+ expected << %{<select id="post_updated_at_5i" name="post[updated_at(5i)]">\n}
+ expected << %{<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n<option value="32">32</option>\n<option value="33">33</option>\n<option value="34">34</option>\n<option value="35" selected="selected">35</option>\n<option value="36">36</option>\n<option value="37">37</option>\n<option value="38">38</option>\n<option value="39">39</option>\n<option value="40">40</option>\n<option value="41">41</option>\n<option value="42">42</option>\n<option value="43">43</option>\n<option value="44">44</option>\n<option value="45">45</option>\n<option value="46">46</option>\n<option value="47">47</option>\n<option value="48">48</option>\n<option value="49">49</option>\n<option value="50">50</option>\n<option value="51">51</option>\n<option value="52">52</option>\n<option value="53">53</option>\n<option value="54">54</option>\n<option value="55">55</option>\n<option value="56">56</option>\n<option value="57">57</option>\n<option value="58">58</option>\n<option value="59">59</option>\n}
+ expected << "</select>\n"
+
+ assert_dom_equal expected, datetime_select("post", "updated_at")
+ ensure
+ Time.zone_default = nil
end
def test_datetime_select_with_html_options_within_fields_for
diff --git a/actionpack/test/template/form_helper_test.rb b/actionpack/test/template/form_helper_test.rb
index 33a542af7e..b7ea2c0176 100644
--- a/actionpack/test/template/form_helper_test.rb
+++ b/actionpack/test/template/form_helper_test.rb
@@ -586,6 +586,15 @@ class FormHelperTest < ActionView::TestCase
assert_dom_equal expected, output_buffer
end
+ def test_nested_fields_for_with_explicitly_passed_object_on_a_nested_attributes_one_to_one_association
+ form_for(:post, @post) do |f|
+ f.fields_for(:author, Author.new(123)) do |af|
+ assert_not_nil af.object
+ assert_equal 123, af.object.id
+ end
+ end
+ end
+
def test_nested_fields_for_with_an_existing_record_on_a_nested_attributes_one_to_one_association
@post.author = Author.new(321)
diff --git a/actionpack/test/template/form_options_helper_test.rb b/actionpack/test/template/form_options_helper_test.rb
index 86b321e6e5..83c27ac042 100644
--- a/actionpack/test/template/form_options_helper_test.rb
+++ b/actionpack/test/template/form_options_helper_test.rb
@@ -3,42 +3,54 @@ require 'tzinfo'
TZInfo::Timezone.cattr_reader :loaded_zones
-uses_mocha "FormOptionsHelperTest" do
- class FormOptionsHelperTest < ActionView::TestCase
- tests ActionView::Helpers::FormOptionsHelper
-
- silence_warnings do
- Post = Struct.new('Post', :title, :author_name, :body, :secret, :written_on, :category, :origin)
- Continent = Struct.new('Continent', :continent_name, :countries)
- Country = Struct.new('Country', :country_id, :country_name)
- Firm = Struct.new('Firm', :time_zone)
- Album = Struct.new('Album', :id, :title, :genre)
- end
+class FormOptionsHelperTest < ActionView::TestCase
+ tests ActionView::Helpers::FormOptionsHelper
+
+ silence_warnings do
+ Post = Struct.new('Post', :title, :author_name, :body, :secret, :written_on, :category, :origin)
+ Continent = Struct.new('Continent', :continent_name, :countries)
+ Country = Struct.new('Country', :country_id, :country_name)
+ Firm = Struct.new('Firm', :time_zone)
+ Album = Struct.new('Album', :id, :title, :genre)
+ end
- def setup
- @fake_timezones = %w(A B C D E).inject([]) do |zones, id|
- tz = TZInfo::Timezone.loaded_zones[id] = stub(:name => id, :to_s => id)
- ActiveSupport::TimeZone.stubs(:[]).with(id).returns(tz)
- zones << tz
- end
- ActiveSupport::TimeZone.stubs(:all).returns(@fake_timezones)
+ def setup
+ @fake_timezones = %w(A B C D E).inject([]) do |zones, id|
+ tz = TZInfo::Timezone.loaded_zones[id] = stub(:name => id, :to_s => id)
+ ActiveSupport::TimeZone.stubs(:[]).with(id).returns(tz)
+ zones << tz
end
+ ActiveSupport::TimeZone.stubs(:all).returns(@fake_timezones)
+ end
- def test_collection_options
- @posts = [
- Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
- Post.new("Babe went home", "Babe", "To a little house", "shh!"),
- Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
- ]
+ def test_collection_options
+ @posts = [
+ Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
+ Post.new("Babe went home", "Babe", "To a little house", "shh!"),
+ Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
+ ]
+
+ assert_dom_equal(
+ "<option value=\"&lt;Abe&gt;\">&lt;Abe&gt; went home</option>\n<option value=\"Babe\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>",
+ options_from_collection_for_select(@posts, "author_name", "title")
+ )
+ end
- assert_dom_equal(
- "<option value=\"&lt;Abe&gt;\">&lt;Abe&gt; went home</option>\n<option value=\"Babe\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>",
- options_from_collection_for_select(@posts, "author_name", "title")
- )
- end
+ def test_collection_options_with_preselected_value
+ @posts = [
+ Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
+ Post.new("Babe went home", "Babe", "To a little house", "shh!"),
+ Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
+ ]
- def test_collection_options_with_preselected_value
+ assert_dom_equal(
+ "<option value=\"&lt;Abe&gt;\">&lt;Abe&gt; went home</option>\n<option value=\"Babe\" selected=\"selected\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>",
+ options_from_collection_for_select(@posts, "author_name", "title", "Babe")
+ )
+ end
+
+ def test_collection_options_with_preselected_value_array
@posts = [
Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
Post.new("Babe went home", "Babe", "To a little house", "shh!"),
@@ -46,683 +58,669 @@ uses_mocha "FormOptionsHelperTest" do
]
assert_dom_equal(
- "<option value=\"&lt;Abe&gt;\">&lt;Abe&gt; went home</option>\n<option value=\"Babe\" selected=\"selected\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>",
- options_from_collection_for_select(@posts, "author_name", "title", "Babe")
+ "<option value=\"&lt;Abe&gt;\">&lt;Abe&gt; went home</option>\n<option value=\"Babe\" selected=\"selected\">Babe went home</option>\n<option value=\"Cabe\" selected=\"selected\">Cabe went home</option>",
+ options_from_collection_for_select(@posts, "author_name", "title", [ "Babe", "Cabe" ])
)
- end
+ end
- def test_collection_options_with_preselected_value_array
- @posts = [
- Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
- Post.new("Babe went home", "Babe", "To a little house", "shh!"),
- Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
- ]
-
- assert_dom_equal(
- "<option value=\"&lt;Abe&gt;\">&lt;Abe&gt; went home</option>\n<option value=\"Babe\" selected=\"selected\">Babe went home</option>\n<option value=\"Cabe\" selected=\"selected\">Cabe went home</option>",
- options_from_collection_for_select(@posts, "author_name", "title", [ "Babe", "Cabe" ])
- )
- end
+ def test_array_options_for_select
+ assert_dom_equal(
+ "<option value=\"&lt;Denmark&gt;\">&lt;Denmark&gt;</option>\n<option value=\"USA\">USA</option>\n<option value=\"Sweden\">Sweden</option>",
+ options_for_select([ "<Denmark>", "USA", "Sweden" ])
+ )
+ end
- def test_array_options_for_select
- assert_dom_equal(
- "<option value=\"&lt;Denmark&gt;\">&lt;Denmark&gt;</option>\n<option value=\"USA\">USA</option>\n<option value=\"Sweden\">Sweden</option>",
- options_for_select([ "<Denmark>", "USA", "Sweden" ])
- )
- end
+ def test_array_options_for_select_with_selection
+ assert_dom_equal(
+ "<option value=\"Denmark\">Denmark</option>\n<option value=\"&lt;USA&gt;\" selected=\"selected\">&lt;USA&gt;</option>\n<option value=\"Sweden\">Sweden</option>",
+ options_for_select([ "Denmark", "<USA>", "Sweden" ], "<USA>")
+ )
+ end
- def test_array_options_for_select_with_selection
+ def test_array_options_for_select_with_selection_array
assert_dom_equal(
- "<option value=\"Denmark\">Denmark</option>\n<option value=\"&lt;USA&gt;\" selected=\"selected\">&lt;USA&gt;</option>\n<option value=\"Sweden\">Sweden</option>",
- options_for_select([ "Denmark", "<USA>", "Sweden" ], "<USA>")
+ "<option value=\"Denmark\">Denmark</option>\n<option value=\"&lt;USA&gt;\" selected=\"selected\">&lt;USA&gt;</option>\n<option value=\"Sweden\" selected=\"selected\">Sweden</option>",
+ options_for_select([ "Denmark", "<USA>", "Sweden" ], [ "<USA>", "Sweden" ])
)
- end
-
- def test_array_options_for_select_with_selection_array
- assert_dom_equal(
- "<option value=\"Denmark\">Denmark</option>\n<option value=\"&lt;USA&gt;\" selected=\"selected\">&lt;USA&gt;</option>\n<option value=\"Sweden\" selected=\"selected\">Sweden</option>",
- options_for_select([ "Denmark", "<USA>", "Sweden" ], [ "<USA>", "Sweden" ])
- )
- end
-
- def test_array_options_for_string_include_in_other_string_bug_fix
- assert_dom_equal(
- "<option value=\"ruby\">ruby</option>\n<option value=\"rubyonrails\" selected=\"selected\">rubyonrails</option>",
- options_for_select([ "ruby", "rubyonrails" ], "rubyonrails")
- )
- assert_dom_equal(
- "<option value=\"ruby\" selected=\"selected\">ruby</option>\n<option value=\"rubyonrails\">rubyonrails</option>",
- options_for_select([ "ruby", "rubyonrails" ], "ruby")
- )
- assert_dom_equal(
- %(<option value="ruby" selected="selected">ruby</option>\n<option value="rubyonrails">rubyonrails</option>\n<option value=""></option>),
- options_for_select([ "ruby", "rubyonrails", nil ], "ruby")
- )
- end
+ end
- def test_hash_options_for_select
+ def test_array_options_for_string_include_in_other_string_bug_fix
assert_dom_equal(
- "<option value=\"&lt;Kroner&gt;\">&lt;DKR&gt;</option>\n<option value=\"Dollar\">$</option>",
- options_for_select("$" => "Dollar", "<DKR>" => "<Kroner>").split("\n").sort.join("\n")
+ "<option value=\"ruby\">ruby</option>\n<option value=\"rubyonrails\" selected=\"selected\">rubyonrails</option>",
+ options_for_select([ "ruby", "rubyonrails" ], "rubyonrails")
)
assert_dom_equal(
- "<option value=\"&lt;Kroner&gt;\">&lt;DKR&gt;</option>\n<option value=\"Dollar\" selected=\"selected\">$</option>",
- options_for_select({ "$" => "Dollar", "<DKR>" => "<Kroner>" }, "Dollar").split("\n").sort.join("\n")
+ "<option value=\"ruby\" selected=\"selected\">ruby</option>\n<option value=\"rubyonrails\">rubyonrails</option>",
+ options_for_select([ "ruby", "rubyonrails" ], "ruby")
)
assert_dom_equal(
- "<option value=\"&lt;Kroner&gt;\" selected=\"selected\">&lt;DKR&gt;</option>\n<option value=\"Dollar\" selected=\"selected\">$</option>",
- options_for_select({ "$" => "Dollar", "<DKR>" => "<Kroner>" }, [ "Dollar", "<Kroner>" ]).split("\n").sort.join("\n")
+ %(<option value="ruby" selected="selected">ruby</option>\n<option value="rubyonrails">rubyonrails</option>\n<option value=""></option>),
+ options_for_select([ "ruby", "rubyonrails", nil ], "ruby")
)
- end
+ end
- def test_ducktyped_options_for_select
- quack = Struct.new(:first, :last)
- assert_dom_equal(
- "<option value=\"&lt;Kroner&gt;\">&lt;DKR&gt;</option>\n<option value=\"Dollar\">$</option>",
- options_for_select([quack.new("<DKR>", "<Kroner>"), quack.new("$", "Dollar")])
- )
- assert_dom_equal(
- "<option value=\"&lt;Kroner&gt;\">&lt;DKR&gt;</option>\n<option value=\"Dollar\" selected=\"selected\">$</option>",
- options_for_select([quack.new("<DKR>", "<Kroner>"), quack.new("$", "Dollar")], "Dollar")
- )
- assert_dom_equal(
- "<option value=\"&lt;Kroner&gt;\" selected=\"selected\">&lt;DKR&gt;</option>\n<option value=\"Dollar\" selected=\"selected\">$</option>",
- options_for_select([quack.new("<DKR>", "<Kroner>"), quack.new("$", "Dollar")], ["Dollar", "<Kroner>"])
- )
- end
+ def test_hash_options_for_select
+ assert_dom_equal(
+ "<option value=\"&lt;Kroner&gt;\">&lt;DKR&gt;</option>\n<option value=\"Dollar\">$</option>",
+ options_for_select("$" => "Dollar", "<DKR>" => "<Kroner>").split("\n").sort.join("\n")
+ )
+ assert_dom_equal(
+ "<option value=\"&lt;Kroner&gt;\">&lt;DKR&gt;</option>\n<option value=\"Dollar\" selected=\"selected\">$</option>",
+ options_for_select({ "$" => "Dollar", "<DKR>" => "<Kroner>" }, "Dollar").split("\n").sort.join("\n")
+ )
+ assert_dom_equal(
+ "<option value=\"&lt;Kroner&gt;\" selected=\"selected\">&lt;DKR&gt;</option>\n<option value=\"Dollar\" selected=\"selected\">$</option>",
+ options_for_select({ "$" => "Dollar", "<DKR>" => "<Kroner>" }, [ "Dollar", "<Kroner>" ]).split("\n").sort.join("\n")
+ )
+ end
- def test_option_groups_from_collection_for_select
- @continents = [
- Continent.new("<Africa>", [Country.new("<sa>", "<South Africa>"), Country.new("so", "Somalia")] ),
- Continent.new("Europe", [Country.new("dk", "Denmark"), Country.new("ie", "Ireland")] )
- ]
+ def test_ducktyped_options_for_select
+ quack = Struct.new(:first, :last)
+ assert_dom_equal(
+ "<option value=\"&lt;Kroner&gt;\">&lt;DKR&gt;</option>\n<option value=\"Dollar\">$</option>",
+ options_for_select([quack.new("<DKR>", "<Kroner>"), quack.new("$", "Dollar")])
+ )
+ assert_dom_equal(
+ "<option value=\"&lt;Kroner&gt;\">&lt;DKR&gt;</option>\n<option value=\"Dollar\" selected=\"selected\">$</option>",
+ options_for_select([quack.new("<DKR>", "<Kroner>"), quack.new("$", "Dollar")], "Dollar")
+ )
+ assert_dom_equal(
+ "<option value=\"&lt;Kroner&gt;\" selected=\"selected\">&lt;DKR&gt;</option>\n<option value=\"Dollar\" selected=\"selected\">$</option>",
+ options_for_select([quack.new("<DKR>", "<Kroner>"), quack.new("$", "Dollar")], ["Dollar", "<Kroner>"])
+ )
+ end
- assert_dom_equal(
- "<optgroup label=\"&lt;Africa&gt;\"><option value=\"&lt;sa&gt;\">&lt;South Africa&gt;</option>\n<option value=\"so\">Somalia</option></optgroup><optgroup label=\"Europe\"><option value=\"dk\" selected=\"selected\">Denmark</option>\n<option value=\"ie\">Ireland</option></optgroup>",
- option_groups_from_collection_for_select(@continents, "countries", "continent_name", "country_id", "country_name", "dk")
- )
- end
+ def test_option_groups_from_collection_for_select
+ @continents = [
+ Continent.new("<Africa>", [Country.new("<sa>", "<South Africa>"), Country.new("so", "Somalia")] ),
+ Continent.new("Europe", [Country.new("dk", "Denmark"), Country.new("ie", "Ireland")] )
+ ]
- def test_grouped_options_for_select_with_array
- assert_dom_equal(
- "<optgroup label=\"North America\"><option value=\"US\">United States</option>\n<option value=\"Canada\">Canada</option></optgroup><optgroup label=\"Europe\"><option value=\"GB\">Great Britain</option>\n<option value=\"Germany\">Germany</option></optgroup>",
- grouped_options_for_select([
- ["North America",
- [['United States','US'],"Canada"]],
- ["Europe",
- [["Great Britain","GB"], "Germany"]]
- ])
- )
- end
+ assert_dom_equal(
+ "<optgroup label=\"&lt;Africa&gt;\"><option value=\"&lt;sa&gt;\">&lt;South Africa&gt;</option>\n<option value=\"so\">Somalia</option></optgroup><optgroup label=\"Europe\"><option value=\"dk\" selected=\"selected\">Denmark</option>\n<option value=\"ie\">Ireland</option></optgroup>",
+ option_groups_from_collection_for_select(@continents, "countries", "continent_name", "country_id", "country_name", "dk")
+ )
+ end
- def test_grouped_options_for_select_with_selected_and_prompt
- assert_dom_equal(
- "<option value=\"\">Choose a product...</option><optgroup label=\"Hats\"><option value=\"Baseball Cap\">Baseball Cap</option>\n<option selected=\"selected\" value=\"Cowboy Hat\">Cowboy Hat</option></optgroup>",
- grouped_options_for_select([["Hats", ["Baseball Cap","Cowboy Hat"]]], "Cowboy Hat", "Choose a product...")
- )
- end
+ def test_grouped_options_for_select_with_array
+ assert_dom_equal(
+ "<optgroup label=\"North America\"><option value=\"US\">United States</option>\n<option value=\"Canada\">Canada</option></optgroup><optgroup label=\"Europe\"><option value=\"GB\">Great Britain</option>\n<option value=\"Germany\">Germany</option></optgroup>",
+ grouped_options_for_select([
+ ["North America",
+ [['United States','US'],"Canada"]],
+ ["Europe",
+ [["Great Britain","GB"], "Germany"]]
+ ])
+ )
+ end
- def test_optgroups_with_with_options_with_hash
- assert_dom_equal(
- "<optgroup label=\"Europe\"><option value=\"Denmark\">Denmark</option>\n<option value=\"Germany\">Germany</option></optgroup><optgroup label=\"North America\"><option value=\"United States\">United States</option>\n<option value=\"Canada\">Canada</option></optgroup>",
- grouped_options_for_select({'North America' => ['United States','Canada'], 'Europe' => ['Denmark','Germany']})
- )
- end
+ def test_grouped_options_for_select_with_selected_and_prompt
+ assert_dom_equal(
+ "<option value=\"\">Choose a product...</option><optgroup label=\"Hats\"><option value=\"Baseball Cap\">Baseball Cap</option>\n<option selected=\"selected\" value=\"Cowboy Hat\">Cowboy Hat</option></optgroup>",
+ grouped_options_for_select([["Hats", ["Baseball Cap","Cowboy Hat"]]], "Cowboy Hat", "Choose a product...")
+ )
+ end
- def test_time_zone_options_no_parms
- opts = time_zone_options_for_select
- assert_dom_equal "<option value=\"A\">A</option>\n" +
- "<option value=\"B\">B</option>\n" +
- "<option value=\"C\">C</option>\n" +
- "<option value=\"D\">D</option>\n" +
- "<option value=\"E\">E</option>",
- opts
- end
+ def test_optgroups_with_with_options_with_hash
+ assert_dom_equal(
+ "<optgroup label=\"Europe\"><option value=\"Denmark\">Denmark</option>\n<option value=\"Germany\">Germany</option></optgroup><optgroup label=\"North America\"><option value=\"United States\">United States</option>\n<option value=\"Canada\">Canada</option></optgroup>",
+ grouped_options_for_select({'North America' => ['United States','Canada'], 'Europe' => ['Denmark','Germany']})
+ )
+ end
- def test_time_zone_options_with_selected
- opts = time_zone_options_for_select( "D" )
- assert_dom_equal "<option value=\"A\">A</option>\n" +
- "<option value=\"B\">B</option>\n" +
- "<option value=\"C\">C</option>\n" +
- "<option value=\"D\" selected=\"selected\">D</option>\n" +
- "<option value=\"E\">E</option>",
- opts
- end
+ def test_time_zone_options_no_parms
+ opts = time_zone_options_for_select
+ assert_dom_equal "<option value=\"A\">A</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\">D</option>\n" +
+ "<option value=\"E\">E</option>",
+ opts
+ end
- def test_time_zone_options_with_unknown_selected
- opts = time_zone_options_for_select( "K" )
- assert_dom_equal "<option value=\"A\">A</option>\n" +
- "<option value=\"B\">B</option>\n" +
- "<option value=\"C\">C</option>\n" +
- "<option value=\"D\">D</option>\n" +
- "<option value=\"E\">E</option>",
- opts
- end
+ def test_time_zone_options_with_selected
+ opts = time_zone_options_for_select( "D" )
+ assert_dom_equal "<option value=\"A\">A</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\" selected=\"selected\">D</option>\n" +
+ "<option value=\"E\">E</option>",
+ opts
+ end
- def test_time_zone_options_with_priority_zones
- zones = [ ActiveSupport::TimeZone.new( "B" ), ActiveSupport::TimeZone.new( "E" ) ]
- opts = time_zone_options_for_select( nil, zones )
- assert_dom_equal "<option value=\"B\">B</option>\n" +
- "<option value=\"E\">E</option>" +
- "<option value=\"\" disabled=\"disabled\">-------------</option>\n" +
- "<option value=\"A\">A</option>\n" +
- "<option value=\"C\">C</option>\n" +
- "<option value=\"D\">D</option>",
- opts
- end
+ def test_time_zone_options_with_unknown_selected
+ opts = time_zone_options_for_select( "K" )
+ assert_dom_equal "<option value=\"A\">A</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\">D</option>\n" +
+ "<option value=\"E\">E</option>",
+ opts
+ end
- def test_time_zone_options_with_selected_priority_zones
- zones = [ ActiveSupport::TimeZone.new( "B" ), ActiveSupport::TimeZone.new( "E" ) ]
- opts = time_zone_options_for_select( "E", zones )
- assert_dom_equal "<option value=\"B\">B</option>\n" +
- "<option value=\"E\" selected=\"selected\">E</option>" +
- "<option value=\"\" disabled=\"disabled\">-------------</option>\n" +
- "<option value=\"A\">A</option>\n" +
- "<option value=\"C\">C</option>\n" +
- "<option value=\"D\">D</option>",
- opts
- end
+ def test_time_zone_options_with_priority_zones
+ zones = [ ActiveSupport::TimeZone.new( "B" ), ActiveSupport::TimeZone.new( "E" ) ]
+ opts = time_zone_options_for_select( nil, zones )
+ assert_dom_equal "<option value=\"B\">B</option>\n" +
+ "<option value=\"E\">E</option>" +
+ "<option value=\"\" disabled=\"disabled\">-------------</option>\n" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\">D</option>",
+ opts
+ end
- def test_time_zone_options_with_unselected_priority_zones
- zones = [ ActiveSupport::TimeZone.new( "B" ), ActiveSupport::TimeZone.new( "E" ) ]
- opts = time_zone_options_for_select( "C", zones )
- assert_dom_equal "<option value=\"B\">B</option>\n" +
- "<option value=\"E\">E</option>" +
- "<option value=\"\" disabled=\"disabled\">-------------</option>\n" +
- "<option value=\"A\">A</option>\n" +
- "<option value=\"C\" selected=\"selected\">C</option>\n" +
- "<option value=\"D\">D</option>",
- opts
- end
+ def test_time_zone_options_with_selected_priority_zones
+ zones = [ ActiveSupport::TimeZone.new( "B" ), ActiveSupport::TimeZone.new( "E" ) ]
+ opts = time_zone_options_for_select( "E", zones )
+ assert_dom_equal "<option value=\"B\">B</option>\n" +
+ "<option value=\"E\" selected=\"selected\">E</option>" +
+ "<option value=\"\" disabled=\"disabled\">-------------</option>\n" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\">D</option>",
+ opts
+ end
- def test_select
- @post = Post.new
- @post.category = "<mus>"
- assert_dom_equal(
- "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"&lt;mus&gt;\" selected=\"selected\">&lt;mus&gt;</option>\n<option value=\"hest\">hest</option></select>",
- select("post", "category", %w( abe <mus> hest))
- )
- end
+ def test_time_zone_options_with_unselected_priority_zones
+ zones = [ ActiveSupport::TimeZone.new( "B" ), ActiveSupport::TimeZone.new( "E" ) ]
+ opts = time_zone_options_for_select( "C", zones )
+ assert_dom_equal "<option value=\"B\">B</option>\n" +
+ "<option value=\"E\">E</option>" +
+ "<option value=\"\" disabled=\"disabled\">-------------</option>\n" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"C\" selected=\"selected\">C</option>\n" +
+ "<option value=\"D\">D</option>",
+ opts
+ end
- def test_select_under_fields_for
- @post = Post.new
- @post.category = "<mus>"
+ def test_select
+ @post = Post.new
+ @post.category = "<mus>"
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"&lt;mus&gt;\" selected=\"selected\">&lt;mus&gt;</option>\n<option value=\"hest\">hest</option></select>",
+ select("post", "category", %w( abe <mus> hest))
+ )
+ end
- fields_for :post, @post do |f|
- concat f.select(:category, %w( abe <mus> hest))
- end
-
- assert_dom_equal(
- "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"&lt;mus&gt;\" selected=\"selected\">&lt;mus&gt;</option>\n<option value=\"hest\">hest</option></select>",
- output_buffer
- )
- end
+ def test_select_under_fields_for
+ @post = Post.new
+ @post.category = "<mus>"
- def test_select_under_fields_for_with_index
- @post = Post.new
- @post.category = "<mus>"
+ fields_for :post, @post do |f|
+ concat f.select(:category, %w( abe <mus> hest))
+ end
+
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"&lt;mus&gt;\" selected=\"selected\">&lt;mus&gt;</option>\n<option value=\"hest\">hest</option></select>",
+ output_buffer
+ )
+ end
- fields_for :post, @post, :index => 108 do |f|
- concat f.select(:category, %w( abe <mus> hest))
- end
+ def test_select_under_fields_for_with_index
+ @post = Post.new
+ @post.category = "<mus>"
- assert_dom_equal(
- "<select id=\"post_108_category\" name=\"post[108][category]\"><option value=\"abe\">abe</option>\n<option value=\"&lt;mus&gt;\" selected=\"selected\">&lt;mus&gt;</option>\n<option value=\"hest\">hest</option></select>",
- output_buffer
- )
+ fields_for :post, @post, :index => 108 do |f|
+ concat f.select(:category, %w( abe <mus> hest))
end
- def test_select_under_fields_for_with_auto_index
- @post = Post.new
- @post.category = "<mus>"
- def @post.to_param; 108; end
+ assert_dom_equal(
+ "<select id=\"post_108_category\" name=\"post[108][category]\"><option value=\"abe\">abe</option>\n<option value=\"&lt;mus&gt;\" selected=\"selected\">&lt;mus&gt;</option>\n<option value=\"hest\">hest</option></select>",
+ output_buffer
+ )
+ end
- fields_for "post[]", @post do |f|
- concat f.select(:category, %w( abe <mus> hest))
- end
+ def test_select_under_fields_for_with_auto_index
+ @post = Post.new
+ @post.category = "<mus>"
+ def @post.to_param; 108; end
- assert_dom_equal(
- "<select id=\"post_108_category\" name=\"post[108][category]\"><option value=\"abe\">abe</option>\n<option value=\"&lt;mus&gt;\" selected=\"selected\">&lt;mus&gt;</option>\n<option value=\"hest\">hest</option></select>",
- output_buffer
- )
+ fields_for "post[]", @post do |f|
+ concat f.select(:category, %w( abe <mus> hest))
end
- def test_select_with_blank
- @post = Post.new
- @post.category = "<mus>"
- assert_dom_equal(
- "<select id=\"post_category\" name=\"post[category]\"><option value=\"\"></option>\n<option value=\"abe\">abe</option>\n<option value=\"&lt;mus&gt;\" selected=\"selected\">&lt;mus&gt;</option>\n<option value=\"hest\">hest</option></select>",
- select("post", "category", %w( abe <mus> hest), :include_blank => true)
- )
- end
+ assert_dom_equal(
+ "<select id=\"post_108_category\" name=\"post[108][category]\"><option value=\"abe\">abe</option>\n<option value=\"&lt;mus&gt;\" selected=\"selected\">&lt;mus&gt;</option>\n<option value=\"hest\">hest</option></select>",
+ output_buffer
+ )
+ end
- def test_select_with_blank_as_string
- @post = Post.new
- @post.category = "<mus>"
- assert_dom_equal(
- "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">None</option>\n<option value=\"abe\">abe</option>\n<option value=\"&lt;mus&gt;\" selected=\"selected\">&lt;mus&gt;</option>\n<option value=\"hest\">hest</option></select>",
- select("post", "category", %w( abe <mus> hest), :include_blank => 'None')
- )
- end
+ def test_select_with_blank
+ @post = Post.new
+ @post.category = "<mus>"
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"\"></option>\n<option value=\"abe\">abe</option>\n<option value=\"&lt;mus&gt;\" selected=\"selected\">&lt;mus&gt;</option>\n<option value=\"hest\">hest</option></select>",
+ select("post", "category", %w( abe <mus> hest), :include_blank => true)
+ )
+ end
- def test_select_with_default_prompt
- @post = Post.new
- @post.category = ""
- assert_dom_equal(
- "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">Please select</option>\n<option value=\"abe\">abe</option>\n<option value=\"&lt;mus&gt;\">&lt;mus&gt;</option>\n<option value=\"hest\">hest</option></select>",
- select("post", "category", %w( abe <mus> hest), :prompt => true)
- )
- end
+ def test_select_with_blank_as_string
+ @post = Post.new
+ @post.category = "<mus>"
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">None</option>\n<option value=\"abe\">abe</option>\n<option value=\"&lt;mus&gt;\" selected=\"selected\">&lt;mus&gt;</option>\n<option value=\"hest\">hest</option></select>",
+ select("post", "category", %w( abe <mus> hest), :include_blank => 'None')
+ )
+ end
- def test_select_no_prompt_when_select_has_value
- @post = Post.new
- @post.category = "<mus>"
- assert_dom_equal(
- "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"&lt;mus&gt;\" selected=\"selected\">&lt;mus&gt;</option>\n<option value=\"hest\">hest</option></select>",
- select("post", "category", %w( abe <mus> hest), :prompt => true)
- )
- end
+ def test_select_with_default_prompt
+ @post = Post.new
+ @post.category = ""
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">Please select</option>\n<option value=\"abe\">abe</option>\n<option value=\"&lt;mus&gt;\">&lt;mus&gt;</option>\n<option value=\"hest\">hest</option></select>",
+ select("post", "category", %w( abe <mus> hest), :prompt => true)
+ )
+ end
- def test_select_with_given_prompt
- @post = Post.new
- @post.category = ""
- assert_dom_equal(
- "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">The prompt</option>\n<option value=\"abe\">abe</option>\n<option value=\"&lt;mus&gt;\">&lt;mus&gt;</option>\n<option value=\"hest\">hest</option></select>",
- select("post", "category", %w( abe <mus> hest), :prompt => 'The prompt')
- )
- end
+ def test_select_no_prompt_when_select_has_value
+ @post = Post.new
+ @post.category = "<mus>"
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"&lt;mus&gt;\" selected=\"selected\">&lt;mus&gt;</option>\n<option value=\"hest\">hest</option></select>",
+ select("post", "category", %w( abe <mus> hest), :prompt => true)
+ )
+ end
- def test_select_with_prompt_and_blank
- @post = Post.new
- @post.category = ""
- assert_dom_equal(
- "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">Please select</option>\n<option value=\"\"></option>\n<option value=\"abe\">abe</option>\n<option value=\"&lt;mus&gt;\">&lt;mus&gt;</option>\n<option value=\"hest\">hest</option></select>",
- select("post", "category", %w( abe <mus> hest), :prompt => true, :include_blank => true)
- )
- end
+ def test_select_with_given_prompt
+ @post = Post.new
+ @post.category = ""
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">The prompt</option>\n<option value=\"abe\">abe</option>\n<option value=\"&lt;mus&gt;\">&lt;mus&gt;</option>\n<option value=\"hest\">hest</option></select>",
+ select("post", "category", %w( abe <mus> hest), :prompt => 'The prompt')
+ )
+ end
- def test_select_with_selected_value
- @post = Post.new
- @post.category = "<mus>"
- assert_dom_equal(
- "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\" selected=\"selected\">abe</option>\n<option value=\"&lt;mus&gt;\">&lt;mus&gt;</option>\n<option value=\"hest\">hest</option></select>",
- select("post", "category", %w( abe <mus> hest ), :selected => 'abe')
- )
- end
+ def test_select_with_prompt_and_blank
+ @post = Post.new
+ @post.category = ""
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">Please select</option>\n<option value=\"\"></option>\n<option value=\"abe\">abe</option>\n<option value=\"&lt;mus&gt;\">&lt;mus&gt;</option>\n<option value=\"hest\">hest</option></select>",
+ select("post", "category", %w( abe <mus> hest), :prompt => true, :include_blank => true)
+ )
+ end
+
+ def test_select_with_selected_value
+ @post = Post.new
+ @post.category = "<mus>"
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\" selected=\"selected\">abe</option>\n<option value=\"&lt;mus&gt;\">&lt;mus&gt;</option>\n<option value=\"hest\">hest</option></select>",
+ select("post", "category", %w( abe <mus> hest ), :selected => 'abe')
+ )
+ end
+
+ def test_select_with_index_option
+ @album = Album.new
+ @album.id = 1
- def test_select_with_index_option
- @album = Album.new
- @album.id = 1
-
- expected = "<select id=\"album__genre\" name=\"album[][genre]\"><option value=\"rap\">rap</option>\n<option value=\"rock\">rock</option>\n<option value=\"country\">country</option></select>"
+ expected = "<select id=\"album__genre\" name=\"album[][genre]\"><option value=\"rap\">rap</option>\n<option value=\"rock\">rock</option>\n<option value=\"country\">country</option></select>"
- assert_dom_equal(
- expected,
- select("album[]", "genre", %w[rap rock country], {}, { :index => nil })
- )
- end
+ assert_dom_equal(
+ expected,
+ select("album[]", "genre", %w[rap rock country], {}, { :index => nil })
+ )
+ end
- def test_select_with_selected_nil
- @post = Post.new
- @post.category = "<mus>"
- assert_dom_equal(
- "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"&lt;mus&gt;\">&lt;mus&gt;</option>\n<option value=\"hest\">hest</option></select>",
- select("post", "category", %w( abe <mus> hest ), :selected => nil)
- )
- end
+ def test_select_with_selected_nil
+ @post = Post.new
+ @post.category = "<mus>"
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"&lt;mus&gt;\">&lt;mus&gt;</option>\n<option value=\"hest\">hest</option></select>",
+ select("post", "category", %w( abe <mus> hest ), :selected => nil)
+ )
+ end
- def test_collection_select
- @posts = [
- Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
- Post.new("Babe went home", "Babe", "To a little house", "shh!"),
- Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
- ]
+ def test_collection_select
+ @posts = [
+ Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
+ Post.new("Babe went home", "Babe", "To a little house", "shh!"),
+ Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
+ ]
- @post = Post.new
- @post.author_name = "Babe"
+ @post = Post.new
+ @post.author_name = "Babe"
- assert_dom_equal(
- "<select id=\"post_author_name\" name=\"post[author_name]\"><option value=\"&lt;Abe&gt;\">&lt;Abe&gt;</option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>",
- collection_select("post", "author_name", @posts, "author_name", "author_name")
- )
- end
+ assert_dom_equal(
+ "<select id=\"post_author_name\" name=\"post[author_name]\"><option value=\"&lt;Abe&gt;\">&lt;Abe&gt;</option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>",
+ collection_select("post", "author_name", @posts, "author_name", "author_name")
+ )
+ end
- def test_collection_select_under_fields_for
- @posts = [
- Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
- Post.new("Babe went home", "Babe", "To a little house", "shh!"),
- Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
- ]
+ def test_collection_select_under_fields_for
+ @posts = [
+ Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
+ Post.new("Babe went home", "Babe", "To a little house", "shh!"),
+ Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
+ ]
- @post = Post.new
- @post.author_name = "Babe"
+ @post = Post.new
+ @post.author_name = "Babe"
- fields_for :post, @post do |f|
- concat f.collection_select(:author_name, @posts, :author_name, :author_name)
- end
-
- assert_dom_equal(
- "<select id=\"post_author_name\" name=\"post[author_name]\"><option value=\"&lt;Abe&gt;\">&lt;Abe&gt;</option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>",
- output_buffer
- )
+ fields_for :post, @post do |f|
+ concat f.collection_select(:author_name, @posts, :author_name, :author_name)
end
+
+ assert_dom_equal(
+ "<select id=\"post_author_name\" name=\"post[author_name]\"><option value=\"&lt;Abe&gt;\">&lt;Abe&gt;</option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>",
+ output_buffer
+ )
+ end
- def test_collection_select_under_fields_for_with_index
- @posts = [
- Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
- Post.new("Babe went home", "Babe", "To a little house", "shh!"),
- Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
- ]
-
- @post = Post.new
- @post.author_name = "Babe"
+ def test_collection_select_under_fields_for_with_index
+ @posts = [
+ Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
+ Post.new("Babe went home", "Babe", "To a little house", "shh!"),
+ Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
+ ]
- fields_for :post, @post, :index => 815 do |f|
- concat f.collection_select(:author_name, @posts, :author_name, :author_name)
- end
+ @post = Post.new
+ @post.author_name = "Babe"
- assert_dom_equal(
- "<select id=\"post_815_author_name\" name=\"post[815][author_name]\"><option value=\"&lt;Abe&gt;\">&lt;Abe&gt;</option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>",
- output_buffer
- )
+ fields_for :post, @post, :index => 815 do |f|
+ concat f.collection_select(:author_name, @posts, :author_name, :author_name)
end
- def test_collection_select_under_fields_for_with_auto_index
- @posts = [
- Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
- Post.new("Babe went home", "Babe", "To a little house", "shh!"),
- Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
- ]
+ assert_dom_equal(
+ "<select id=\"post_815_author_name\" name=\"post[815][author_name]\"><option value=\"&lt;Abe&gt;\">&lt;Abe&gt;</option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>",
+ output_buffer
+ )
+ end
- @post = Post.new
- @post.author_name = "Babe"
- def @post.to_param; 815; end
+ def test_collection_select_under_fields_for_with_auto_index
+ @posts = [
+ Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
+ Post.new("Babe went home", "Babe", "To a little house", "shh!"),
+ Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
+ ]
- fields_for "post[]", @post do |f|
- concat f.collection_select(:author_name, @posts, :author_name, :author_name)
- end
+ @post = Post.new
+ @post.author_name = "Babe"
+ def @post.to_param; 815; end
- assert_dom_equal(
- "<select id=\"post_815_author_name\" name=\"post[815][author_name]\"><option value=\"&lt;Abe&gt;\">&lt;Abe&gt;</option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>",
- output_buffer
- )
+ fields_for "post[]", @post do |f|
+ concat f.collection_select(:author_name, @posts, :author_name, :author_name)
end
- def test_collection_select_with_blank_and_style
- @posts = [
- Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
- Post.new("Babe went home", "Babe", "To a little house", "shh!"),
- Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
- ]
+ assert_dom_equal(
+ "<select id=\"post_815_author_name\" name=\"post[815][author_name]\"><option value=\"&lt;Abe&gt;\">&lt;Abe&gt;</option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>",
+ output_buffer
+ )
+ end
- @post = Post.new
- @post.author_name = "Babe"
+ def test_collection_select_with_blank_and_style
+ @posts = [
+ Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
+ Post.new("Babe went home", "Babe", "To a little house", "shh!"),
+ Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
+ ]
- assert_dom_equal(
- "<select id=\"post_author_name\" name=\"post[author_name]\" style=\"width: 200px\"><option value=\"\"></option>\n<option value=\"&lt;Abe&gt;\">&lt;Abe&gt;</option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>",
- collection_select("post", "author_name", @posts, "author_name", "author_name", { :include_blank => true }, "style" => "width: 200px")
- )
- end
+ @post = Post.new
+ @post.author_name = "Babe"
- def test_collection_select_with_blank_as_string_and_style
- @posts = [
- Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
- Post.new("Babe went home", "Babe", "To a little house", "shh!"),
- Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
- ]
+ assert_dom_equal(
+ "<select id=\"post_author_name\" name=\"post[author_name]\" style=\"width: 200px\"><option value=\"\"></option>\n<option value=\"&lt;Abe&gt;\">&lt;Abe&gt;</option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>",
+ collection_select("post", "author_name", @posts, "author_name", "author_name", { :include_blank => true }, "style" => "width: 200px")
+ )
+ end
- @post = Post.new
- @post.author_name = "Babe"
+ def test_collection_select_with_blank_as_string_and_style
+ @posts = [
+ Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
+ Post.new("Babe went home", "Babe", "To a little house", "shh!"),
+ Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
+ ]
- assert_dom_equal(
- "<select id=\"post_author_name\" name=\"post[author_name]\" style=\"width: 200px\"><option value=\"\">No Selection</option>\n<option value=\"&lt;Abe&gt;\">&lt;Abe&gt;</option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>",
- collection_select("post", "author_name", @posts, "author_name", "author_name", { :include_blank => 'No Selection' }, "style" => "width: 200px")
- )
- end
+ @post = Post.new
+ @post.author_name = "Babe"
- def test_collection_select_with_multiple_option_appends_array_brackets
- @posts = [
- Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
- Post.new("Babe went home", "Babe", "To a little house", "shh!"),
- Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
- ]
+ assert_dom_equal(
+ "<select id=\"post_author_name\" name=\"post[author_name]\" style=\"width: 200px\"><option value=\"\">No Selection</option>\n<option value=\"&lt;Abe&gt;\">&lt;Abe&gt;</option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>",
+ collection_select("post", "author_name", @posts, "author_name", "author_name", { :include_blank => 'No Selection' }, "style" => "width: 200px")
+ )
+ end
- @post = Post.new
- @post.author_name = "Babe"
+ def test_collection_select_with_multiple_option_appends_array_brackets
+ @posts = [
+ Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
+ Post.new("Babe went home", "Babe", "To a little house", "shh!"),
+ Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
+ ]
- expected = "<select id=\"post_author_name\" name=\"post[author_name][]\" multiple=\"multiple\"><option value=\"\"></option>\n<option value=\"&lt;Abe&gt;\">&lt;Abe&gt;</option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>"
+ @post = Post.new
+ @post.author_name = "Babe"
- # Should suffix default name with [].
- assert_dom_equal expected, collection_select("post", "author_name", @posts, "author_name", "author_name", { :include_blank => true }, :multiple => true)
+ expected = "<select id=\"post_author_name\" name=\"post[author_name][]\" multiple=\"multiple\"><option value=\"\"></option>\n<option value=\"&lt;Abe&gt;\">&lt;Abe&gt;</option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>"
- # Shouldn't suffix custom name with [].
- assert_dom_equal expected, collection_select("post", "author_name", @posts, "author_name", "author_name", { :include_blank => true, :name => 'post[author_name][]' }, :multiple => true)
- end
+ # Should suffix default name with [].
+ assert_dom_equal expected, collection_select("post", "author_name", @posts, "author_name", "author_name", { :include_blank => true }, :multiple => true)
- def test_collection_select_with_blank_and_selected
- @posts = [
- Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
- Post.new("Babe went home", "Babe", "To a little house", "shh!"),
- Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
- ]
+ # Shouldn't suffix custom name with [].
+ assert_dom_equal expected, collection_select("post", "author_name", @posts, "author_name", "author_name", { :include_blank => true, :name => 'post[author_name][]' }, :multiple => true)
+ end
- @post = Post.new
- @post.author_name = "Babe"
+ def test_collection_select_with_blank_and_selected
+ @posts = [
+ Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
+ Post.new("Babe went home", "Babe", "To a little house", "shh!"),
+ Post.new("Cabe went home", "Cabe", "To a little house", "shh!")
+ ]
- assert_dom_equal(
- %{<select id="post_author_name" name="post[author_name]"><option value=""></option>\n<option value="&lt;Abe&gt;" selected="selected">&lt;Abe&gt;</option>\n<option value="Babe">Babe</option>\n<option value="Cabe">Cabe</option></select>},
- collection_select("post", "author_name", @posts, "author_name", "author_name", {:include_blank => true, :selected => "<Abe>"})
- )
- end
+ @post = Post.new
+ @post.author_name = "Babe"
- def test_time_zone_select
- @firm = Firm.new("D")
- html = time_zone_select( "firm", "time_zone" )
- assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" +
- "<option value=\"A\">A</option>\n" +
- "<option value=\"B\">B</option>\n" +
- "<option value=\"C\">C</option>\n" +
- "<option value=\"D\" selected=\"selected\">D</option>\n" +
- "<option value=\"E\">E</option>" +
- "</select>",
- html
+ assert_dom_equal(
+ %{<select id="post_author_name" name="post[author_name]"><option value=""></option>\n<option value="&lt;Abe&gt;" selected="selected">&lt;Abe&gt;</option>\n<option value="Babe">Babe</option>\n<option value="Cabe">Cabe</option></select>},
+ collection_select("post", "author_name", @posts, "author_name", "author_name", {:include_blank => true, :selected => "<Abe>"})
+ )
+ end
+
+ def test_time_zone_select
+ @firm = Firm.new("D")
+ html = time_zone_select( "firm", "time_zone" )
+ assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\" selected=\"selected\">D</option>\n" +
+ "<option value=\"E\">E</option>" +
+ "</select>",
+ html
+ end
+
+ def test_time_zone_select_under_fields_for
+ @firm = Firm.new("D")
+
+ fields_for :firm, @firm do |f|
+ concat f.time_zone_select(:time_zone)
end
+
+ assert_dom_equal(
+ "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\" selected=\"selected\">D</option>\n" +
+ "<option value=\"E\">E</option>" +
+ "</select>",
+ output_buffer
+ )
+ end
- def test_time_zone_select_under_fields_for
- @firm = Firm.new("D")
+ def test_time_zone_select_under_fields_for_with_index
+ @firm = Firm.new("D")
- fields_for :firm, @firm do |f|
- concat f.time_zone_select(:time_zone)
- end
-
- assert_dom_equal(
- "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" +
- "<option value=\"A\">A</option>\n" +
- "<option value=\"B\">B</option>\n" +
- "<option value=\"C\">C</option>\n" +
- "<option value=\"D\" selected=\"selected\">D</option>\n" +
- "<option value=\"E\">E</option>" +
- "</select>",
- output_buffer
- )
+ fields_for :firm, @firm, :index => 305 do |f|
+ concat f.time_zone_select(:time_zone)
end
- def test_time_zone_select_under_fields_for_with_index
- @firm = Firm.new("D")
+ assert_dom_equal(
+ "<select id=\"firm_305_time_zone\" name=\"firm[305][time_zone]\">" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\" selected=\"selected\">D</option>\n" +
+ "<option value=\"E\">E</option>" +
+ "</select>",
+ output_buffer
+ )
+ end
- fields_for :firm, @firm, :index => 305 do |f|
- concat f.time_zone_select(:time_zone)
- end
+ def test_time_zone_select_under_fields_for_with_auto_index
+ @firm = Firm.new("D")
+ def @firm.to_param; 305; end
- assert_dom_equal(
- "<select id=\"firm_305_time_zone\" name=\"firm[305][time_zone]\">" +
- "<option value=\"A\">A</option>\n" +
- "<option value=\"B\">B</option>\n" +
- "<option value=\"C\">C</option>\n" +
- "<option value=\"D\" selected=\"selected\">D</option>\n" +
- "<option value=\"E\">E</option>" +
- "</select>",
- output_buffer
- )
+ fields_for "firm[]", @firm do |f|
+ concat f.time_zone_select(:time_zone)
end
- def test_time_zone_select_under_fields_for_with_auto_index
- @firm = Firm.new("D")
- def @firm.to_param; 305; end
+ assert_dom_equal(
+ "<select id=\"firm_305_time_zone\" name=\"firm[305][time_zone]\">" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\" selected=\"selected\">D</option>\n" +
+ "<option value=\"E\">E</option>" +
+ "</select>",
+ output_buffer
+ )
+ end
- fields_for "firm[]", @firm do |f|
- concat f.time_zone_select(:time_zone)
- end
+ def test_time_zone_select_with_blank
+ @firm = Firm.new("D")
+ html = time_zone_select("firm", "time_zone", nil, :include_blank => true)
+ assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" +
+ "<option value=\"\"></option>\n" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\" selected=\"selected\">D</option>\n" +
+ "<option value=\"E\">E</option>" +
+ "</select>",
+ html
+ end
- assert_dom_equal(
- "<select id=\"firm_305_time_zone\" name=\"firm[305][time_zone]\">" +
- "<option value=\"A\">A</option>\n" +
- "<option value=\"B\">B</option>\n" +
- "<option value=\"C\">C</option>\n" +
- "<option value=\"D\" selected=\"selected\">D</option>\n" +
- "<option value=\"E\">E</option>" +
- "</select>",
- output_buffer
- )
- end
+ def test_time_zone_select_with_blank_as_string
+ @firm = Firm.new("D")
+ html = time_zone_select("firm", "time_zone", nil, :include_blank => 'No Zone')
+ assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" +
+ "<option value=\"\">No Zone</option>\n" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\" selected=\"selected\">D</option>\n" +
+ "<option value=\"E\">E</option>" +
+ "</select>",
+ html
+ end
- def test_time_zone_select_with_blank
- @firm = Firm.new("D")
- html = time_zone_select("firm", "time_zone", nil, :include_blank => true)
- assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" +
- "<option value=\"\"></option>\n" +
- "<option value=\"A\">A</option>\n" +
- "<option value=\"B\">B</option>\n" +
- "<option value=\"C\">C</option>\n" +
- "<option value=\"D\" selected=\"selected\">D</option>\n" +
- "<option value=\"E\">E</option>" +
- "</select>",
- html
- end
+ def test_time_zone_select_with_style
+ @firm = Firm.new("D")
+ html = time_zone_select("firm", "time_zone", nil, {},
+ "style" => "color: red")
+ assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\" style=\"color: red\">" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\" selected=\"selected\">D</option>\n" +
+ "<option value=\"E\">E</option>" +
+ "</select>",
+ html
+ assert_dom_equal html, time_zone_select("firm", "time_zone", nil, {},
+ :style => "color: red")
+ end
- def test_time_zone_select_with_blank_as_string
- @firm = Firm.new("D")
- html = time_zone_select("firm", "time_zone", nil, :include_blank => 'No Zone')
- assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" +
- "<option value=\"\">No Zone</option>\n" +
- "<option value=\"A\">A</option>\n" +
- "<option value=\"B\">B</option>\n" +
- "<option value=\"C\">C</option>\n" +
- "<option value=\"D\" selected=\"selected\">D</option>\n" +
- "<option value=\"E\">E</option>" +
- "</select>",
- html
- end
+ def test_time_zone_select_with_blank_and_style
+ @firm = Firm.new("D")
+ html = time_zone_select("firm", "time_zone", nil,
+ { :include_blank => true }, "style" => "color: red")
+ assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\" style=\"color: red\">" +
+ "<option value=\"\"></option>\n" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\" selected=\"selected\">D</option>\n" +
+ "<option value=\"E\">E</option>" +
+ "</select>",
+ html
+ assert_dom_equal html, time_zone_select("firm", "time_zone", nil,
+ { :include_blank => true }, :style => "color: red")
+ end
- def test_time_zone_select_with_style
- @firm = Firm.new("D")
- html = time_zone_select("firm", "time_zone", nil, {},
- "style" => "color: red")
- assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\" style=\"color: red\">" +
- "<option value=\"A\">A</option>\n" +
- "<option value=\"B\">B</option>\n" +
- "<option value=\"C\">C</option>\n" +
- "<option value=\"D\" selected=\"selected\">D</option>\n" +
- "<option value=\"E\">E</option>" +
- "</select>",
- html
- assert_dom_equal html, time_zone_select("firm", "time_zone", nil, {},
- :style => "color: red")
- end
+ def test_time_zone_select_with_blank_as_string_and_style
+ @firm = Firm.new("D")
+ html = time_zone_select("firm", "time_zone", nil,
+ { :include_blank => 'No Zone' }, "style" => "color: red")
+ assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\" style=\"color: red\">" +
+ "<option value=\"\">No Zone</option>\n" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\" selected=\"selected\">D</option>\n" +
+ "<option value=\"E\">E</option>" +
+ "</select>",
+ html
+ assert_dom_equal html, time_zone_select("firm", "time_zone", nil,
+ { :include_blank => 'No Zone' }, :style => "color: red")
+ end
- def test_time_zone_select_with_blank_and_style
- @firm = Firm.new("D")
- html = time_zone_select("firm", "time_zone", nil,
- { :include_blank => true }, "style" => "color: red")
- assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\" style=\"color: red\">" +
- "<option value=\"\"></option>\n" +
- "<option value=\"A\">A</option>\n" +
- "<option value=\"B\">B</option>\n" +
- "<option value=\"C\">C</option>\n" +
- "<option value=\"D\" selected=\"selected\">D</option>\n" +
- "<option value=\"E\">E</option>" +
- "</select>",
- html
- assert_dom_equal html, time_zone_select("firm", "time_zone", nil,
- { :include_blank => true }, :style => "color: red")
- end
+ def test_time_zone_select_with_priority_zones
+ @firm = Firm.new("D")
+ zones = [ ActiveSupport::TimeZone.new("A"), ActiveSupport::TimeZone.new("D") ]
+ html = time_zone_select("firm", "time_zone", zones )
+ assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"D\" selected=\"selected\">D</option>" +
+ "<option value=\"\" disabled=\"disabled\">-------------</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"E\">E</option>" +
+ "</select>",
+ html
+ end
- def test_time_zone_select_with_blank_as_string_and_style
- @firm = Firm.new("D")
- html = time_zone_select("firm", "time_zone", nil,
- { :include_blank => 'No Zone' }, "style" => "color: red")
- assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\" style=\"color: red\">" +
- "<option value=\"\">No Zone</option>\n" +
- "<option value=\"A\">A</option>\n" +
- "<option value=\"B\">B</option>\n" +
- "<option value=\"C\">C</option>\n" +
- "<option value=\"D\" selected=\"selected\">D</option>\n" +
- "<option value=\"E\">E</option>" +
- "</select>",
- html
- assert_dom_equal html, time_zone_select("firm", "time_zone", nil,
- { :include_blank => 'No Zone' }, :style => "color: red")
- end
+ def test_time_zone_select_with_priority_zones_as_regexp
+ @firm = Firm.new("D")
+ @fake_timezones.each_with_index do |tz, i|
+ tz.stubs(:=~).returns(i.zero? || i == 3)
+ end
+
+ html = time_zone_select("firm", "time_zone", /A|D/)
+ assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"D\" selected=\"selected\">D</option>" +
+ "<option value=\"\" disabled=\"disabled\">-------------</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"E\">E</option>" +
+ "</select>",
+ html
+ end
- def test_time_zone_select_with_priority_zones
- @firm = Firm.new("D")
- zones = [ ActiveSupport::TimeZone.new("A"), ActiveSupport::TimeZone.new("D") ]
- html = time_zone_select("firm", "time_zone", zones )
+ def test_time_zone_select_with_default_time_zone_and_nil_value
+ @firm = Firm.new()
+ @firm.time_zone = nil
+ html = time_zone_select( "firm", "time_zone", nil, :default => 'B' )
assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" +
"<option value=\"A\">A</option>\n" +
- "<option value=\"D\" selected=\"selected\">D</option>" +
- "<option value=\"\" disabled=\"disabled\">-------------</option>\n" +
- "<option value=\"B\">B</option>\n" +
+ "<option value=\"B\" selected=\"selected\">B</option>\n" +
"<option value=\"C\">C</option>\n" +
+ "<option value=\"D\">D</option>\n" +
"<option value=\"E\">E</option>" +
"</select>",
html
- end
-
- def test_time_zone_select_with_priority_zones_as_regexp
- @firm = Firm.new("D")
- @fake_timezones.each_with_index do |tz, i|
- tz.stubs(:=~).returns(i.zero? || i == 3)
- end
+ end
- html = time_zone_select("firm", "time_zone", /A|D/)
+ def test_time_zone_select_with_default_time_zone_and_value
+ @firm = Firm.new('D')
+ html = time_zone_select( "firm", "time_zone", nil, :default => 'B' )
assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" +
"<option value=\"A\">A</option>\n" +
- "<option value=\"D\" selected=\"selected\">D</option>" +
- "<option value=\"\" disabled=\"disabled\">-------------</option>\n" +
"<option value=\"B\">B</option>\n" +
"<option value=\"C\">C</option>\n" +
+ "<option value=\"D\" selected=\"selected\">D</option>\n" +
"<option value=\"E\">E</option>" +
"</select>",
html
- end
-
- def test_time_zone_select_with_default_time_zone_and_nil_value
- @firm = Firm.new()
- @firm.time_zone = nil
- html = time_zone_select( "firm", "time_zone", nil, :default => 'B' )
- assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" +
- "<option value=\"A\">A</option>\n" +
- "<option value=\"B\" selected=\"selected\">B</option>\n" +
- "<option value=\"C\">C</option>\n" +
- "<option value=\"D\">D</option>\n" +
- "<option value=\"E\">E</option>" +
- "</select>",
- html
- end
-
- def test_time_zone_select_with_default_time_zone_and_value
- @firm = Firm.new('D')
- html = time_zone_select( "firm", "time_zone", nil, :default => 'B' )
- assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" +
- "<option value=\"A\">A</option>\n" +
- "<option value=\"B\">B</option>\n" +
- "<option value=\"C\">C</option>\n" +
- "<option value=\"D\" selected=\"selected\">D</option>\n" +
- "<option value=\"E\">E</option>" +
- "</select>",
- html
- end
-
end
+
end
diff --git a/actionpack/test/template/number_helper_i18n_test.rb b/actionpack/test/template/number_helper_i18n_test.rb
index 3fdf991a44..bf5b81292f 100644
--- a/actionpack/test/template/number_helper_i18n_test.rb
+++ b/actionpack/test/template/number_helper_i18n_test.rb
@@ -5,67 +5,65 @@ class NumberHelperI18nTests < Test::Unit::TestCase
attr_reader :request
- uses_mocha 'number_helper_i18n_tests' do
- def setup
- @number_defaults = { :precision => 3, :delimiter => ',', :separator => '.' }
- @currency_defaults = { :unit => '$', :format => '%u%n', :precision => 2 }
- @human_defaults = { :precision => 1 }
- @human_storage_units_format_default = "%n %u"
- @human_storage_units_units_byte_other = "Bytes"
- @human_storage_units_units_kb_other = "KB"
- @percentage_defaults = { :delimiter => '' }
- @precision_defaults = { :delimiter => '' }
+ def setup
+ @number_defaults = { :precision => 3, :delimiter => ',', :separator => '.' }
+ @currency_defaults = { :unit => '$', :format => '%u%n', :precision => 2 }
+ @human_defaults = { :precision => 1 }
+ @human_storage_units_format_default = "%n %u"
+ @human_storage_units_units_byte_other = "Bytes"
+ @human_storage_units_units_kb_other = "KB"
+ @percentage_defaults = { :delimiter => '' }
+ @precision_defaults = { :delimiter => '' }
- I18n.backend.store_translations 'en', :number => { :format => @number_defaults,
- :currency => { :format => @currency_defaults }, :human => @human_defaults }
- end
+ I18n.backend.store_translations 'en', :number => { :format => @number_defaults,
+ :currency => { :format => @currency_defaults }, :human => @human_defaults }
+ end
- def test_number_to_currency_translates_currency_formats
- I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults)
- I18n.expects(:translate).with(:'number.currency.format', :locale => 'en',
- :raise => true).returns(@currency_defaults)
- number_to_currency(1, :locale => 'en')
- end
+ def test_number_to_currency_translates_currency_formats
+ I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults)
+ I18n.expects(:translate).with(:'number.currency.format', :locale => 'en',
+ :raise => true).returns(@currency_defaults)
+ number_to_currency(1, :locale => 'en')
+ end
- def test_number_with_precision_translates_number_formats
- I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults)
- I18n.expects(:translate).with(:'number.precision.format', :locale => 'en',
- :raise => true).returns(@precision_defaults)
- number_with_precision(1, :locale => 'en')
- end
+ def test_number_with_precision_translates_number_formats
+ I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults)
+ I18n.expects(:translate).with(:'number.precision.format', :locale => 'en',
+ :raise => true).returns(@precision_defaults)
+ number_with_precision(1, :locale => 'en')
+ end
- def test_number_with_delimiter_translates_number_formats
- I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults)
- number_with_delimiter(1, :locale => 'en')
- end
+ def test_number_with_delimiter_translates_number_formats
+ I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults)
+ number_with_delimiter(1, :locale => 'en')
+ end
- def test_number_to_percentage_translates_number_formats
- I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults)
- I18n.expects(:translate).with(:'number.percentage.format', :locale => 'en',
- :raise => true).returns(@percentage_defaults)
- number_to_percentage(1, :locale => 'en')
- end
+ def test_number_to_percentage_translates_number_formats
+ I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults)
+ I18n.expects(:translate).with(:'number.percentage.format', :locale => 'en',
+ :raise => true).returns(@percentage_defaults)
+ number_to_percentage(1, :locale => 'en')
+ end
- def test_number_to_human_size_translates_human_formats
- I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults)
- I18n.expects(:translate).with(:'number.human.format', :locale => 'en',
- :raise => true).returns(@human_defaults)
- I18n.expects(:translate).with(:'number.human.storage_units.format', :locale => 'en',
- :raise => true).returns(@human_storage_units_format_default)
- I18n.expects(:translate).with(:'number.human.storage_units.units.kb', :locale => 'en', :count => 2,
- :raise => true).returns(@human_storage_units_units_kb_other)
- # 2KB
- number_to_human_size(2048, :locale => 'en')
+ def test_number_to_human_size_translates_human_formats
+ I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults)
+ I18n.expects(:translate).with(:'number.human.format', :locale => 'en',
+ :raise => true).returns(@human_defaults)
+ I18n.expects(:translate).with(:'number.human.storage_units.format', :locale => 'en',
+ :raise => true).returns(@human_storage_units_format_default)
+ I18n.expects(:translate).with(:'number.human.storage_units.units.kb', :locale => 'en', :count => 2,
+ :raise => true).returns(@human_storage_units_units_kb_other)
+ # 2KB
+ number_to_human_size(2048, :locale => 'en')
- I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults)
- I18n.expects(:translate).with(:'number.human.format', :locale => 'en',
- :raise => true).returns(@human_defaults)
- I18n.expects(:translate).with(:'number.human.storage_units.format', :locale => 'en',
- :raise => true).returns(@human_storage_units_format_default)
- I18n.expects(:translate).with(:'number.human.storage_units.units.byte', :locale => 'en', :count => 42,
- :raise => true).returns(@human_storage_units_units_byte_other)
- # 42 Bytes
- number_to_human_size(42, :locale => 'en')
- end
+ I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults)
+ I18n.expects(:translate).with(:'number.human.format', :locale => 'en',
+ :raise => true).returns(@human_defaults)
+ I18n.expects(:translate).with(:'number.human.storage_units.format', :locale => 'en',
+ :raise => true).returns(@human_storage_units_format_default)
+ I18n.expects(:translate).with(:'number.human.storage_units.units.byte', :locale => 'en', :count => 42,
+ :raise => true).returns(@human_storage_units_units_byte_other)
+ # 42 Bytes
+ number_to_human_size(42, :locale => 'en')
end
end
diff --git a/actionpack/test/template/test_test.rb b/actionpack/test/template/test_test.rb
index 660f51b3be..ccd299f46a 100644
--- a/actionpack/test/template/test_test.rb
+++ b/actionpack/test/template/test_test.rb
@@ -38,12 +38,10 @@ class PeopleHelperTest < ActionView::TestCase
assert_equal "http://test.host/people", homepage_url
end
- uses_mocha "link_to_person" do
- def test_link_to_person
- person = mock(:name => "David")
- expects(:mocha_mock_path).with(person).returns("/people/1")
- assert_equal '<a href="/people/1">David</a>', link_to_person(person)
- end
+ def test_link_to_person
+ person = mock(:name => "David")
+ expects(:mocha_mock_path).with(person).returns("/people/1")
+ assert_equal '<a href="/people/1">David</a>', link_to_person(person)
end
end
diff --git a/actionpack/test/template/translation_helper_test.rb b/actionpack/test/template/translation_helper_test.rb
index d0d65cb450..6534df6bbd 100644
--- a/actionpack/test/template/translation_helper_test.rb
+++ b/actionpack/test/template/translation_helper_test.rb
@@ -5,24 +5,22 @@ class TranslationHelperTest < Test::Unit::TestCase
include ActionView::Helpers::TranslationHelper
attr_reader :request
- uses_mocha 'translation_helper_test' do
- def setup
- end
-
- def test_delegates_to_i18n_setting_the_raise_option
- I18n.expects(:translate).with(:foo, :locale => 'en', :raise => true)
- translate :foo, :locale => 'en'
- end
-
- def test_returns_missing_translation_message_wrapped_into_span
- expected = '<span class="translation_missing">en, foo</span>'
- assert_equal expected, translate(:foo)
- end
+ def setup
+ end
+
+ def test_delegates_to_i18n_setting_the_raise_option
+ I18n.expects(:translate).with(:foo, :locale => 'en', :raise => true)
+ translate :foo, :locale => 'en'
+ end
- def test_delegates_localize_to_i18n
- @time = Time.utc(2008, 7, 8, 12, 18, 38)
- I18n.expects(:localize).with(@time)
- localize @time
- end
+ def test_returns_missing_translation_message_wrapped_into_span
+ expected = '<span class="translation_missing">en, foo</span>'
+ assert_equal expected, translate(:foo)
+ end
+
+ def test_delegates_localize_to_i18n
+ @time = Time.utc(2008, 7, 8, 12, 18, 38)
+ I18n.expects(:localize).with(@time)
+ localize @time
end
-end \ No newline at end of file
+end
diff --git a/actionpack/test/template/url_helper_test.rb b/actionpack/test/template/url_helper_test.rb
index 2f6fa134b5..e7799fb204 100644
--- a/actionpack/test/template/url_helper_test.rb
+++ b/actionpack/test/template/url_helper_test.rb
@@ -252,6 +252,27 @@ class UrlHelperTest < ActionView::TestCase
assert_equal "Showing", link_to_if(false, "Showing", :action => "show", :controller => "weblog", :id => 1)
end
+ def test_current_page_with_simple_url
+ @controller.request = RequestMock.new("http://www.example.com/weblog/show")
+ @controller.url = "http://www.example.com/weblog/show"
+ assert current_page?({ :action => "show", :controller => "weblog" })
+ assert current_page?("http://www.example.com/weblog/show")
+ end
+
+ def test_current_page_ignoring_params
+ @controller.request = RequestMock.new("http://www.example.com/weblog/show?order=desc&page=1")
+ @controller.url = "http://www.example.com/weblog/show?order=desc&page=1"
+ assert current_page?({ :action => "show", :controller => "weblog" })
+ assert current_page?("http://www.example.com/weblog/show")
+ end
+
+ def test_current_page_with_params_that_match
+ @controller.request = RequestMock.new("http://www.example.com/weblog/show?order=desc&page=1")
+ @controller.url = "http://www.example.com/weblog/show?order=desc&page=1"
+ assert current_page?({ :action => "show", :controller => "weblog", :order => "desc", :page => "1" })
+ assert current_page?("http://www.example.com/weblog/show?order=desc&amp;page=1")
+ end
+
def test_link_unless_current
@controller.request = RequestMock.new("http://www.example.com/weblog/show")
@controller.url = "http://www.example.com/weblog/show"
@@ -263,11 +284,23 @@ class UrlHelperTest < ActionView::TestCase
assert_equal "Showing", link_to_unless_current("Showing", { :action => "show", :controller => "weblog" })
assert_equal "Showing", link_to_unless_current("Showing", "http://www.example.com/weblog/show")
+ @controller.request = RequestMock.new("http://www.example.com/weblog/show?order=desc&page=1")
+ @controller.url = "http://www.example.com/weblog/show?order=desc&page=1"
+ assert_equal "Showing", link_to_unless_current("Showing", { :action => "show", :controller => "weblog", :order=>'desc', :page=>'1' })
+ assert_equal "Showing", link_to_unless_current("Showing", "http://www.example.com/weblog/show?order=desc&amp;page=1")
+ assert_equal "Showing", link_to_unless_current("Showing", "http://www.example.com/weblog/show?order=desc&page=1")
+
@controller.request = RequestMock.new("http://www.example.com/weblog/show?order=desc")
@controller.url = "http://www.example.com/weblog/show?order=asc"
assert_equal "<a href=\"http://www.example.com/weblog/show?order=asc\">Showing</a>", link_to_unless_current("Showing", { :action => "show", :controller => "weblog" })
assert_equal "<a href=\"http://www.example.com/weblog/show?order=asc\">Showing</a>", link_to_unless_current("Showing", "http://www.example.com/weblog/show?order=asc")
+ @controller.request = RequestMock.new("http://www.example.com/weblog/show?order=desc&page=1")
+ @controller.url = "http://www.example.com/weblog/show?order=desc&page=2"
+ assert_equal "<a href=\"http://www.example.com/weblog/show?order=desc&amp;page=2\">Showing</a>", link_to_unless_current("Showing", { :action => "show", :controller => "weblog" })
+ assert_equal "<a href=\"http://www.example.com/weblog/show?order=desc&amp;page=2\">Showing</a>", link_to_unless_current("Showing", "http://www.example.com/weblog/show?order=desc&page=2")
+
+
@controller.request = RequestMock.new("http://www.example.com/weblog/show")
@controller.url = "http://www.example.com/weblog/list"
assert_equal "<a href=\"http://www.example.com/weblog/list\">Listing</a>",
@@ -319,7 +352,7 @@ class UrlHelperTest < ActionView::TestCase
assert_dom_equal "<script type=\"text/javascript\">eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%22%3e%4d%79%20%65%6d%61%69%6c%3c%2f%61%3e%27%29%3b'))</script>", mail_to("me@domain.com", "My email", :encode => "javascript", :replace_at => "(at)", :replace_dot => "(dot)")
assert_dom_equal "<script type=\"text/javascript\">eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%22%3e%6d%65%28%61%74%29%64%6f%6d%61%69%6e%28%64%6f%74%29%63%6f%6d%3c%2f%61%3e%27%29%3b'))</script>", mail_to("me@domain.com", nil, :encode => "javascript", :replace_at => "(at)", :replace_dot => "(dot)")
end
-
+
def protect_against_forgery?
false
end
diff --git a/activerecord/CHANGELOG b/activerecord/CHANGELOG
index 027533aa2d..a63c09bbaa 100644
--- a/activerecord/CHANGELOG
+++ b/activerecord/CHANGELOG
@@ -1,3 +1,8 @@
+*Edge*
+
+* Added that ActiveRecord::Base.exists? can be called with no arguments #1817 [Scott Taylor]
+
+
*2.3.0 [RC1] (February 1st, 2009)*
* Add Support for updating deeply nested models from a single form. #1202 [Eloy Duran]
diff --git a/activerecord/lib/active_record/attribute_methods.rb b/activerecord/lib/active_record/attribute_methods.rb
index 177d156834..3ffc48941c 100644
--- a/activerecord/lib/active_record/attribute_methods.rb
+++ b/activerecord/lib/active_record/attribute_methods.rb
@@ -324,6 +324,7 @@ module ActiveRecord
if Numeric === value || value !~ /[^0-9]/
!value.to_i.zero?
else
+ return false if ActiveRecord::ConnectionAdapters::Column::FALSE_VALUES.include?(value)
!value.blank?
end
elsif column.number?
diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb
index 07660ebd03..680b41518c 100644
--- a/activerecord/lib/active_record/autosave_association.rb
+++ b/activerecord/lib/active_record/autosave_association.rb
@@ -129,6 +129,7 @@ module ActiveRecord
base.class_eval do
alias_method_chain :reload, :autosave_associations
alias_method_chain :save, :autosave_associations
+ alias_method_chain :save!, :autosave_associations
alias_method_chain :valid?, :autosave_associations
%w{ has_one belongs_to has_many has_and_belongs_to_many }.each do |type|
@@ -161,6 +162,17 @@ module ActiveRecord
end
end
+ # Attempts to save the record just like save_with_autosave_associations but
+ # will raise a RecordInvalid exception instead of returning false if the
+ # record is not valid.
+ def save_with_autosave_associations!
+ if valid_with_autosave_associations?
+ save_with_autosave_associations(false) || raise(RecordNotSaved)
+ else
+ raise RecordInvalid.new(self)
+ end
+ end
+
# Returns whether or not the parent, <tt>self</tt>, and any loaded autosave associations are valid.
def valid_with_autosave_associations?
if valid_without_autosave_associations?
diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb
index f9168c8dc2..78c6ac2ba8 100755
--- a/activerecord/lib/active_record/base.rb
+++ b/activerecord/lib/active_record/base.rb
@@ -663,7 +663,7 @@ module ActiveRecord #:nodoc:
# Returns true if a record exists in the table that matches the +id+ or
- # conditions given, or false otherwise. The argument can take four forms:
+ # conditions given, or false otherwise. The argument can take five forms:
#
# * Integer - Finds the record with this primary key.
# * String - Finds the record with a primary key corresponding to this
@@ -672,6 +672,7 @@ module ActiveRecord #:nodoc:
# (such as <tt>['color = ?', 'red']</tt>).
# * Hash - Finds the record that matches these +find+-style conditions
# (such as <tt>{:color => 'red'}</tt>).
+ # * No args - Returns false if the table is empty, true otherwise.
#
# For more information about specifying conditions as a Hash or Array,
# see the Conditions section in the introduction to ActiveRecord::Base.
@@ -685,7 +686,8 @@ module ActiveRecord #:nodoc:
# Person.exists?('5')
# Person.exists?(:name => "David")
# Person.exists?(['name LIKE ?', "%#{query}%"])
- def exists?(id_or_conditions)
+ # Person.exists?
+ def exists?(id_or_conditions = {})
connection.select_all(
construct_finder_sql(
:select => "#{quoted_table_name}.#{primary_key}",
@@ -1990,12 +1992,16 @@ module ActiveRecord #:nodoc:
attribute_names.all? { |name| column_methods_hash.include?(name.to_sym) }
end
- def attribute_condition(argument)
+ def attribute_condition(quoted_column_name, argument)
case argument
- when nil then "IS ?"
- when Array, ActiveRecord::Associations::AssociationCollection, ActiveRecord::NamedScope::Scope then "IN (?)"
- when Range then "BETWEEN ? AND ?"
- else "= ?"
+ when nil then "#{quoted_column_name} IS ?"
+ when Array, ActiveRecord::Associations::AssociationCollection, ActiveRecord::NamedScope::Scope then "#{quoted_column_name} IN (?)"
+ when Range then if argument.exclude_end?
+ "#{quoted_column_name} >= ? AND #{quoted_column_name} < ?"
+ else
+ "#{quoted_column_name} BETWEEN ? AND ?"
+ end
+ else "#{quoted_column_name} = ?"
end
end
@@ -2305,7 +2311,7 @@ module ActiveRecord #:nodoc:
table_name = connection.quote_table_name(table_name)
end
- "#{table_name}.#{connection.quote_column_name(attr)} #{attribute_condition(value)}"
+ attribute_condition("#{table_name}.#{connection.quote_column_name(attr)}", value)
else
sanitize_sql_hash_for_conditions(value, connection.quote_table_name(attr.to_s))
end
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 273f823e7f..24c734cddb 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
@@ -8,6 +8,7 @@ module ActiveRecord
# An abstract definition of a column in a table.
class Column
TRUE_VALUES = [true, 1, '1', 't', 'T', 'true', 'TRUE'].to_set
+ FALSE_VALUES = [false, 0, '0', 'f', 'F', 'false', 'FALSE'].to_set
module Format
ISO_DATE = /\A(\d{4})-(\d\d)-(\d\d)\z/
diff --git a/activerecord/lib/active_record/nested_attributes.rb b/activerecord/lib/active_record/nested_attributes.rb
index 8bfdadd0e3..5778223c74 100644
--- a/activerecord/lib/active_record/nested_attributes.rb
+++ b/activerecord/lib/active_record/nested_attributes.rb
@@ -86,7 +86,8 @@ module ActiveRecord
# For each key in the hash that starts with the string 'new' a new model
# will be instantiated. When the proc given with the <tt>:reject_if</tt>
# option evaluates to +false+ for a certain attribute hash no record will
- # be built for that hash.
+ # be built for that hash. (Rejecting new records can alternatively be done
+ # by utilizing the <tt>'_delete'</tt> key. Scroll down for more info.)
#
# params = { 'member' => {
# 'name' => 'joe', 'posts_attributes' => {
@@ -258,11 +259,14 @@ module ActiveRecord
# If a <tt>:reject_if</tt> proc exists for this association, it will be
# called with the attributes as its argument. If the proc returns a truthy
# value, the record is _not_ build.
+ #
+ # Alternatively, you can specify the <tt>'_delete'</tt> key to _not_ build
+ # a record. See should_destroy_nested_attributes_record? for more info.
def build_new_nested_attributes_record(association_name, attributes)
if reject_proc = self.class.reject_new_nested_attributes_procs[association_name]
return if reject_proc.call(attributes)
end
- send(association_name).build(attributes)
+ send(association_name).build(attributes) unless should_destroy_nested_attributes_record?(true, attributes)
end
# Assigns the attributes to the record specified by +id+. Or marks it for
diff --git a/activerecord/lib/active_record/session_store.rb b/activerecord/lib/active_record/session_store.rb
index 5e45cf65ab..de199d30bf 100644
--- a/activerecord/lib/active_record/session_store.rb
+++ b/activerecord/lib/active_record/session_store.rb
@@ -99,7 +99,7 @@ module ActiveRecord
define_method(:session_id=) { |session_id| self.sessid = session_id }
else
def self.find_by_session_id(session_id)
- find :first, :conditions => ["session_id #{attribute_condition(session_id)}", session_id]
+ find :first, :conditions => {:session_id=>session_id}
end
end
end
diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb
index ce93b0f270..8f3c80565e 100644
--- a/activerecord/lib/active_record/validations.rb
+++ b/activerecord/lib/active_record/validations.rb
@@ -744,7 +744,7 @@ module ActiveRecord
if scope = configuration[:scope]
Array(scope).map do |scope_item|
scope_value = record.send(scope_item)
- condition_sql << " AND #{record.class.quoted_table_name}.#{scope_item} #{attribute_condition(scope_value)}"
+ condition_sql << " AND " << attribute_condition("#{record.class.quoted_table_name}.#{scope_item}", scope_value)
condition_params << scope_value
end
end
diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
index 1e3b423471..0f43d97f4a 100644
--- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
@@ -767,12 +767,10 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
assert_equal 1, developer.projects.count
end
- uses_mocha 'mocking Post.transaction' do
- def test_association_proxy_transaction_method_starts_transaction_in_association_class
- Post.expects(:transaction)
- Category.find(:first).posts.transaction do
- # nothing
- end
+ def test_association_proxy_transaction_method_starts_transaction_in_association_class
+ Post.expects(:transaction)
+ Category.find(:first).posts.transaction do
+ # nothing
end
end
diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb
index 428fb50013..a2525f1d70 100644
--- a/activerecord/test/cases/associations/has_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_associations_test.rb
@@ -1097,12 +1097,10 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
ActiveRecord::Base.store_full_sti_class = old
end
- uses_mocha 'mocking Comment.transaction' do
- def test_association_proxy_transaction_method_starts_transaction_in_association_class
- Comment.expects(:transaction)
- Post.find(:first).comments.transaction do
- # nothing
- end
+ def test_association_proxy_transaction_method_starts_transaction_in_association_class
+ Comment.expects(:transaction)
+ Post.find(:first).comments.transaction do
+ # nothing
end
end
diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb
index ad6a5d6840..1e5d1a0202 100644
--- a/activerecord/test/cases/associations/has_many_through_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb
@@ -228,12 +228,10 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
assert !person.posts.loaded?
end
- uses_mocha 'mocking Tag.transaction' do
- def test_association_proxy_transaction_method_starts_transaction_in_association_class
- Tag.expects(:transaction)
- Post.find(:first).tags.transaction do
- # nothing
- end
+ def test_association_proxy_transaction_method_starts_transaction_in_association_class
+ Tag.expects(:transaction)
+ Post.find(:first).tags.transaction do
+ # nothing
end
end
diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb
index 7a0427aabc..b1060d01af 100644
--- a/activerecord/test/cases/associations/join_model_test.rb
+++ b/activerecord/test/cases/associations/join_model_test.rb
@@ -510,13 +510,11 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
assert !author.comments.loaded?
end
- uses_mocha('has_many_through_collection_size_uses_counter_cache_if_it_exists') do
- def test_has_many_through_collection_size_uses_counter_cache_if_it_exists
- author = authors(:david)
- author.stubs(:read_attribute).with('comments_count').returns(100)
- assert_equal 100, author.comments.size
- assert !author.comments.loaded?
- end
+ def test_has_many_through_collection_size_uses_counter_cache_if_it_exists
+ author = authors(:david)
+ author.stubs(:read_attribute).with('comments_count').returns(100)
+ assert_equal 100, author.comments.size
+ assert !author.comments.loaded?
end
def test_adding_junk_to_has_many_through_should_raise_type_mismatch
diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb
index 77ee8d8fc4..759f9f3872 100644
--- a/activerecord/test/cases/attribute_methods_test.rb
+++ b/activerecord/test/cases/attribute_methods_test.rb
@@ -56,6 +56,18 @@ class AttributeMethodsTest < ActiveRecord::TestCase
assert_equal myobj, topic.content
end
+ def test_typecast_attribute_from_select_to_false
+ topic = Topic.create(:title => 'Budget')
+ topic = Topic.find(:first, :select => "topics.*, 1=2 as is_test")
+ assert !topic.is_test?
+ end
+
+ def test_typecast_attribute_from_select_to_true
+ topic = Topic.create(:title => 'Budget')
+ topic = Topic.find(:first, :select => "topics.*, 2=2 as is_test")
+ assert topic.is_test?
+ end
+
def test_kernel_methods_not_implemented_in_activerecord
%w(test name display y).each do |method|
assert !ActiveRecord::Base.instance_method_already_implemented?(method), "##{method} is defined"
diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb
index 3c656b2430..381249c0c2 100644
--- a/activerecord/test/cases/autosave_association_test.rb
+++ b/activerecord/test/cases/autosave_association_test.rb
@@ -169,6 +169,12 @@ class TestAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCase
assert_equal 'The Vile Insanity', @pirate.reload.ship.name
end
+ def test_should_automatically_save_bang_the_associated_model
+ @pirate.ship.name = 'The Vile Insanity'
+ @pirate.save!
+ assert_equal 'The Vile Insanity', @pirate.reload.ship.name
+ end
+
def test_should_automatically_validate_the_associated_model
@pirate.ship.name = ''
assert !@pirate.valid?
@@ -245,6 +251,12 @@ class TestAutosaveAssociationOnABelongsToAssociation < ActiveRecord::TestCase
assert_equal 'Arr', @ship.reload.pirate.catchphrase
end
+ def test_should_automatically_save_bang_the_associated_model
+ @ship.pirate.catchphrase = 'Arr'
+ @ship.save!
+ assert_equal 'Arr', @ship.reload.pirate.catchphrase
+ end
+
def test_should_automatically_validate_the_associated_model
@ship.pirate.catchphrase = ''
assert !@ship.valid?
@@ -298,6 +310,14 @@ module AutosaveAssociationOnACollectionAssociationTests
assert_equal new_names, @pirate.reload.send(@association_name).map(&:name)
end
+ def test_should_automatically_save_bang_the_associated_models
+ new_names = ['Grace OMalley', 'Privateers Greed']
+ @pirate.send(@association_name).each_with_index { |child, i| child.name = new_names[i] }
+
+ @pirate.save!
+ assert_equal new_names, @pirate.reload.send(@association_name).map(&:name)
+ end
+
def test_should_automatically_validate_the_associated_models
@pirate.send(@association_name).each { |child| child.name = '' }
@@ -347,7 +367,9 @@ module AutosaveAssociationOnACollectionAssociationTests
def test_should_not_load_the_associated_models_if_they_were_not_loaded_yet
assert_queries(1) { @pirate.catchphrase = 'Arr'; @pirate.save! }
- assert_queries(2) do
+ @pirate.send(@association_name).class # hack to load the target
+
+ assert_queries(3) do
@pirate.catchphrase = 'Yarr'
new_names = ['Grace OMalley', 'Privateers Greed']
@pirate.send(@association_name).each_with_index { |child, i| child.name = new_names[i] }
diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb
index 080f6a7007..5a4ed429b6 100644
--- a/activerecord/test/cases/calculations_test.rb
+++ b/activerecord/test/cases/calculations_test.rb
@@ -156,25 +156,23 @@ class CalculationsTest < ActiveRecord::TestCase
assert_equal 1, c[companies(:first_client)]
end
- uses_mocha 'group_by_non_numeric_foreign_key_association' do
- def test_should_group_by_association_with_non_numeric_foreign_key
- ActiveRecord::Base.connection.expects(:select_all).returns([{"count_all" => 1, "firm_id" => "ABC"}])
-
- firm = mock()
- firm.expects(:id).returns("ABC")
- firm.expects(:class).returns(Firm)
- Company.expects(:find).with(["ABC"]).returns([firm])
-
- column = mock()
- column.expects(:name).at_least_once.returns(:firm_id)
- column.expects(:type_cast).with("ABC").returns("ABC")
- Account.expects(:columns).at_least_once.returns([column])
-
- c = Account.count(:all, :group => :firm)
- first_key = c.keys.first
- assert_equal Firm, first_key.class
- assert_equal 1, c[first_key]
- end
+ def test_should_group_by_association_with_non_numeric_foreign_key
+ ActiveRecord::Base.connection.expects(:select_all).returns([{"count_all" => 1, "firm_id" => "ABC"}])
+
+ firm = mock()
+ firm.expects(:id).returns("ABC")
+ firm.expects(:class).returns(Firm)
+ Company.expects(:find).with(["ABC"]).returns([firm])
+
+ column = mock()
+ column.expects(:name).at_least_once.returns(:firm_id)
+ column.expects(:type_cast).with("ABC").returns("ABC")
+ Account.expects(:columns).at_least_once.returns([column])
+
+ c = Account.count(:all, :group => :firm)
+ first_key = c.keys.first
+ assert_equal Firm, first_key.class
+ assert_equal 1, c[first_key]
end
def test_should_calculate_grouped_association_with_foreign_key_option
diff --git a/activerecord/test/cases/datatype_test_postgresql.rb b/activerecord/test/cases/datatype_test_postgresql.rb
index bff092b5d7..88fb6f7384 100644
--- a/activerecord/test/cases/datatype_test_postgresql.rb
+++ b/activerecord/test/cases/datatype_test_postgresql.rb
@@ -26,6 +26,7 @@ class PostgresqlDataTypeTest < ActiveRecord::TestCase
def setup
@connection = ActiveRecord::Base.connection
+ @connection.execute("set lc_monetary = 'C'")
@connection.execute("INSERT INTO postgresql_arrays (commission_by_quarter, nicknames) VALUES ( '{35000,21000,18000,17000}', '{foo,bar,baz}' )")
@first_array = PostgresqlArray.find(1)
diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb
index d4d770b04e..ee8f4901f9 100644
--- a/activerecord/test/cases/finder_test.rb
+++ b/activerecord/test/cases/finder_test.rb
@@ -94,7 +94,16 @@ class FinderTest < ActiveRecord::TestCase
assert_raise(NoMethodError) { Topic.exists?([1,2]) }
end
-
+
+ def test_exists_returns_true_with_one_record_and_no_args
+ assert Topic.exists?
+ end
+
+ def test_does_not_exist_with_empty_table_and_no_args_given
+ Topic.delete_all
+ assert !Topic.exists?
+ end
+
def test_exists_with_aggregate_having_three_mappings
existing_address = customers(:david).address
assert Customer.exists?(:address => existing_address)
@@ -298,6 +307,12 @@ class FinderTest < ActiveRecord::TestCase
assert_raises(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => { :id => 2..3 }) }
end
+ def test_find_on_hash_conditions_with_end_exclusive_range
+ assert_equal [1,2,3], Topic.find(:all, :conditions => { :id => 1..3 }).map(&:id).sort
+ assert_equal [1,2], Topic.find(:all, :conditions => { :id => 1...3 }).map(&:id).sort
+ assert_raises(ActiveRecord::RecordNotFound) { Topic.find(3, :conditions => { :id => 2...3 }) }
+ end
+
def test_find_on_hash_conditions_with_multiple_ranges
assert_equal [1,2,3], Comment.find(:all, :conditions => { :id => 1..3, :post_id => 1..2 }).map(&:id).sort
assert_equal [1], Comment.find(:all, :conditions => { :id => 1..1, :post_id => 1..10 }).map(&:id).sort
@@ -507,21 +522,19 @@ class FinderTest < ActiveRecord::TestCase
assert_equal(2, Entrant.count_by_sql(["SELECT COUNT(*) FROM entrants WHERE id > ?", 1]))
end
- uses_mocha('test_dynamic_finder_should_go_through_the_find_class_method') do
- def test_dynamic_finders_should_go_through_the_find_class_method
- Topic.expects(:find).with(:first, :conditions => { :title => 'The First Topic!' })
- Topic.find_by_title("The First Topic!")
+ def test_dynamic_finders_should_go_through_the_find_class_method
+ Topic.expects(:find).with(:first, :conditions => { :title => 'The First Topic!' })
+ Topic.find_by_title("The First Topic!")
- Topic.expects(:find).with(:last, :conditions => { :title => 'The Last Topic!' })
- Topic.find_last_by_title("The Last Topic!")
+ Topic.expects(:find).with(:last, :conditions => { :title => 'The Last Topic!' })
+ Topic.find_last_by_title("The Last Topic!")
- Topic.expects(:find).with(:all, :conditions => { :title => 'A Topic.' })
- Topic.find_all_by_title("A Topic.")
+ Topic.expects(:find).with(:all, :conditions => { :title => 'A Topic.' })
+ Topic.find_all_by_title("A Topic.")
- Topic.expects(:find).with(:first, :conditions => { :title => 'Does not exist yet for sure!' }).times(2)
- Topic.find_or_initialize_by_title('Does not exist yet for sure!')
- Topic.find_or_create_by_title('Does not exist yet for sure!')
- end
+ Topic.expects(:find).with(:first, :conditions => { :title => 'Does not exist yet for sure!' }).times(2)
+ Topic.find_or_initialize_by_title('Does not exist yet for sure!')
+ Topic.find_or_create_by_title('Does not exist yet for sure!')
end
def test_find_by_one_attribute
diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb
index ed2915b023..eb63fd5f34 100644
--- a/activerecord/test/cases/fixtures_test.rb
+++ b/activerecord/test/cases/fixtures_test.rb
@@ -265,12 +265,10 @@ class FixturesWithoutInstantiationTest < ActiveRecord::TestCase
assert_raise(StandardError) { topics([:first, :second]) }
end
- uses_mocha 'reloading_fixtures_through_accessor_methods' do
- def test_reloading_fixtures_through_accessor_methods
- assert_equal "The First Topic", topics(:first).title
- @loaded_fixtures['topics']['first'].expects(:find).returns(stub(:title => "Fresh Topic!"))
- assert_equal "Fresh Topic!", topics(:first, true).title
- end
+ def test_reloading_fixtures_through_accessor_methods
+ assert_equal "The First Topic", topics(:first).title
+ @loaded_fixtures['topics']['first'].expects(:find).returns(stub(:title => "Fresh Topic!"))
+ assert_equal "Fresh Topic!", topics(:first, true).title
end
end
@@ -639,17 +637,15 @@ class ActiveSupportSubclassWithFixturesTest < ActiveRecord::TestCase
end
class FixtureLoadingTest < ActiveRecord::TestCase
- uses_mocha 'reloading_fixtures_through_accessor_methods' do
- def test_logs_message_for_failed_dependency_load
- ActiveRecord::TestCase.expects(:require_dependency).with(:does_not_exist).raises(LoadError)
- ActiveRecord::Base.logger.expects(:warn)
- ActiveRecord::TestCase.try_to_load_dependency(:does_not_exist)
- end
+ def test_logs_message_for_failed_dependency_load
+ ActiveRecord::TestCase.expects(:require_dependency).with(:does_not_exist).raises(LoadError)
+ ActiveRecord::Base.logger.expects(:warn)
+ ActiveRecord::TestCase.try_to_load_dependency(:does_not_exist)
+ end
- def test_does_not_logs_message_for_successful_dependency_load
- ActiveRecord::TestCase.expects(:require_dependency).with(:works_out_fine)
- ActiveRecord::Base.logger.expects(:warn).never
- ActiveRecord::TestCase.try_to_load_dependency(:works_out_fine)
- end
+ def test_does_not_logs_message_for_successful_dependency_load
+ ActiveRecord::TestCase.expects(:require_dependency).with(:works_out_fine)
+ ActiveRecord::Base.logger.expects(:warn).never
+ ActiveRecord::TestCase.try_to_load_dependency(:works_out_fine)
end
end
diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb
index 24ce35e2e2..1ec52ac24d 100644
--- a/activerecord/test/cases/helper.rb
+++ b/activerecord/test/cases/helper.rb
@@ -2,7 +2,11 @@ $:.unshift(File.dirname(__FILE__) + '/../../lib')
$:.unshift(File.dirname(__FILE__) + '/../../../activesupport/lib')
require 'config'
+
+require 'rubygems'
require 'test/unit'
+gem 'mocha', '>= 0.9.5'
+require 'mocha'
require 'active_record'
require 'active_record/test_case'
@@ -24,15 +28,6 @@ def current_adapter?(*types)
end
end
-def uses_mocha(description)
- require 'rubygems'
- gem 'mocha', '>= 0.9.3'
- require 'mocha'
- yield
-rescue LoadError
- $stderr.puts "Skipping #{description} tests. `gem install mocha` and try again."
-end
-
ActiveRecord::Base.connection.class.class_eval do
IGNORED_SQL = [/^PRAGMA/, /^SELECT currval/, /^SELECT CAST/, /^SELECT @@IDENTITY/, /^SELECT @@ROWCOUNT/, /^SAVEPOINT/, /^ROLLBACK TO SAVEPOINT/, /^RELEASE SAVEPOINT/, /SHOW FIELDS/]
diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb
index 2ec3d40332..1c974e4825 100644
--- a/activerecord/test/cases/migration_test.rb
+++ b/activerecord/test/cases/migration_test.rb
@@ -219,22 +219,20 @@ if ActiveRecord::Base.connection.supports_migrations?
ActiveRecord::Base.primary_key_prefix_type = nil
end
- uses_mocha('test_create_table_with_force_true_does_not_drop_nonexisting_table') do
- def test_create_table_with_force_true_does_not_drop_nonexisting_table
- if Person.connection.table_exists?(:testings2)
- Person.connection.drop_table :testings2
- end
+ def test_create_table_with_force_true_does_not_drop_nonexisting_table
+ if Person.connection.table_exists?(:testings2)
+ Person.connection.drop_table :testings2
+ end
- # using a copy as we need the drop_table method to
- # continue to work for the ensure block of the test
- temp_conn = Person.connection.dup
- temp_conn.expects(:drop_table).never
- temp_conn.create_table :testings2, :force => true do |t|
- t.column :foo, :string
- end
- ensure
- Person.connection.drop_table :testings2 rescue nil
+ # using a copy as we need the drop_table method to
+ # continue to work for the ensure block of the test
+ temp_conn = Person.connection.dup
+ temp_conn.expects(:drop_table).never
+ temp_conn.create_table :testings2, :force => true do |t|
+ t.column :foo, :string
end
+ ensure
+ Person.connection.drop_table :testings2 rescue nil
end
def test_create_table_with_timestamps_should_create_datetime_columns
@@ -1203,277 +1201,271 @@ if ActiveRecord::Base.connection.supports_migrations?
end
- uses_mocha 'Sexy migration tests' do
- class SexyMigrationsTest < ActiveRecord::TestCase
- def test_references_column_type_adds_id
- with_new_table do |t|
- t.expects(:column).with('customer_id', :integer, {})
- t.references :customer
- end
+ class SexyMigrationsTest < ActiveRecord::TestCase
+ def test_references_column_type_adds_id
+ with_new_table do |t|
+ t.expects(:column).with('customer_id', :integer, {})
+ t.references :customer
end
+ end
- def test_references_column_type_with_polymorphic_adds_type
- with_new_table do |t|
- t.expects(:column).with('taggable_type', :string, {})
- t.expects(:column).with('taggable_id', :integer, {})
- t.references :taggable, :polymorphic => true
- end
+ def test_references_column_type_with_polymorphic_adds_type
+ with_new_table do |t|
+ t.expects(:column).with('taggable_type', :string, {})
+ t.expects(:column).with('taggable_id', :integer, {})
+ t.references :taggable, :polymorphic => true
end
+ end
- def test_references_column_type_with_polymorphic_and_options_null_is_false_adds_table_flag
- with_new_table do |t|
- t.expects(:column).with('taggable_type', :string, {:null => false})
- t.expects(:column).with('taggable_id', :integer, {:null => false})
- t.references :taggable, :polymorphic => true, :null => false
- end
+ def test_references_column_type_with_polymorphic_and_options_null_is_false_adds_table_flag
+ with_new_table do |t|
+ t.expects(:column).with('taggable_type', :string, {:null => false})
+ t.expects(:column).with('taggable_id', :integer, {:null => false})
+ t.references :taggable, :polymorphic => true, :null => false
end
+ end
- def test_belongs_to_works_like_references
- with_new_table do |t|
- t.expects(:column).with('customer_id', :integer, {})
- t.belongs_to :customer
- end
+ def test_belongs_to_works_like_references
+ with_new_table do |t|
+ t.expects(:column).with('customer_id', :integer, {})
+ t.belongs_to :customer
end
+ end
- def test_timestamps_creates_updated_at_and_created_at
- with_new_table do |t|
- t.expects(:column).with(:created_at, :datetime, kind_of(Hash))
- t.expects(:column).with(:updated_at, :datetime, kind_of(Hash))
- t.timestamps
- end
+ def test_timestamps_creates_updated_at_and_created_at
+ with_new_table do |t|
+ t.expects(:column).with(:created_at, :datetime, kind_of(Hash))
+ t.expects(:column).with(:updated_at, :datetime, kind_of(Hash))
+ t.timestamps
end
+ end
- def test_integer_creates_integer_column
- with_new_table do |t|
- t.expects(:column).with(:foo, 'integer', {})
- t.expects(:column).with(:bar, 'integer', {})
- t.integer :foo, :bar
- end
+ def test_integer_creates_integer_column
+ with_new_table do |t|
+ t.expects(:column).with(:foo, 'integer', {})
+ t.expects(:column).with(:bar, 'integer', {})
+ t.integer :foo, :bar
end
+ end
- def test_string_creates_string_column
- with_new_table do |t|
- t.expects(:column).with(:foo, 'string', {})
- t.expects(:column).with(:bar, 'string', {})
- t.string :foo, :bar
- end
+ def test_string_creates_string_column
+ with_new_table do |t|
+ t.expects(:column).with(:foo, 'string', {})
+ t.expects(:column).with(:bar, 'string', {})
+ t.string :foo, :bar
end
+ end
- protected
- def with_new_table
- Person.connection.create_table :delete_me, :force => true do |t|
- yield t
- end
- ensure
- Person.connection.drop_table :delete_me rescue nil
+ protected
+ def with_new_table
+ Person.connection.create_table :delete_me, :force => true do |t|
+ yield t
end
+ ensure
+ Person.connection.drop_table :delete_me rescue nil
+ end
- end # SexyMigrationsTest
- end # uses_mocha
+ end # SexyMigrationsTest
- uses_mocha 'ChangeTable migration tests' do
- class ChangeTableMigrationsTest < ActiveRecord::TestCase
- def setup
- @connection = Person.connection
- @connection.create_table :delete_me, :force => true do |t|
- end
+ class ChangeTableMigrationsTest < ActiveRecord::TestCase
+ def setup
+ @connection = Person.connection
+ @connection.create_table :delete_me, :force => true do |t|
end
+ end
- def teardown
- Person.connection.drop_table :delete_me rescue nil
- end
+ def teardown
+ Person.connection.drop_table :delete_me rescue nil
+ end
- def test_references_column_type_adds_id
- with_change_table do |t|
- @connection.expects(:add_column).with(:delete_me, 'customer_id', :integer, {})
- t.references :customer
- end
+ def test_references_column_type_adds_id
+ with_change_table do |t|
+ @connection.expects(:add_column).with(:delete_me, 'customer_id', :integer, {})
+ t.references :customer
end
+ end
- def test_remove_references_column_type_removes_id
- with_change_table do |t|
- @connection.expects(:remove_column).with(:delete_me, 'customer_id')
- t.remove_references :customer
- end
+ def test_remove_references_column_type_removes_id
+ with_change_table do |t|
+ @connection.expects(:remove_column).with(:delete_me, 'customer_id')
+ t.remove_references :customer
end
+ end
- def test_add_belongs_to_works_like_add_references
- with_change_table do |t|
- @connection.expects(:add_column).with(:delete_me, 'customer_id', :integer, {})
- t.belongs_to :customer
- end
+ def test_add_belongs_to_works_like_add_references
+ with_change_table do |t|
+ @connection.expects(:add_column).with(:delete_me, 'customer_id', :integer, {})
+ t.belongs_to :customer
end
+ end
- def test_remove_belongs_to_works_like_remove_references
- with_change_table do |t|
- @connection.expects(:remove_column).with(:delete_me, 'customer_id')
- t.remove_belongs_to :customer
- end
+ def test_remove_belongs_to_works_like_remove_references
+ with_change_table do |t|
+ @connection.expects(:remove_column).with(:delete_me, 'customer_id')
+ t.remove_belongs_to :customer
end
+ end
- def test_references_column_type_with_polymorphic_adds_type
- with_change_table do |t|
- @connection.expects(:add_column).with(:delete_me, 'taggable_type', :string, {})
- @connection.expects(:add_column).with(:delete_me, 'taggable_id', :integer, {})
- t.references :taggable, :polymorphic => true
- end
+ def test_references_column_type_with_polymorphic_adds_type
+ with_change_table do |t|
+ @connection.expects(:add_column).with(:delete_me, 'taggable_type', :string, {})
+ @connection.expects(:add_column).with(:delete_me, 'taggable_id', :integer, {})
+ t.references :taggable, :polymorphic => true
end
+ end
- def test_remove_references_column_type_with_polymorphic_removes_type
- with_change_table do |t|
- @connection.expects(:remove_column).with(:delete_me, 'taggable_type')
- @connection.expects(:remove_column).with(:delete_me, 'taggable_id')
- t.remove_references :taggable, :polymorphic => true
- end
+ def test_remove_references_column_type_with_polymorphic_removes_type
+ with_change_table do |t|
+ @connection.expects(:remove_column).with(:delete_me, 'taggable_type')
+ @connection.expects(:remove_column).with(:delete_me, 'taggable_id')
+ t.remove_references :taggable, :polymorphic => true
end
+ end
- def test_references_column_type_with_polymorphic_and_options_null_is_false_adds_table_flag
- with_change_table do |t|
- @connection.expects(:add_column).with(:delete_me, 'taggable_type', :string, {:null => false})
- @connection.expects(:add_column).with(:delete_me, 'taggable_id', :integer, {:null => false})
- t.references :taggable, :polymorphic => true, :null => false
- end
+ def test_references_column_type_with_polymorphic_and_options_null_is_false_adds_table_flag
+ with_change_table do |t|
+ @connection.expects(:add_column).with(:delete_me, 'taggable_type', :string, {:null => false})
+ @connection.expects(:add_column).with(:delete_me, 'taggable_id', :integer, {:null => false})
+ t.references :taggable, :polymorphic => true, :null => false
end
+ end
- def test_remove_references_column_type_with_polymorphic_and_options_null_is_false_removes_table_flag
- with_change_table do |t|
- @connection.expects(:remove_column).with(:delete_me, 'taggable_type')
- @connection.expects(:remove_column).with(:delete_me, 'taggable_id')
- t.remove_references :taggable, :polymorphic => true, :null => false
- end
+ def test_remove_references_column_type_with_polymorphic_and_options_null_is_false_removes_table_flag
+ with_change_table do |t|
+ @connection.expects(:remove_column).with(:delete_me, 'taggable_type')
+ @connection.expects(:remove_column).with(:delete_me, 'taggable_id')
+ t.remove_references :taggable, :polymorphic => true, :null => false
end
+ end
- def test_timestamps_creates_updated_at_and_created_at
- with_change_table do |t|
- @connection.expects(:add_timestamps).with(:delete_me)
- t.timestamps
- end
+ def test_timestamps_creates_updated_at_and_created_at
+ with_change_table do |t|
+ @connection.expects(:add_timestamps).with(:delete_me)
+ t.timestamps
end
+ end
- def test_remove_timestamps_creates_updated_at_and_created_at
- with_change_table do |t|
- @connection.expects(:remove_timestamps).with(:delete_me)
- t.remove_timestamps
- end
+ def test_remove_timestamps_creates_updated_at_and_created_at
+ with_change_table do |t|
+ @connection.expects(:remove_timestamps).with(:delete_me)
+ t.remove_timestamps
end
+ end
- def string_column
- if current_adapter?(:PostgreSQLAdapter)
- "character varying(255)"
- else
- 'varchar(255)'
- end
+ def string_column
+ if current_adapter?(:PostgreSQLAdapter)
+ "character varying(255)"
+ else
+ 'varchar(255)'
end
+ end
- def integer_column
- if current_adapter?(:MysqlAdapter)
- 'int(11)'
- else
- 'integer'
- end
+ def integer_column
+ if current_adapter?(:MysqlAdapter)
+ 'int(11)'
+ else
+ 'integer'
end
+ end
- def test_integer_creates_integer_column
- with_change_table do |t|
- @connection.expects(:add_column).with(:delete_me, :foo, integer_column, {})
- @connection.expects(:add_column).with(:delete_me, :bar, integer_column, {})
- t.integer :foo, :bar
- end
+ def test_integer_creates_integer_column
+ with_change_table do |t|
+ @connection.expects(:add_column).with(:delete_me, :foo, integer_column, {})
+ @connection.expects(:add_column).with(:delete_me, :bar, integer_column, {})
+ t.integer :foo, :bar
end
+ end
- def test_string_creates_string_column
- with_change_table do |t|
- @connection.expects(:add_column).with(:delete_me, :foo, string_column, {})
- @connection.expects(:add_column).with(:delete_me, :bar, string_column, {})
- t.string :foo, :bar
- end
+ def test_string_creates_string_column
+ with_change_table do |t|
+ @connection.expects(:add_column).with(:delete_me, :foo, string_column, {})
+ @connection.expects(:add_column).with(:delete_me, :bar, string_column, {})
+ t.string :foo, :bar
end
+ end
- def test_column_creates_column
- with_change_table do |t|
- @connection.expects(:add_column).with(:delete_me, :bar, :integer, {})
- t.column :bar, :integer
- end
+ def test_column_creates_column
+ with_change_table do |t|
+ @connection.expects(:add_column).with(:delete_me, :bar, :integer, {})
+ t.column :bar, :integer
end
+ end
- def test_column_creates_column_with_options
- with_change_table do |t|
- @connection.expects(:add_column).with(:delete_me, :bar, :integer, {:null => false})
- t.column :bar, :integer, :null => false
- end
+ def test_column_creates_column_with_options
+ with_change_table do |t|
+ @connection.expects(:add_column).with(:delete_me, :bar, :integer, {:null => false})
+ t.column :bar, :integer, :null => false
end
+ end
- def test_index_creates_index
- with_change_table do |t|
- @connection.expects(:add_index).with(:delete_me, :bar, {})
- t.index :bar
- end
+ def test_index_creates_index
+ with_change_table do |t|
+ @connection.expects(:add_index).with(:delete_me, :bar, {})
+ t.index :bar
end
+ end
- def test_index_creates_index_with_options
- with_change_table do |t|
- @connection.expects(:add_index).with(:delete_me, :bar, {:unique => true})
- t.index :bar, :unique => true
- end
+ def test_index_creates_index_with_options
+ with_change_table do |t|
+ @connection.expects(:add_index).with(:delete_me, :bar, {:unique => true})
+ t.index :bar, :unique => true
end
+ end
- def test_change_changes_column
- with_change_table do |t|
- @connection.expects(:change_column).with(:delete_me, :bar, :string, {})
- t.change :bar, :string
- end
+ def test_change_changes_column
+ with_change_table do |t|
+ @connection.expects(:change_column).with(:delete_me, :bar, :string, {})
+ t.change :bar, :string
end
+ end
- def test_change_changes_column_with_options
- with_change_table do |t|
- @connection.expects(:change_column).with(:delete_me, :bar, :string, {:null => true})
- t.change :bar, :string, :null => true
- end
+ def test_change_changes_column_with_options
+ with_change_table do |t|
+ @connection.expects(:change_column).with(:delete_me, :bar, :string, {:null => true})
+ t.change :bar, :string, :null => true
end
+ end
- def test_change_default_changes_column
- with_change_table do |t|
- @connection.expects(:change_column_default).with(:delete_me, :bar, :string)
- t.change_default :bar, :string
- end
+ def test_change_default_changes_column
+ with_change_table do |t|
+ @connection.expects(:change_column_default).with(:delete_me, :bar, :string)
+ t.change_default :bar, :string
end
+ end
- def test_remove_drops_single_column
- with_change_table do |t|
- @connection.expects(:remove_column).with(:delete_me, [:bar])
- t.remove :bar
- end
+ def test_remove_drops_single_column
+ with_change_table do |t|
+ @connection.expects(:remove_column).with(:delete_me, [:bar])
+ t.remove :bar
end
+ end
- def test_remove_drops_multiple_columns
- with_change_table do |t|
- @connection.expects(:remove_column).with(:delete_me, [:bar, :baz])
- t.remove :bar, :baz
- end
+ def test_remove_drops_multiple_columns
+ with_change_table do |t|
+ @connection.expects(:remove_column).with(:delete_me, [:bar, :baz])
+ t.remove :bar, :baz
end
+ end
- def test_remove_index_removes_index_with_options
- with_change_table do |t|
- @connection.expects(:remove_index).with(:delete_me, {:unique => true})
- t.remove_index :unique => true
- end
+ def test_remove_index_removes_index_with_options
+ with_change_table do |t|
+ @connection.expects(:remove_index).with(:delete_me, {:unique => true})
+ t.remove_index :unique => true
end
+ end
- def test_rename_renames_column
- with_change_table do |t|
- @connection.expects(:rename_column).with(:delete_me, :bar, :baz)
- t.rename :bar, :baz
- end
+ def test_rename_renames_column
+ with_change_table do |t|
+ @connection.expects(:rename_column).with(:delete_me, :bar, :baz)
+ t.rename :bar, :baz
end
+ end
- protected
- def with_change_table
- Person.connection.change_table :delete_me do |t|
- yield t
- end
+ protected
+ def with_change_table
+ Person.connection.change_table :delete_me do |t|
+ yield t
end
-
- end # ChangeTable test
- end # uses_mocha
-
+ end
+ end
end
diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb
index 1605684677..2e531a284e 100644
--- a/activerecord/test/cases/nested_attributes_test.rb
+++ b/activerecord/test/cases/nested_attributes_test.rb
@@ -233,6 +233,20 @@ module NestedAttributesOnACollectionAssociationTests
assert_equal 'Privateers Greed', @pirate.send(@association_name).last.name
end
+ def test_should_remove_delete_key_from_arguments_hash_of_new_records
+ assert_nothing_raised ActiveRecord::UnknownAttributeError do
+ @pirate.send(association_setter, { 'new_1' => { '_delete' => '0' }})
+ end
+ end
+
+ def test_should_ignore_new_associated_records_with_truthy_delete_attribute
+ @pirate.send(@association_name).destroy_all
+ @pirate.reload.attributes = { association_getter => { 'new_1' => { :name => 'Grace OMalley' }, 'new_2' => { :name => 'Privateers Greed', '_delete' => '1' }}}
+
+ assert_equal 1, @pirate.send(@association_name).length
+ assert_equal 'Grace OMalley', @pirate.send(@association_name).first.name
+ end
+
def test_should_sort_the_hash_by_the_keys_before_building_new_associated_models
attributes = ActiveSupport::OrderedHash.new
attributes['new_123726353'] = { :name => 'Grace OMalley' }
diff --git a/activerecord/test/cases/query_cache_test.rb b/activerecord/test/cases/query_cache_test.rb
index 171d0e6dae..f90a66d1dc 100644
--- a/activerecord/test/cases/query_cache_test.rb
+++ b/activerecord/test/cases/query_cache_test.rb
@@ -55,8 +55,6 @@ class QueryCacheTest < ActiveRecord::TestCase
end
end
-uses_mocha 'QueryCacheExpiryTest' do
-
class QueryCacheExpiryTest < ActiveRecord::TestCase
fixtures :tasks, :posts, :categories, :categories_posts
@@ -123,5 +121,3 @@ class QueryCacheExpiryTest < ActiveRecord::TestCase
end
end
end
-
-end
diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb
index 4a07a8bb1d..40abd935df 100644
--- a/activerecord/test/cases/transactions_test.rb
+++ b/activerecord/test/cases/transactions_test.rb
@@ -306,17 +306,15 @@ class TransactionTest < ActiveRecord::TestCase
assert_equal "Three", @three
end if Topic.connection.supports_savepoints?
- uses_mocha 'mocking connection.commit_db_transaction' do
- def test_rollback_when_commit_raises
- Topic.connection.expects(:begin_db_transaction)
- Topic.connection.expects(:commit_db_transaction).raises('OH NOES')
- Topic.connection.expects(:outside_transaction?).returns(false)
- Topic.connection.expects(:rollback_db_transaction)
+ def test_rollback_when_commit_raises
+ Topic.connection.expects(:begin_db_transaction)
+ Topic.connection.expects(:commit_db_transaction).raises('OH NOES')
+ Topic.connection.expects(:outside_transaction?).returns(false)
+ Topic.connection.expects(:rollback_db_transaction)
- assert_raise RuntimeError do
- Topic.transaction do
- # do nothing
- end
+ assert_raise RuntimeError do
+ Topic.transaction do
+ # do nothing
end
end
end
@@ -330,14 +328,12 @@ class TransactionTest < ActiveRecord::TestCase
assert Topic.connection.outside_transaction?
end
- uses_mocha 'mocking connection.rollback_db_transaction' do
- def test_rollback_wont_be_executed_if_no_transaction_active
- assert_raise RuntimeError do
- Topic.transaction do
- Topic.connection.rollback_db_transaction
- Topic.connection.expects(:rollback_db_transaction).never
- raise "Rails doesn't scale!"
- end
+ def test_rollback_wont_be_executed_if_no_transaction_active
+ assert_raise RuntimeError do
+ Topic.transaction do
+ Topic.connection.rollback_db_transaction
+ Topic.connection.expects(:rollback_db_transaction).never
+ raise "Rails doesn't scale!"
end
end
end
diff --git a/activerecord/test/cases/validations_i18n_test.rb b/activerecord/test/cases/validations_i18n_test.rb
index e893a704f1..66982346e9 100644
--- a/activerecord/test/cases/validations_i18n_test.rb
+++ b/activerecord/test/cases/validations_i18n_test.rb
@@ -71,359 +71,353 @@ class ActiveRecordValidationsI18nTests < ActiveSupport::TestCase
end
# ActiveRecord::Errors
- uses_mocha 'ActiveRecord::Errors' do
+ def test_errors_generate_message_translates_custom_model_attribute_key
- def test_errors_generate_message_translates_custom_model_attribute_key
-
- I18n.expects(:translate).with(
- :topic,
- { :count => 1,
- :default => ['Topic'],
- :scope => [:activerecord, :models]
- }
- ).returns('Topic')
+ I18n.expects(:translate).with(
+ :topic,
+ { :count => 1,
+ :default => ['Topic'],
+ :scope => [:activerecord, :models]
+ }
+ ).returns('Topic')
- I18n.expects(:translate).with(
- :"topic.title",
- { :count => 1,
- :default => ['Title'],
- :scope => [:activerecord, :attributes]
- }
- ).returns('Title')
+ I18n.expects(:translate).with(
+ :"topic.title",
+ { :count => 1,
+ :default => ['Title'],
+ :scope => [:activerecord, :attributes]
+ }
+ ).returns('Title')
+
+ I18n.expects(:translate).with(
+ :"models.topic.attributes.title.invalid",
+ :value => nil,
+ :scope => [:activerecord, :errors],
+ :default => [
+ :"models.topic.invalid",
+ 'default from class def error 1',
+ :"messages.invalid"],
+ :attribute => "Title",
+ :model => "Topic"
+ ).returns('default from class def error 1')
+
+ @topic.errors.generate_message :title, :invalid, :default => 'default from class def error 1'
+ end
+
+ def test_errors_generate_message_translates_custom_model_attribute_keys_with_sti
+
+ I18n.expects(:translate).with(
+ :reply,
+ { :count => 1,
+ :default => [:topic, 'Reply'],
+ :scope => [:activerecord, :models]
+ }
+ ).returns('Reply')
- I18n.expects(:translate).with(
+ I18n.expects(:translate).with(
+ :"reply.title",
+ { :count => 1,
+ :default => [:'topic.title', 'Title'],
+ :scope => [:activerecord, :attributes]
+ }
+ ).returns('Title')
+
+ I18n.expects(:translate).with(
+ :"models.reply.attributes.title.invalid",
+ :value => nil,
+ :scope => [:activerecord, :errors],
+ :default => [
+ :"models.reply.invalid",
:"models.topic.attributes.title.invalid",
- :value => nil,
- :scope => [:activerecord, :errors],
- :default => [
- :"models.topic.invalid",
- 'default from class def error 1',
- :"messages.invalid"],
- :attribute => "Title",
- :model => "Topic"
- ).returns('default from class def error 1')
-
- @topic.errors.generate_message :title, :invalid, :default => 'default from class def error 1'
- end
-
- def test_errors_generate_message_translates_custom_model_attribute_keys_with_sti
-
- I18n.expects(:translate).with(
- :reply,
- { :count => 1,
- :default => [:topic, 'Reply'],
- :scope => [:activerecord, :models]
- }
- ).returns('Reply')
+ :"models.topic.invalid",
+ 'default from class def',
+ :"messages.invalid"],
+ :model => 'Reply',
+ :attribute => 'Title'
+ ).returns("default from class def")
- I18n.expects(:translate).with(
- :"reply.title",
- { :count => 1,
- :default => [:'topic.title', 'Title'],
- :scope => [:activerecord, :attributes]
- }
- ).returns('Title')
-
- I18n.expects(:translate).with(
- :"models.reply.attributes.title.invalid",
- :value => nil,
- :scope => [:activerecord, :errors],
- :default => [
- :"models.reply.invalid",
- :"models.topic.attributes.title.invalid",
- :"models.topic.invalid",
- 'default from class def',
- :"messages.invalid"],
- :model => 'Reply',
- :attribute => 'Title'
- ).returns("default from class def")
-
- Reply.new.errors.generate_message :title, :invalid, :default => 'default from class def'
+ Reply.new.errors.generate_message :title, :invalid, :default => 'default from class def'
- end
+ end
- def test_errors_add_on_empty_generates_message
- @topic.errors.expects(:generate_message).with(:title, :empty, {:default => nil})
- @topic.errors.add_on_empty :title
- end
+ def test_errors_add_on_empty_generates_message
+ @topic.errors.expects(:generate_message).with(:title, :empty, {:default => nil})
+ @topic.errors.add_on_empty :title
+ end
- def test_errors_add_on_empty_generates_message_with_custom_default_message
- @topic.errors.expects(:generate_message).with(:title, :empty, {:default => 'custom'})
- @topic.errors.add_on_empty :title, 'custom'
- end
+ def test_errors_add_on_empty_generates_message_with_custom_default_message
+ @topic.errors.expects(:generate_message).with(:title, :empty, {:default => 'custom'})
+ @topic.errors.add_on_empty :title, 'custom'
+ end
- def test_errors_add_on_blank_generates_message
- @topic.errors.expects(:generate_message).with(:title, :blank, {:default => nil})
- @topic.errors.add_on_blank :title
- end
+ def test_errors_add_on_blank_generates_message
+ @topic.errors.expects(:generate_message).with(:title, :blank, {:default => nil})
+ @topic.errors.add_on_blank :title
+ end
- def test_errors_add_on_blank_generates_message_with_custom_default_message
- @topic.errors.expects(:generate_message).with(:title, :blank, {:default => 'custom'})
- @topic.errors.add_on_blank :title, 'custom'
- end
+ def test_errors_add_on_blank_generates_message_with_custom_default_message
+ @topic.errors.expects(:generate_message).with(:title, :blank, {:default => 'custom'})
+ @topic.errors.add_on_blank :title, 'custom'
+ end
- def test_errors_full_messages_translates_human_attribute_name_for_model_attributes
- @topic.errors.instance_variable_set :@errors, { 'title' => ['empty'] }
- I18n.expects(:translate).with(:"topic.title", :default => ['Title'], :scope => [:activerecord, :attributes], :count => 1).returns('Title')
- @topic.errors.full_messages :locale => 'en'
- end
+ def test_errors_full_messages_translates_human_attribute_name_for_model_attributes
+ @topic.errors.instance_variable_set :@errors, { 'title' => ['empty'] }
+ I18n.expects(:translate).with(:"topic.title", :default => ['Title'], :scope => [:activerecord, :attributes], :count => 1).returns('Title')
+ @topic.errors.full_messages :locale => 'en'
end
# ActiveRecord::Validations
- uses_mocha 'ActiveRecord::Validations' do
- # validates_confirmation_of w/ mocha
-
- def test_validates_confirmation_of_generates_message
- Topic.validates_confirmation_of :title
- @topic.title_confirmation = 'foo'
- @topic.errors.expects(:generate_message).with(:title, :confirmation, {:default => nil})
- @topic.valid?
- end
+ # validates_confirmation_of w/ mocha
+ def test_validates_confirmation_of_generates_message
+ Topic.validates_confirmation_of :title
+ @topic.title_confirmation = 'foo'
+ @topic.errors.expects(:generate_message).with(:title, :confirmation, {:default => nil})
+ @topic.valid?
+ end
- def test_validates_confirmation_of_generates_message_with_custom_default_message
- Topic.validates_confirmation_of :title, :message => 'custom'
- @topic.title_confirmation = 'foo'
- @topic.errors.expects(:generate_message).with(:title, :confirmation, {:default => 'custom'})
- @topic.valid?
- end
+ def test_validates_confirmation_of_generates_message_with_custom_default_message
+ Topic.validates_confirmation_of :title, :message => 'custom'
+ @topic.title_confirmation = 'foo'
+ @topic.errors.expects(:generate_message).with(:title, :confirmation, {:default => 'custom'})
+ @topic.valid?
+ end
- # validates_acceptance_of w/ mocha
+ # validates_acceptance_of w/ mocha
- def test_validates_acceptance_of_generates_message
- Topic.validates_acceptance_of :title, :allow_nil => false
- @topic.errors.expects(:generate_message).with(:title, :accepted, {:default => nil})
- @topic.valid?
- end
+ def test_validates_acceptance_of_generates_message
+ Topic.validates_acceptance_of :title, :allow_nil => false
+ @topic.errors.expects(:generate_message).with(:title, :accepted, {:default => nil})
+ @topic.valid?
+ end
- def test_validates_acceptance_of_generates_message_with_custom_default_message
- Topic.validates_acceptance_of :title, :message => 'custom', :allow_nil => false
- @topic.errors.expects(:generate_message).with(:title, :accepted, {:default => 'custom'})
- @topic.valid?
- end
+ def test_validates_acceptance_of_generates_message_with_custom_default_message
+ Topic.validates_acceptance_of :title, :message => 'custom', :allow_nil => false
+ @topic.errors.expects(:generate_message).with(:title, :accepted, {:default => 'custom'})
+ @topic.valid?
+ end
- # validates_presence_of w/ mocha
+ # validates_presence_of w/ mocha
- def test_validates_presence_of_generates_message
- Topic.validates_presence_of :title
- @topic.errors.expects(:generate_message).with(:title, :blank, {:default => nil})
- @topic.valid?
- end
+ def test_validates_presence_of_generates_message
+ Topic.validates_presence_of :title
+ @topic.errors.expects(:generate_message).with(:title, :blank, {:default => nil})
+ @topic.valid?
+ end
- def test_validates_presence_of_generates_message_with_custom_default_message
- Topic.validates_presence_of :title, :message => 'custom'
- @topic.errors.expects(:generate_message).with(:title, :blank, {:default => 'custom'})
- @topic.valid?
- end
+ def test_validates_presence_of_generates_message_with_custom_default_message
+ Topic.validates_presence_of :title, :message => 'custom'
+ @topic.errors.expects(:generate_message).with(:title, :blank, {:default => 'custom'})
+ @topic.valid?
+ end
- def test_validates_length_of_within_generates_message_with_title_too_short
- Topic.validates_length_of :title, :within => 3..5
- @topic.errors.expects(:generate_message).with(:title, :too_short, {:count => 3, :default => nil})
- @topic.valid?
- end
+ def test_validates_length_of_within_generates_message_with_title_too_short
+ Topic.validates_length_of :title, :within => 3..5
+ @topic.errors.expects(:generate_message).with(:title, :too_short, {:count => 3, :default => nil})
+ @topic.valid?
+ end
- def test_validates_length_of_within_generates_message_with_title_too_short_and_custom_default_message
- Topic.validates_length_of :title, :within => 3..5, :too_short => 'custom'
- @topic.errors.expects(:generate_message).with(:title, :too_short, {:count => 3, :default => 'custom'})
- @topic.valid?
- end
+ def test_validates_length_of_within_generates_message_with_title_too_short_and_custom_default_message
+ Topic.validates_length_of :title, :within => 3..5, :too_short => 'custom'
+ @topic.errors.expects(:generate_message).with(:title, :too_short, {:count => 3, :default => 'custom'})
+ @topic.valid?
+ end
- def test_validates_length_of_within_generates_message_with_title_too_long
- Topic.validates_length_of :title, :within => 3..5
- @topic.title = 'this title is too long'
- @topic.errors.expects(:generate_message).with(:title, :too_long, {:count => 5, :default => nil})
- @topic.valid?
- end
+ def test_validates_length_of_within_generates_message_with_title_too_long
+ Topic.validates_length_of :title, :within => 3..5
+ @topic.title = 'this title is too long'
+ @topic.errors.expects(:generate_message).with(:title, :too_long, {:count => 5, :default => nil})
+ @topic.valid?
+ end
- def test_validates_length_of_within_generates_message_with_title_too_long_and_custom_default_message
- Topic.validates_length_of :title, :within => 3..5, :too_long => 'custom'
- @topic.title = 'this title is too long'
- @topic.errors.expects(:generate_message).with(:title, :too_long, {:count => 5, :default => 'custom'})
- @topic.valid?
- end
+ def test_validates_length_of_within_generates_message_with_title_too_long_and_custom_default_message
+ Topic.validates_length_of :title, :within => 3..5, :too_long => 'custom'
+ @topic.title = 'this title is too long'
+ @topic.errors.expects(:generate_message).with(:title, :too_long, {:count => 5, :default => 'custom'})
+ @topic.valid?
+ end
- # validates_length_of :within w/ mocha
+ # validates_length_of :within w/ mocha
- def test_validates_length_of_within_generates_message_with_title_too_short
- Topic.validates_length_of :title, :within => 3..5
- @topic.errors.expects(:generate_message).with(:title, :too_short, {:count => 3, :default => nil})
- @topic.valid?
- end
+ def test_validates_length_of_within_generates_message_with_title_too_short
+ Topic.validates_length_of :title, :within => 3..5
+ @topic.errors.expects(:generate_message).with(:title, :too_short, {:count => 3, :default => nil})
+ @topic.valid?
+ end
- def test_validates_length_of_within_generates_message_with_title_too_short_and_custom_default_message
- Topic.validates_length_of :title, :within => 3..5, :too_short => 'custom'
- @topic.errors.expects(:generate_message).with(:title, :too_short, {:count => 3, :default => 'custom'})
- @topic.valid?
- end
+ def test_validates_length_of_within_generates_message_with_title_too_short_and_custom_default_message
+ Topic.validates_length_of :title, :within => 3..5, :too_short => 'custom'
+ @topic.errors.expects(:generate_message).with(:title, :too_short, {:count => 3, :default => 'custom'})
+ @topic.valid?
+ end
- def test_validates_length_of_within_generates_message_with_title_too_long
- Topic.validates_length_of :title, :within => 3..5
- @topic.title = 'this title is too long'
- @topic.errors.expects(:generate_message).with(:title, :too_long, {:count => 5, :default => nil})
- @topic.valid?
- end
+ def test_validates_length_of_within_generates_message_with_title_too_long
+ Topic.validates_length_of :title, :within => 3..5
+ @topic.title = 'this title is too long'
+ @topic.errors.expects(:generate_message).with(:title, :too_long, {:count => 5, :default => nil})
+ @topic.valid?
+ end
- def test_validates_length_of_within_generates_message_with_title_too_long_and_custom_default_message
- Topic.validates_length_of :title, :within => 3..5, :too_long => 'custom'
- @topic.title = 'this title is too long'
- @topic.errors.expects(:generate_message).with(:title, :too_long, {:count => 5, :default => 'custom'})
- @topic.valid?
- end
+ def test_validates_length_of_within_generates_message_with_title_too_long_and_custom_default_message
+ Topic.validates_length_of :title, :within => 3..5, :too_long => 'custom'
+ @topic.title = 'this title is too long'
+ @topic.errors.expects(:generate_message).with(:title, :too_long, {:count => 5, :default => 'custom'})
+ @topic.valid?
+ end
- # validates_length_of :is w/ mocha
+ # validates_length_of :is w/ mocha
- def test_validates_length_of_is_generates_message
- Topic.validates_length_of :title, :is => 5
- @topic.errors.expects(:generate_message).with(:title, :wrong_length, {:count => 5, :default => nil})
- @topic.valid?
- end
+ def test_validates_length_of_is_generates_message
+ Topic.validates_length_of :title, :is => 5
+ @topic.errors.expects(:generate_message).with(:title, :wrong_length, {:count => 5, :default => nil})
+ @topic.valid?
+ end
- def test_validates_length_of_is_generates_message_with_custom_default_message
- Topic.validates_length_of :title, :is => 5, :message => 'custom'
- @topic.errors.expects(:generate_message).with(:title, :wrong_length, {:count => 5, :default => 'custom'})
- @topic.valid?
- end
+ def test_validates_length_of_is_generates_message_with_custom_default_message
+ Topic.validates_length_of :title, :is => 5, :message => 'custom'
+ @topic.errors.expects(:generate_message).with(:title, :wrong_length, {:count => 5, :default => 'custom'})
+ @topic.valid?
+ end
- # validates_uniqueness_of w/ mocha
+ # validates_uniqueness_of w/ mocha
- def test_validates_uniqueness_of_generates_message
- Topic.validates_uniqueness_of :title
- @topic.title = unique_topic.title
- @topic.errors.expects(:generate_message).with(:title, :taken, {:default => nil, :value => 'unique!'})
- @topic.valid?
- end
+ def test_validates_uniqueness_of_generates_message
+ Topic.validates_uniqueness_of :title
+ @topic.title = unique_topic.title
+ @topic.errors.expects(:generate_message).with(:title, :taken, {:default => nil, :value => 'unique!'})
+ @topic.valid?
+ end
- def test_validates_uniqueness_of_generates_message_with_custom_default_message
- Topic.validates_uniqueness_of :title, :message => 'custom'
- @topic.title = unique_topic.title
- @topic.errors.expects(:generate_message).with(:title, :taken, {:default => 'custom', :value => 'unique!'})
- @topic.valid?
- end
+ def test_validates_uniqueness_of_generates_message_with_custom_default_message
+ Topic.validates_uniqueness_of :title, :message => 'custom'
+ @topic.title = unique_topic.title
+ @topic.errors.expects(:generate_message).with(:title, :taken, {:default => 'custom', :value => 'unique!'})
+ @topic.valid?
+ end
- # validates_format_of w/ mocha
+ # validates_format_of w/ mocha
- def test_validates_format_of_generates_message
- Topic.validates_format_of :title, :with => /^[1-9][0-9]*$/
- @topic.title = '72x'
- @topic.errors.expects(:generate_message).with(:title, :invalid, {:value => '72x', :default => nil})
- @topic.valid?
- end
+ def test_validates_format_of_generates_message
+ Topic.validates_format_of :title, :with => /^[1-9][0-9]*$/
+ @topic.title = '72x'
+ @topic.errors.expects(:generate_message).with(:title, :invalid, {:value => '72x', :default => nil})
+ @topic.valid?
+ end
- def test_validates_format_of_generates_message_with_custom_default_message
- Topic.validates_format_of :title, :with => /^[1-9][0-9]*$/, :message => 'custom'
- @topic.title = '72x'
- @topic.errors.expects(:generate_message).with(:title, :invalid, {:value => '72x', :default => 'custom'})
- @topic.valid?
- end
+ def test_validates_format_of_generates_message_with_custom_default_message
+ Topic.validates_format_of :title, :with => /^[1-9][0-9]*$/, :message => 'custom'
+ @topic.title = '72x'
+ @topic.errors.expects(:generate_message).with(:title, :invalid, {:value => '72x', :default => 'custom'})
+ @topic.valid?
+ end
- # validates_inclusion_of w/ mocha
+ # validates_inclusion_of w/ mocha
- def test_validates_inclusion_of_generates_message
- Topic.validates_inclusion_of :title, :in => %w(a b c)
- @topic.title = 'z'
- @topic.errors.expects(:generate_message).with(:title, :inclusion, {:value => 'z', :default => nil})
- @topic.valid?
- end
+ def test_validates_inclusion_of_generates_message
+ Topic.validates_inclusion_of :title, :in => %w(a b c)
+ @topic.title = 'z'
+ @topic.errors.expects(:generate_message).with(:title, :inclusion, {:value => 'z', :default => nil})
+ @topic.valid?
+ end
- def test_validates_inclusion_of_generates_message_with_custom_default_message
- Topic.validates_inclusion_of :title, :in => %w(a b c), :message => 'custom'
- @topic.title = 'z'
- @topic.errors.expects(:generate_message).with(:title, :inclusion, {:value => 'z', :default => 'custom'})
- @topic.valid?
- end
+ def test_validates_inclusion_of_generates_message_with_custom_default_message
+ Topic.validates_inclusion_of :title, :in => %w(a b c), :message => 'custom'
+ @topic.title = 'z'
+ @topic.errors.expects(:generate_message).with(:title, :inclusion, {:value => 'z', :default => 'custom'})
+ @topic.valid?
+ end
- # validates_exclusion_of w/ mocha
+ # validates_exclusion_of w/ mocha
- def test_validates_exclusion_of_generates_message
- Topic.validates_exclusion_of :title, :in => %w(a b c)
- @topic.title = 'a'
- @topic.errors.expects(:generate_message).with(:title, :exclusion, {:value => 'a', :default => nil})
- @topic.valid?
- end
+ def test_validates_exclusion_of_generates_message
+ Topic.validates_exclusion_of :title, :in => %w(a b c)
+ @topic.title = 'a'
+ @topic.errors.expects(:generate_message).with(:title, :exclusion, {:value => 'a', :default => nil})
+ @topic.valid?
+ end
- def test_validates_exclusion_of_generates_message_with_custom_default_message
- Topic.validates_exclusion_of :title, :in => %w(a b c), :message => 'custom'
- @topic.title = 'a'
- @topic.errors.expects(:generate_message).with(:title, :exclusion, {:value => 'a', :default => 'custom'})
- @topic.valid?
- end
+ def test_validates_exclusion_of_generates_message_with_custom_default_message
+ Topic.validates_exclusion_of :title, :in => %w(a b c), :message => 'custom'
+ @topic.title = 'a'
+ @topic.errors.expects(:generate_message).with(:title, :exclusion, {:value => 'a', :default => 'custom'})
+ @topic.valid?
+ end
- # validates_numericality_of without :only_integer w/ mocha
+ # validates_numericality_of without :only_integer w/ mocha
- def test_validates_numericality_of_generates_message
- Topic.validates_numericality_of :title
- @topic.title = 'a'
- @topic.errors.expects(:generate_message).with(:title, :not_a_number, {:value => 'a', :default => nil})
- @topic.valid?
- end
+ def test_validates_numericality_of_generates_message
+ Topic.validates_numericality_of :title
+ @topic.title = 'a'
+ @topic.errors.expects(:generate_message).with(:title, :not_a_number, {:value => 'a', :default => nil})
+ @topic.valid?
+ end
- def test_validates_numericality_of_generates_message_with_custom_default_message
- Topic.validates_numericality_of :title, :message => 'custom'
- @topic.title = 'a'
- @topic.errors.expects(:generate_message).with(:title, :not_a_number, {:value => 'a', :default => 'custom'})
- @topic.valid?
- end
+ def test_validates_numericality_of_generates_message_with_custom_default_message
+ Topic.validates_numericality_of :title, :message => 'custom'
+ @topic.title = 'a'
+ @topic.errors.expects(:generate_message).with(:title, :not_a_number, {:value => 'a', :default => 'custom'})
+ @topic.valid?
+ end
- # validates_numericality_of with :only_integer w/ mocha
+ # validates_numericality_of with :only_integer w/ mocha
- def test_validates_numericality_of_only_integer_generates_message
- Topic.validates_numericality_of :title, :only_integer => true
- @topic.title = 'a'
- @topic.errors.expects(:generate_message).with(:title, :not_a_number, {:value => 'a', :default => nil})
- @topic.valid?
- end
+ def test_validates_numericality_of_only_integer_generates_message
+ Topic.validates_numericality_of :title, :only_integer => true
+ @topic.title = 'a'
+ @topic.errors.expects(:generate_message).with(:title, :not_a_number, {:value => 'a', :default => nil})
+ @topic.valid?
+ end
- def test_validates_numericality_of_only_integer_generates_message_with_custom_default_message
- Topic.validates_numericality_of :title, :only_integer => true, :message => 'custom'
- @topic.title = 'a'
- @topic.errors.expects(:generate_message).with(:title, :not_a_number, {:value => 'a', :default => 'custom'})
- @topic.valid?
- end
+ def test_validates_numericality_of_only_integer_generates_message_with_custom_default_message
+ Topic.validates_numericality_of :title, :only_integer => true, :message => 'custom'
+ @topic.title = 'a'
+ @topic.errors.expects(:generate_message).with(:title, :not_a_number, {:value => 'a', :default => 'custom'})
+ @topic.valid?
+ end
- # validates_numericality_of :odd w/ mocha
+ # validates_numericality_of :odd w/ mocha
- def test_validates_numericality_of_odd_generates_message
- Topic.validates_numericality_of :title, :only_integer => true, :odd => true
- @topic.title = 0
- @topic.errors.expects(:generate_message).with(:title, :odd, {:value => 0, :default => nil})
- @topic.valid?
- end
+ def test_validates_numericality_of_odd_generates_message
+ Topic.validates_numericality_of :title, :only_integer => true, :odd => true
+ @topic.title = 0
+ @topic.errors.expects(:generate_message).with(:title, :odd, {:value => 0, :default => nil})
+ @topic.valid?
+ end
- def test_validates_numericality_of_odd_generates_message_with_custom_default_message
- Topic.validates_numericality_of :title, :only_integer => true, :odd => true, :message => 'custom'
- @topic.title = 0
- @topic.errors.expects(:generate_message).with(:title, :odd, {:value => 0, :default => 'custom'})
- @topic.valid?
- end
+ def test_validates_numericality_of_odd_generates_message_with_custom_default_message
+ Topic.validates_numericality_of :title, :only_integer => true, :odd => true, :message => 'custom'
+ @topic.title = 0
+ @topic.errors.expects(:generate_message).with(:title, :odd, {:value => 0, :default => 'custom'})
+ @topic.valid?
+ end
- # validates_numericality_of :less_than w/ mocha
+ # validates_numericality_of :less_than w/ mocha
- def test_validates_numericality_of_less_than_generates_message
- Topic.validates_numericality_of :title, :only_integer => true, :less_than => 0
- @topic.title = 1
- @topic.errors.expects(:generate_message).with(:title, :less_than, {:value => 1, :count => 0, :default => nil})
- @topic.valid?
- end
+ def test_validates_numericality_of_less_than_generates_message
+ Topic.validates_numericality_of :title, :only_integer => true, :less_than => 0
+ @topic.title = 1
+ @topic.errors.expects(:generate_message).with(:title, :less_than, {:value => 1, :count => 0, :default => nil})
+ @topic.valid?
+ end
- def test_validates_numericality_of_odd_generates_message_with_custom_default_message
- Topic.validates_numericality_of :title, :only_integer => true, :less_than => 0, :message => 'custom'
- @topic.title = 1
- @topic.errors.expects(:generate_message).with(:title, :less_than, {:value => 1, :count => 0, :default => 'custom'})
- @topic.valid?
- end
+ def test_validates_numericality_of_odd_generates_message_with_custom_default_message
+ Topic.validates_numericality_of :title, :only_integer => true, :less_than => 0, :message => 'custom'
+ @topic.title = 1
+ @topic.errors.expects(:generate_message).with(:title, :less_than, {:value => 1, :count => 0, :default => 'custom'})
+ @topic.valid?
+ end
- # validates_associated w/ mocha
+ # validates_associated w/ mocha
- def test_validates_associated_generates_message
- Topic.validates_associated :replies
- replied_topic.errors.expects(:generate_message).with(:replies, :invalid, {:value => replied_topic.replies, :default => nil})
- replied_topic.valid?
- end
+ def test_validates_associated_generates_message
+ Topic.validates_associated :replies
+ replied_topic.errors.expects(:generate_message).with(:replies, :invalid, {:value => replied_topic.replies, :default => nil})
+ replied_topic.valid?
+ end
- def test_validates_associated_generates_message_with_custom_default_message
- Topic.validates_associated :replies
- replied_topic.errors.expects(:generate_message).with(:replies, :invalid, {:value => replied_topic.replies, :default => nil})
- replied_topic.valid?
- end
+ def test_validates_associated_generates_message_with_custom_default_message
+ Topic.validates_associated :replies
+ replied_topic.errors.expects(:generate_message).with(:replies, :invalid, {:value => replied_topic.replies, :default => nil})
+ replied_topic.valid?
end
# validates_confirmation_of w/o mocha
diff --git a/activeresource/test/abstract_unit.rb b/activeresource/test/abstract_unit.rb
index e612412033..83bf1ed510 100644
--- a/activeresource/test/abstract_unit.rb
+++ b/activeresource/test/abstract_unit.rb
@@ -1,5 +1,9 @@
+require 'rubygems'
require 'test/unit'
+gem 'mocha', '>= 0.9.5'
+require 'mocha'
+
$:.unshift "#{File.dirname(__FILE__)}/../lib"
require 'active_resource'
require 'active_resource/http_mock'
@@ -10,17 +14,9 @@ require 'setter_trap'
ActiveResource::Base.logger = Logger.new("#{File.dirname(__FILE__)}/debug.log")
def uses_gem(gem_name, test_name, version = '> 0')
- require 'rubygems'
gem gem_name.to_s, version
require gem_name.to_s
yield
rescue LoadError
$stderr.puts "Skipping #{test_name} tests. `gem install #{gem_name}` and try again."
end
-
-# Wrap tests that use Mocha and skip if unavailable.
-unless defined? uses_mocha
- def uses_mocha(test_name, &block)
- uses_gem('mocha', test_name, '>= 0.5.5', &block)
- end
-end
diff --git a/activeresource/test/connection_test.rb b/activeresource/test/connection_test.rb
index 84bcf69219..831fbc4003 100644
--- a/activeresource/test/connection_test.rb
+++ b/activeresource/test/connection_test.rb
@@ -168,21 +168,19 @@ class ConnectionTest < Test::Unit::TestCase
assert_equal 200, response.code
end
- uses_mocha('test_timeout, test_accept_http_header') do
- def test_timeout
- @http = mock('new Net::HTTP')
- @conn.expects(:http).returns(@http)
- @http.expects(:get).raises(Timeout::Error, 'execution expired')
- assert_raise(ActiveResource::TimeoutError) { @conn.get('/people_timeout.xml') }
- end
-
- def test_accept_http_header
- @http = mock('new Net::HTTP')
- @conn.expects(:http).returns(@http)
- path = '/people/1.xml'
- @http.expects(:get).with(path, {'Accept' => 'application/xhtml+xml'}).returns(ActiveResource::Response.new(@matz, 200, {'Content-Type' => 'text/xhtml'}))
- assert_nothing_raised(Mocha::ExpectationError) { @conn.get(path, {'Accept' => 'application/xhtml+xml'}) }
- end
+ def test_timeout
+ @http = mock('new Net::HTTP')
+ @conn.expects(:http).returns(@http)
+ @http.expects(:get).raises(Timeout::Error, 'execution expired')
+ assert_raise(ActiveResource::TimeoutError) { @conn.get('/people_timeout.xml') }
+ end
+
+ def test_accept_http_header
+ @http = mock('new Net::HTTP')
+ @conn.expects(:http).returns(@http)
+ path = '/people/1.xml'
+ @http.expects(:get).with(path, {'Accept' => 'application/xhtml+xml'}).returns(ActiveResource::Response.new(@matz, 200, {'Content-Type' => 'text/xhtml'}))
+ assert_nothing_raised(Mocha::ExpectationError) { @conn.get(path, {'Accept' => 'application/xhtml+xml'}) }
end
protected
diff --git a/activesupport/lib/active_support/inflector.rb b/activesupport/lib/active_support/inflector.rb
index 4921b99677..5ff6f50fb3 100644
--- a/activesupport/lib/active_support/inflector.rb
+++ b/activesupport/lib/active_support/inflector.rb
@@ -284,7 +284,7 @@ module ActiveSupport
# The iconv transliteration code doesn't function correctly
# on some platforms, but it's very fast where it does function.
- elsif "foo" != Inflector.transliterate("föö")
+ elsif "foo" != (Inflector.transliterate("föö") rescue nil)
undef_method :transliterate
def transliterate(string)
string.mb_chars.normalize(:kd). # Decompose accented characters
diff --git a/activesupport/lib/active_support/multibyte/chars.rb b/activesupport/lib/active_support/multibyte/chars.rb
index a00b165222..62b6d798ef 100644
--- a/activesupport/lib/active_support/multibyte/chars.rb
+++ b/activesupport/lib/active_support/multibyte/chars.rb
@@ -617,6 +617,8 @@ module ActiveSupport #:nodoc:
# Replaces all ISO-8859-1 or CP1252 characters by their UTF-8 equivalent resulting in a valid UTF-8 string.
def tidy_bytes(string)
string.split(//u).map do |c|
+ c.force_encoding(Encoding::ASCII) if c.respond_to?(:force_encoding)
+
if !UTF8_PAT.match(c)
n = c.unpack('C')[0]
n < 128 ? n.chr :
diff --git a/activesupport/test/abstract_unit.rb b/activesupport/test/abstract_unit.rb
index ac362d14c8..a0c0c59e47 100644
--- a/activesupport/test/abstract_unit.rb
+++ b/activesupport/test/abstract_unit.rb
@@ -1,6 +1,7 @@
require 'rubygems'
require 'test/unit'
-gem 'mocha', '>= 0.9.3'
+
+gem 'mocha', '>= 0.9.5'
require 'mocha'
$:.unshift "#{File.dirname(__FILE__)}/../lib"
diff --git a/ci/ci_build.rb b/ci/ci_build.rb
index 010f78ba09..0b9bd3d278 100755
--- a/ci/ci_build.rb
+++ b/ci/ci_build.rb
@@ -98,9 +98,9 @@ puts "[CruiseControl] #{`mysql --version`}"
puts "[CruiseControl] #{`pg_config --version`}"
puts "[CruiseControl] SQLite2: #{`sqlite -version`}"
puts "[CruiseControl] SQLite3: #{`sqlite3 -version`}"
-`gem env`.each {|line| print "[CruiseControl] #{line}"}
+`gem env`.each_line {|line| print "[CruiseControl] #{line}"}
puts "[CruiseControl] Local gems:"
-`gem list`.each {|line| print "[CruiseControl] #{line}"}
+`gem list`.each_line {|line| print "[CruiseControl] #{line}"}
failures = build_results.select { |key, value| value == false }
diff --git a/ci/geminstaller.yml b/ci/geminstaller.yml
index d11bf04485..33f1e81179 100644
--- a/ci/geminstaller.yml
+++ b/ci/geminstaller.yml
@@ -7,7 +7,7 @@ gems:
- name: memcache-client
version: >= 1.5.0
- name: mocha
- version: >= 0.9.4
+ version: >= 0.9.5
- name: mysql
#version: >= 2.7
version: = 2.7
diff --git a/railties/guides/files/javascripts/code_highlighter.js b/railties/guides/files/javascripts/code_highlighter.js
index 4ed72e1692..ce983dad52 100755
--- a/railties/guides/files/javascripts/code_highlighter.js
+++ b/railties/guides/files/javascripts/code_highlighter.js
@@ -1,188 +1,188 @@
-/* Unobtrustive Code Highlighter By Dan Webb 11/2005
- Version: 0.4
-
- Usage:
- Add a script tag for this script and any stylesets you need to use
- to the page in question, add correct class names to CODE elements,
- define CSS styles for elements. That's it!
-
- Known to work on:
- IE 5.5+ PC
- Firefox/Mozilla PC/Mac
- Opera 7.23 + PC
- Safari 2
-
- Known to degrade gracefully on:
- IE5.0 PC
-
- Note: IE5.0 fails due to the use of lookahead in some stylesets. To avoid script errors
- in older browsers use expressions that use lookahead in string format when defining stylesets.
-
- This script is inspired by star-light by entirely cunning Dean Edwards
- http://dean.edwards.name/star-light/.
-*/
-
-// replace callback support for safari.
-if ("a".replace(/a/, function() {return "b"}) != "b") (function(){
- var default_replace = String.prototype.replace;
- String.prototype.replace = function(search,replace){
- // replace is not function
- if(typeof replace != "function"){
- return default_replace.apply(this,arguments)
- }
- var str = "" + this;
- var callback = replace;
- // search string is not RegExp
- if(!(search instanceof RegExp)){
- var idx = str.indexOf(search);
- return (
- idx == -1 ? str :
- default_replace.apply(str,[search,callback(search, idx, str)])
- )
- }
- var reg = search;
- var result = [];
- var lastidx = reg.lastIndex;
- var re;
- while((re = reg.exec(str)) != null){
- var idx = re.index;
- var args = re.concat(idx, str);
- result.push(
- str.slice(lastidx,idx),
- callback.apply(null,args).toString()
- );
- if(!reg.global){
- lastidx += RegExp.lastMatch.length;
- break
- }else{
- lastidx = reg.lastIndex;
- }
- }
- result.push(str.slice(lastidx));
- return result.join("")
- }
-})();
-
-var CodeHighlighter = { styleSets : new Array };
-
-CodeHighlighter.addStyle = function(name, rules) {
- // using push test to disallow older browsers from adding styleSets
- if ([].push) this.styleSets.push({
- name : name,
- rules : rules,
- ignoreCase : arguments[2] || false
- })
-
- function setEvent() {
- // set highlighter to run on load (use LowPro if present)
- if (typeof Event != 'undefined' && typeof Event.onReady == 'function')
- return Event.onReady(CodeHighlighter.init.bind(CodeHighlighter));
-
- var old = window.onload;
-
- if (typeof window.onload != 'function') {
- window.onload = function() { CodeHighlighter.init() };
- } else {
- window.onload = function() {
- old();
- CodeHighlighter.init();
- }
- }
- }
-
- // only set the event when the first style is added
- if (this.styleSets.length==1) setEvent();
-}
-
-CodeHighlighter.init = function() {
- if (!document.getElementsByTagName) return;
- if ("a".replace(/a/, function() {return "b"}) != "b") return; // throw out Safari versions that don't support replace function
- // throw out older browsers
-
- var codeEls = document.getElementsByTagName("CODE");
- // collect array of all pre elements
- codeEls.filter = function(f) {
- var a = new Array;
- for (var i = 0; i < this.length; i++) if (f(this[i])) a[a.length] = this[i];
- return a;
- }
-
- var rules = new Array;
- rules.toString = function() {
- // joins regexes into one big parallel regex
- var exps = new Array;
- for (var i = 0; i < this.length; i++) exps.push(this[i].exp);
- return exps.join("|");
- }
-
- function addRule(className, rule) {
- // add a replace rule
- var exp = (typeof rule.exp != "string")?String(rule.exp).substr(1, String(rule.exp).length-2):rule.exp;
- // converts regex rules to strings and chops of the slashes
- rules.push({
- className : className,
- exp : "(" + exp + ")",
- length : (exp.match(/(^|[^\\])\([^?]/g) || "").length + 1, // number of subexps in rule
- replacement : rule.replacement || null
- });
- }
-
- function parse(text, ignoreCase) {
- // main text parsing and replacement
- return text.replace(new RegExp(rules, (ignoreCase)?"gi":"g"), function() {
- var i = 0, j = 1, rule;
- while (rule = rules[i++]) {
- if (arguments[j]) {
- // if no custom replacement defined do the simple replacement
- if (!rule.replacement) return "<span class=\"" + rule.className + "\">" + arguments[0] + "</span>";
- else {
- // replace $0 with the className then do normal replaces
- var str = rule.replacement.replace("$0", rule.className);
- for (var k = 1; k <= rule.length - 1; k++) str = str.replace("$" + k, arguments[j + k]);
- return str;
- }
- } else j+= rule.length;
- }
- });
- }
-
- function highlightCode(styleSet) {
- // clear rules array
- var parsed, clsRx = new RegExp("(\\s|^)" + styleSet.name + "(\\s|$)");
- rules.length = 0;
-
- // get stylable elements by filtering out all code elements without the correct className
- var stylableEls = codeEls.filter(function(item) { return clsRx.test(item.className) });
-
- // add style rules to parser
- for (var className in styleSet.rules) addRule(className, styleSet.rules[className]);
-
-
- // replace for all elements
- for (var i = 0; i < stylableEls.length; i++) {
- // EVIL hack to fix IE whitespace badness if it's inside a <pre>
- if (/MSIE/.test(navigator.appVersion) && stylableEls[i].parentNode.nodeName == 'PRE') {
- stylableEls[i] = stylableEls[i].parentNode;
-
- parsed = stylableEls[i].innerHTML.replace(/(<code[^>]*>)([^<]*)<\/code>/i, function() {
- return arguments[1] + parse(arguments[2], styleSet.ignoreCase) + "</code>"
- });
- parsed = parsed.replace(/\n( *)/g, function() {
- var spaces = "";
- for (var i = 0; i < arguments[1].length; i++) spaces+= "&nbsp;";
- return "\n" + spaces;
- });
- parsed = parsed.replace(/\t/g, "&nbsp;&nbsp;&nbsp;&nbsp;");
- parsed = parsed.replace(/\n(<\/\w+>)?/g, "<br />$1").replace(/<br \/>[\n\r\s]*<br \/>/g, "<p><br></p>");
-
- } else parsed = parse(stylableEls[i].innerHTML, styleSet.ignoreCase);
-
- stylableEls[i].innerHTML = parsed;
- }
- }
-
- // run highlighter on all stylesets
- for (var i=0; i < this.styleSets.length; i++) {
- highlightCode(this.styleSets[i]);
- }
-} \ No newline at end of file
+/* Unobtrustive Code Highlighter By Dan Webb 11/2005
+ Version: 0.4
+
+ Usage:
+ Add a script tag for this script and any stylesets you need to use
+ to the page in question, add correct class names to CODE elements,
+ define CSS styles for elements. That's it!
+
+ Known to work on:
+ IE 5.5+ PC
+ Firefox/Mozilla PC/Mac
+ Opera 7.23 + PC
+ Safari 2
+
+ Known to degrade gracefully on:
+ IE5.0 PC
+
+ Note: IE5.0 fails due to the use of lookahead in some stylesets. To avoid script errors
+ in older browsers use expressions that use lookahead in string format when defining stylesets.
+
+ This script is inspired by star-light by entirely cunning Dean Edwards
+ http://dean.edwards.name/star-light/.
+*/
+
+// replace callback support for safari.
+if ("a".replace(/a/, function() {return "b"}) != "b") (function(){
+ var default_replace = String.prototype.replace;
+ String.prototype.replace = function(search,replace){
+ // replace is not function
+ if(typeof replace != "function"){
+ return default_replace.apply(this,arguments)
+ }
+ var str = "" + this;
+ var callback = replace;
+ // search string is not RegExp
+ if(!(search instanceof RegExp)){
+ var idx = str.indexOf(search);
+ return (
+ idx == -1 ? str :
+ default_replace.apply(str,[search,callback(search, idx, str)])
+ )
+ }
+ var reg = search;
+ var result = [];
+ var lastidx = reg.lastIndex;
+ var re;
+ while((re = reg.exec(str)) != null){
+ var idx = re.index;
+ var args = re.concat(idx, str);
+ result.push(
+ str.slice(lastidx,idx),
+ callback.apply(null,args).toString()
+ );
+ if(!reg.global){
+ lastidx += RegExp.lastMatch.length;
+ break
+ }else{
+ lastidx = reg.lastIndex;
+ }
+ }
+ result.push(str.slice(lastidx));
+ return result.join("")
+ }
+})();
+
+var CodeHighlighter = { styleSets : new Array };
+
+CodeHighlighter.addStyle = function(name, rules) {
+ // using push test to disallow older browsers from adding styleSets
+ if ([].push) this.styleSets.push({
+ name : name,
+ rules : rules,
+ ignoreCase : arguments[2] || false
+ })
+
+ function setEvent() {
+ // set highlighter to run on load (use LowPro if present)
+ if (typeof Event != 'undefined' && typeof Event.onReady == 'function')
+ return Event.onReady(CodeHighlighter.init.bind(CodeHighlighter));
+
+ var old = window.onload;
+
+ if (typeof window.onload != 'function') {
+ window.onload = function() { CodeHighlighter.init() };
+ } else {
+ window.onload = function() {
+ old();
+ CodeHighlighter.init();
+ }
+ }
+ }
+
+ // only set the event when the first style is added
+ if (this.styleSets.length==1) setEvent();
+}
+
+CodeHighlighter.init = function() {
+ if (!document.getElementsByTagName) return;
+ if ("a".replace(/a/, function() {return "b"}) != "b") return; // throw out Safari versions that don't support replace function
+ // throw out older browsers
+
+ var codeEls = document.getElementsByTagName("CODE");
+ // collect array of all pre elements
+ codeEls.filter = function(f) {
+ var a = new Array;
+ for (var i = 0; i < this.length; i++) if (f(this[i])) a[a.length] = this[i];
+ return a;
+ }
+
+ var rules = new Array;
+ rules.toString = function() {
+ // joins regexes into one big parallel regex
+ var exps = new Array;
+ for (var i = 0; i < this.length; i++) exps.push(this[i].exp);
+ return exps.join("|");
+ }
+
+ function addRule(className, rule) {
+ // add a replace rule
+ var exp = (typeof rule.exp != "string")?String(rule.exp).substr(1, String(rule.exp).length-2):rule.exp;
+ // converts regex rules to strings and chops of the slashes
+ rules.push({
+ className : className,
+ exp : "(" + exp + ")",
+ length : (exp.match(/(^|[^\\])\([^?]/g) || "").length + 1, // number of subexps in rule
+ replacement : rule.replacement || null
+ });
+ }
+
+ function parse(text, ignoreCase) {
+ // main text parsing and replacement
+ return text.replace(new RegExp(rules, (ignoreCase)?"gi":"g"), function() {
+ var i = 0, j = 1, rule;
+ while (rule = rules[i++]) {
+ if (arguments[j]) {
+ // if no custom replacement defined do the simple replacement
+ if (!rule.replacement) return "<span class=\"" + rule.className + "\">" + arguments[0] + "</span>";
+ else {
+ // replace $0 with the className then do normal replaces
+ var str = rule.replacement.replace("$0", rule.className);
+ for (var k = 1; k <= rule.length - 1; k++) str = str.replace("$" + k, arguments[j + k]);
+ return str;
+ }
+ } else j+= rule.length;
+ }
+ });
+ }
+
+ function highlightCode(styleSet) {
+ // clear rules array
+ var parsed, clsRx = new RegExp("(\\s|^)" + styleSet.name + "(\\s|$)");
+ rules.length = 0;
+
+ // get stylable elements by filtering out all code elements without the correct className
+ var stylableEls = codeEls.filter(function(item) { return clsRx.test(item.className) });
+
+ // add style rules to parser
+ for (var className in styleSet.rules) addRule(className, styleSet.rules[className]);
+
+
+ // replace for all elements
+ for (var i = 0; i < stylableEls.length; i++) {
+ // EVIL hack to fix IE whitespace badness if it's inside a <pre>
+ if (/MSIE/.test(navigator.appVersion) && stylableEls[i].parentNode.nodeName == 'PRE') {
+ stylableEls[i] = stylableEls[i].parentNode;
+
+ parsed = stylableEls[i].innerHTML.replace(/(<code[^>]*>)([^<]*)<\/code>/i, function() {
+ return arguments[1] + parse(arguments[2], styleSet.ignoreCase) + "</code>"
+ });
+ parsed = parsed.replace(/\n( *)/g, function() {
+ var spaces = "";
+ for (var i = 0; i < arguments[1].length; i++) spaces+= "&nbsp;";
+ return "\n" + spaces;
+ });
+ parsed = parsed.replace(/\t/g, "&nbsp;&nbsp;&nbsp;&nbsp;");
+ parsed = parsed.replace(/\n(<\/\w+>)?/g, "<br />$1").replace(/<br \/>[\n\r\s]*<br \/>/g, "<p><br></p>");
+
+ } else parsed = parse(stylableEls[i].innerHTML, styleSet.ignoreCase);
+
+ stylableEls[i].innerHTML = parsed;
+ }
+ }
+
+ // run highlighter on all stylesets
+ for (var i=0; i < this.styleSets.length; i++) {
+ highlightCode(this.styleSets[i]);
+ }
+}
diff --git a/railties/guides/files/javascripts/guides.js b/railties/guides/files/javascripts/guides.js
index 63c127d04a..81fc07e799 100755
--- a/railties/guides/files/javascripts/guides.js
+++ b/railties/guides/files/javascripts/guides.js
@@ -1,8 +1,8 @@
-function guideMenu(){
-
- if (document.getElementById('guides').style.display == "none") {
- document.getElementById('guides').style.display = "block";
- } else {
- document.getElementById('guides').style.display = "none";
- }
-}
+function guideMenu(){
+
+ if (document.getElementById('guides').style.display == "none") {
+ document.getElementById('guides').style.display = "block";
+ } else {
+ document.getElementById('guides').style.display = "none";
+ }
+}
diff --git a/railties/guides/files/javascripts/highlighters.js b/railties/guides/files/javascripts/highlighters.js
index bf46367dfe..4f5f0779d7 100644
--- a/railties/guides/files/javascripts/highlighters.js
+++ b/railties/guides/files/javascripts/highlighters.js
@@ -47,14 +47,14 @@ CodeHighlighter.addStyle("html", {
exp: /&lt;!\s*(--([^-]|[\r\n]|-[^-])*--\s*)&gt;/
},
tag : {
- exp: /(&lt;\/?)([a-zA-Z1-9]+\s?)/,
+ exp: /(&lt;\/?)([a-zA-Z1-9]+\s?)/,
replacement: "$1<span class=\"$0\">$2</span>"
},
string : {
exp : /'[^']*'|"[^"]*"/
},
attribute : {
- exp: /\b([a-zA-Z-:]+)(=)/,
+ exp: /\b([a-zA-Z-:]+)(=)/,
replacement: "<span class=\"$0\">$1</span>$2"
},
doctype : {
diff --git a/railties/guides/files/stylesheets/main.css b/railties/guides/files/stylesheets/main.css
index 9c9ef5151b..64243be945 100644
--- a/railties/guides/files/stylesheets/main.css
+++ b/railties/guides/files/stylesheets/main.css
@@ -22,7 +22,7 @@ ol { list-style-type: decimal; }
dl { margin: 0 0 1.5em 0; }
dl dt { font-weight: bold; }
dd { margin-left: 1.5em;}
-
+
pre,code { margin: 1.5em 0; white-space: pre; }
pre,code,tt { font: 1em 'andale mono', 'lucida console', monospace; line-height: 1.5; }
@@ -86,7 +86,7 @@ body {
font-family: Helvetica, Arial, sans-serif;
font-size: 87.5%;
line-height: 1.5em;
- background: #222;
+ background: #222;
color: #999;
}
@@ -124,7 +124,7 @@ body {
#mainCol {
width: 45em;
margin-left: 2em;
- }
+ }
#subCol {
position: absolute;
@@ -137,7 +137,7 @@ body {
font-size: 0.9285em;
line-height: 1.3846em;
}
-
+
#extraCol {display: none;}
#footer {
@@ -190,7 +190,7 @@ a, a:link, a:visited {
#header .nav .index a {
background: #980905 url(../../images/nav_arrow.gif) no-repeat right top;
- padding-right: 1em;
+ padding-right: 1em;
position: relative;
z-index: 15;
padding-bottom: 0.125em;
@@ -256,7 +256,7 @@ h3 {
margin: 0.875em 0 0.2916em;
font-weight: bold;
}
-
+
h4 {
font-size: 1.2857em;
line-height: 1.2em;
@@ -271,7 +271,7 @@ h5 {
font-weight: bold;
}
-h6 {
+h6 {
font-size: 1em;
line-height: 1.5em;
margin: 1em 0 .5em;
@@ -418,15 +418,15 @@ em.highlight {
padding-left: 1em;
margin-left: 0;
}
-
+
/* Clearing
--------------------------------------- */
.clearfix:after {
- content: ".";
- display: block;
- height: 0;
- clear: both;
+ content: ".";
+ display: block;
+ height: 0;
+ clear: both;
visibility: hidden;
}
diff --git a/railties/guides/files/stylesheets/print.css b/railties/guides/files/stylesheets/print.css
index 6aa1662c0b..628da105d4 100755
--- a/railties/guides/files/stylesheets/print.css
+++ b/railties/guides/files/stylesheets/print.css
@@ -1,52 +1,52 @@
-/* Guides.rubyonrails.org */
-/* Print.css */
-/* Created January 30, 2009 */
-/* Modified January 31, 2009
---------------------------------------- */
-
-body, .wrapper, .note, .info, code, #topNav, .L, .R, #frame, #container, #header, #navigation, #footer, #feature, #mainCol, #subCol, #extraCol, .content {position: static; text-align: left; text-indent: 0; background: White; color: Black; border-color: Black; width: auto; height: auto; display: block; float: none; min-height: 0; margin: 0; padding: 0;}
-
-body {
- background: #FFF;
- font-size: 10pt !important;
- font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
- line-height: 1.5;
- color: #000;
- padding: 0 3%;
- }
-
-.hide, .nav {
- display: none !important;
- }
-
-a:link, a:visited {
- background: transparent;
- font-weight: bold;
- text-decoration: underline;
- }
-
-hr {
- background:#ccc;
- color:#ccc;
- width:100%;
- height:2px;
- margin:2em 0;
- padding:0;
- border:none;
-}
-
-h1,h2,h3,h4,h5,h6 { font-family: "Helvetica Neue", Arial, "Lucida Grande", sans-serif; }
-code { font:.9em "Courier New", Monaco, Courier, monospace; }
-
-img { float:left; margin:1.5em 1.5em 1.5em 0; }
-a img { border:none; }
-
-blockquote {
- margin:1.5em;
- padding:1em;
- font-style:italic;
- font-size:.9em;
-}
-
-.small { font-size: .9em; }
-.large { font-size: 1.1em; } \ No newline at end of file
+/* Guides.rubyonrails.org */
+/* Print.css */
+/* Created January 30, 2009 */
+/* Modified January 31, 2009
+--------------------------------------- */
+
+body, .wrapper, .note, .info, code, #topNav, .L, .R, #frame, #container, #header, #navigation, #footer, #feature, #mainCol, #subCol, #extraCol, .content {position: static; text-align: left; text-indent: 0; background: White; color: Black; border-color: Black; width: auto; height: auto; display: block; float: none; min-height: 0; margin: 0; padding: 0;}
+
+body {
+ background: #FFF;
+ font-size: 10pt !important;
+ font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
+ line-height: 1.5;
+ color: #000;
+ padding: 0 3%;
+ }
+
+.hide, .nav {
+ display: none !important;
+ }
+
+a:link, a:visited {
+ background: transparent;
+ font-weight: bold;
+ text-decoration: underline;
+ }
+
+hr {
+ background:#ccc;
+ color:#ccc;
+ width:100%;
+ height:2px;
+ margin:2em 0;
+ padding:0;
+ border:none;
+}
+
+h1,h2,h3,h4,h5,h6 { font-family: "Helvetica Neue", Arial, "Lucida Grande", sans-serif; }
+code { font:.9em "Courier New", Monaco, Courier, monospace; }
+
+img { float:left; margin:1.5em 1.5em 1.5em 0; }
+a img { border:none; }
+
+blockquote {
+ margin:1.5em;
+ padding:1em;
+ font-style:italic;
+ font-size:.9em;
+}
+
+.small { font-size: .9em; }
+.large { font-size: 1.1em; }
diff --git a/railties/guides/files/stylesheets/reset.css b/railties/guides/files/stylesheets/reset.css
index 48c2451cb3..cb14fbcc55 100755
--- a/railties/guides/files/stylesheets/reset.css
+++ b/railties/guides/files/stylesheets/reset.css
@@ -1,43 +1,43 @@
-/* Guides.rubyonrails.org */
-/* Reset.css */
-/* Created January 30, 2009
---------------------------------------- */
-
-html, body, div, span, applet, object, iframe,
-h1, h2, h3, h4, h5, h6, p, blockquote, pre,
-a, abbr, acronym, address, big, cite, code,
-del, dfn, em, font, img, ins, kbd, q, s, samp,
-small, strike, strong, sub, sup, tt, var,
-b, u, i, center,
-dl, dt, dd, ol, ul, li,
-fieldset, form, label, legend,
-table, caption, tbody, tfoot, thead, tr, th, td {
- margin: 0;
- padding: 0;
- border: 0;
- outline: 0;
- font-size: 100%;
- background: transparent;
-}
-
-body {line-height: 1; color: black; background: white;}
-a img {border:none;}
-ins {text-decoration: none;}
-del {text-decoration: line-through;}
-
-:focus {
- -moz-outline:0;
- outline:0;
- outline-offset:0;
-}
-
-/* tables still need 'cellspacing="0"' in the markup */
-table {border-collapse: collapse; border-spacing: 0;}
-caption, th, td {text-align: left; font-weight: normal;}
-
-blockquote, q {quotes: none;}
-blockquote:before, blockquote:after,
-q:before, q:after {
- content: '';
- content: none;
-} \ No newline at end of file
+/* Guides.rubyonrails.org */
+/* Reset.css */
+/* Created January 30, 2009
+--------------------------------------- */
+
+html, body, div, span, applet, object, iframe,
+h1, h2, h3, h4, h5, h6, p, blockquote, pre,
+a, abbr, acronym, address, big, cite, code,
+del, dfn, em, font, img, ins, kbd, q, s, samp,
+small, strike, strong, sub, sup, tt, var,
+b, u, i, center,
+dl, dt, dd, ol, ul, li,
+fieldset, form, label, legend,
+table, caption, tbody, tfoot, thead, tr, th, td {
+ margin: 0;
+ padding: 0;
+ border: 0;
+ outline: 0;
+ font-size: 100%;
+ background: transparent;
+}
+
+body {line-height: 1; color: black; background: white;}
+a img {border:none;}
+ins {text-decoration: none;}
+del {text-decoration: line-through;}
+
+:focus {
+ -moz-outline:0;
+ outline:0;
+ outline-offset:0;
+}
+
+/* tables still need 'cellspacing="0"' in the markup */
+table {border-collapse: collapse; border-spacing: 0;}
+caption, th, td {text-align: left; font-weight: normal;}
+
+blockquote, q {quotes: none;}
+blockquote:before, blockquote:after,
+q:before, q:after {
+ content: '';
+ content: none;
+}
diff --git a/railties/guides/files/stylesheets/style.css b/railties/guides/files/stylesheets/style.css
index 0249c77e85..89b2ab885a 100755
--- a/railties/guides/files/stylesheets/style.css
+++ b/railties/guides/files/stylesheets/style.css
@@ -1,13 +1,13 @@
-/* Guides.rubyonrails.org */
-/* Style.css */
-/* Created January 30, 2009
---------------------------------------- */
-
-/*
----------------------------------------
-Import advanced style sheet
----------------------------------------
-*/
-
-@import url("reset.css");
-@import url("main.css");
+/* Guides.rubyonrails.org */
+/* Style.css */
+/* Created January 30, 2009
+--------------------------------------- */
+
+/*
+---------------------------------------
+Import advanced style sheet
+---------------------------------------
+*/
+
+@import url("reset.css");
+@import url("main.css");
diff --git a/railties/guides/files/stylesheets/syntax.css b/railties/guides/files/stylesheets/syntax.css
index 7e5b4bd8c7..55fc5b209f 100644
--- a/railties/guides/files/stylesheets/syntax.css
+++ b/railties/guides/files/stylesheets/syntax.css
@@ -27,5 +27,5 @@
}
.ruby .symbol {
- color: green;
-} \ No newline at end of file
+ color: green;
+}
diff --git a/railties/guides/rails_guides/indexer.rb b/railties/guides/rails_guides/indexer.rb
index 7f1c55a980..52809829e2 100644
--- a/railties/guides/rails_guides/indexer.rb
+++ b/railties/guides/rails_guides/indexer.rb
@@ -43,7 +43,7 @@ module RailsGuides
counters << last + 1
end
end
- s.getch
+ s.getch
end
level_hash
end
diff --git a/railties/guides/source/2_2_release_notes.textile b/railties/guides/source/2_2_release_notes.textile
index f88cd7c5b0..6f882f6d7d 100644
--- a/railties/guides/source/2_2_release_notes.textile
+++ b/railties/guides/source/2_2_release_notes.textile
@@ -137,7 +137,7 @@ development:
</ruby>
* Lead Contributor: "Nick Sieger":http://blog.nicksieger.com/
-* More information:
+* More information:
** "What's New in Edge Rails: Connection Pools":http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-connection-pools
h4. Hashes for Join Table Conditions
@@ -175,7 +175,7 @@ User.find_last_by_city('London')
* Lead Contributor: "Emilio Tagua":http://www.workingwithrails.com/person/9147-emilio-tagua
-h5. +find_by_<attribute>!+
+h5. +find_by_<attribute>!+
The new bang! version of +find_by_<attribute>!+ is equivalent to +Model.first(:conditions => {:attribute => value}) || raise ActiveRecord::RecordNotFound+ Instead of returning +nil+ if it can't find a matching record, this method will raise an exception if it cannot find a match.
@@ -197,7 +197,7 @@ Active Record association proxies now respect the scope of methods on the proxie
h4. Other ActiveRecord Changes
* +rake db:migrate:redo+ now accepts an optional VERSION to target that specific migration to redo
-* Set +config.active_record.timestamped_migrations = false+ to have migrations with numeric prefix instead of UTC timestamp.
+* Set +config.active_record.timestamped_migrations = false+ to have migrations with numeric prefix instead of UTC timestamp.
* Counter cache columns (for associations declared with +:counter_cache => true+) do not need to be initialized to zero any longer.
* +ActiveRecord::Base.human_name+ for an internationalization-aware humane translation of model names
@@ -207,7 +207,7 @@ On the controller side, there are several changes that will help tidy up your ro
h4. Shallow Route Nesting
-Shallow route nesting provides a solution to the well-known difficulty of using deeply-nested resources. With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with.
+Shallow route nesting provides a solution to the well-known difficulty of using deeply-nested resources. With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with.
<ruby>
map.resources :publishers, :shallow => true do |publisher|
@@ -228,7 +228,7 @@ This will enable recognition of (among others) these routes:
</ruby>
* Lead Contributor: "S. Brent Faulkner":http://www.unwwwired.net/
-* More information:
+* More information:
** "Rails Routing from the Outside In":http://guides.rails.info/routing/routing_outside_in.html#_nested_resources
** "What's New in Edge Rails: Shallow Routes":http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-shallow-routes
diff --git a/railties/guides/source/2_3_release_notes.textile b/railties/guides/source/2_3_release_notes.textile
index 235554f904..334416f3f6 100644
--- a/railties/guides/source/2_3_release_notes.textile
+++ b/railties/guides/source/2_3_release_notes.textile
@@ -38,7 +38,7 @@ Here's a summary of the rack-related changes:
* The Rails router and controller classes follow the Rack spec. You can call a controller directly with +SomeController.call(env)+. The router stores the routing parameters in +rack.routing_args+.
* +ActionController::Request+ inherits from +Rack::Request+
* Instead of +config.action_controller.session = { :session_key => 'foo', ...+ use +config.action_controller.session = { :key => 'foo', ...+
-* Using the +ParamsParser+ middleware preprocesses any XML, JSON, or YAML requests so they can be read normally with any +Rack::Request+ object after it.
+* Using the +ParamsParser+ middleware preprocesses any XML, JSON, or YAML requests so they can be read normally with any +Rack::Request+ object after it.
h4. Renewed Support for Rails Engines
@@ -68,7 +68,7 @@ end
</ruby>
Turning on nested attributes enables a number of things: automatic (and atomic) saving of a record together with its associated children, child-aware validations, and support for nested forms (discussed later).
-
+
* Lead Contributor: "Eloy Duran":http://www.superalloy.nl/blog/
* More Information: "Nested Model Forms":http://weblog.rubyonrails.org/2009/1/26/nested-model-forms
@@ -84,7 +84,7 @@ User.transaction do
raise ActiveRecord::Rollback
end
end
-
+
User.find(:all) # => Returns only Admin
</ruby>
@@ -98,7 +98,7 @@ You know about dynamic finders in Rails (which allow you to concoct methods like
<ruby>
Order.scoped_by_customer_id(12)
-Order.scoped_by_customer_id(12).find(:all,
+Order.scoped_by_customer_id(12).find(:all,
:conditions => "status = 'open'")
Order.scoped_by_customer_id(12).scoped_by_status("open")
</ruby>
@@ -110,7 +110,7 @@ There's nothing to define to use dynamic scopes: they just work.
h4. Default Scopes
-Rails 2.3 will introduce the notion of _default scopes_ similar to named scopes, but applying to all named scopes or find methods within the model. For example, you can write +default_scope :order => 'name ASC'+ and any time you retrieve records from that model they'll come out sorted by name (unless you override the option, of course).
+Rails 2.3 will introduce the notion of _default scopes_ similar to named scopes, but applying to all named scopes or find methods within the model. For example, you can write +default_scope :order => 'name ASC'+ and any time you retrieve records from that model they'll come out sorted by name (unless you override the option, of course).
* Lead Contributor: Paweł Kondzior
* More Information: "What's New in Edge Rails: Default Scoping":http://ryandaigle.com/articles/2008/11/18/what-s-new-in-edge-rails-default-scoping
@@ -120,7 +120,7 @@ h4. Multiple Conditions for Callbacks
When using Active Record callbacks, you can now combine +:if+ and +:unless+ options on the same callback, and supply multiple conditions as an array:
<ruby>
-before_save :update_credit_rating, :if => :active,
+before_save :update_credit_rating, :if => :active,
:unless => [:admin, :cash_only]
</ruby>
* Lead Contributor: L. Caviola
@@ -130,7 +130,7 @@ h4. Find with having
Rails now has a +:having+ option on find (as well as on +has_many+ and +has_and_belongs_to_many+ associations) for filtering records in grouped finds. As those with heavy SQL backgrounds know, this allows filtering based on grouped results:
<ruby>
-developers = Developer.find(:all, :group => "salary",
+developers = Developer.find(:all, :group => "salary",
:having => "sum(salary) > 10000", :select => "salary")
</ruby>
@@ -144,7 +144,7 @@ You can once again use a hash in conditions for a +has_many+ relationship:
has_many :orders, :conditions => {:status => 'confirmed'}
</ruby>
-That worked in Rails 2.1, fails in Rails 2.2, and will now work again in Rails 2.3 (if you're dealing with this issue in Rails 2.2, you can use a string rather than a hash to specify conditions).
+That worked in Rails 2.1, fails in Rails 2.2, and will now work again in Rails 2.3 (if you're dealing with this issue in Rails 2.2, you can use a string rather than a hash to specify conditions).
* Lead Contributor: "Frederick Cheung":http://www.spacevatican.org/
@@ -153,7 +153,7 @@ h4. Reconnecting MySQL Connections
MySQL supports a reconnect flag in its connections - if set to true, then the client will try reconnecting to the server before giving up in case of a lost connection. You can now set +reconnect = true+ for your MySQL connections in +database.yml+ to get this behavior from a Rails application. The default is +false+, so the behavior of existing applications doesn't change.
* Lead Contributor: "Dov Murik":http://twitter.com/dubek
-* More information:
+* More information:
** "Controlling Automatic Reconnection Behavior":http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html
** "MySQL auto-reconnect revisited":http://groups.google.com/group/rubyonrails-core/browse_thread/thread/49d2a7e9c96cb9f4
@@ -162,7 +162,7 @@ h4. Other Active Record Changes
* An extra +AS+ was removed from the generated SQL for has_and_belongs_to_many preloading, making it work better for some databases.
* +ActiveRecord::Base#new_record?+ now returns +false+ rather than +nil+ when confronted with an existing record.
* A bug in quoting table names in some +has_many :through+ associations was fixed.
-* You can now specify a particular timestamp for +updated_at+ timestamps: +cust = Customer.create(:name => "ABC Industries", :updated_at => 1.day.ago)+
+* You can now specify a particular timestamp for +updated_at+ timestamps: +cust = Customer.create(:name => "ABC Industries", :updated_at => 1.day.ago)+
* Better error messages on failed +find_by_attribute!+ calls.
* Active Record's +to_xml+ support gets just a little bit more flexible with the addition of a +:camelize+ option.
* A bug in canceling callbacks from +before_update+ or +before_create_ was fixed.
@@ -195,10 +195,10 @@ Rails chooses between file, template, and action depending on whether there is a
h4. Application Controller Renamed
-If you're one of the people who has always been bothered by the special-case naming of +application.rb+, rejoice! It's been reworked to be application_controller.rb in Rails 2.3. In addition, there's a new rake task, +rake rails:update:application_controller+ to do this automatically for you - and it will be run as part of the normal +rake rails:update+ process.
+If you're one of the people who has always been bothered by the special-case naming of +application.rb+, rejoice! It's been reworked to be application_controller.rb in Rails 2.3. In addition, there's a new rake task, +rake rails:update:application_controller+ to do this automatically for you - and it will be run as part of the normal +rake rails:update+ process.
* More Information:
-** "The Death of Application.rb":http://afreshcup.com/2008/11/17/rails-2x-the-death-of-applicationrb/
+** "The Death of Application.rb":http://afreshcup.com/2008/11/17/rails-2x-the-death-of-applicationrb/
** "What's New in Edge Rails: Application.rb Duality is no More":http://ryandaigle.com/articles/2008/11/19/what-s-new-in-edge-rails-application-rb-duality-is-no-more
h4. HTTP Digest Authentication Support
@@ -211,12 +211,12 @@ class PostsController < ApplicationController
before_filter :authenticate
def secret
- render :text => "Password Required!"
+ render :text => "Password Required!"
end
private
def authenticate
- realm = "Application"
+ realm = "Application"
authenticate_or_request_with_http_digest(realm) do |name|
Users[name]
end
@@ -266,15 +266,15 @@ Rails now keeps a per-request local cache of requests, cutting down on unnecessa
h4. Localized Views
-Rails can now provide localized views, depending on the locale that you have set. For example, suppose you have a +Posts+ controller with a +show+ action. By default, this will render +app/views/posts/show.html.erb+. But if you set +I18n.locale = :da+, it will render +app/views/posts/show.da.html.erb+. If the localized template isn't present, the undecorated version will be used. Rails also includes +I18n#available_locales+ and +I18n::SimpleBackend#available_locales+, which return an array of the translations that are available in the current Rails project.
+Rails can now provide localized views, depending on the locale that you have set. For example, suppose you have a +Posts+ controller with a +show+ action. By default, this will render +app/views/posts/show.html.erb+. But if you set +I18n.locale = :da+, it will render +app/views/posts/show.da.html.erb+. If the localized template isn't present, the undecorated version will be used. Rails also includes +I18n#available_locales+ and +I18n::SimpleBackend#available_locales+, which return an array of the translations that are available in the current Rails project.
h4. Other Action Controller Changes
* ETag handling has been cleaned up a bit: Rails will now skip sending an ETag header when there's no body to the response or when sending files with +send_file+.
-* The fact that Rails checks for IP spoofing can be a nuisance for sites that do heavy traffic with cell phones, because their proxies don't generally set things up right. If that's you, you can now set +ActionController::Base.ip_spoofing_check = false+ to disable the check entirely.
-* +ActionController::Dispatcher+ now implements its own middleware stack, which you can see by running +rake middleware+.
-* Cookie sessions now have persistent session identifiers, with API compatibility with the server-side stores.
-* You can now use symbols for the +:type+ option of +send_file+ and +send_data+, like this: +send_file("fabulous.png", :type => :png)+.
+* The fact that Rails checks for IP spoofing can be a nuisance for sites that do heavy traffic with cell phones, because their proxies don't generally set things up right. If that's you, you can now set +ActionController::Base.ip_spoofing_check = false+ to disable the check entirely.
+* +ActionController::Dispatcher+ now implements its own middleware stack, which you can see by running +rake middleware+.
+* Cookie sessions now have persistent session identifiers, with API compatibility with the server-side stores.
+* You can now use symbols for the +:type+ option of +send_file+ and +send_data+, like this: +send_file("fabulous.png", :type => :png)+.
* The +:only+ and +:except+ options for +map.resources+ are no longer inherited by nested resources.
h3. Action View
@@ -327,7 +327,7 @@ You can write this view in Rails 2.3:
</erb>
* Lead Contributor: "Eloy Duran":http://www.superalloy.nl/blog/
-* More Information:
+* More Information:
** "Nested Model Forms":http://weblog.rubyonrails.org/2009/1/26/nested-model-forms
** "complex-form-examples":http://github.com/alloy/complex-form-examples/tree/nested_attributes
** "What's New in Edge Rails: Nested Object Forms":http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes
@@ -337,11 +337,11 @@ h4. Smart Rendering of Partials
The render method has been getting smarter over the years, and it's even smarter now. If you have an object or a collection and an appropriate partial, and the naming matches up, you can now just render the object and things will work. For example, in Rails 2.3, these render calls will work in your view (assuming sensible naming):
<ruby>
-# Equivalent of render :partial => 'articles/_article',
+# Equivalent of render :partial => 'articles/_article',
# :object => @article
-render @article
+render @article
-# Equivalent of render :partial => 'articles/_article',
+# Equivalent of render :partial => 'articles/_article',
# :collection => @articles
render @articles
</ruby>
@@ -357,9 +357,9 @@ select_datetime(DateTime.now, :prompt => true)
select_datetime(DateTime.now, :prompt => "Choose date and time")
-select_datetime(DateTime.now, :prompt =>
- {:day => 'Choose day', :month => 'Choose month',
- :year => 'Choose year', :hour => 'Choose hour',
+select_datetime(DateTime.now, :prompt =>
+ {:day => 'Choose day', :month => 'Choose month',
+ :year => 'Choose year', :hour => 'Choose hour',
:minute => 'Choose minute'})
</ruby>
@@ -380,7 +380,7 @@ h4. grouped_options_for_select Helper Method
Action View already had a bunch of helpers to aid in generating select controls, but now there's one more: +grouped_options_for_select+. This one accepts an array or hash of strings, and converts them into a string of +option+ tags wrapped with +optgroup+ tags. For example:
<ruby>
-grouped_options_for_select([["Hats", ["Baseball Cap","Cowboy Hat"]]],
+grouped_options_for_select([["Hats", ["Baseball Cap","Cowboy Hat"]]],
"Cowboy Hat", "Choose a product...")
</ruby>
@@ -396,9 +396,9 @@ returns
h4. Other Action View Changes
-* Token generation for CSRF protection has been simplified; now Rails uses a simple random string generated by +ActiveSupport::SecureRandom+ rather than mucking around with session IDs.
-* +auto_link+ now properly applies options (such as +:target+ and +:class+) to generated e-mail links.
-* The +autolink+ helper has been refactored to make it a bit less messy and more intuitive.
+* Token generation for CSRF protection has been simplified; now Rails uses a simple random string generated by +ActiveSupport::SecureRandom+ rather than mucking around with session IDs.
+* +auto_link+ now properly applies options (such as +:target+ and +:class+) to generated e-mail links.
+* The +autolink+ helper has been refactored to make it a bit less messy and more intuitive.
h3. Active Support
@@ -408,7 +408,7 @@ h4. Object#try
A lot of folks have adopted the notion of using try() to attempt operations on objects. It's especially helpful in views where you can avoid nil-checking by writing code like +<%= @person.try(:name) %>+. Well, now it's baked right into Rails. As implemented in Rails, it raises +NoMethodError+ on private methods and always returns +nil+ if the object is nil.
-* More Information: "try()":http://ozmm.org/posts/try.html.
+* More Information: "try()":http://ozmm.org/posts/try.html.
h4. Object#tap Backport
@@ -432,10 +432,10 @@ If you look up the spec on the "json.org" site, you'll discover that all keys in
h4. Other Active Support Changes
* You can use +Enumerable#none?+ to check that none of the elements match the supplied block.
-* If you're using Active Support "delegates":http://afreshcup.com/2008/10/19/coming-in-rails-22-delegate-prefixes/, the new +:allow_nil+ option lets you return +nil+ instead of raising an exception when the target object is nil.
-* +ActiveSupport::OrderedHash+: now implements +each_key+ and +each_value+.
-* +ActiveSupport::MessageEncryptor+ provides a simple way to encrypt information for storage in an untrusted location (like cookies).
-* Active Support's +from_xml+ no longer depends on XmlSimple. Instead, Rails now includes its own XmlMini implementation, with just the functionality that it requires. This lets Rails dispense with the bundled copy of XmlSimple that it's been carting around.
+* If you're using Active Support "delegates":http://afreshcup.com/2008/10/19/coming-in-rails-22-delegate-prefixes/, the new +:allow_nil+ option lets you return +nil+ instead of raising an exception when the target object is nil.
+* +ActiveSupport::OrderedHash+: now implements +each_key+ and +each_value+.
+* +ActiveSupport::MessageEncryptor+ provides a simple way to encrypt information for storage in an untrusted location (like cookies).
+* Active Support's +from_xml+ no longer depends on XmlSimple. Instead, Rails now includes its own XmlMini implementation, with just the functionality that it requires. This lets Rails dispense with the bundled copy of XmlSimple that it's been carting around.
h3. Railties
@@ -443,7 +443,7 @@ In addition to the Rack changes covered above, Railties (the core code of Rails
h4. Rails Metal
-Rails Metal is a new mechanism that provides superfast endpoints inside of your Rails applications. Metal classes bypass routing and Action Controller to give you raw speed (at the cost of all the things in Action Controller, of course). This builds on all of the recent foundation work to make Rails a Rack application with an exposed middleware stack.
+Rails Metal is a new mechanism that provides superfast endpoints inside of your Rails applications. Metal classes bypass routing and Action Controller to give you raw speed (at the cost of all the things in Action Controller, of course). This builds on all of the recent foundation work to make Rails a Rack application with an exposed middleware stack.
* More Information:
** "Introducing Rails Metal":http://weblog.rubyonrails.org/2008/12/17/introducing-rails-metal
@@ -470,7 +470,7 @@ Building on Thoughtbot's "Quiet Backtrace":http://www.thoughtbot.com/projects/qu
h4. Faster Boot Time in Development Mode with Lazy Loading/Autoload
-Quite a bit of work was done to make sure that bits of Rails (and its dependencies) are only brought into memory when they're actually needed. The core frameworks - Active Support, Active Record, Action Controller, Action Mailer and Action View - are now using +autoload+ to lazy-load their individual classes. This work should help keep the memory footprint down and improve overall Rails performance.
+Quite a bit of work was done to make sure that bits of Rails (and its dependencies) are only brought into memory when they're actually needed. The core frameworks - Active Support, Active Record, Action Controller, Action Mailer and Action View - are now using +autoload+ to lazy-load their individual classes. This work should help keep the memory footprint down and improve overall Rails performance.
You can also specify (by using the new +preload_frameworks+ option) whether the core libraries should be autoloaded at startup. This defaults to +false+ so that Rails autoloads itself piece-by-piece, but there are some circumstances where you still need to bring in everything at once - Passenger and JRuby both want to see all of Rails loaded together.
@@ -479,16 +479,16 @@ h4. Other Railties Changes
* The instructions for updating a CI server to build Rails have been updated and expanded.
* Internal Rails testing has been switched from +Test::Unit::TestCase+ to +ActiveSupport::TestCase+, and the Rails core requires Mocha to test.
* The default +environment.rb+ file has been decluttered.
-* The dbconsole script now lets you use an all-numeric password without crashing.
-* +Rails.root+ now returns a +Pathname+ object, which means you can use it directly with the +join+ method to "clean up existing code":http://afreshcup.com/2008/12/05/a-little-rails_root-tidiness/ that uses +File.join+.
-* Various files in /public that deal with CGI and FCGI dispatching are no longer generated in every Rails application by default (you can still get them if you need them by adding +--with-dispatches+ when you run the +rails+ command, or add them later with +rake rails:generate_dispatchers+).
+* The dbconsole script now lets you use an all-numeric password without crashing.
+* +Rails.root+ now returns a +Pathname+ object, which means you can use it directly with the +join+ method to "clean up existing code":http://afreshcup.com/2008/12/05/a-little-rails_root-tidiness/ that uses +File.join+.
+* Various files in /public that deal with CGI and FCGI dispatching are no longer generated in every Rails application by default (you can still get them if you need them by adding +--with-dispatches+ when you run the +rails+ command, or add them later with +rake rails:generate_dispatchers+).
h3. Deprecated
A few pieces of older code are deprecated in this release:
-* If you're one of the (fairly rare) Rails developers who deploys in a fashion that depends on the inspector, reaper, and spawner scripts, you'll need to know that those scripts are no longer included in core Rails. If you need them, you'll be able to pick up copies via the "irs_process_scripts":http://github.com/rails/irs_process_scripts/tree plugin.
-* +render_component+ goes from "deprecated" to "nonexistent" in Rails 2.3. If you still need it, you can install the "render_component plugin":http://github.com/rails/render_component/tree/master.
+* If you're one of the (fairly rare) Rails developers who deploys in a fashion that depends on the inspector, reaper, and spawner scripts, you'll need to know that those scripts are no longer included in core Rails. If you need them, you'll be able to pick up copies via the "irs_process_scripts":http://github.com/rails/irs_process_scripts/tree plugin.
+* +render_component+ goes from "deprecated" to "nonexistent" in Rails 2.3. If you still need it, you can install the "render_component plugin":http://github.com/rails/render_component/tree/master.
* Support for Rails components has been removed.
* If you were one of the people who got used to running +script/performance/request+ to look at performance based on integration tests, you need to learn a new trick: that script has been removed from core Rails now. There’s a new request_profiler plugin that you can install to get the exact same functionality back.
* +ActionController::Base#session_enabled?+ is deprecated because sessions are lazy-loaded now.
diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile
index d51f2a9745..31a9c6819c 100644
--- a/railties/guides/source/action_controller_overview.textile
+++ b/railties/guides/source/action_controller_overview.textile
@@ -68,9 +68,9 @@ You will probably want to access data sent in by the user or other parameters in
<ruby>
class ClientsController < ActionController::Base
- # This action uses query string parameters because it gets run by a HTTP
- # GET request, but this does not make any difference to the way in which
- # the parameters are accessed. The URL for this action would look like this
+ # This action uses query string parameters because it gets run by a HTTP
+ # GET request, but this does not make any difference to the way in which
+ # the parameters are accessed. The URL for this action would look like this
# in order to list activated clients: /clients?status=activated
def index
if params[:status] = "activated"
diff --git a/railties/guides/source/action_mailer_basics.textile b/railties/guides/source/action_mailer_basics.textile
index 5157e62788..9c56691dc1 100644
--- a/railties/guides/source/action_mailer_basics.textile
+++ b/railties/guides/source/action_mailer_basics.textile
@@ -184,7 +184,7 @@ class UserMailer < ActionMailer::Base
sent_on Time.now
body {:user => user, :url => "http://example.com/login"}
content_type "text/html"
-
+
# change the default from welcome_email.[html, txt].erb
template "some_other_template" # this will be in app/views/user_mailer/some_other_template.[html, txt].erb
end
@@ -254,15 +254,15 @@ class UserMailer < ActionMailer::Base
subject "New account information"
from "system@example.com"
content_type "multipart/alternative"
-
+
part :content_type => "text/html",
:body => "<p>html content, can also be the name of an action that you call<p>"
-
+
part "text/plain" do |p|
p.body = "text content, can also be the name of an action that you call"
end
end
-
+
end
</ruby>
@@ -278,15 +278,15 @@ class UserMailer < ActionMailer::Base
subject "New account information"
from "system@example.com"
content_type "multipart/alternative"
-
+
attachment :content_type => "image/jpeg",
:body => File.read("an-image.jpg")
-
+
attachment "application/pdf" do |a|
a.body = generate_your_pdf_here()
end
end
-
+
end
</ruby>
@@ -307,21 +307,21 @@ class UserMailer < ActionMailer::Base
def receive(email)
page = Page.find_by_address(email.to.first)
page.emails.create(
- :subject => email.subject,
+ :subject => email.subject,
:body => email.body
)
if email.has_attachments?
for attachment in email.attachments
- page.attachments.create({
- :file => attachment,
+ page.attachments.create({
+ :file => attachment,
:description => email.subject
})
end
end
end
-
-
+
+
end
</ruby>
@@ -363,8 +363,8 @@ ActionMailer::Base.sendmail_settings = {
:location => '/usr/sbin/sendmail',
:arguments => '-i -t'
}
-ActionMailer::Base.perform_deliveries = true
-ActionMailer::Base.raise_delivery_errors = true
+ActionMailer::Base.perform_deliveries = true
+ActionMailer::Base.raise_delivery_errors = true
ActionMailer::Base.default_charset = "iso-8859-1"
</ruby>
diff --git a/railties/guides/source/active_record_basics.textile b/railties/guides/source/active_record_basics.textile
index 5446c5dd81..ab3e4c6e96 100644
--- a/railties/guides/source/active_record_basics.textile
+++ b/railties/guides/source/active_record_basics.textile
@@ -8,7 +8,7 @@ After reading this guide we hope that you'll be able to:
* Create basic Active Record models and map them with your database tables.
* Use your models to execute CRUD (Create, Read, Update and Delete) database operations.
* Follow the naming conventions used by Rails to make developing database applications easier and obvious.
-* Take advantage of the way Active Record maps it's attributes with the database tables' columns to implement your application's logic.
+* Take advantage of the way Active Record maps it's attributes with the database tables' columns to implement your application's logic.
* Use Active Record with legacy databases that do not follow the Rails naming conventions.
endprologue.
@@ -39,7 +39,7 @@ ActiveRecord gives us several mechanisms, being the most important ones the habi
* Validate models before they get recorded to the database.
* Perform database operations in an object-oriented fashion.
-It's easy to see that the Rails Active Record implementation goes way beyond the basic description of the Active Record Pattern.
+It's easy to see that the Rails Active Record implementation goes way beyond the basic description of the Active Record Pattern.
h3. Active Record inside the MVC model
@@ -54,7 +54,7 @@ h4. Naming Conventions
By default, ActiveRecord uses some naming conventions to find out how the mapping between models and database tables should be created. Rails will pluralize your class names to find the respective database table. So, for a class +Book+, you should have a database table called *books*. The Rails pluralization mechanisms are very powerful, being capable to pluralize (and singularize) both regular and irregular words. When using class names composed of two or more words, the model class name should follow the Ruby conventions, using the camelCase form, while the table name must contain the words separated by underscores. Examples:
* Database Table - Plural with underscores separating words i.e. (book_clubs)
-* Model Class - Singular with the first letter of each word capitalized i.e. (BookClub)
+* Model Class - Singular with the first letter of each word capitalized i.e. (BookClub)
|_.Model / Class |_.Table / Schema |
|Post |posts|
@@ -109,7 +109,7 @@ puts p.name # "Some Book"
h3. Overriding the naming conventions
-What if you need to follow a different naming convention or need to use your Rails application with a legacy database? No problem, you can easily override the default conventions.
+What if you need to follow a different naming convention or need to use your Rails application with a legacy database? No problem, you can easily override the default conventions.
You can use the +ActiveRecord::Base.set_table_name+ method to specify the table name that should be used:
<ruby>
diff --git a/railties/guides/source/activerecord_validations_callbacks.textile b/railties/guides/source/activerecord_validations_callbacks.textile
index c84b458a8c..28948eca77 100644
--- a/railties/guides/source/activerecord_validations_callbacks.textile
+++ b/railties/guides/source/activerecord_validations_callbacks.textile
@@ -23,7 +23,7 @@ Before you dive into the detail of validations in Rails, you should understand a
h4. Why Use ActiveRecord Validations?
-The main reason for validating your objects before they get into the database is to ensure that only valid data is recorded. It's important to be sure that an email address column only contains valid email addresses, or that the customer's name column will never be empty. Constraints like that keep your database organized and helps your application to work properly.
+The main reason for validating your objects before they get into the database is to ensure that only valid data is recorded. It's important to be sure that an email address column only contains valid email addresses, or that the customer's name column will never be empty. Constraints like that keep your database organized and helps your application to work properly.
There are several ways that you could validate the data that goes to the database, including native database constraints, client-side validations, and model-level validations. Each of these has pros and cons:
@@ -31,7 +31,7 @@ There are several ways that you could validate the data that goes to the databas
* Implementing validations only at the client side can be difficult in web-based applications. Usually this kind of validation is done using javascript, which may be turned off in the user's browser, leading to invalid data getting inside your database. However, if combined with server side validation, client side validation may be useful, since the user can have a faster feedback from the application when trying to save invalid data.
* Using validation directly in your Active Record classes ensures that only valid data gets recorded, while still keeping the validation code in the right place, avoiding breaking the MVC pattern. Since the validation happens on the server side, the user cannot disable it, so it's also safer. It may be a hard and tedious work to implement some of the logic involved in your models' validations, but fear not: Active Record gives you the ability to easily create validations, providing built-in helpers for common validations while still allowing you to create your own validation methods.
-# TODO consider adding a bullet point on validations in controllers, and why model validations should be preferred over complicated controllers.
+# TODO consider adding a bullet point on validations in controllers, and why model validations should be preferred over complicated controllers.
# http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model
h4. When Does Validation Happen?
@@ -58,7 +58,7 @@ We can see how it works by looking at some script/console output:
Creating and saving a new record will send an SQL +INSERT+ operation to the database. Updating an existing record will send an SQL +UPDATE+ operation instead. Validations are typically run before these commands are sent to the database. If any validations fail, the object will be marked as invalid and Active Record will not trigger the +INSERT+ or +UPDATE+ operation. This helps to avoid storing an object in the database that's invalid. You can choose to have specific validations run when an object is created, saved, or updated.
-CAUTION: There are many ways to change the state of an object in the database. Some methods will trigger validations, but some will not. This means that it's possible to save an object in the database in an invalid state if you aren't careful.
+CAUTION: There are many ways to change the state of an object in the database. Some methods will trigger validations, but some will not. This means that it's possible to save an object in the database in an invalid state if you aren't careful.
The following methods trigger validations, and will save the object to the database only if the object is valid. The bang versions (e.g. +save!+) will raise an exception if the record is invalid. The non-bang versions (e.g. +save+) simply return +false+.
@@ -100,7 +100,7 @@ Person.create(:name => "John Doe").valid? # => true
Person.create.valid? # => false
</ruby>
-When Active Record is performing validations, any errors found are collected into an +errors+ instance variable and can be accessed through an +errors+ instance method. An object is considered invalid if it has errors, and calling +save+ or +save!+ will not save it to the database.
+When Active Record is performing validations, any errors found are collected into an +errors+ instance variable and can be accessed through an +errors+ instance method. An object is considered invalid if it has errors, and calling +save+ or +save!+ will not save it to the database.
However, note that an object instantiated with +new+ will not report errors even if it's technically invalid, because validations are not run when using +new+.
@@ -129,20 +129,20 @@ end
=> ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
</ruby>
-To verify whether or not a particular attribute of an object is valid, you can use the +invalid?+ method. This method is only useful _after_ validations have been run, because it only inspects the errors collection and does not trigger validations itself. It's different from the +valid?+ method because it doesn't verify the validity of the object as a whole, but only if there are errors found on an individual attribute of the object.
+To verify whether or not a particular attribute of an object is valid, you can use the +invalid?+ method. This method is only useful _after_ validations have been run, because it only inspects the errors collection and does not trigger validations itself. It's different from the +valid?+ method because it doesn't verify the validity of the object as a whole, but only if there are errors found on an individual attribute of the object.
<ruby>
class Person < ActiveRecord::Base
validates_presence_of :name
end
-
+
>> Person.new.errors.invalid?(:name) # => false
>> Person.create.errors.invalid?(:name) # => true
</ruby>
h3. Declarative Validation Helpers
-Active Record offers many pre-defined validation helpers that you can use directly inside your class definitions. These helpers create validation rules that are commonly used. Every time a validation fails, an error message is added to the object's +errors+ collection, and this message is associated with the field being validated.
+Active Record offers many pre-defined validation helpers that you can use directly inside your class definitions. These helpers create validation rules that are commonly used. Every time a validation fails, an error message is added to the object's +errors+ collection, and this message is associated with the field being validated.
Each helper accepts an arbitrary number of attributes identified by symbols, so with a single line of code you can add the same kind of validation to several attributes.
@@ -219,7 +219,7 @@ This helper validates that the attributes' values are not included in a given se
<ruby>
class MovieFile < ActiveRecord::Base
- validates_exclusion_of :format, :in => %w(mov avi),
+ validates_exclusion_of :format, :in => %w(mov avi),
:message => "Extension %s is not allowed"
end
</ruby>
@@ -234,7 +234,7 @@ This helper validates the attributes' values by testing whether they match a giv
<ruby>
class Product < ActiveRecord::Base
- validates_format_of :description, :with => /^[a-zA-Z]+$/,
+ validates_format_of :description, :with => /^[a-zA-Z]+$/,
:message => "Only letters allowed"
end
</ruby>
@@ -247,7 +247,7 @@ This helper validates that the attributes' values are included in a given set. I
<ruby>
class Coffee < ActiveRecord::Base
- validates_inclusion_of :size, :in => %w(small medium large),
+ validates_inclusion_of :size, :in => %w(small medium large),
:message => "%s is not a valid size"
end
</ruby>
@@ -273,7 +273,7 @@ The possible length constraint options are:
* +:minimum+ - The attribute cannot have less than the specified length.
* +:maximum+ - The attribute cannot have more than the specified length.
-* +:in+ (or +:within+) - The attribute length must be included in a given interval. The value for this option must be a Ruby range.
+* +:in+ (or +:within+) - The attribute length must be included in a given interval. The value for this option must be a Ruby range.
* +:is+ - The attribute length must be equal to a given value.
The default error messages depend on the type of length validation being performed. You can personalize these messages, using the +:wrong_length+, +:too_long+ and +:too_short+ options and the +%d+ format mask as a placeholder for the number corresponding to the length constraint being used. You can still use the +:message+ option to specify an error message.
@@ -314,7 +314,7 @@ The default error message for +validates_numericality_of+ is "_is not a number_"
h4. validates_presence_of
-This helper validates that the specified attributes are not empty. It uses the +blank?+ method to check if the value is either +nil+ or an empty string (if the string has only spaces, it will still be considered empty).
+This helper validates that the specified attributes are not empty. It uses the +blank?+ method to check if the value is either +nil+ or an empty string (if the string has only spaces, it will still be considered empty).
<ruby>
class Person < ActiveRecord::Base
@@ -331,7 +331,7 @@ class LineItem < ActiveRecord::Base
end
</ruby>
-NOTE: If you want to validate the presence of a boolean field (where the real values are true and false), you should use validates_inclusion_of :field_name, :in => [true, false] This is due to the way Object#blank? handles boolean values. false.blank? # => true
+NOTE: If you want to validate the presence of a boolean field (where the real values are true and false), you should use validates_inclusion_of :field_name, :in => [true, false] This is due to the way Object#blank? handles boolean values. false.blank? # => true
The default error message for +validates_presence_of+ is "_can't be empty_".
@@ -351,7 +351,7 @@ There is a +:scope+ option that you can use to specify other attributes that are
<ruby>
class Holiday < ActiveRecord::Base
- validates_uniqueness_of :name, :scope => :year,
+ validates_uniqueness_of :name, :scope => :year,
:message => "Should happen once per year"
end
</ruby>
@@ -390,7 +390,7 @@ The +:allow_nil+ option skips the validation when the value being validated is +
<ruby>
class Coffee < ActiveRecord::Base
- validates_inclusion_of :size, :in => %w(small medium large),
+ validates_inclusion_of :size, :in => %w(small medium large),
:message => "%s is not a valid size", :allow_nil => true
end
</ruby>
@@ -419,13 +419,13 @@ The +:on+ option lets you specify when the validation should happen. The default
<ruby>
class Person < ActiveRecord::Base
# => it will be possible to update email with a duplicated value
- validates_uniqueness_of :email, :on => :create
-
+ validates_uniqueness_of :email, :on => :create
+
# => it will be possible to create the record with a 'non-numerical age'
- validates_numericality_of :age, :on => :update
-
+ validates_numericality_of :age, :on => :update
+
# => the default (validates on both create and update)
- validates_presence_of :name, :on => :save
+ validates_presence_of :name, :on => :save
end
</ruby>
@@ -440,7 +440,7 @@ You can associate the +:if+ and +:unless+ options with a symbol corresponding to
<ruby>
class Order < ActiveRecord::Base
validates_presence_of :card_number, :if => :paid_with_card?
-
+
def paid_with_card?
payment_type == "card"
end
@@ -463,7 +463,7 @@ Finally, it's possible to associate +:if+ and +:unless+ with a Ruby Proc object
<ruby>
class Account < ActiveRecord::Base
- validates_confirmation_of :password,
+ validates_confirmation_of :password,
:unless => Proc.new { |a| a.password.blank? }
end
</ruby>
@@ -474,16 +474,16 @@ When the built-in validation helpers are not enough for your needs, you can writ
<ruby>
class Invoice < ActiveRecord::Base
- validate :expiration_date_cannot_be_in_the_past,
+ validate :expiration_date_cannot_be_in_the_past,
:discount_cannot_be_more_than_total_value
def expiration_date_cannot_be_in_the_past
- errors.add(:expiration_date, "can't be in the past") if
+ errors.add(:expiration_date, "can't be in the past") if
!expiration_date.blank? and expiration_date < Date.today
- end
-
+ end
+
def discount_cannot_be_greater_than_total_value
- errors.add(:discount, "can't be greater than total value") unless
+ errors.add(:discount, "can't be greater than total value") unless
discount <= total_value
end
end
@@ -567,7 +567,7 @@ person.errors.on(:name) # => nil
person = Person.new(:name => "JD")
person.valid? # => false
-person.errors.on(:name)
+person.errors.on(:name)
# => "is too short (minimum is 3 characters)"
person = Person.new
@@ -586,11 +586,11 @@ end
person = Person.new
person.valid? # => false
-person.errors.on(:name)
+person.errors.on(:name)
# => ["can't be blank", "is too short (minimum is 3 characters)"]
person.errors.clear
-person.errors.empty? # => true
+person.errors.empty? # => true
p.save # => false
p.errors.on(:name)
# => ["can't be blank", "is too short (minimum is 3 characters)"]
@@ -655,7 +655,7 @@ It's also possible to change the CSS classes used by the +error_messages+ helper
* +.fieldWithErrors+ - Style for the form fields with errors.
* +#errorExplanation+ - Style for the +div+ element with the error messages.
-* +#errorExplanation h2+ - Style for the header of the +div+ element.
+* +#errorExplanation h2+ - Style for the header of the +div+ element.
* +#errorExplanation p+ - Style for the paragraph that holds the message that appears right below the header of the +div+ element.
* +#errorExplanation ul li+ - Style for the list of error messages.
@@ -679,7 +679,7 @@ This will result in something like the following content:
!images/validation_error_messages.png(Validation error messages)!
-The way form fields with errors are treated is defined by the +ActionView::Base.field_error_proc+ Ruby Proc. This Proc receives two parameters:
+The way form fields with errors are treated is defined by the +ActionView::Base.field_error_proc+ Ruby Proc. This Proc receives two parameters:
* A string with the HTML tag
* An object of the +ActionView::Helpers::InstanceTag+ class.
@@ -689,7 +689,7 @@ h3. Callbacks
Callbacks are methods that get called at certain moments of an object's lifecycle. With callbacks it's possible to write code that will run whenever an Active Record object is created, saved, updated, deleted or loaded from the database.
# TODO discuss what does/doesn't trigger callbacks, like we did in the validations section (e.g. destroy versus delete).
-# Consider moving up to the (new) intro overview section, before getting into details.
+# Consider moving up to the (new) intro overview section, before getting into details.
# http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002220
# http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
@@ -700,15 +700,15 @@ In order to use the available callbacks, you need to register them. You can do t
<ruby>
class User < ActiveRecord::Base
validates_presence_of :login, :email
-
+
before_validation :ensure_login_has_a_value
-
+
protected
def ensure_login_has_a_value
if self.login.nil?
self.login = email unless email.blank?
end
- end
+ end
end
</ruby>
@@ -717,7 +717,7 @@ The macro-style class methods can also receive a block. Rails best practices say
<ruby>
class User < ActiveRecord::Base
validates_presence_of :login, :email
-
+
before_create {|user| user.name = user.login.capitalize if user.name.blank?}
end
</ruby>
@@ -756,7 +756,7 @@ Finally, it's possible to associate +:if+ and +:unless+ with a Ruby Proc object.
<ruby>
class Order < ActiveRecord::Base
- before_save :normalize_card_number,
+ before_save :normalize_card_number,
:if => Proc.new { |order| order.paid_with_card? }
end
</ruby>
@@ -767,14 +767,14 @@ When writing conditional callbacks, it's possible to mix both +:if+ and +:unless
<ruby>
class Comment < ActiveRecord::Base
- after_create :send_email_to_author, :if => :author_wants_emails?,
+ after_create :send_email_to_author, :if => :author_wants_emails?,
:unless => Proc.new { |comment| comment.post.ignore_comments? }
end
</ruby>
h3. Available callbacks
-# TODO consider moving above the code examples and details, possibly combining with intro lifecycle stuff?
+# TODO consider moving above the code examples and details, possibly combining with intro lifecycle stuff?
Here is a list with all the available Active Record callbacks, listed in the same order in which they will get called during the respective operations.
@@ -783,16 +783,16 @@ h4. Callbacks called both when creating or updating a record.
# TODO consider just listing these in the possible lifecycle of an object, roughly as they do here:
# http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
-* +before_validation+
-* +after_validation+
-* +before_save+
+* +before_validation+
+* +after_validation+
+* +before_save+
* *INSERT OR UPDATE OPERATION*
-* +after_save+
+* +after_save+
h4. Callbacks called only when creating a new record.
-* +before_validation_on_create+
-* +after_validation_on_create+
+* +before_validation_on_create+
+* +after_validation_on_create+
* +before_create+
* *INSERT OPERATION*
* +after_create+
@@ -817,7 +817,7 @@ h4. after_initialize and after_find callbacks
The +after_initialize+ callback will be called whenever an Active Record object is instantiated, either by directly using +new+ or when a record is loaded from the database. It can be useful to avoid the need to directly override your Active Record +initialize+ method.
-The +after_find+ callback will be called whenever Active Record loads a record from the database. When used together with +after_initialize+ it will run first, since Active Record will first read the record from the database and them create the model object that will hold it.
+The +after_find+ callback will be called whenever Active Record loads a record from the database. When used together with +after_initialize+ it will run first, since Active Record will first read the record from the database and them create the model object that will hold it.
The +after_initialize+ and +after_find+ callbacks are a bit different from the others, since the only way to register those callbacks is by defining them as methods. If you try to register +after_initialize+ or +after_find+ using macro-style class methods, they will just be ignored. This behaviour is due to performance reasons, since +after_initialize+ and +after_find+ will both be called for each record found in the database, significantly slowing down the queries.
@@ -854,7 +854,7 @@ class PictureFileCallbacks
def self.after_destroy(picture_file)
File.delete(picture_file.filepath) if File.exists?(picture_file.filepath)
end
-end
+end
</ruby>
If the callback method is declared this way, it won't be necessary to instantiate a PictureFileCallbacks object.
@@ -887,7 +887,7 @@ end
Like in callback classes, the observer's methods receive the observed model as a parameter.
-Sometimes using the ModelName + Observer naming convention won't be the best choice, mainly when you want to use the same observer for more than one model class. It's possible to explicity specify the models that our observer should observe.
+Sometimes using the ModelName + Observer naming convention won't be the best choice, mainly when you want to use the same observer for more than one model class. It's possible to explicity specify the models that our observer should observe.
<ruby>
class Auditor < ActiveRecord::Observer
diff --git a/railties/guides/source/association_basics.textile b/railties/guides/source/association_basics.textile
index b18bc47d80..43e81123e9 100644
--- a/railties/guides/source/association_basics.textile
+++ b/railties/guides/source/association_basics.textile
@@ -23,7 +23,7 @@ end
Now, suppose we wanted to add a new order for an existing customer. We'd need to do something like this:
<ruby>
-@order = Order.create(:order_date => Time.now,
+@order = Order.create(:order_date => Time.now,
:customer_id => @customer.id)
</ruby>
@@ -268,7 +268,7 @@ class Part < ActiveRecord::Base
end
</ruby>
-The simplest rule of thumb is that you should set up a +has_many :through+ relationship if you need to work with the relationship model as an independent entity. If you don't need to do anything with the relationship model, it may be simpler to set up a +has_and_belongs_to_many+ relationship (though you'll need to remember to create the joining table).
+The simplest rule of thumb is that you should set up a +has_many :through+ relationship if you need to work with the relationship model as an independent entity. If you don't need to do anything with the relationship model, it may be simpler to set up a +has_and_belongs_to_many+ relationship (though you'll need to remember to create the joining table).
You should use +has_many :through+ if you need validations, callbacks, or extra attributes on the join model.
@@ -290,7 +290,7 @@ class Product < ActiveRecord::Base
end
</ruby>
-You can think of a polymorphic +belongs_to+ declaration as setting up an interface that any other model can use. From an instance of the +Employee+ model, you can retrieve a collection of pictures: +@employee.pictures+.
+You can think of a polymorphic +belongs_to+ declaration as setting up an interface that any other model can use. From an instance of the +Employee+ model, you can retrieve a collection of pictures: +@employee.pictures+.
Similarly, you can retrieve +@product.pictures+.
@@ -371,7 +371,7 @@ But what if you want to reload the cache, because data might have been changed b
<ruby>
customer.orders # retrieves orders from the database
customer.orders.size # uses the cached copy of orders
-customer.orders(true).empty? # discards the cached copy of orders
+customer.orders(true).empty? # discards the cached copy of orders
# and goes back to the database
</ruby>
@@ -400,8 +400,8 @@ class CreateOrders < ActiveRecord::Migration
def self.up
create_table :orders do |t|
t.datetime :order_date
- t.string :order_number
- t.integer :customer_id
+ t.string :order_number
+ t.integer :customer_id
end
end
@@ -415,7 +415,7 @@ If you create an association some time after you build the underlying model, you
h5. Creating Join Tables for has_and_belongs_to_many Associations
-If you create a +has_and_belongs_to_many+ association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the +:join_table+ option, Active Record create the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering.
+If you create a +has_and_belongs_to_many+ association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the +:join_table+ option, Active Record create the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering.
WARNING: The precedence between model names is calculated using the +<+ operator for +String+. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers" to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", but it in fact generates a join table name of "paper_boxes_papers".
@@ -490,14 +490,14 @@ To associate a model with a model in a different scope, you must specify the com
module MyApplication
module Business
class Supplier < ActiveRecord::Base
- has_one :account,
+ has_one :account,
:class_name => "MyApplication::Billing::Account"
end
end
module Billing
class Account < ActiveRecord::Base
- belongs_to :supplier,
+ belongs_to :supplier,
:class_name => "MyApplication::Business::Supplier"
end
end
@@ -573,7 +573,7 @@ h6. build_<em>association</em>(attributes = {})
The <tt>build_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set, but the associated object will _not_ yet be saved.
<ruby>
-@customer = @order.build_customer({:customer_number => 123,
+@customer = @order.build_customer({:customer_number => 123,
:customer_name => "John Doe"})
</ruby>
@@ -582,7 +582,7 @@ h6. create_<em>association</em>(attributes = {})
The <tt>create_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set. In addition, the associated object _will_ be saved (assuming that it passes any validations).
<ruby>
-@customer = @order.create_customer({:customer_number => 123,
+@customer = @order.create_customer({:customer_number => 123,
:customer_name => "John Doe"})
</ruby>
@@ -592,7 +592,7 @@ In many situations, you can use the default behavior of +belongs_to+ without any
<ruby>
class Order < ActiveRecord::Base
- belongs_to :customer, :counter_cache => true,
+ belongs_to :customer, :counter_cache => true,
:conditions => "active = 1"
end
</ruby>
@@ -659,7 +659,7 @@ class Customer < ActiveRecord::Base
end
</ruby>
-With this declaration, Rails will keep the cache value up to date, and then return that value in response to the +.size+ method.
+With this declaration, Rails will keep the cache value up to date, and then return that value in response to the +.size+ method.
Although the +:counter_cache+ option is specified on the model that includes the +belongs_to+ declaration, the actual column must be added to the _associated_ model. In the case above, you would need to add a column named +orders_count+ to the +Customer+ model. You can override the default column name if you need to:
@@ -686,7 +686,7 @@ By convention, Rails guesses that the column used to hold the foreign key on thi
<ruby>
class Order < ActiveRecord::Base
- belongs_to :customer, :class_name => "Patron",
+ belongs_to :customer, :class_name => "Patron",
:foreign_key => "patron_id"
end
</ruby>
@@ -1109,7 +1109,7 @@ h6. <em>collection</em>.build(attributes = {}, ...)
The <tt><em>collection</em>.build</tt> method returns one or more new objects of the associated type. These objects will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will _not_ yet be saved.
<ruby>
-@order = @customer.orders.build({:order_date => Time.now,
+@order = @customer.orders.build({:order_date => Time.now,
:order_number => "A12345"})
</ruby>
@@ -1118,7 +1118,7 @@ h6. <em>collection</em>.create(attributes = {})
The <tt><em>collection</em>.create</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be created, and the associated object _will_ be saved (assuming that it passes any validations).
<ruby>
-@order = @customer.orders.create({:order_date => Time.now,
+@order = @customer.orders.create({:order_date => Time.now,
:order_number => "A12345"})
</ruby>
@@ -1181,7 +1181,7 @@ The +:conditions+ option lets you specify the conditions that the associated obj
<ruby>
class Customer < ActiveRecord::Base
- has_many :confirmed_orders, :class_name => "Order",
+ has_many :confirmed_orders, :class_name => "Order",
:conditions => "confirmed = 1"
end
</ruby>
@@ -1190,7 +1190,7 @@ You can also set conditions via a hash:
<ruby>
class Customer < ActiveRecord::Base
- has_many :confirmed_orders, :class_name => "Order",
+ has_many :confirmed_orders, :class_name => "Order",
:conditions => { :confirmed => true }
end
</ruby>
@@ -1199,7 +1199,7 @@ If you use a hash-style +:conditions+ option, then record creation via this asso
h6. :counter_sql
-Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself.
+Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself.
NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL will be generated by substituting +SELECT COUNT(*) FROM+ for the +SELECT ... FROM+ clause of your +:finder_sql+ statement.
@@ -1281,7 +1281,7 @@ The +:limit+ option lets you restrict the total number of objects that will be f
<ruby>
class Customer < ActiveRecord::Base
- has_many :recent_orders, :class_name => "Order",
+ has_many :recent_orders, :class_name => "Order",
:order => "order_date DESC", :limit => 100
end
</ruby>
@@ -1468,7 +1468,7 @@ h6. <em>collection</em>.find(...)
The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+. It also adds the additional condition that the object must be in the collection.
<ruby>
-@new_assemblies = @part.assemblies.find(:all,
+@new_assemblies = @part.assemblies.find(:all,
:conditions => ["created_at > ?", 2.days.ago])
</ruby>
@@ -1500,7 +1500,7 @@ In many situations, you can use the default behavior for +has_and_belongs_to_man
<ruby>
class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :uniq => true,
+ has_and_belongs_to_many :assemblies, :uniq => true,
:read_only => true
end
</ruby>
@@ -1536,8 +1536,8 @@ TIP: The +:foreign_key+ and +:association_foreign_key+ options are useful when s
<ruby>
class User < ActiveRecord::Base
- has_and_belongs_to_many :friends, :class_name => "User",
- :foreign_key => "this_user_id",
+ has_and_belongs_to_many :friends, :class_name => "User",
+ :foreign_key => "this_user_id",
:association_foreign_key => "other_user_id"
end
</ruby>
@@ -1562,7 +1562,7 @@ The +:conditions+ option lets you specify the conditions that the associated obj
<ruby>
class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies,
+ has_and_belongs_to_many :assemblies,
:conditions => "factory = 'Seattle'"
end
</ruby>
@@ -1571,7 +1571,7 @@ You can also set conditions via a hash:
<ruby>
class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies,
+ has_and_belongs_to_many :assemblies,
:conditions => { :factory => 'Seattle' }
end
</ruby>
@@ -1580,7 +1580,7 @@ If you use a hash-style +:conditions+ option, then record creation via this asso
h6. :counter_sql
-Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself.
+Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself.
NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL will be generated by substituting +SELECT COUNT(*) FROM+ for the +SELECT ... FROM+ clause of your +:finder_sql+ statement.
@@ -1602,8 +1602,8 @@ By convention, Rails guesses that the column in the join table used to hold the
<ruby>
class User < ActiveRecord::Base
- has_and_belongs_to_many :friends, :class_name => "User",
- :foreign_key => "this_user_id",
+ has_and_belongs_to_many :friends, :class_name => "User",
+ :foreign_key => "this_user_id",
:association_foreign_key => "other_user_id"
end
</ruby>
@@ -1620,7 +1620,7 @@ end
h6. :include
-You can use the :include option to specify second-order associations that should be eager-loaded when this association is used.
+You can use the :include option to specify second-order associations that should be eager-loaded when this association is used.
h6. :insert_sql
@@ -1710,7 +1710,7 @@ You can stack callbacks on a single event by passing them as an array:
<ruby>
class Customer < ActiveRecord::Base
- has_many :orders,
+ has_many :orders,
:before_add => [:check_credit_limit, :calculate_shipping_charges]
def check_credit_limit(order)
@@ -1761,7 +1761,7 @@ To include more than one extension module in a single association, specify an ar
<ruby>
class Customer < ActiveRecord::Base
- has_many :orders,
+ has_many :orders,
:extend => [FindRecentExtension, FindActiveExtension]
end
</ruby>
@@ -1776,7 +1776,7 @@ h3. Changelog
"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/11
-* February 1, 2009: Added +:autosave+ option "Mike Gunderloy":credits.html#mgunderloy
+* February 1, 2009: Added +:autosave+ option "Mike Gunderloy":credits.html#mgunderloy
* September 28, 2008: Corrected +has_many :through+ diagram, added polymorphic diagram, some reorganization by "Mike Gunderloy":credits.html#mgunderloy . First release version.
* September 22, 2008: Added diagrams, misc. cleanup by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
* September 14, 2008: initial version by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
diff --git a/railties/guides/source/caching_with_rails.textile b/railties/guides/source/caching_with_rails.textile
index 456b0c48a7..940466ecb3 100644
--- a/railties/guides/source/caching_with_rails.textile
+++ b/railties/guides/source/caching_with_rails.textile
@@ -27,7 +27,7 @@ page to be fulfilled by the webserver, without ever having to go through the
Rails stack at all. Obviously, this is super-fast. Unfortunately, it can't be
applied to every situation (such as pages that need authentication) and since
the webserver is literally just serving a file from the filesystem, cache
-expiration is an issue that needs to be dealt with.
+expiration is an issue that needs to be dealt with.
So, how do you enable this super-fast cache behavior? Simple, let's say you
have a controller called ProductsController and a 'list' action that lists all
@@ -95,7 +95,7 @@ result of the output from a cached copy.
Clearing the cache works in the exact same way as with Page Caching.
Let's say you only wanted authenticated users to edit or create a Product
-object, but still cache those pages:
+object, but still cache those pages:
<ruby>
class ProductsController < ActionController
@@ -138,7 +138,7 @@ created page where different parts of the page need to be cached and expired
differently Rails provides a mechanism called Fragment Caching.
Fragment Caching allows a fragment of view logic to be wrapped in a cache
-block and served out of the cache store when the next request comes in.
+block and served out of the cache store when the next request comes in.
As an example, if you wanted to show all the orders placed on your website
in real time and didn't want to cache that part of the page, but did want
@@ -149,9 +149,9 @@ could use this piece of code:
<% Order.find_recent.each do |o| %>
<%= o.buyer.name %> bought <% o.product.name %>
<% end %>
-
+
<% cache do %>
- All available products:
+ All available products:
<% Product.find(:all).each do |p| %>
<%= link_to p.name, product_url(p) %>
<% end %>
@@ -164,7 +164,7 @@ want to cache multiple fragments per action, you should provide an +action_suffi
<ruby>
<% cache(:action => 'recent', :action_suffix => 'all_products') do %>
- All available products:
+ All available products:
</ruby>
and you can expire it using the +expire_fragment+ method, like so:
@@ -179,7 +179,7 @@ so:
<ruby>
<% cache(:key => ['all_available_products', @latest_product.created_at].join(':')) do %>
- All available products:
+ All available products:
<% end %>
</ruby>
@@ -212,23 +212,23 @@ class StoreSweeper < ActionController::Caching::Sweeper
def after_create(product)
expire_cache_for(product)
end
-
+
# If our sweeper detects that a Product was updated call this
def after_update(product)
expire_cache_for(product)
end
-
+
# If our sweeper detects that a Product was deleted call this
def after_destroy(product)
expire_cache_for(product)
end
-
+
private
def expire_cache_for(record)
# Expire the list page now that we added a new product
expire_page(:controller => '#{record}', :action => 'list')
-
- # Expire a fragment
+
+ # Expire a fragment
expire_fragment(:controller => '#{record}', :action => 'recent', :action_suffix => 'all_products')
end
end
diff --git a/railties/guides/source/command_line.textile b/railties/guides/source/command_line.textile
index 788629617b..b1a3dace16 100644
--- a/railties/guides/source/command_line.textile
+++ b/railties/guides/source/command_line.textile
@@ -21,7 +21,7 @@ There are a few commands that are absolutely critical to your everyday usage of
* rake
* generate
* rails
-
+
Let's create a simple Rails application to step through each of these commands in context.
h4. rails
@@ -33,7 +33,7 @@ WARNING: You know you need the rails gem installed by typing +gem install rails+
<shell>
$ rails commandsapp
- create
+ create
create app/controllers
create app/helpers
create app/models
@@ -190,7 +190,7 @@ Examples:
creates a Post model with a string title, text body, and published flag.
</shell>
-But instead of generating a model directly (which we'll be doing later), let's set up a scaffold. A *scaffold* in Rails is a full set of model, database migration for that model, controller to manipulate it, views to view and manipulate the data, and a test suite for each of the above.
+But instead of generating a model directly (which we'll be doing later), let's set up a scaffold. A *scaffold* in Rails is a full set of model, database migration for that model, controller to manipulate it, views to view and manipulate the data, and a test suite for each of the above.
Let's set up a simple resource called "HighScore" that will keep track of our highest score on video games we play.
@@ -345,7 +345,7 @@ $ cd gitapp
$ git init
Initialized empty Git repository in .git/
$ rails . --git --database=postgresql
- exists
+ exists
create app/controllers
create app/helpers
...
@@ -367,7 +367,7 @@ add 'log/test.log'
We had to create the *gitapp* directory and initialize an empty git repository before Rails would add files it created to our repository. Let's see what it put in our database configuration:
<shell>
-$ cat config/database.yml
+$ cat config/database.yml
# PostgreSQL. Versions 7.4 and 8.x are supported.
#
# Install the ruby-postgres driver:
@@ -448,7 +448,7 @@ class TutorialTestGenerator < Rails::Generator::Base
super(*runtime_args)
@tut_args = runtime_args
end
-
+
def manifest
record do |m|
m.directory "public"
@@ -469,10 +469,10 @@ We take whatever args are supplied, save them to an instance variable, and liter
Next we'll build the template:
<shell>
-$ cat ~/.rails/generators/tutorial_test/templates/tutorial.erb
+$ cat ~/.rails/generators/tutorial_test/templates/tutorial.erb
I'm a template!
-I got assigned some args:
+I got assigned some args:
<%= require 'pp'; PP.pp(args, "") %>
</shell>
@@ -497,10 +497,10 @@ $ ./script/generate tutorial_test arg1 arg2 arg3
And the result:
<shell>
-$ cat public/tutorial.txt
+$ cat public/tutorial.txt
I'm a template!
-I got assigned some args:
+I got assigned some args:
[["arg1", "arg2", "arg3"],
{:collision=>:ask,
:quiet=>false,
@@ -508,4 +508,4 @@ I got assigned some args:
:command=>:create}]
</shell>
-Tada! \ No newline at end of file
+Tada!
diff --git a/railties/guides/source/debugging_rails_applications.textile b/railties/guides/source/debugging_rails_applications.textile
index f096747b52..dd89bef027 100644
--- a/railties/guides/source/debugging_rails_applications.textile
+++ b/railties/guides/source/debugging_rails_applications.textile
@@ -193,14 +193,14 @@ Here's an example of the log generated by this method:
Processing PostsController#create (for 127.0.0.1 at 2008-09-08 11:52:54) [POST]
Session ID: BAh7BzoMY3NyZl9pZCIlMDY5MWU1M2I1ZDRjODBlMzkyMWI1OTg2NWQyNzViZjYiCmZsYXNoSUM6J0FjdGl
vbkNvbnRyb2xsZXI6OkZsYXNoOjpGbGFzaEhhc2h7AAY6CkB1c2VkewA=--b18cd92fba90eacf8137e5f6b3b06c4d724596a4
- Parameters: {"commit"=>"Create", "post"=>{"title"=>"Debugging Rails",
- "body"=>"I'm learning how to print in logs!!!", "published"=>"0"},
+ Parameters: {"commit"=>"Create", "post"=>{"title"=>"Debugging Rails",
+ "body"=>"I'm learning how to print in logs!!!", "published"=>"0"},
"authenticity_token"=>"2059c1286e93402e389127b1153204e0d1e275dd", "action"=>"create", "controller"=>"posts"}
-New post: {"updated_at"=>nil, "title"=>"Debugging Rails", "body"=>"I'm learning how to print in logs!!!",
+New post: {"updated_at"=>nil, "title"=>"Debugging Rails", "body"=>"I'm learning how to print in logs!!!",
"published"=>false, "created_at"=>nil}
Post should be valid: true
- Post Create (0.000443) INSERT INTO "posts" ("updated_at", "title", "body", "published",
- "created_at") VALUES('2008-09-08 14:52:54', 'Debugging Rails',
+ Post Create (0.000443) INSERT INTO "posts" ("updated_at", "title", "body", "published",
+ "created_at") VALUES('2008-09-08 14:52:54', 'Debugging Rails',
'I''m learning how to print in logs!!!', 'f', '2008-09-08 14:52:54')
The post was saved and now is the user is going to be redirected...
Redirected to #<Post:0x20af760>
@@ -646,8 +646,8 @@ Make sure to run a couple hundred requests to get better data samples, then pres
** BleakHouse: complete
** Bleakhouse: run 'bleak /tmp/bleak.5979.0.dump' to analyze.
</shell>
-
-To analyze it, just run the listed command. The top 20 leakiest lines will be listed:
+
+To analyze it, just run the listed command. The top 20 leakiest lines will be listed:
<shell>
191691 total objects
@@ -682,7 +682,7 @@ There are some Rails plugins to help you to find errors and debug your applicati
* "Footnotes":http://github.com/drnic/rails-footnotes/tree/master: Every Rails page has footnotes that give request information and link back to your source via TextMate.
* "Query Trace":http://github.com/ntalbott/query_trace/tree/master: Adds query origin tracing to your logs.
-* "Query Stats":http://github.com/dan-manges/query_stats/tree/master: A Rails plugin to track database queries.
+* "Query Stats":http://github.com/dan-manges/query_stats/tree/master: A Rails plugin to track database queries.
* "Query Reviewer":http://code.google.com/p/query-reviewer/: This rails plugin not only runs "EXPLAIN" before each of your select queries in development, but provides a small DIV in the rendered output of each page with the summary of warnings for each query that it analyzed.
* "Exception Notifier":http://github.com/rails/exception_notification/tree/master: Provides a mailer object and a default set of templates for sending email notifications when errors occur in a Rails application.
* "Exception Logger":http://github.com/defunkt/exception_logger/tree/master: Logs your Rails exceptions in the database and provides a funky web interface to manage them.
diff --git a/railties/guides/source/form_helpers.textile b/railties/guides/source/form_helpers.textile
index 8d29816e54..4e61bdcd26 100644
--- a/railties/guides/source/form_helpers.textile
+++ b/railties/guides/source/form_helpers.textile
@@ -273,7 +273,7 @@ which produces the following output:
<html>
<form action="/people/create" class="new_person" id="new_person" method="post">
- <input id="person_name" name="person[name]" size="30" type="text" />
+ <input id="person_name" name="person[name]" size="30" type="text" />
<input id="contact_detail_phone_number" name="contact_detail[phone_number]" size="30" type="text" />
</form>
</html>
@@ -553,7 +553,7 @@ h3. Uploading Files
A common task is uploading some sort of file, whether it's a picture of a person or a CSV file containing data to process. The most important thing to remember with file uploads is that the form's encoding *MUST* be set to "multipart/form-data". If you forget to do this the file will not be uploaded. This can be done by passing +:multi_part => true+ as an HTML option. This means that in the case of +form_tag+ it must be passed in the second options hash and in the case of +form_for+ inside the +:html+ hash.
-The following two forms both upload a file.
+The following two forms both upload a file.
<erb>
<% form_tag({:action => :upload}, :multipart => true) do %>
@@ -590,7 +590,7 @@ Unlike other forms making an asynchronous file upload form is not as simple as r
h3. Customising Form Builders
-As mentioned previously the object yielded by +form_for+ and +fields_for+ is an instance of FormBuilder (or a subclass thereof). Form builders encapsulate the notion of displaying form elements for a single object. While you can of course write helpers for your forms in the usual way you can also subclass FormBuilder and add the helpers there. For example
+As mentioned previously the object yielded by +form_for+ and +fields_for+ is an instance of FormBuilder (or a subclass thereof). Form builders encapsulate the notion of displaying form elements for a single object. While you can of course write helpers for your forms in the usual way you can also subclass FormBuilder and add the helpers there. For example
<erb>
<% form_for @person do |f| %>
@@ -598,7 +598,7 @@ As mentioned previously the object yielded by +form_for+ and +fields_for+ is an
<% end %>
</erb>
-can be replaced with
+can be replaced with
<erb>
<% form_for @person, :builder => LabellingFormBuilder do |f| %>
@@ -698,9 +698,9 @@ You might want to render a form with a set of edit fields for each of a person's
<erb>
<% form_for @person do |person_form| %>
<%= person_form.text_field :name %>
- <% for address in @person.addresses %>
+ <% for address in @person.addresses %>
<% person_form.fields_for address, :index => address do |address_form|%>
- <%= address_form.text_field :city %>
+ <%= address_form.text_field :city %>
<% end %>
<% end %>
<% end %>
@@ -711,8 +711,8 @@ Assuming the person had two addresses, with ids 23 and 45 this would create outp
<html>
<form action="/people/1" class="edit_person" id="edit_person_1" method="post">
<input id="person_name" name="person[name]" size="30" type="text" />
- <input id="person_address_23_city" name="person[address][23][city]" size="30" type="text" />
- <input id="person_address_45_city" name="person[address][45][city]" size="30" type="text" />
+ <input id="person_address_23_city" name="person[address][23][city]" size="30" type="text" />
+ <input id="person_address_45_city" name="person[address][45][city]" size="30" type="text" />
</form>
</html>
diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile
index bdd2a9d429..3163fdb4bc 100644
--- a/railties/guides/source/getting_started.textile
+++ b/railties/guides/source/getting_started.textile
@@ -248,7 +248,7 @@ Now that you have your database configured, it's time to have Rails create an em
$ rake db:create
</shell>
-NOTE. Rake is a general-purpose command-runner that Rails uses for many things. You can see the list of available rake commands in your application by running +rake -T+.
+NOTE. Rake is a general-purpose command-runner that Rails uses for many things. You can see the list of available rake commands in your application by running +rake -T+.
h3. Hello, Rails!
@@ -313,7 +313,7 @@ NOTE. For more information about routing, refer to "Rails Routing from the Outsi
h3. Getting Up and Running Quickly With Scaffolding
-Rails _scaffolding_ is a quick way to generate some of the major pieces of an application. If you want to create the models, views, and controllers for a new resource in a single operation, scaffolding is the tool for the job.
+Rails _scaffolding_ is a quick way to generate some of the major pieces of an application. If you want to create the models, views, and controllers for a new resource in a single operation, scaffolding is the tool for the job.
h3. Creating a Resource
@@ -440,14 +440,14 @@ After the console loads, you can use it to work with your application's models:
<shell>
>> p = Post.create(:content => "A new post")
-=> #<Post id: nil, name: nil, title: nil, content: "A new post",
+=> #<Post id: nil, name: nil, title: nil, content: "A new post",
created_at: nil, updated_at: nil>
>> p.save
=> false
>> p.errors
-=> #<ActiveRecord::Errors:0x23bcf0c @base=#<Post id: nil, name: nil,
-title: nil, content: "A new post", created_at: nil, updated_at: nil>,
-@errors={"name"=>["can't be blank"], "title"=>["can't be blank",
+=> #<ActiveRecord::Errors:0x23bcf0c @base=#<Post id: nil, name: nil,
+title: nil, content: "A new post", created_at: nil, updated_at: nil>,
+@errors={"name"=>["can't be blank"], "title"=>["can't be blank",
"is too short (minimum is 5 characters)"]}>
</shell>
@@ -493,7 +493,7 @@ The +respond_to+ block handles both HTML and XML calls to this action. If you br
<td><%=h post.content %></td>
<td><%= link_to 'Show', post %></td>
<td><%= link_to 'Edit', edit_post_path(post) %></td>
- <td><%= link_to 'Destroy', post, :confirm => 'Are you sure?',
+ <td><%= link_to 'Destroy', post, :confirm => 'Are you sure?',
:method => :delete %></td>
</tr>
<% end %>
@@ -522,7 +522,7 @@ The view is only part of the story of how HTML is displayed in your web browser.
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
- <meta http-equiv="content-type"
+ <meta http-equiv="content-type"
content="text/html;charset=UTF-8" />
<title>Posts: <%= controller.action_name %></title>
<%= stylesheet_link_tag 'scaffold' %>
@@ -596,11 +596,11 @@ def create
if @post.save
flash[:notice] = 'Post was successfully created.'
format.html { redirect_to(@post) }
- format.xml { render :xml => @post, :status => :created,
+ format.xml { render :xml => @post, :status => :created,
:location => @post }
else
format.html { render :action => "new" }
- format.xml { render :xml => @post.errors,
+ format.xml { render :xml => @post.errors,
:status => :unprocessable_entity }
end
end
@@ -701,7 +701,7 @@ def update
format.xml { head :ok }
else
format.html { render :action => "edit" }
- format.xml { render :xml => @post.errors,
+ format.xml { render :xml => @post.errors,
:status => :unprocessable_entity }
end
end
@@ -796,7 +796,7 @@ class PostsController < ApplicationController
# ...
def show
@post = Post.find(params[:id])
- # ...
+ # ...
end
def edit
@@ -819,11 +819,11 @@ Four instances of the exact same line of code doesn’t seem very DRY. Rails pro
<ruby>
class PostsController < ApplicationController
- before_filter :find_post,
+ before_filter :find_post,
:only => [:show, :edit, :update, :destroy]
# ...
def show
- # ...
+ # ...
end
def edit
@@ -852,12 +852,12 @@ h3. Adding a Second Model
Now that you've seen what's in a model built with scaffolding, it's time to add a second model to the application. The second model will handle comments on blog posts.
-h4. Generating a Model
+h4. Generating a Model
Models in Rails use a singular name, and their corresponding database tables use a plural name. For the model to hold comments, the convention is to use the name Comment. Even if you don't want to use the entire apparatus set up by scaffolding, most Rails developers still use generators to make things like models and controllers. To create the new model, run this command in your terminal:
<shell>
-$ script/generate model Comment commenter:string body:text
+$ script/generate model Comment commenter:string body:text
post:references
</shell>
@@ -1011,7 +1011,7 @@ class CommentsController < ApplicationController
render :action => "new"
end
end
-
+
def edit
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
@@ -1075,7 +1075,7 @@ The +views/comments/index.html.erb+ view:
<%= link_to 'Edit', edit_post_comment_path(@post, comment) %>
</td>
<td>
- <%= link_to 'Destroy', post_comment_path(@post, comment),
+ <%= link_to 'Destroy', post_comment_path(@post, comment),
:confirm => 'Are you sure?', :method => :delete %>
</td>
</tr>
@@ -1220,7 +1220,7 @@ class Post < ActiveRecord::Base
validates_length_of :title, :minimum => 5
has_many :comments
has_many :tags
-
+
accepts_nested_attributes_for :tags, :allow_destroy => :true ,
:reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
end
@@ -1294,4 +1294,4 @@ h3. Changelog
* October 16, 2008: Revised based on feedback from Pratik Naik by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
* October 13, 2008: First complete draft by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
* October 12, 2008: More detail, rearrangement, editing by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
-* September 8, 2008: initial version by James Miller (not yet approved for publication) \ No newline at end of file
+* September 8, 2008: initial version by James Miller (not yet approved for publication)
diff --git a/railties/guides/source/i18n.textile b/railties/guides/source/i18n.textile
index 53a0cc2834..c5025eb86b 100644
--- a/railties/guides/source/i18n.textile
+++ b/railties/guides/source/i18n.textile
@@ -93,7 +93,7 @@ The I18n library will use *English* as a *default locale*, ie. if you don't set
NOTE: The i18n library takes *pragmatic approach* to locale keys (after "some discussion":http://groups.google.com/group/rails-i18n/browse_thread/thread/14dede2c7dbe9470/80eec34395f64f3c?hl=en), including only the _locale_ ("language") part, like +:en+, +:pl+, not the _region_ part, like +:en-US+ or +:en-UK+, which are traditionally used for separating "languages" and "regional setting" or "dialects". (For instance, in the +:en-US+ locale you would have $ as a currency symbol, while in +:en-UK+, you would have £. Also, insults would be different in American and British English :) Reason for this pragmatic approach is that most of the time, you usually care about making your application available in different "languages", and working with locales is much simpler this way. However, nothing stops you from separating regional and other settings in the traditional way. In this case, you could eg. inherit from the default +en+ locale and then provide UK specific settings in a +:en-UK+ dictionary.
-The *translations load path* (+I18n.load_path+) is just a Ruby Array of paths to your translation files that will be loaded automatically and available in your application. You can pick whatever directory and translation file naming scheme makes sense for you.
+The *translations load path* (+I18n.load_path+) is just a Ruby Array of paths to your translation files that will be loaded automatically and available in your application. You can pick whatever directory and translation file naming scheme makes sense for you.
NOTE: The backend will lazy-load these translations when a translation is looked up for the first time. This makes it possible to just swap the backend with something else even after translations have already been announced.
@@ -145,7 +145,7 @@ This requires you to pass the locale as a URL query parameter as in +http://exam
Of course, you probably don't want to manually include locale in every URL all over your application, or want the URLs look differently, eg. the usual +http://example.com/pt/books+ versus +http://example.com/en/books+. Let's discuss the different options you have.
-IMPORTANT: Following examples rely on having locales loaded into your application available as an array of strings like +["en", "es", "gr"]+. This is not inclued in current version of Rails 2.2 -- forthcoming Rails version 2.3 will contain easy accesor +available_locales+. (See "this commit":http://github.com/svenfuchs/i18n/commit/411f8fe7 and background at "Rails I18n Wiki":http://rails-i18n.org/wiki/pages/i18n-available_locales.)
+IMPORTANT: Following examples rely on having locales loaded into your application available as an array of strings like +["en", "es", "gr"]+. This is not inclued in current version of Rails 2.2 -- forthcoming Rails version 2.3 will contain easy accesor +available_locales+. (See "this commit":http://github.com/svenfuchs/i18n/commit/411f8fe7 and background at "Rails I18n Wiki":http://rails-i18n.org/wiki/pages/i18n-available_locales.)
So, for having available locales easily available in Rails 2.2, we have to include this support manually in an initializer, like this:
@@ -314,7 +314,7 @@ h3. Internationalizing your application
OK! Now you've initialized I18n support for your Ruby on Rails application and told it which locale should be used and how to preserve it between requests. With that in place, you're now ready for the really interesting stuff.
-Let's _internationalize_ our application, ie. abstract every locale-specific parts, and that _localize_ it, ie. provide neccessary translations for these abstracts.
+Let's _internationalize_ our application, ie. abstract every locale-specific parts, and that _localize_ it, ie. provide neccessary translations for these abstracts.
You most probably have something like this in one of your applications:
@@ -323,7 +323,7 @@ You most probably have something like this in one of your applications:
ActionController::Routing::Routes.draw do |map|
map.root :controller => 'home', :action => 'index'
end
-
+
# app/controllers/home_controller.rb
class HomeController < ApplicationController
def index
@@ -368,12 +368,12 @@ So let's add the missing translations into the dictionary files (i.e. do the "lo
en:
hello_world: Hello World
hello_flash: Hello Flash
-
+
# config/locale/pirate.yml
pirate:
hello_world: Ahoy World
hello_flash: Ahoy Flash
-</ruby>
+</ruby>
There you go. Because you haven't changed the default_locale, I18n will use English. Your application now shows:
@@ -551,7 +551,7 @@ The +:count+ interpolation variable has a special role in that it both is interp
<ruby>
I18n.backend.store_translations :en, :inbox => {
- :one => '1 message',
+ :one => '1 message',
:other => '{{count}} messages'
}
I18n.translate :inbox, :count => 2
@@ -561,7 +561,7 @@ I18n.translate :inbox, :count => 2
The algorithm for pluralizations in +:en+ is as simple as:
<ruby>
-entry[count == 1 ? 0 : 1]
+entry[count == 1 ? 0 : 1]
</ruby>
I.e. the translation denoted as +:one+ is regarded as singular, the other is used as plural (including the count being zero).
@@ -576,7 +576,7 @@ If no locale is passed +I18n.locale+ is used:
<ruby>
I18n.locale = :de
-I18n.t :foo
+I18n.t :foo
I18n.l Time.now
</ruby>
@@ -615,7 +615,7 @@ The equivalent YAML file would look like this:
pt:
foo:
bar: baz
-</ruby>
+</ruby>
As you see in both cases the toplevel key is the locale. +:foo+ is a namespace key and +:bar+ is the key for the translation "baz".
@@ -657,9 +657,9 @@ en:
login: "Handle"
# will translate User attribute "login" as "Handle"
</ruby>
-
+
Then +User.human_name+ will return "Dude" and +User.human_attribute_name(:login)+ will return "Handle".
-
+
h5. Error message scopes
Active Record validation error messages can also be translated easily. Active Record gives you a couple of namespaces where you can place your message translations in order to provide different messages and translation for certain models, attributes and/or validations. It also transparently takes single table inheritance into account.
@@ -690,7 +690,7 @@ activerecord.errors.messages.models.user.blank
activerecord.errors.messages.blank
</ruby>
-When your models are additionally using inheritance then the messages are looked up for the inherited model class names are looked up.
+When your models are additionally using inheritance then the messages are looked up for the inherited model class names are looked up.
For example, you might have an Admin model inheriting from User:
@@ -810,9 +810,9 @@ ReservedInterpolationKey # the translation contains a reserved interpolation
UnknownFileType # the backend does not know how to handle a file type that was added to I18n.load_path
</ruby>
-The I18n API will catch all of these exceptions when they were thrown in the backend and pass them to the default_exception_handler method. This method will re-raise all exceptions except for +MissingTranslationData+ exceptions. When a +MissingTranslationData+ exception has been caught it will return the exception’s error message string containing the missing key/scope.
+The I18n API will catch all of these exceptions when they were thrown in the backend and pass them to the default_exception_handler method. This method will re-raise all exceptions except for +MissingTranslationData+ exceptions. When a +MissingTranslationData+ exception has been caught it will return the exception’s error message string containing the missing key/scope.
-The reason for this is that during development you'd usually want your views to still render even though a translation is missing.
+The reason for this is that during development you'd usually want your views to still render even though a translation is missing.
In other contexts you might want to change this behaviour though. E.g. the default exception handling does not allow to catch missing translations during automated tests easily. For this purpose a different exception handler can be specified. The specified exception handler must be a method on the I18n module:
@@ -855,7 +855,7 @@ If you find your own locale (language) missing from our "example translations da
h3. Resources
* "rails-i18n.org":http://rails-i18n.org - Homepage of the rails-i18n project. You can find lots of useful resources on the "wiki":http://rails-i18n.org/wiki.
-* "rails-i18n Google group":http://groups.google.com/group/rails-i18n - The project's mailing list.
+* "rails-i18n Google group":http://groups.google.com/group/rails-i18n - The project's mailing list.
* "Github: rails-i18n":http://github.com/svenfuchs/rails-i18n/tree/master - Code repository for the rails-i18n project. Most importantly you can find lots of "example translations":http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale for Rails that should work for your application in most cases.
* "Lighthouse: rails-i18n":http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview - Issue tracker for the rails-i18n project.
* "Github: i18n":http://github.com/svenfuchs/i18n/tree/master - Code repository for the i18n gem.
diff --git a/railties/guides/source/layout.html.erb b/railties/guides/source/layout.html.erb
index b1ac7d36f8..141471a50f 100644
--- a/railties/guides/source/layout.html.erb
+++ b/railties/guides/source/layout.html.erb
@@ -1,7 +1,7 @@
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
-
+
<title><%= yield(:page_title) || 'Ruby on Rails guides' %></title>
<link rel="stylesheet" type="text/css" href="files/stylesheets/style.css" />
@@ -67,11 +67,11 @@
</li>
<li><a href="http://hackfest.rubyonrails.org">Contribute</a></li>
<li><a href="credits.html">Credits</a></li>
- </ul>
+ </ul>
</div>
</div>
<hr class="hide" />
-
+
<div id="feature">
<div class="wrapper">
<%= yield :header_section %>
diff --git a/railties/guides/source/layouts_and_rendering.textile b/railties/guides/source/layouts_and_rendering.textile
index dbaaed2281..d4738ec19f 100644
--- a/railties/guides/source/layouts_and_rendering.textile
+++ b/railties/guides/source/layouts_and_rendering.textile
@@ -228,7 +228,7 @@ render :file => filename, :content_type => 'application/rss'
h6. The :layout Option
-With most of the options to +render+, the rendered content is displayed as part of the current layout. You'll learn more about layouts and how to use them later in this guide.
+With most of the options to +render+, the rendered content is displayed as part of the current layout. You'll learn more about layouts and how to use them later in this guide.
You can use the +:layout+ option to tell Rails to use a specific file as the layout for the current action:
@@ -296,7 +296,7 @@ You can use a symbol to defer the choice of layout until a request is processed:
<ruby>
class ProductsController < ApplicationController
layout :products_layout
-
+
def show
@product = Product.find(params[:id])
end
@@ -314,7 +314,7 @@ Now, if the current user is a special user, they'll get a special layout when vi
<ruby>
class ProductsController < ApplicationController
layout proc{ |controller| controller.
- # ...
+ # ...
end
</ruby>
@@ -725,7 +725,7 @@ The +content_for+ method is very helpful when your layout contains distinct regi
h4. Using Partials
-Partial templates - usually just called "partials" - are another device for breaking apart the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file.
+Partial templates - usually just called "partials" - are another device for breaking apart the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file.
h5. Naming Partials
@@ -826,7 +826,7 @@ If you have an instance of a model to render into a partial, you can use a short
Assuming that the +@customer+ instance variable contains an instance of the +Customer+ model, this will use +_customer.html.erb+ to render it.
-h5. Rendering Collections
+h5. Rendering Collections
Partials are very useful in rendering collections. When you pass a collection to a partial via the +:collection+ option, the partial will be inserted once for each member in the collection:
@@ -949,9 +949,9 @@ h3. Changelog
"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/15
* December 27, 2008: Merge patch from Rodrigo Rosenfeld Rosas covering subtemplates
-* December 27, 2008: Information on new rendering defaults by "Mike Gunderloy":credits.html#mgunderloy
-* November 9, 2008: Added partial collection counter by "Mike Gunderloy":credits.html#mgunderloy
-* November 1, 2008: Added +:js+ option for +render+ by "Mike Gunderloy":credits.html#mgunderloy
-* October 16, 2008: Ready for publication by "Mike Gunderloy":credits.html#mgunderloy
+* December 27, 2008: Information on new rendering defaults by "Mike Gunderloy":credits.html#mgunderloy
+* November 9, 2008: Added partial collection counter by "Mike Gunderloy":credits.html#mgunderloy
+* November 1, 2008: Added +:js+ option for +render+ by "Mike Gunderloy":credits.html#mgunderloy
+* October 16, 2008: Ready for publication by "Mike Gunderloy":credits.html#mgunderloy
* October 4, 2008: Additional info on partials (+:object+, +:as+, and +:spacer_template+) by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
-* September 28, 2008: First draft by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication) \ No newline at end of file
+* September 28, 2008: First draft by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
diff --git a/railties/guides/source/migrations.textile b/railties/guides/source/migrations.textile
index 9e7597ff22..58ae54f53f 100644
--- a/railties/guides/source/migrations.textile
+++ b/railties/guides/source/migrations.textile
@@ -1,6 +1,6 @@
h2. Migrations
-Migrations are a convenient way for you to alter your database in a structured and organised manner. You could edit fragments of SQL by hand but you would then be responsible for telling other developers that they need to go and run it. You'd also have to keep track of which changes need to be run against the production machines next time you deploy. Active Record tracks which migrations have already been run so all you have to do is update your source and run +rake db:migrate+. Active Record will work out which migrations should be run. It will also update your db/schema.rb file to match the structure of your database.
+Migrations are a convenient way for you to alter your database in a structured and organised manner. You could edit fragments of SQL by hand but you would then be responsible for telling other developers that they need to go and run it. You'd also have to keep track of which changes need to be run against the production machines next time you deploy. Active Record tracks which migrations have already been run so all you have to do is update your source and run +rake db:migrate+. Active Record will work out which migrations should be run. It will also update your db/schema.rb file to match the structure of your database.
Migrations also allow you to describe these transformations using Ruby. The great thing about this is that (like most of Active Record's functionality) it is database independent: you don't need to worry about the precise syntax of CREATE TABLE any more that you worry about variations on SELECT * (you can drop down to raw SQL for database specific features). For example you could use SQLite3 in development, but MySQL in production.
@@ -15,7 +15,7 @@ endprologue.
h3. Anatomy Of A Migration
-Before I dive into the details of a migration, here are a few examples of the sorts of things you can do:
+Before I dive into the details of a migration, here are a few examples of the sorts of things you can do:
<ruby>
class CreateProducts < ActiveRecord::Migration
@@ -70,7 +70,7 @@ Active Record provides methods that perform common data definition tasks in a da
* +add_column+
* +remove_column+
* +change_column+
-* +rename_column+
+* +rename_column+
* +add_index+
* +remove_index+
@@ -340,12 +340,12 @@ class ExampleMigration < ActiveRecord::Migration
end
#add a foreign key
execute "ALTER TABLE products ADD CONSTRAINT fk_products_categories FOREIGN KEY (category_id) REFERENCES categories(id)"
-
+
add_column :users, :home_page_url, :string
-
+
rename_column :users, :email, :email_address
end
-
+
def self.down
rename_column :users, :email_address, :email
remove_column :users, :home_page_url
@@ -473,7 +473,7 @@ If you just want Active Record to shut up then running +rake db:migrate VERBOSE=
h3. Using Models In Your Migrations
-When creating or updating data in a migration it is often tempting to use one of your models. After all they exist to provide easy access to the underlying data. This can be done but some caution should be observed.
+When creating or updating data in a migration it is often tempting to use one of your models. After all they exist to provide easy access to the underlying data. This can be done but some caution should be observed.
Consider for example a migration that uses the Product model to update a row in the corresponding table. Alice later updates the Product model, adding a new column and a validation on it. Bob comes back from holiday, updates the source and runs outstanding migrations with +rake db:migrate+, including the one that used the Product model. When the migration runs the source is up to date and so the Product model has the validation added by Alice. The database however is still old and so does not have that column and an error ensues because that validation is on a column that does not yet exist.
@@ -483,7 +483,7 @@ Frequently I just want to update rows in the database without writing out the SQ
class AddPartNumberToProducts < ActiveRecord::Migration
class Product < ActiveRecord::Base
end
-
+
def self.up
...
end
@@ -503,7 +503,7 @@ For performance reasons information about the columns a model has is cached. For
class AddPartNumberToProducts < ActiveRecord::Migration
class Product < ActiveRecord::Base
end
-
+
def self.up
add_column :product, :part_number, :string
Product.reset_column_information
@@ -555,7 +555,7 @@ end
In many ways this is exactly what it is. This file is created by inspecting the database and expressing its structure using +create_table+, +add_index+ and so on. Because this is database independent it could be loaded into any database that Active Record supports. This could be very useful if you were to distribute an application that is able to run against multiple databases.
-There is however a trade-off: +schema.rb+ cannot express database specific items such as foreign key constraints, triggers or stored procedures. While in a migration you can execute custom SQL statements, the schema dumper cannot reconstitute those statements from the database. If you are using features like this then you should set the schema format to +:sql+.
+There is however a trade-off: +schema.rb+ cannot express database specific items such as foreign key constraints, triggers or stored procedures. While in a migration you can execute custom SQL statements, the schema dumper cannot reconstitute those statements from the database. If you are using features like this then you should set the schema format to +:sql+.
Instead of using Active Record's schema dumper the database's structure will be dumped using a tool specific to that database (via the +db:structure:dump+ Rake task) into +db/#{RAILS_ENV}_structure.sql+. For example for PostgreSQL the +pg_dump+ utility is used and for MySQL this file will contain the output of SHOW CREATE TABLE for the various tables. Loading this schema is simply a question of executing the SQL statements contained inside.
@@ -577,4 +577,4 @@ h3. Changelog
"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/6
-* September 14, 2008: initial version by "Frederick Cheung":credits.html#fcheung \ No newline at end of file
+* September 14, 2008: initial version by "Frederick Cheung":credits.html#fcheung
diff --git a/railties/guides/source/performance_testing.textile b/railties/guides/source/performance_testing.textile
index 578625783e..972b7aac50 100644
--- a/railties/guides/source/performance_testing.textile
+++ b/railties/guides/source/performance_testing.textile
@@ -88,7 +88,7 @@ class Post < ActiveRecord::Base
end
private
-
+
def recalculate_costly_stats
# CPU heavy calculations
end
@@ -97,7 +97,7 @@ end
h5. Controller Example
-Because performance tests are a special kind of integration test, you can use the +get+ and +post+ methods in them.
+Because performance tests are a special kind of integration test, you can use the +get+ and +post+ methods in them.
Here's the performance test for +HomeController#dashboard+ and +PostsController#create+:
@@ -151,7 +151,7 @@ Performance tests can be run in two modes : Benchmarking and Profiling.
h5. Benchmarking
-Benchmarking helps find out how fast each performance test runs. Each test case is run +4 times+ in benchmarking mode.
+Benchmarking helps find out how fast each performance test runs. Each test case is run +4 times+ in benchmarking mode.
To run performance tests in benchmarking mode:
@@ -161,7 +161,7 @@ $ rake test:benchmark
h5. Profiling
-Profiling helps you see the details of a performance test and provide an in-depth picture of the slow and memory hungry parts. Each test case is run +1 time+ in profiling mode.
+Profiling helps you see the details of a performance test and provide an in-depth picture of the slow and memory hungry parts. Each test case is run +1 time+ in profiling mode.
To run performance tests in profiling mode:
@@ -305,7 +305,7 @@ As +ActionController::Base.perform_caching+ is set to +true+, performance tests
h4. Installing GC-Patched Ruby
-To get the best from Rails performance tests, you need to build a special Ruby binary with some super powers - "GC patch":http://rubyforge.org/tracker/download.php/1814/7062/17676/3291/ruby186gc.patch for measuring GC Runs/Time and memory/object allocation.
+To get the best from Rails performance tests, you need to build a special Ruby binary with some super powers - "GC patch":http://rubyforge.org/tracker/download.php/1814/7062/17676/3291/ruby186gc.patch for measuring GC Runs/Time and memory/object allocation.
The process is fairly straight forward. If you've never compiled a Ruby binary before, follow these steps to build a ruby binary inside your home directory:
@@ -490,7 +490,7 @@ For this section, we're only interested in the last line:
Completed in 5ms (View: 2, DB: 0) | 200 OK [http://0.0.0.0/items]
</shell>
-This data is fairly straightforward to understand. Rails uses millisecond(ms) as the metric to measures the time taken. The complete request spent 5 ms inside Rails, out of which 2 ms were spent rendering views and none was spent communication with the database. It's safe to assume that the remaining 3 ms were spent inside the controller.
+This data is fairly straightforward to understand. Rails uses millisecond(ms) as the metric to measures the time taken. The complete request spent 5 ms inside Rails, out of which 2 ms were spent rendering views and none was spent communication with the database. It's safe to assume that the remaining 3 ms were spent inside the controller.
Michael Koziarski has an "interesting blog post":http://www.therailsway.com/2009/1/6/requests-per-second explaining the importance of using milliseconds as the metric.
diff --git a/railties/guides/source/plugins.textile b/railties/guides/source/plugins.textile
index 9096aecc91..c4fa7a88cd 100644
--- a/railties/guides/source/plugins.textile
+++ b/railties/guides/source/plugins.textile
@@ -222,18 +222,18 @@ require File.dirname(__FILE__) + '/test_helper.rb'
class YaffleTest < Test::Unit::TestCase
load_schema
-
+
class Hickwall < ActiveRecord::Base
end
class Wickwall < ActiveRecord::Base
end
-
+
def test_schema_has_loaded_correctly
assert_equal [], Hickwall.all
assert_equal [], Wickwall.all
end
-
+
end
</ruby>
@@ -247,7 +247,7 @@ rake
You should see output like:
<shell>
-/opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb"
+/opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb"
create_table(:hickwalls, {:force=>true})
-> 0.0220s
-- create_table(:wickwalls, {:force=>true})
@@ -507,18 +507,18 @@ class ActsAsYaffleTest < Test::Unit::TestCase
def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
assert_equal "last_tweet", Wickwall.yaffle_text_field
end
-
+
def test_hickwalls_squawk_should_populate_last_squawk
hickwall = Hickwall.new
hickwall.squawk("Hello World")
assert_equal "squawk! Hello World", hickwall.last_squawk
- end
-
+ end
+
def test_wickwalls_squawk_should_populate_last_tweeted_at
wickwall = Wickwall.new
wickwall.squawk("Hello World")
assert_equal "squawk! Hello World", wickwall.last_tweet
- end
+ end
end
</ruby>
@@ -642,10 +642,10 @@ class WoodpeckersControllerTest < Test::Unit::TestCase
@controller = WoodpeckersController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
-
+
ActionController::Routing::Routes.draw do |map|
map.resources :woodpeckers
- end
+ end
end
def test_index
@@ -672,11 +672,11 @@ end
<ruby>
class WoodpeckersController < ActionController::Base
-
+
def index
render :text => "Squawk!"
end
-
+
end
</ruby>
@@ -718,11 +718,11 @@ end
<ruby>
module WoodpeckersHelper
-
+
def tweet(text)
"Tweet! #{text}"
end
-
+
end
</ruby>
@@ -828,7 +828,7 @@ class DefinitionGeneratorTest < Test::Unit::TestCase
def teardown
FileUtils.rm_r(fake_rails_root)
end
-
+
def test_generates_correct_file_name
Rails::Generator::Scripts::Generate.new.run(["yaffle_definition"], :destination => fake_rails_root)
new_file = (file_list - @original_files).first
@@ -836,15 +836,15 @@ class DefinitionGeneratorTest < Test::Unit::TestCase
end
private
-
+
def fake_rails_root
File.join(File.dirname(__FILE__), 'rails_root')
end
-
+
def file_list
Dir.glob(File.join(fake_rails_root, "*"))
end
-
+
end
</ruby>
@@ -882,7 +882,7 @@ Installed Generators
Builtin: controller, integration_test, mailer, migration, model, observer, plugin, resource, scaffold, session_migration
</shell>
-When you run +script/generate yaffle_definition -h+ you should see the contents of your 'vendor/plugins/yaffle/generators/yaffle_definition/USAGE'.
+When you run +script/generate yaffle_definition -h+ you should see the contents of your 'vendor/plugins/yaffle/generators/yaffle_definition/USAGE'.
For this plugin, update the USAGE file could look like this:
@@ -998,11 +998,11 @@ class RouteGeneratorTest < Test::Unit::TestCase
def setup
FileUtils.mkdir_p(File.join(fake_rails_root, "config"))
end
-
+
def teardown
FileUtils.rm_r(fake_rails_root)
end
-
+
def test_generates_route
content = <<-END
ActionController::Routing::Routes.draw do |map|
@@ -1011,7 +1011,7 @@ class RouteGeneratorTest < Test::Unit::TestCase
end
END
File.open(routes_path, 'wb') {|f| f.write(content) }
-
+
Rails::Generator::Scripts::Generate.new.run(["yaffle_route"], :destination => fake_rails_root)
assert_match /map\.yaffles/, File.read(routes_path)
end
@@ -1025,21 +1025,21 @@ class RouteGeneratorTest < Test::Unit::TestCase
end
END
File.open(routes_path, 'wb') {|f| f.write(content) }
-
+
Rails::Generator::Scripts::Destroy.new.run(["yaffle_route"], :destination => fake_rails_root)
assert_no_match /map\.yaffles/, File.read(routes_path)
end
-
+
private
-
+
def fake_rails_root
File.join(File.dirname(__FILE__), "rails_root")
end
-
+
def routes_path
File.join(fake_rails_root, "config", "routes.rb")
end
-
+
end
</ruby>
@@ -1152,7 +1152,7 @@ h4. Create a custom rake task
namespace :db do
namespace :migrate do
description = "Migrate the database through scripts in vendor/plugins/yaffle/lib/db/migrate"
- description << "and update db/schema.rb by invoking db:schema:dump."
+ description << "and update db/schema.rb by invoking db:schema:dump."
description << "Target specific version with VERSION=x. Turn off output with VERBOSE=false."
desc description
@@ -1218,9 +1218,9 @@ class MigrationGeneratorTest < Test::Unit::TestCase
ActiveRecord::Base.pluralize_table_names = true
FileUtils.rm_r(fake_rails_root)
end
-
+
def test_generates_correct_file_name
- Rails::Generator::Scripts::Generate.new.run(["yaffle_migration", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"],
+ Rails::Generator::Scripts::Generate.new.run(["yaffle_migration", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"],
:destination => fake_rails_root)
new_file = (file_list - @original_files).first
assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migrations/, new_file
@@ -1229,7 +1229,7 @@ class MigrationGeneratorTest < Test::Unit::TestCase
def test_pluralizes_properly
ActiveRecord::Base.pluralize_table_names = false
- Rails::Generator::Scripts::Generate.new.run(["yaffle_migration", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"],
+ Rails::Generator::Scripts::Generate.new.run(["yaffle_migration", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"],
:destination => fake_rails_root)
new_file = (file_list - @original_files).first
assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migration/, new_file
@@ -1240,11 +1240,11 @@ class MigrationGeneratorTest < Test::Unit::TestCase
def fake_rails_root
File.join(File.dirname(__FILE__), 'rails_root')
end
-
+
def file_list
Dir.glob(File.join(fake_rails_root, "db", "migrate", "*"))
end
-
+
end
</ruby>
@@ -1348,14 +1348,14 @@ It's common practice to put any developer-centric rake tasks (such as tests, rdo
<ruby>
PKG_FILES = FileList[
'[a-zA-Z]*',
- 'generators/**/*',
- 'lib/**/*',
+ 'generators/**/*',
+ 'lib/**/*',
'rails/**/*',
- 'tasks/**/*',
+ 'tasks/**/*',
'test/**/*'
]
-spec = Gem::Specification.new do |s|
+spec = Gem::Specification.new do |s|
s.name = "yaffle"
s.version = "0.0.1"
s.author = "Gleeful Yaffler"
@@ -1372,7 +1372,7 @@ end
desc 'Turn this plugin into a gem.'
Rake::GemPackageTask.new(spec) do |pkg|
pkg.gem_spec = spec
-end
+end
</ruby>
To build and install the gem locally, run the following commands:
diff --git a/railties/guides/source/rails_on_rack.textile b/railties/guides/source/rails_on_rack.textile
index 1166ec1c3b..8e169dd1fb 100644
--- a/railties/guides/source/rails_on_rack.textile
+++ b/railties/guides/source/rails_on_rack.textile
@@ -199,7 +199,7 @@ Metal applications are an optimization. You should make sure to "understand the
h4. Execution Order
-All Metal Applications are executed by +Rails::Rack::Metal+ middleware, which is a part of the +ActionController::MiddlewareStack+ chain.
+All Metal Applications are executed by +Rails::Rack::Metal+ middleware, which is a part of the +ActionController::MiddlewareStack+ chain.
Here's the primary method responsible for running the Metal applications:
@@ -223,4 +223,4 @@ h3. Changelog
"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/4
-* January 11, 2009: First version by "Pratik":credits.html#lifo \ No newline at end of file
+* January 11, 2009: First version by "Pratik":credits.html#lifo
diff --git a/railties/guides/source/routing.textile b/railties/guides/source/routing.textile
index 7dadbf0231..c31307e77f 100644
--- a/railties/guides/source/routing.textile
+++ b/railties/guides/source/routing.textile
@@ -22,7 +22,7 @@ GET /patients/17
</pre>
the routing engine within Rails is the piece of code that dispatches the request to the appropriate spot in your application. In this case, the application would most likely end up running the +show+ action within the +patients+ controller, displaying the details of the patient whose ID is 17.
-
+
h4. Generating URLs from Code
Routing also works in reverse. If your application contains this code:
@@ -111,7 +111,7 @@ h4. What is REST?
The foundation of RESTful routing is generally considered to be Roy Fielding's doctoral thesis, "Architectural Styles and the Design of Network-based Software Architectures":http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm. Fortunately, you need not read this entire document to understand how REST works in Rails. REST, an acronym for Representational State Transfer, boils down to two main principles for our purposes:
* Using resource identifiers (which, for the purposes of discussion, you can think of as URLs) to represent resources
-* Transferring representations of the state of that resource between system components.
+* Transferring representations of the state of that resource between system components.
For example, to a Rails application a request such as this:
@@ -120,7 +120,7 @@ DELETE /photos/17
</pre>
would be understood to refer to a photo resource with the ID of 17, and to indicate a desired action - deleting that resource. REST is a natural style for the architecture of web applications, and Rails makes it even more natural by using conventions to shield you from some of the RESTful complexities.
-
+
h4. CRUD, Verbs, and Actions
In Rails, a RESTful route provides a mapping between HTTP verbs, controller actions, and (implicitly) CRUD operations in a database. A single entry in the routing file, such as
@@ -170,7 +170,7 @@ If you need to create routes for more than one RESTful resource, you can save a
map.resources :photos, :books, :videos
</ruby>
-This has exactly the same effect as
+This has exactly the same effect as
<ruby>
map.resources :photos
@@ -229,7 +229,7 @@ The +:controller+ option lets you use a controller name that is different from t
map.resources :photos, :controller => "images"
</ruby>
-will recognize incoming URLs containing +photo+ but route the requests to the Images controller:
+will recognize incoming URLs containing +photo+ but route the requests to the Images controller:
|_.HTTP verb |_.URL |_.controller |_.action |_.used for|
|GET |/photos |Images |index |display a list of all images|
@@ -302,7 +302,7 @@ The +:as+ option lets you override the normal naming for the actual generated pa
map.resources :photos, :as => "images"
</ruby>
-will recognize incoming URLs containing +image+ but route the requests to the Photos controller:
+will recognize incoming URLs containing +image+ but route the requests to the Photos controller:
|_.HTTP verb |_.URL |_.controller |_.action |_:used for|
|GET |/images |Photos |index |display a list of all photos|
@@ -411,7 +411,7 @@ Each ad is logically subservient to one magazine. Nested routes allow you to cap
<ruby>
map.resources :magazines do |magazine|
magazine.resources :ads
-end
+end
</ruby>
In addition to the routes for magazines, this declaration will also create routes for ads, each of which requires the specification of a magazine in the URL:
@@ -435,7 +435,7 @@ The +:name_prefix+ option overrides the automatically-generated prefix in nested
<ruby>
map.resources :magazines do |magazine|
magazine.resources :ads, :name_prefix => 'periodical'
-end
+end
</ruby>
This will create routing helpers such as +periodical_ads_url+ and +periodical_edit_ad_path+. You can even use +:name_prefix+ to suppress the prefix entirely:
@@ -443,7 +443,7 @@ This will create routing helpers such as +periodical_ads_url+ and +periodical_ed
<ruby>
map.resources :magazines do |magazine|
magazine.resources :ads, :name_prefix => nil
-end
+end
</ruby>
This will create routing helpers such as +ads_url+ and +edit_ad_path+. Note that calling these will still require supplying an article id:
@@ -470,7 +470,7 @@ map.resources :photos do |photo|
photo.resources :versions
end
</ruby>
-
+
h5. Limits to Nesting
You can nest resources within other nested resources if you like. For example:
@@ -544,7 +544,7 @@ Another way to refer to the same route is with an array of objects:
</ruby>
This format is especially useful when you might not know until runtime which of several types of object will be used in a particular link.
-
+
h4. Namespaced Resources
It's possible to do some quite complex things by combining +:path_prefix+ and +:name_prefix+. For example, you can use the combination of these two options to move administrative resources to their own folder in your application:
@@ -628,7 +628,7 @@ h3. Regular Routes
In addition to RESTful routing, Rails supports regular routing - a way to map URLs to controllers and actions. With regular routing, you don't get the masses of routes automatically generated by RESTful routing. Instead, you must set up each route within your application separately.
-While RESTful routing has become the Rails standard, there are still plenty of places where the simpler regular routing works fine. You can even mix the two styles within a single application. In general, you should prefer RESTful routing _when possible_, because it will make parts of your application easier to write. But there's no need to try to shoehorn every last piece of your application into a RESTful framework if that's not a good fit.
+While RESTful routing has become the Rails standard, there are still plenty of places where the simpler regular routing works fine. You can even mix the two styles within a single application. In general, you should prefer RESTful routing _when possible_, because it will make parts of your application easier to write. But there's no need to try to shoehorn every last piece of your application into a RESTful framework if that's not a good fit.
h4. Bound Parameters
@@ -711,7 +711,7 @@ This route would respond to URLs such as +/photo/A12345+. You can more succinctl
<ruby>
map.connect 'photo/:id', :controller => 'photos', :action => 'show',
- :id => /[A-Z]\d{5}/
+ :id => /[A-Z]\d{5}/
</ruby>
h4. Route Conditions
diff --git a/railties/guides/source/security.textile b/railties/guides/source/security.textile
index 28e0e12e34..a89cfaddbe 100644
--- a/railties/guides/source/security.textile
+++ b/railties/guides/source/security.textile
@@ -641,7 +641,7 @@ And now let's inject another query using the UNION statement:
This will result in the following SQL query:
<pre>
-SELECT * FROM projects WHERE (name = '') UNION
+SELECT * FROM projects WHERE (name = '') UNION
SELECT id,login AS name,password AS description,1,1,1 FROM users --')
</pre>
@@ -750,7 +750,7 @@ Especially for XSS, it is important to do _(highlight)whitelist input filtering
Imagine a blacklist deletes “script” from the user input. Now the attacker injects “&lt;scrscriptipt&gt;”, and after the filter, “&lt;script&gt;” remains. Earlier versions of Rails used a blacklist approach for the strip_tags(), strip_links() and sanitize() method. So this kind of injection was possible:
<pre>
-strip_tags("some<<b>script>alert('hello')<</b>/script>")
+strip_tags("some<<b>script>alert('hello')<</b>/script>")
</pre>
This returned "some&lt;script&gt;alert('hello')&lt;/script&gt;", which makes an attack work. That's why I vote for a whitelist approach, using the updated Rails 2 method sanitize():
@@ -782,7 +782,7 @@ h5. Examples from the underground
The following is an excerpt from the "Js.Yamanner@m":http://www.symantec.com/security_response/writeup.jsp?docid=2006-061211-4111-99&tabid=1 Yahoo! Mail "worm":http://groovin.net/stuff/yammer.txt. It appeared on June 11, 2006 and was the first webmail interface worm:
<pre>
-<img src='http://us.i1.yimg.com/us.yimg.com/i/us/nt/ma/ma_mail_1.gif'
+<img src='http://us.i1.yimg.com/us.yimg.com/i/us/nt/ma/ma_mail_1.gif'
target=""onload="var http_request = false; var Email = '';
var IDList = ''; var CRumb = ''; function makeRequest(url, Func, Method,Param) { ...
</pre>
@@ -810,13 +810,13 @@ MySpace blocks many tags, however it allows CSS. So the worm's author put JavaSc
So the payload is in the style attribute. But there are no quotes allowed in the payload, because single and double quotes have already been used. But JavaScript allows has a handy eval() function which executes any string as code.
<pre>
-<div id="mycode" expr="alert('hah!')" style="background:url('javascript:eval(document.all.mycode.expr)')">
+<div id="mycode" expr="alert('hah!')" style="background:url('javascript:eval(document.all.mycode.expr)')">
</pre>
The eval() function is a nightmare for blacklist input filters, as it allows the style attribute to hide the word “innerHTML”:
<pre>
-alert(eval('document.body.inne' + 'rHTML'));
+alert(eval('document.body.inne' + 'rHTML'));
</pre>
The next problem was MySpace filtering the word “javascript”, so the author used “java&lt;NEWLINE&gt;script" to get around this:
diff --git a/railties/guides/source/testing.textile b/railties/guides/source/testing.textile
index ad51c053f1..8129dc34c2 100644
--- a/railties/guides/source/testing.textile
+++ b/railties/guides/source/testing.textile
@@ -186,7 +186,7 @@ The +PostTest+ class defines a _test case_ because it inherits from +ActiveSuppo
def test_truth
</ruby>
-Any method defined within a test case that begins with +test+ (case sensitive) is simply called a test. So, +test_password+, +test_valid_password+ and +testValidPassword+ all are legal test names and are run automatically when the test case is run.
+Any method defined within a test case that begins with +test+ (case sensitive) is simply called a test. So, +test_password+, +test_valid_password+ and +testValidPassword+ all are legal test names and are run automatically when the test case is run.
<ruby>
assert true
@@ -194,10 +194,10 @@ assert true
This line of code is called an _assertion_. An assertion is a line of code that evaluates an object (or expression) for expected results. For example, an assertion can check:
-* is this value = that value?
-* is this object nil?
-* does this line of code throw an exception?
-* is the user's password greater than 5 characters?
+* is this value = that value?
+* is this object nil?
+* does this line of code throw an exception?
+* is the user's password greater than 5 characters?
Every test contains one or more assertions. Only when all the assertions are successful the test passes.
@@ -232,7 +232,7 @@ Running a test is as simple as invoking the file containing the test cases throu
<shell>
$ cd test
-$ ruby unit/post_test.rb
+$ ruby unit/post_test.rb
Loaded suite unit/post_test
Started
@@ -257,7 +257,7 @@ Finished in 0.023513 seconds.
1 tests, 1 assertions, 0 failures, 0 errors
</pre>
-The +.+ (dot) above indicates a passing test. When a test fails you see an +F+; when a test throws an error you see an +E+ in its place. The last line of the output is the summary.
+The +.+ (dot) above indicates a passing test. When a test fails you see an +F+; when a test throws an error you see an +E+ in its place. The last line of the output is the summary.
To see how a test failure is reported, you can add a failing test to the +post_test.rb+ test case.
@@ -336,7 +336,7 @@ Finished in 0.193608 seconds.
1 tests, 1 assertions, 0 failures, 0 errors
</pre>
-Now if you noticed we first wrote a test which fails for a desired functionality, then we wrote some code which adds the functionality and finally we ensured that our test passes. This approach to software development is referred to as _Test-Driven Development_ (TDD).
+Now if you noticed we first wrote a test which fails for a desired functionality, then we wrote some code which adds the functionality and finally we ensured that our test passes. This approach to software development is referred to as _Test-Driven Development_ (TDD).
TIP: Many Rails developers practice _Test-Driven Development_ (TDD). This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with "15 TDD steps to create a Rails application":http://andrzejonsoftware.blogspot.com/2007/05/15-tdd-steps-to-create-rails.html.
@@ -370,7 +370,7 @@ NameError: undefined local variable or method `some_undefined_variable' for #<Po
1 tests, 0 assertions, 0 failures, 1 errors
</pre>
-Notice the 'E' in the output. It denotes a test with error.
+Notice the 'E' in the output. It denotes a test with error.
NOTE: The execution of each test method stops as soon as any error or a assertion failure is encountered, and the test suite continues with the next method. All test methods are executed in alphabetical order.
@@ -427,7 +427,7 @@ You'll see the usage of some of these assertions in the next chapter.
h3. Functional Tests for Your Controllers
-In Rails, testing the various actions of a single controller is called writing functional tests for that controller. Controllers handle the incoming web requests to your application and eventually respond with a rendered view.
+In Rails, testing the various actions of a single controller is called writing functional tests for that controller. Controllers handle the incoming web requests to your application and eventually respond with a rendered view.
h4. What to include in your Functional Tests
@@ -451,11 +451,11 @@ def test_should_get_index
end
</ruby>
-In the +test_should_get_index+ test, Rails simulates a request on the action called index, making sure the request was successful and also ensuring that it assigns a valid +posts+ instance variable.
+In the +test_should_get_index+ test, Rails simulates a request on the action called index, making sure the request was successful and also ensuring that it assigns a valid +posts+ instance variable.
The +get+ method kicks off the web request and populates the results into the response. It accepts 4 arguments:
-* The action of the controller you are requesting. This can be in the form of a string or a symbol.
+* The action of the controller you are requesting. This can be in the form of a string or a symbol.
* An optional hash of request parameters to pass into the action (eg. query string parameters or post variables).
* An optional hash of session variables to pass along with the request.
* An optional hash of flash values.
@@ -604,12 +604,12 @@ end
h3. Integration Testing
-Integration tests are used to test the interaction among any number of controllers. They are generally used to test important work flows within your application.
+Integration tests are used to test the interaction among any number of controllers. They are generally used to test important work flows within your application.
-Unlike Unit and Functional tests, integration tests have to be explicitly created under the 'test/integration' folder within your application. Rails provides a generator to create an integration test skeleton for you.
+Unlike Unit and Functional tests, integration tests have to be explicitly created under the 'test/integration' folder within your application. Rails provides a generator to create an integration test skeleton for you.
<shell>
-$ script/generate integration_test user_flows
+$ script/generate integration_test user_flows
exists test/integration/
create test/integration/user_flows_test.rb
</shell>
@@ -629,7 +629,7 @@ class UserFlowsTest < ActionController::IntegrationTest
end
</ruby>
-Integration tests inherit from +ActionController::IntegrationTest+. This makes available some additional helpers to use in your integration tests. Also you need to explicitly include the fixtures to be made available to the test.
+Integration tests inherit from +ActionController::IntegrationTest+. This makes available some additional helpers to use in your integration tests. Also you need to explicitly include the fixtures to be made available to the test.
h4. Helpers Available for Integration tests
@@ -663,11 +663,11 @@ class UserFlowsTest < ActionController::IntegrationTest
https!
get "/login"
assert_response :success
-
+
post_via_redirect "/login", :username => users(:avs).username, :password => users(:avs).password
assert_equal '/welcome', path
assert_equal 'Welcome avs!', flash[:notice]
-
+
https!(false)
get "/posts/all"
assert_response :success
@@ -687,26 +687,26 @@ class UserFlowsTest < ActionController::IntegrationTest
fixtures :users
def test_login_and_browse_site
-
+
# User avs logs in
avs = login(:avs)
# User guest logs in
guest = login(:guest)
-
+
# Both are now available in different sessions
assert_equal 'Welcome avs!', avs.flash[:notice]
assert_equal 'Welcome guest!', guest.flash[:notice]
-
+
# User avs can browse site
avs.browses_site
# User guest can browse site aswell
guest.browses_site
-
+
# Continue with other assertions
end
-
+
private
-
+
module CustomDsl
def browses_site
get "/products/all"
@@ -714,7 +714,7 @@ class UserFlowsTest < ActionController::IntegrationTest
assert assigns(:products)
end
end
-
+
def login(user)
open_session do |sess|
sess.extend(CustomDsl)
@@ -764,7 +764,7 @@ class PostsControllerTest < ActionController::TestCase
# called after every single test
def teardown
# as we are re-initializing @post before every test
- # setting it to nil here is not essential but I hope
+ # setting it to nil here is not essential but I hope
# you understand how you can use the teardown method
@post = nil
end
@@ -781,7 +781,7 @@ class PostsControllerTest < ActionController::TestCase
assert_redirected_to posts_path
end
-
+
end
</ruby>
@@ -791,7 +791,7 @@ Above, the +setup+ method is called before each test and so +@post+ is available
* a method (like in the earlier example)
* a method name as a symbol
* a lambda
-
+
Let's see the earlier example by specifying +setup+ callback by specifying a method name as a symbol:
<ruby>
@@ -811,7 +811,7 @@ class PostsControllerTest < ActionController::TestCase
get :show, :id => @post.id
assert_response :success
end
-
+
def test_should_update_post
put :update, :id => @post.id, :post => { }
assert_redirected_to post_path(assigns(:post))
@@ -824,13 +824,13 @@ class PostsControllerTest < ActionController::TestCase
assert_redirected_to posts_path
end
-
- private
-
+
+ private
+
def initialize_post
@post = posts(:one)
end
-
+
end
</ruby>
@@ -870,7 +870,7 @@ h5. Revenge of the Fixtures
For the purposes of unit testing a mailer, fixtures are used to provide an example of how the output _should_ look. Because these are example emails, and not Active Record data like the other fixtures, they are kept in their own subdirectory apart from the other fixtures. The name of the directory within +test/fixtures+ directly corresponds to the name of the mailer. So, for a mailer named +UserMailer+, the fixtures should reside in +test/fixtures/user_mailer+ directory.
-When you generated your mailer, the generator creates stub fixtures for each of the mailers actions. If you didn't use the generator you'll have to make those files yourself.
+When you generated your mailer, the generator creates stub fixtures for each of the mailers actions. If you didn't use the generator you'll have to make those files yourself.
h5. The Basic Test case
@@ -901,7 +901,7 @@ Here's the content of the +invite+ fixture:
<pre>
Hi friend@example.com,
-You have been invited.
+You have been invited.
Cheers!
</pre>
@@ -923,7 +923,7 @@ class UserControllerTest < ActionController::TestCase
post :invite_friend, :email => 'friend@example.com'
end
invite_email = ActionMailer::Base.deliveries.first
-
+
assert_equal invite_email.subject, "You have been invited by me@example.com"
assert_equal invite_email.to[0], 'friend@example.com'
assert_match /Hi friend@example.com/, invite_email.body
diff --git a/railties/lib/commands/server.rb b/railties/lib/commands/server.rb
index 43b18004c0..ebe34a42cd 100644
--- a/railties/lib/commands/server.rb
+++ b/railties/lib/commands/server.rb
@@ -17,7 +17,8 @@ options = {
:environment => (ENV['RAILS_ENV'] || "development").dup,
:config => RAILS_ROOT + "/config.ru",
:detach => false,
- :debugger => false
+ :debugger => false,
+ :path => nil
}
ARGV.clone.options do |opts|
@@ -32,6 +33,7 @@ ARGV.clone.options do |opts|
opts.on("-e", "--environment=name", String,
"Specifies the environment to run this server under (test/development/production).",
"Default: development") { |v| options[:environment] = v }
+ opts.on("-P", "--path=/path", String, "Runs Rails app mounted at a specific path.", "Default: /") { |v| options[:path] = v }
opts.separator ""
@@ -50,7 +52,7 @@ unless server
end
puts "=> Booting #{ActiveSupport::Inflector.demodulize(server)}"
-puts "=> Rails #{Rails.version} application starting on http://#{options[:Host]}:#{options[:Port]}"
+puts "=> Rails #{Rails.version} application starting on http://#{options[:Host]}:#{options[:Port]}#{options[:path]}"
%w(cache pids sessions sockets).each do |dir_to_make|
FileUtils.mkdir_p(File.join(RAILS_ROOT, 'tmp', dir_to_make))
@@ -83,11 +85,20 @@ else
inner_app = ActionController::Dispatcher.new
end
+if options[:path].nil?
+ map_path = "/"
+else
+ ActionController::Base.relative_url_root = options[:path]
+ map_path = options[:path]
+end
+
app = Rack::Builder.new {
use Rails::Rack::LogTailer unless options[:detach]
- use Rails::Rack::Static
use Rails::Rack::Debugger if options[:debugger]
- run inner_app
+ map map_path do
+ use Rails::Rack::Static
+ run inner_app
+ end
}.to_app
puts "=> Call with -d to detach"
diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb
index da064c86aa..e3811dd8be 100644
--- a/railties/lib/initializer.rb
+++ b/railties/lib/initializer.rb
@@ -132,10 +132,10 @@ module Rails
add_gem_load_paths
require_frameworks
- preload_frameworks
set_autoload_paths
add_plugin_load_paths
load_environment
+ preload_frameworks
initialize_encoding
initialize_database
@@ -270,7 +270,7 @@ module Rails
configuration.frameworks.each do |framework|
# String#classify and #constantize aren't available yet.
toplevel = Object.const_get(framework.to_s.gsub(/(?:^|_)(.)/) { $1.upcase })
- toplevel.load_all!
+ toplevel.load_all! if toplevel.respond_to?(:load_all!)
end
end
end
diff --git a/railties/lib/rails_generator/generators/components/scaffold/templates/controller.rb b/railties/lib/rails_generator/generators/components/scaffold/templates/controller.rb
index cbfd88f3bd..4d190b9362 100644
--- a/railties/lib/rails_generator/generators/components/scaffold/templates/controller.rb
+++ b/railties/lib/rails_generator/generators/components/scaffold/templates/controller.rb
@@ -2,7 +2,7 @@ class <%= controller_class_name %>Controller < ApplicationController
# GET /<%= table_name %>
# GET /<%= table_name %>.xml
def index
- @<%= table_name %> = <%= class_name %>.find(:all)
+ @<%= table_name %> = <%= class_name %>.all
respond_to do |format|
format.html # index.html.erb
diff --git a/railties/lib/rails_generator/generators/components/scaffold/templates/layout.html.erb b/railties/lib/rails_generator/generators/components/scaffold/templates/layout.html.erb
index 5c1f304232..ebc97f8130 100644
--- a/railties/lib/rails_generator/generators/components/scaffold/templates/layout.html.erb
+++ b/railties/lib/rails_generator/generators/components/scaffold/templates/layout.html.erb
@@ -11,7 +11,7 @@
<p style="color: green"><%%= flash[:notice] %></p>
-<%%= yield %>
+<%%= yield %>
</body>
</html>
diff --git a/railties/lib/rails_generator/generators/components/scaffold/templates/view_edit.html.erb b/railties/lib/rails_generator/generators/components/scaffold/templates/view_edit.html.erb
index e289975596..cca1d61c68 100644
--- a/railties/lib/rails_generator/generators/components/scaffold/templates/view_edit.html.erb
+++ b/railties/lib/rails_generator/generators/components/scaffold/templates/view_edit.html.erb
@@ -10,9 +10,9 @@
</p>
<% end -%>
<p>
- <%%= f.submit "Update" %>
+ <%%= f.submit 'Update' %>
</p>
<%% end %>
<%%= link_to 'Show', @<%= singular_name %> %> |
-<%%= link_to 'Back', <%= plural_name %>_path %>
+<%%= link_to 'Back', <%= plural_name %>_path %> \ No newline at end of file
diff --git a/railties/lib/rails_generator/generators/components/scaffold/templates/view_index.html.erb b/railties/lib/rails_generator/generators/components/scaffold/templates/view_index.html.erb
index e89757e3e9..2e603d5b4a 100644
--- a/railties/lib/rails_generator/generators/components/scaffold/templates/view_index.html.erb
+++ b/railties/lib/rails_generator/generators/components/scaffold/templates/view_index.html.erb
@@ -7,7 +7,7 @@
<% end -%>
</tr>
-<%% for <%= singular_name %> in @<%= plural_name %> %>
+<%% @<%= plural_name %>.each do |<%= singular_name %>| %>
<tr>
<% for attribute in attributes -%>
<td><%%=h <%= singular_name %>.<%= attribute.name %> %></td>
@@ -21,4 +21,4 @@
<br />
-<%%= link_to 'New <%= singular_name %>', new_<%= singular_name %>_path %>
+<%%= link_to 'New <%= singular_name %>', new_<%= singular_name %>_path %> \ No newline at end of file
diff --git a/railties/lib/rails_generator/generators/components/scaffold/templates/view_new.html.erb b/railties/lib/rails_generator/generators/components/scaffold/templates/view_new.html.erb
index c47e8117b4..96c89fc50e 100644
--- a/railties/lib/rails_generator/generators/components/scaffold/templates/view_new.html.erb
+++ b/railties/lib/rails_generator/generators/components/scaffold/templates/view_new.html.erb
@@ -10,8 +10,8 @@
</p>
<% end -%>
<p>
- <%%= f.submit "Create" %>
+ <%%= f.submit 'Create' %>
</p>
<%% end %>
-<%%= link_to 'Back', <%= plural_name %>_path %>
+<%%= link_to 'Back', <%= plural_name %>_path %> \ No newline at end of file
diff --git a/railties/lib/rails_generator/generators/components/scaffold/templates/view_show.html.erb b/railties/lib/rails_generator/generators/components/scaffold/templates/view_show.html.erb
index 9b6b11b029..adecaf70c6 100644
--- a/railties/lib/rails_generator/generators/components/scaffold/templates/view_show.html.erb
+++ b/railties/lib/rails_generator/generators/components/scaffold/templates/view_show.html.erb
@@ -7,4 +7,4 @@
<% end -%>
<%%= link_to 'Edit', edit_<%= singular_name %>_path(@<%= singular_name %>) %> |
-<%%= link_to 'Back', <%= plural_name %>_path %>
+<%%= link_to 'Back', <%= plural_name %>_path %> \ No newline at end of file
diff --git a/railties/lib/tasks/databases.rake b/railties/lib/tasks/databases.rake
index 68ffefae0b..9588fabb2d 100644
--- a/railties/lib/tasks/databases.rake
+++ b/railties/lib/tasks/databases.rake
@@ -250,6 +250,7 @@ namespace :db do
File.open(ENV['SCHEMA'] || "#{RAILS_ROOT}/db/schema.rb", "w") do |file|
ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
end
+ Rake::Task["db:schema:dump"].reenable
end
desc "Load a schema.rb file into the database"
diff --git a/railties/test/abstract_unit.rb b/railties/test/abstract_unit.rb
index b6edc03391..43736ee7ec 100644
--- a/railties/test/abstract_unit.rb
+++ b/railties/test/abstract_unit.rb
@@ -3,20 +3,18 @@ $:.unshift File.dirname(__FILE__) + "/../../actionpack/lib"
$:.unshift File.dirname(__FILE__) + "/../lib"
$:.unshift File.dirname(__FILE__) + "/../builtin/rails_info"
+require 'stringio'
require 'rubygems'
require 'test/unit'
-gem 'mocha', '>= 0.9.3'
+
+gem 'mocha', '>= 0.9.5'
require 'mocha'
-require 'stringio'
+
require 'active_support'
require 'active_support/test_case'
-def uses_mocha(test_name)
- yield
-end
-
if defined?(RAILS_ROOT)
RAILS_ROOT.replace File.dirname(__FILE__)
else
RAILS_ROOT = File.dirname(__FILE__)
-end \ No newline at end of file
+end
diff --git a/railties/test/boot_test.rb b/railties/test/boot_test.rb
index 7736a8f4c0..16776af098 100644
--- a/railties/test/boot_test.rb
+++ b/railties/test/boot_test.rb
@@ -2,8 +2,6 @@ require 'abstract_unit'
require 'initializer'
require "#{File.dirname(__FILE__)}/../environments/boot"
-uses_mocha 'boot tests' do
-
class BootTest < Test::Unit::TestCase
def test_boot_returns_if_booted
Rails.expects(:booted?).returns(true)
@@ -121,9 +119,6 @@ class GemBootTest < Test::Unit::TestCase
end
end
-end # uses_mocha
-
-
class ParseGemVersionTest < Test::Unit::TestCase
def test_should_return_nil_if_no_lines_are_passed
assert_equal nil, parse('')
diff --git a/railties/test/console_app_test.rb b/railties/test/console_app_test.rb
index f419fe0d8d..7a5de5af8f 100644
--- a/railties/test/console_app_test.rb
+++ b/railties/test/console_app_test.rb
@@ -23,20 +23,18 @@ class ConsoleAppTest < Test::Unit::TestCase
end
end
- uses_mocha 'console reload test' do
- def test_reload_should_fire_preparation_callbacks
- a = b = c = nil
+ def test_reload_should_fire_preparation_callbacks
+ a = b = c = nil
- Dispatcher.to_prepare { a = b = c = 1 }
- Dispatcher.to_prepare { b = c = 2 }
- Dispatcher.to_prepare { c = 3 }
- ActionController::Routing::Routes.expects(:reload)
+ Dispatcher.to_prepare { a = b = c = 1 }
+ Dispatcher.to_prepare { b = c = 2 }
+ Dispatcher.to_prepare { c = 3 }
+ ActionController::Routing::Routes.expects(:reload)
- reload!
+ reload!
- assert_equal 1, a
- assert_equal 2, b
- assert_equal 3, c
- end
+ assert_equal 1, a
+ assert_equal 2, b
+ assert_equal 3, c
end
end
diff --git a/railties/test/gem_dependency_test.rb b/railties/test/gem_dependency_test.rb
index 6c1f0961a1..9cb02fcd06 100644
--- a/railties/test/gem_dependency_test.rb
+++ b/railties/test/gem_dependency_test.rb
@@ -6,141 +6,139 @@ end
Rails::VendorGemSourceIndex.silence_spec_warnings = true
-uses_mocha "Plugin Tests" do
- class GemDependencyTest < Test::Unit::TestCase
- def setup
- @gem = Rails::GemDependency.new "xhpricotx"
- @gem_with_source = Rails::GemDependency.new "xhpricotx", :source => "http://code.whytheluckystiff.net"
- @gem_with_version = Rails::GemDependency.new "xhpricotx", :version => "= 0.6"
- @gem_with_lib = Rails::GemDependency.new "xaws-s3x", :lib => "aws/s3"
- @gem_without_load = Rails::GemDependency.new "xhpricotx", :lib => false
- end
+class GemDependencyTest < Test::Unit::TestCase
+ def setup
+ @gem = Rails::GemDependency.new "xhpricotx"
+ @gem_with_source = Rails::GemDependency.new "xhpricotx", :source => "http://code.whytheluckystiff.net"
+ @gem_with_version = Rails::GemDependency.new "xhpricotx", :version => "= 0.6"
+ @gem_with_lib = Rails::GemDependency.new "xaws-s3x", :lib => "aws/s3"
+ @gem_without_load = Rails::GemDependency.new "xhpricotx", :lib => false
+ end
- def test_configuration_adds_gem_dependency
- config = Rails::Configuration.new
- config.gem "xaws-s3x", :lib => "aws/s3", :version => "0.4.0"
- assert_equal [["install", "xaws-s3x", "--version", '"= 0.4.0"']], config.gems.collect(&:install_command)
- end
+ def test_configuration_adds_gem_dependency
+ config = Rails::Configuration.new
+ config.gem "xaws-s3x", :lib => "aws/s3", :version => "0.4.0"
+ assert_equal [["install", "xaws-s3x", "--version", '"= 0.4.0"']], config.gems.collect(&:install_command)
+ end
- def test_gem_creates_install_command
- assert_equal %w(install xhpricotx), @gem.install_command
- end
+ def test_gem_creates_install_command
+ assert_equal %w(install xhpricotx), @gem.install_command
+ end
- def test_gem_with_source_creates_install_command
- assert_equal %w(install xhpricotx --source http://code.whytheluckystiff.net), @gem_with_source.install_command
- end
+ def test_gem_with_source_creates_install_command
+ assert_equal %w(install xhpricotx --source http://code.whytheluckystiff.net), @gem_with_source.install_command
+ end
- def test_gem_with_version_creates_install_command
- assert_equal ["install", "xhpricotx", "--version", '"= 0.6"'], @gem_with_version.install_command
- end
+ def test_gem_with_version_creates_install_command
+ assert_equal ["install", "xhpricotx", "--version", '"= 0.6"'], @gem_with_version.install_command
+ end
- def test_gem_creates_unpack_command
- assert_equal %w(unpack xhpricotx), @gem.unpack_command
- end
+ def test_gem_creates_unpack_command
+ assert_equal %w(unpack xhpricotx), @gem.unpack_command
+ end
- def test_gem_with_version_unpack_install_command
- # stub out specification method, or else test will fail if hpricot 0.6 isn't installed
- mock_spec = mock()
- mock_spec.stubs(:version).returns('0.6')
- @gem_with_version.stubs(:specification).returns(mock_spec)
- assert_equal ["unpack", "xhpricotx", "--version", '= 0.6'], @gem_with_version.unpack_command
- end
+ def test_gem_with_version_unpack_install_command
+ # stub out specification method, or else test will fail if hpricot 0.6 isn't installed
+ mock_spec = mock()
+ mock_spec.stubs(:version).returns('0.6')
+ @gem_with_version.stubs(:specification).returns(mock_spec)
+ assert_equal ["unpack", "xhpricotx", "--version", '= 0.6'], @gem_with_version.unpack_command
+ end
- def test_gem_adds_load_paths
- @gem.expects(:gem).with(Gem::Dependency.new(@gem.name, nil))
- @gem.add_load_paths
- end
+ def test_gem_adds_load_paths
+ @gem.expects(:gem).with(Gem::Dependency.new(@gem.name, nil))
+ @gem.add_load_paths
+ end
- def test_gem_with_version_adds_load_paths
- @gem_with_version.expects(:gem).with(Gem::Dependency.new(@gem_with_version.name, @gem_with_version.requirement.to_s))
- @gem_with_version.add_load_paths
- end
+ def test_gem_with_version_adds_load_paths
+ @gem_with_version.expects(:gem).with(Gem::Dependency.new(@gem_with_version.name, @gem_with_version.requirement.to_s))
+ @gem_with_version.add_load_paths
+ end
- def test_gem_loading
- @gem.expects(:gem).with(Gem::Dependency.new(@gem.name, nil))
- @gem.expects(:require).with(@gem.name)
- @gem.add_load_paths
- @gem.load
- end
+ def test_gem_loading
+ @gem.expects(:gem).with(Gem::Dependency.new(@gem.name, nil))
+ @gem.expects(:require).with(@gem.name)
+ @gem.add_load_paths
+ @gem.load
+ end
- def test_gem_with_lib_loading
- @gem_with_lib.expects(:gem).with(Gem::Dependency.new(@gem_with_lib.name, nil))
- @gem_with_lib.expects(:require).with(@gem_with_lib.lib)
- @gem_with_lib.add_load_paths
- @gem_with_lib.load
- end
+ def test_gem_with_lib_loading
+ @gem_with_lib.expects(:gem).with(Gem::Dependency.new(@gem_with_lib.name, nil))
+ @gem_with_lib.expects(:require).with(@gem_with_lib.lib)
+ @gem_with_lib.add_load_paths
+ @gem_with_lib.load
+ end
- def test_gem_without_lib_loading
- @gem_without_load.expects(:gem).with(Gem::Dependency.new(@gem_without_load.name, nil))
- @gem_without_load.expects(:require).with(@gem_without_load.lib).never
- @gem_without_load.add_load_paths
- @gem_without_load.load
- end
+ def test_gem_without_lib_loading
+ @gem_without_load.expects(:gem).with(Gem::Dependency.new(@gem_without_load.name, nil))
+ @gem_without_load.expects(:require).with(@gem_without_load.lib).never
+ @gem_without_load.add_load_paths
+ @gem_without_load.load
+ end
- def test_gem_dependencies_compare_for_uniq
- gem1 = Rails::GemDependency.new "gem1"
- gem1a = Rails::GemDependency.new "gem1"
- gem2 = Rails::GemDependency.new "gem2"
- gem2a = Rails::GemDependency.new "gem2"
- gem3 = Rails::GemDependency.new "gem2", :version => ">=0.1"
- gem3a = Rails::GemDependency.new "gem2", :version => ">=0.1"
- gem4 = Rails::GemDependency.new "gem3"
- gems = [gem1, gem2, gem1a, gem3, gem2a, gem4, gem3a, gem2, gem4]
- assert_equal 4, gems.uniq.size
- end
+ def test_gem_dependencies_compare_for_uniq
+ gem1 = Rails::GemDependency.new "gem1"
+ gem1a = Rails::GemDependency.new "gem1"
+ gem2 = Rails::GemDependency.new "gem2"
+ gem2a = Rails::GemDependency.new "gem2"
+ gem3 = Rails::GemDependency.new "gem2", :version => ">=0.1"
+ gem3a = Rails::GemDependency.new "gem2", :version => ">=0.1"
+ gem4 = Rails::GemDependency.new "gem3"
+ gems = [gem1, gem2, gem1a, gem3, gem2a, gem4, gem3a, gem2, gem4]
+ assert_equal 4, gems.uniq.size
+ end
- def test_gem_load_frozen
- dummy_gem = Rails::GemDependency.new "dummy-gem-a"
- dummy_gem.add_load_paths
- dummy_gem.load
- assert_not_nil DUMMY_GEM_A_VERSION
- end
+ def test_gem_load_frozen
+ dummy_gem = Rails::GemDependency.new "dummy-gem-a"
+ dummy_gem.add_load_paths
+ dummy_gem.load
+ assert_not_nil DUMMY_GEM_A_VERSION
+ end
- def test_gem_load_frozen_specific_version
- dummy_gem = Rails::GemDependency.new "dummy-gem-b", :version => '0.4.0'
- dummy_gem.add_load_paths
- dummy_gem.load
- assert_not_nil DUMMY_GEM_B_VERSION
- assert_equal '0.4.0', DUMMY_GEM_B_VERSION
- end
+ def test_gem_load_frozen_specific_version
+ dummy_gem = Rails::GemDependency.new "dummy-gem-b", :version => '0.4.0'
+ dummy_gem.add_load_paths
+ dummy_gem.load
+ assert_not_nil DUMMY_GEM_B_VERSION
+ assert_equal '0.4.0', DUMMY_GEM_B_VERSION
+ end
- def test_gem_load_frozen_minimum_version
- dummy_gem = Rails::GemDependency.new "dummy-gem-c", :version => '>=0.5.0'
- dummy_gem.add_load_paths
- dummy_gem.load
- assert_not_nil DUMMY_GEM_C_VERSION
- assert_equal '0.6.0', DUMMY_GEM_C_VERSION
- end
+ def test_gem_load_frozen_minimum_version
+ dummy_gem = Rails::GemDependency.new "dummy-gem-c", :version => '>=0.5.0'
+ dummy_gem.add_load_paths
+ dummy_gem.load
+ assert_not_nil DUMMY_GEM_C_VERSION
+ assert_equal '0.6.0', DUMMY_GEM_C_VERSION
+ end
- def test_gem_load_missing_specification
- dummy_gem = Rails::GemDependency.new "dummy-gem-d"
- dummy_gem.add_load_paths
- dummy_gem.load
- assert_not_nil DUMMY_GEM_D_VERSION
- assert_equal '1.0.0', DUMMY_GEM_D_VERSION
- assert_equal ['lib', 'lib/dummy-gem-d.rb'], dummy_gem.specification.files
- end
+ def test_gem_load_missing_specification
+ dummy_gem = Rails::GemDependency.new "dummy-gem-d"
+ dummy_gem.add_load_paths
+ dummy_gem.load
+ assert_not_nil DUMMY_GEM_D_VERSION
+ assert_equal '1.0.0', DUMMY_GEM_D_VERSION
+ assert_equal ['lib', 'lib/dummy-gem-d.rb'], dummy_gem.specification.files
+ end
- def test_gem_load_bad_specification
- dummy_gem = Rails::GemDependency.new "dummy-gem-e", :version => "= 1.0.0"
- dummy_gem.add_load_paths
- dummy_gem.load
- assert_not_nil DUMMY_GEM_E_VERSION
- assert_equal '1.0.0', DUMMY_GEM_E_VERSION
- end
+ def test_gem_load_bad_specification
+ dummy_gem = Rails::GemDependency.new "dummy-gem-e", :version => "= 1.0.0"
+ dummy_gem.add_load_paths
+ dummy_gem.load
+ assert_not_nil DUMMY_GEM_E_VERSION
+ assert_equal '1.0.0', DUMMY_GEM_E_VERSION
+ end
- def test_gem_handle_missing_dependencies
- dummy_gem = Rails::GemDependency.new "dummy-gem-g"
- dummy_gem.add_load_paths
- dummy_gem.load
- assert dummy_gem.loaded?
- assert_equal 2, dummy_gem.dependencies.size
- assert_nothing_raised do
- dummy_gem.dependencies.each do |g|
- g.dependencies
- end
+ def test_gem_handle_missing_dependencies
+ dummy_gem = Rails::GemDependency.new "dummy-gem-g"
+ dummy_gem.add_load_paths
+ dummy_gem.load
+ assert dummy_gem.loaded?
+ assert_equal 2, dummy_gem.dependencies.size
+ assert_nothing_raised do
+ dummy_gem.dependencies.each do |g|
+ g.dependencies
end
end
-
end
+
end
diff --git a/railties/test/generators/rails_scaffold_generator_test.rb b/railties/test/generators/rails_scaffold_generator_test.rb
index 926607f55c..70829a77fd 100644
--- a/railties/test/generators/rails_scaffold_generator_test.rb
+++ b/railties/test/generators/rails_scaffold_generator_test.rb
@@ -19,7 +19,7 @@ class RailsScaffoldGeneratorTest < GeneratorTestCase
assert_generated_controller_for :products do |f|
assert_has_method f, :index do |name, m|
- assert_match /@products = Product\.find\(:all\)/, m, "#{name} should query products table"
+ assert_match /@products = Product\.all/, m, "#{name} should query products table"
end
assert_has_method f, :show, :edit, :update, :destroy do |name, m|
@@ -71,7 +71,7 @@ class RailsScaffoldGeneratorTest < GeneratorTestCase
assert_generated_controller_for :products do |f|
assert_has_method f, :index do |name, m|
- assert_match /@products = Product\.find\(:all\)/, m, "#{name} should query products table"
+ assert_match /@products = Product\.all/, m, "#{name} should query products table"
end
assert_has_method f, :show, :edit, :update, :destroy do |name, m|
@@ -107,17 +107,15 @@ class RailsScaffoldGeneratorTest < GeneratorTestCase
assert_added_route_for :products
end
- uses_mocha("scaffold_force_plural_names") do
- def test_scaffolded_plural_names
- Rails::Generator::Base.logger.expects(:warning)
- g = Rails::Generator::Base.instance('scaffold', %w(ProductLines))
- assert_equal "ProductLines", g.controller_name
- assert_equal "ProductLines", g.controller_class_name
- assert_equal "ProductLine", g.controller_singular_name
- assert_equal "product_lines", g.controller_plural_name
- assert_equal "product_lines", g.controller_file_name
- assert_equal "product_lines", g.controller_table_name
- end
+ def test_scaffolded_plural_names
+ Rails::Generator::Base.logger.expects(:warning)
+ g = Rails::Generator::Base.instance('scaffold', %w(ProductLines))
+ assert_equal "ProductLines", g.controller_name
+ assert_equal "ProductLines", g.controller_class_name
+ assert_equal "ProductLine", g.controller_singular_name
+ assert_equal "product_lines", g.controller_plural_name
+ assert_equal "product_lines", g.controller_file_name
+ assert_equal "product_lines", g.controller_table_name
end
def test_scaffold_plural_model_name_without_force_plural_generates_singular_model
diff --git a/railties/test/initializer_test.rb b/railties/test/initializer_test.rb
index dad9e55e61..39372dc5ab 100644
--- a/railties/test/initializer_test.rb
+++ b/railties/test/initializer_test.rb
@@ -47,268 +47,260 @@ class Initializer_eager_loading_Test < Test::Unit::TestCase
end
end
-uses_mocha 'Initializer after_initialize' do
- class Initializer_after_initialize_with_blocks_environment_Test < Test::Unit::TestCase
- def setup
- config = ConfigurationMock.new("")
- config.after_initialize do
- $test_after_initialize_block1 = "success"
- end
- config.after_initialize do
- $test_after_initialize_block2 = "congratulations"
- end
- assert_nil $test_after_initialize_block1
- assert_nil $test_after_initialize_block2
-
- Rails::Initializer.any_instance.expects(:gems_dependencies_loaded).returns(true)
- Rails::Initializer.run(:after_initialize, config)
+class Initializer_after_initialize_with_blocks_environment_Test < Test::Unit::TestCase
+ def setup
+ config = ConfigurationMock.new("")
+ config.after_initialize do
+ $test_after_initialize_block1 = "success"
end
-
- def teardown
- $test_after_initialize_block1 = nil
- $test_after_initialize_block2 = nil
+ config.after_initialize do
+ $test_after_initialize_block2 = "congratulations"
end
+ assert_nil $test_after_initialize_block1
+ assert_nil $test_after_initialize_block2
- def test_should_have_called_the_first_after_initialize_block
- assert_equal "success", $test_after_initialize_block1
- end
+ Rails::Initializer.any_instance.expects(:gems_dependencies_loaded).returns(true)
+ Rails::Initializer.run(:after_initialize, config)
+ end
- def test_should_have_called_the_second_after_initialize_block
- assert_equal "congratulations", $test_after_initialize_block2
- end
+ def teardown
+ $test_after_initialize_block1 = nil
+ $test_after_initialize_block2 = nil
end
- class Initializer_after_initialize_with_no_block_environment_Test < Test::Unit::TestCase
- def setup
- config = ConfigurationMock.new("")
- config.after_initialize do
- $test_after_initialize_block1 = "success"
- end
- config.after_initialize # don't pass a block, this is what we're testing!
- config.after_initialize do
- $test_after_initialize_block2 = "congratulations"
- end
- assert_nil $test_after_initialize_block1
-
- Rails::Initializer.any_instance.expects(:gems_dependencies_loaded).returns(true)
- Rails::Initializer.run(:after_initialize, config)
- end
+ def test_should_have_called_the_first_after_initialize_block
+ assert_equal "success", $test_after_initialize_block1
+ end
- def teardown
- $test_after_initialize_block1 = nil
- $test_after_initialize_block2 = nil
- end
+ def test_should_have_called_the_second_after_initialize_block
+ assert_equal "congratulations", $test_after_initialize_block2
+ end
+end
- def test_should_have_called_the_first_after_initialize_block
- assert_equal "success", $test_after_initialize_block1, "should still get set"
+class Initializer_after_initialize_with_no_block_environment_Test < Test::Unit::TestCase
+ def setup
+ config = ConfigurationMock.new("")
+ config.after_initialize do
+ $test_after_initialize_block1 = "success"
end
-
- def test_should_have_called_the_second_after_initialize_block
- assert_equal "congratulations", $test_after_initialize_block2
+ config.after_initialize # don't pass a block, this is what we're testing!
+ config.after_initialize do
+ $test_after_initialize_block2 = "congratulations"
end
+ assert_nil $test_after_initialize_block1
+
+ Rails::Initializer.any_instance.expects(:gems_dependencies_loaded).returns(true)
+ Rails::Initializer.run(:after_initialize, config)
end
-end
-uses_mocha 'framework paths' do
- class ConfigurationFrameworkPathsTests < Test::Unit::TestCase
- def setup
- @config = Rails::Configuration.new
- @config.frameworks.clear
+ def teardown
+ $test_after_initialize_block1 = nil
+ $test_after_initialize_block2 = nil
+ end
- File.stubs(:directory?).returns(true)
- @config.stubs(:framework_root_path).returns('')
- end
+ def test_should_have_called_the_first_after_initialize_block
+ assert_equal "success", $test_after_initialize_block1, "should still get set"
+ end
- def test_minimal
- expected = %w(
- /railties
- /railties/lib
- /activesupport/lib
- )
- assert_equal expected, @config.framework_paths
- end
+ def test_should_have_called_the_second_after_initialize_block
+ assert_equal "congratulations", $test_after_initialize_block2
+ end
+end
- def test_actioncontroller_or_actionview_add_actionpack
- @config.frameworks << :action_controller
- assert_framework_path '/actionpack/lib'
+class ConfigurationFrameworkPathsTests < Test::Unit::TestCase
+ def setup
+ @config = Rails::Configuration.new
+ @config.frameworks.clear
- @config.frameworks = [:action_view]
- assert_framework_path '/actionpack/lib'
- end
+ File.stubs(:directory?).returns(true)
+ @config.stubs(:framework_root_path).returns('')
+ end
- def test_paths_for_ar_ares_and_mailer
- [:active_record, :action_mailer, :active_resource, :action_web_service].each do |framework|
- @config.frameworks = [framework]
- assert_framework_path "/#{framework.to_s.gsub('_', '')}/lib"
- end
- end
+ def test_minimal
+ expected = %w(
+ /railties
+ /railties/lib
+ /activesupport/lib
+ )
+ assert_equal expected, @config.framework_paths
+ end
+
+ def test_actioncontroller_or_actionview_add_actionpack
+ @config.frameworks << :action_controller
+ assert_framework_path '/actionpack/lib'
- def test_unknown_framework_raises_error
- @config.frameworks << :action_foo
- initializer = Rails::Initializer.new @config
- initializer.expects(:require).raises(LoadError)
+ @config.frameworks = [:action_view]
+ assert_framework_path '/actionpack/lib'
+ end
- assert_raise RuntimeError do
- initializer.send :require_frameworks
- end
+ def test_paths_for_ar_ares_and_mailer
+ [:active_record, :action_mailer, :active_resource, :action_web_service].each do |framework|
+ @config.frameworks = [framework]
+ assert_framework_path "/#{framework.to_s.gsub('_', '')}/lib"
end
+ end
- def test_action_mailer_load_paths_set_only_if_action_mailer_in_use
- @config.frameworks = [:action_controller]
- initializer = Rails::Initializer.new @config
- initializer.send :require_frameworks
+ def test_unknown_framework_raises_error
+ @config.frameworks << :action_foo
+ initializer = Rails::Initializer.new @config
+ initializer.expects(:require).raises(LoadError)
- assert_nothing_raised NameError do
- initializer.send :load_view_paths
- end
+ assert_raise RuntimeError do
+ initializer.send :require_frameworks
end
+ end
- def test_action_controller_load_paths_set_only_if_action_controller_in_use
- @config.frameworks = []
- initializer = Rails::Initializer.new @config
- initializer.send :require_frameworks
+ def test_action_mailer_load_paths_set_only_if_action_mailer_in_use
+ @config.frameworks = [:action_controller]
+ initializer = Rails::Initializer.new @config
+ initializer.send :require_frameworks
- assert_nothing_raised NameError do
- initializer.send :load_view_paths
- end
+ assert_nothing_raised NameError do
+ initializer.send :load_view_paths
end
-
- protected
- def assert_framework_path(path)
- assert @config.framework_paths.include?(path),
- "<#{path.inspect}> not found among <#{@config.framework_paths.inspect}>"
- end
end
-end
-uses_mocha "Initializer plugin loading tests" do
- require File.dirname(__FILE__) + '/plugin_test_helper'
+ def test_action_controller_load_paths_set_only_if_action_controller_in_use
+ @config.frameworks = []
+ initializer = Rails::Initializer.new @config
+ initializer.send :require_frameworks
- class InitializerPluginLoadingTests < Test::Unit::TestCase
- def setup
- @configuration = Rails::Configuration.new
- @configuration.plugin_paths << plugin_fixture_root_path
- @initializer = Rails::Initializer.new(@configuration)
- @valid_plugin_path = plugin_fixture_path('default/stubby')
- @empty_plugin_path = plugin_fixture_path('default/empty')
+ assert_nothing_raised NameError do
+ initializer.send :load_view_paths
end
+ end
- def test_no_plugins_are_loaded_if_the_configuration_has_an_empty_plugin_list
- only_load_the_following_plugins! []
- @initializer.load_plugins
- assert_equal [], @initializer.loaded_plugins
+ protected
+ def assert_framework_path(path)
+ assert @config.framework_paths.include?(path),
+ "<#{path.inspect}> not found among <#{@config.framework_paths.inspect}>"
end
+end
- def test_only_the_specified_plugins_are_located_in_the_order_listed
- plugin_names = [:plugin_with_no_lib_dir, :acts_as_chunky_bacon]
- only_load_the_following_plugins! plugin_names
- load_plugins!
- assert_plugins plugin_names, @initializer.loaded_plugins
- end
+require File.dirname(__FILE__) + '/plugin_test_helper'
- def test_all_plugins_are_loaded_when_registered_plugin_list_is_untouched
- failure_tip = "It's likely someone has added a new plugin fixture without updating this list"
- load_plugins!
- assert_plugins [:a, :acts_as_chunky_bacon, :engine, :gemlike, :plugin_with_no_lib_dir, :stubby], @initializer.loaded_plugins, failure_tip
- end
+class InitializerPluginLoadingTests < Test::Unit::TestCase
+ def setup
+ @configuration = Rails::Configuration.new
+ @configuration.plugin_paths << plugin_fixture_root_path
+ @initializer = Rails::Initializer.new(@configuration)
+ @valid_plugin_path = plugin_fixture_path('default/stubby')
+ @empty_plugin_path = plugin_fixture_path('default/empty')
+ end
- def test_all_plugins_loaded_when_all_is_used
- plugin_names = [:stubby, :acts_as_chunky_bacon, :all]
- only_load_the_following_plugins! plugin_names
- load_plugins!
- failure_tip = "It's likely someone has added a new plugin fixture without updating this list"
- assert_plugins [:stubby, :acts_as_chunky_bacon, :a, :engine, :gemlike, :plugin_with_no_lib_dir], @initializer.loaded_plugins, failure_tip
- end
+ def test_no_plugins_are_loaded_if_the_configuration_has_an_empty_plugin_list
+ only_load_the_following_plugins! []
+ @initializer.load_plugins
+ assert_equal [], @initializer.loaded_plugins
+ end
- def test_all_plugins_loaded_after_all
- plugin_names = [:stubby, :all, :acts_as_chunky_bacon]
- only_load_the_following_plugins! plugin_names
- load_plugins!
- failure_tip = "It's likely someone has added a new plugin fixture without updating this list"
- assert_plugins [:stubby, :a, :engine, :gemlike, :plugin_with_no_lib_dir, :acts_as_chunky_bacon], @initializer.loaded_plugins, failure_tip
- end
+ def test_only_the_specified_plugins_are_located_in_the_order_listed
+ plugin_names = [:plugin_with_no_lib_dir, :acts_as_chunky_bacon]
+ only_load_the_following_plugins! plugin_names
+ load_plugins!
+ assert_plugins plugin_names, @initializer.loaded_plugins
+ end
- def test_plugin_names_may_be_strings
- plugin_names = ['stubby', 'acts_as_chunky_bacon', :a, :plugin_with_no_lib_dir]
- only_load_the_following_plugins! plugin_names
- load_plugins!
- failure_tip = "It's likely someone has added a new plugin fixture without updating this list"
- assert_plugins plugin_names, @initializer.loaded_plugins, failure_tip
- end
+ def test_all_plugins_are_loaded_when_registered_plugin_list_is_untouched
+ failure_tip = "It's likely someone has added a new plugin fixture without updating this list"
+ load_plugins!
+ assert_plugins [:a, :acts_as_chunky_bacon, :engine, :gemlike, :plugin_with_no_lib_dir, :stubby], @initializer.loaded_plugins, failure_tip
+ end
- def test_registering_a_plugin_name_that_does_not_exist_raises_a_load_error
- only_load_the_following_plugins! [:stubby, :acts_as_a_non_existant_plugin]
- assert_raises(LoadError) do
- load_plugins!
- end
- end
+ def test_all_plugins_loaded_when_all_is_used
+ plugin_names = [:stubby, :acts_as_chunky_bacon, :all]
+ only_load_the_following_plugins! plugin_names
+ load_plugins!
+ failure_tip = "It's likely someone has added a new plugin fixture without updating this list"
+ assert_plugins [:stubby, :acts_as_chunky_bacon, :a, :engine, :gemlike, :plugin_with_no_lib_dir], @initializer.loaded_plugins, failure_tip
+ end
- def test_should_ensure_all_loaded_plugins_load_paths_are_added_to_the_load_path
- only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon]
+ def test_all_plugins_loaded_after_all
+ plugin_names = [:stubby, :all, :acts_as_chunky_bacon]
+ only_load_the_following_plugins! plugin_names
+ load_plugins!
+ failure_tip = "It's likely someone has added a new plugin fixture without updating this list"
+ assert_plugins [:stubby, :a, :engine, :gemlike, :plugin_with_no_lib_dir, :acts_as_chunky_bacon], @initializer.loaded_plugins, failure_tip
+ end
- @initializer.add_plugin_load_paths
+ def test_plugin_names_may_be_strings
+ plugin_names = ['stubby', 'acts_as_chunky_bacon', :a, :plugin_with_no_lib_dir]
+ only_load_the_following_plugins! plugin_names
+ load_plugins!
+ failure_tip = "It's likely someone has added a new plugin fixture without updating this list"
+ assert_plugins plugin_names, @initializer.loaded_plugins, failure_tip
+ end
- assert $LOAD_PATH.include?(File.join(plugin_fixture_path('default/stubby'), 'lib'))
- assert $LOAD_PATH.include?(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib'))
+ def test_registering_a_plugin_name_that_does_not_exist_raises_a_load_error
+ only_load_the_following_plugins! [:stubby, :acts_as_a_non_existant_plugin]
+ assert_raises(LoadError) do
+ load_plugins!
end
+ end
+ def test_should_ensure_all_loaded_plugins_load_paths_are_added_to_the_load_path
+ only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon]
- private
+ @initializer.add_plugin_load_paths
- def load_plugins!
- @initializer.add_plugin_load_paths
- @initializer.load_plugins
- end
+ assert $LOAD_PATH.include?(File.join(plugin_fixture_path('default/stubby'), 'lib'))
+ assert $LOAD_PATH.include?(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib'))
end
-end
-uses_mocha 'i18n settings' do
- class InitializerSetupI18nTests < Test::Unit::TestCase
- def test_no_config_locales_dir_present_should_return_empty_load_path
- File.stubs(:exist?).returns(false)
- assert_equal [], Rails::Configuration.new.i18n.load_path
- end
- def test_config_locales_dir_present_should_be_added_to_load_path
- File.stubs(:exist?).returns(true)
- Dir.stubs(:[]).returns([ "my/test/locale.yml" ])
- assert_equal [ "my/test/locale.yml" ], Rails::Configuration.new.i18n.load_path
+ private
+
+ def load_plugins!
+ @initializer.add_plugin_load_paths
+ @initializer.load_plugins
end
-
- def test_config_defaults_should_be_added_with_config_settings
- File.stubs(:exist?).returns(true)
- Dir.stubs(:[]).returns([ "my/test/locale.yml" ])
+end
+
+class InitializerSetupI18nTests < Test::Unit::TestCase
+ def test_no_config_locales_dir_present_should_return_empty_load_path
+ File.stubs(:exist?).returns(false)
+ assert_equal [], Rails::Configuration.new.i18n.load_path
+ end
- config = Rails::Configuration.new
- config.i18n.load_path << "my/other/locale.yml"
+ def test_config_locales_dir_present_should_be_added_to_load_path
+ File.stubs(:exist?).returns(true)
+ Dir.stubs(:[]).returns([ "my/test/locale.yml" ])
+ assert_equal [ "my/test/locale.yml" ], Rails::Configuration.new.i18n.load_path
+ end
+
+ def test_config_defaults_should_be_added_with_config_settings
+ File.stubs(:exist?).returns(true)
+ Dir.stubs(:[]).returns([ "my/test/locale.yml" ])
- assert_equal [ "my/test/locale.yml", "my/other/locale.yml" ], config.i18n.load_path
- end
-
- def test_config_defaults_and_settings_should_be_added_to_i18n_defaults
- File.stubs(:exist?).returns(true)
- Dir.stubs(:[]).returns([ "my/test/locale.yml" ])
-
- config = Rails::Configuration.new
- config.i18n.load_path << "my/other/locale.yml"
-
- # To bring in AV's i18n load path.
- require 'action_view'
-
- Rails::Initializer.run(:initialize_i18n, config)
- assert_equal [
- File.expand_path("./test/../../activesupport/lib/active_support/locale/en.yml"),
- File.expand_path("./test/../../actionpack/lib/action_view/locale/en.yml"),
- "my/test/locale.yml",
- "my/other/locale.yml" ], I18n.load_path.collect { |path| path =~ /^\./ ? File.expand_path(path) : path }
- end
-
- def test_setting_another_default_locale
- config = Rails::Configuration.new
- config.i18n.default_locale = :de
- Rails::Initializer.run(:initialize_i18n, config)
- assert_equal :de, I18n.default_locale
- end
+ config = Rails::Configuration.new
+ config.i18n.load_path << "my/other/locale.yml"
+
+ assert_equal [ "my/test/locale.yml", "my/other/locale.yml" ], config.i18n.load_path
+ end
+
+ def test_config_defaults_and_settings_should_be_added_to_i18n_defaults
+ File.stubs(:exist?).returns(true)
+ Dir.stubs(:[]).returns([ "my/test/locale.yml" ])
+
+ config = Rails::Configuration.new
+ config.i18n.load_path << "my/other/locale.yml"
+
+ # To bring in AV's i18n load path.
+ require 'action_view'
+
+ Rails::Initializer.run(:initialize_i18n, config)
+ assert_equal [
+ File.expand_path("./test/../../activesupport/lib/active_support/locale/en.yml"),
+ File.expand_path("./test/../../actionpack/lib/action_view/locale/en.yml"),
+ "my/test/locale.yml",
+ "my/other/locale.yml" ], I18n.load_path.collect { |path| path =~ /^\./ ? File.expand_path(path) : path }
+ end
+
+ def test_setting_another_default_locale
+ config = Rails::Configuration.new
+ config.i18n.default_locale = :de
+ Rails::Initializer.run(:initialize_i18n, config)
+ assert_equal :de, I18n.default_locale
end
end
@@ -320,4 +312,4 @@ class RailsRootTest < Test::Unit::TestCase
def test_rails_dot_root_should_be_a_pathname
assert_equal File.join(RAILS_ROOT, 'app', 'controllers'), Rails.root.join('app', 'controllers').to_s
end
-end \ No newline at end of file
+end
diff --git a/railties/test/plugin_locator_test.rb b/railties/test/plugin_locator_test.rb
index 5a8c651e5a..c8404e126e 100644
--- a/railties/test/plugin_locator_test.rb
+++ b/railties/test/plugin_locator_test.rb
@@ -1,69 +1,62 @@
require 'plugin_test_helper'
-uses_mocha "Plugin Locator Tests" do
-
- class PluginLocatorTest < Test::Unit::TestCase
-
- def test_should_require_subclasses_to_implement_the_plugins_method
- assert_raises(RuntimeError) do
- Rails::Plugin::Locator.new(nil).plugins
- end
+class PluginLocatorTest < Test::Unit::TestCase
+ def test_should_require_subclasses_to_implement_the_plugins_method
+ assert_raises(RuntimeError) do
+ Rails::Plugin::Locator.new(nil).plugins
end
+ end
+
+ def test_should_iterator_over_plugins_returned_by_plugins_when_calling_each
+ locator = Rails::Plugin::Locator.new(nil)
+ locator.stubs(:plugins).returns([:a, :b, :c])
+ plugin_consumer = mock
+ plugin_consumer.expects(:consume).with(:a)
+ plugin_consumer.expects(:consume).with(:b)
+ plugin_consumer.expects(:consume).with(:c)
- def test_should_iterator_over_plugins_returned_by_plugins_when_calling_each
- locator = Rails::Plugin::Locator.new(nil)
- locator.stubs(:plugins).returns([:a, :b, :c])
- plugin_consumer = mock
- plugin_consumer.expects(:consume).with(:a)
- plugin_consumer.expects(:consume).with(:b)
- plugin_consumer.expects(:consume).with(:c)
-
- locator.each do |plugin|
- plugin_consumer.consume(plugin)
- end
+ locator.each do |plugin|
+ plugin_consumer.consume(plugin)
end
-
end
+end
+class PluginFileSystemLocatorTest < Test::Unit::TestCase
+ def setup
+ @configuration = Rails::Configuration.new
+ # We need to add our testing plugin directory to the plugin paths so
+ # the locator knows where to look for our plugins
+ @configuration.plugin_paths << plugin_fixture_root_path
+ @initializer = Rails::Initializer.new(@configuration)
+ @locator = Rails::Plugin::FileSystemLocator.new(@initializer)
+ @valid_plugin_path = plugin_fixture_path('default/stubby')
+ @empty_plugin_path = plugin_fixture_path('default/empty')
+ end
- class PluginFileSystemLocatorTest < Test::Unit::TestCase
- def setup
- @configuration = Rails::Configuration.new
- # We need to add our testing plugin directory to the plugin paths so
- # the locator knows where to look for our plugins
- @configuration.plugin_paths << plugin_fixture_root_path
- @initializer = Rails::Initializer.new(@configuration)
- @locator = Rails::Plugin::FileSystemLocator.new(@initializer)
- @valid_plugin_path = plugin_fixture_path('default/stubby')
- @empty_plugin_path = plugin_fixture_path('default/empty')
- end
+ def test_should_return_rails_plugin_instances_when_calling_create_plugin_with_a_valid_plugin_directory
+ assert_kind_of Rails::Plugin, @locator.send(:create_plugin, @valid_plugin_path)
+ end
- def test_should_return_rails_plugin_instances_when_calling_create_plugin_with_a_valid_plugin_directory
- assert_kind_of Rails::Plugin, @locator.send(:create_plugin, @valid_plugin_path)
- end
-
- def test_should_return_nil_when_calling_create_plugin_with_an_invalid_plugin_directory
- assert_nil @locator.send(:create_plugin, @empty_plugin_path)
- end
-
- def test_should_return_all_plugins_found_under_the_set_plugin_paths
- assert_equal ["a", "acts_as_chunky_bacon", "engine", "gemlike", "plugin_with_no_lib_dir", "stubby"].sort, @locator.plugins.map(&:name).sort
- end
-
- def test_should_find_plugins_only_under_the_plugin_paths_set_in_configuration
- @configuration.plugin_paths = [File.join(plugin_fixture_root_path, "default")]
- assert_equal ["acts_as_chunky_bacon", "gemlike", "plugin_with_no_lib_dir", "stubby"].sort, @locator.plugins.map(&:name).sort
-
- @configuration.plugin_paths = [File.join(plugin_fixture_root_path, "alternate")]
- assert_equal ["a"], @locator.plugins.map(&:name)
- end
+ def test_should_return_nil_when_calling_create_plugin_with_an_invalid_plugin_directory
+ assert_nil @locator.send(:create_plugin, @empty_plugin_path)
+ end
+
+ def test_should_return_all_plugins_found_under_the_set_plugin_paths
+ assert_equal ["a", "acts_as_chunky_bacon", "engine", "gemlike", "plugin_with_no_lib_dir", "stubby"].sort, @locator.plugins.map(&:name).sort
+ end
+
+ def test_should_find_plugins_only_under_the_plugin_paths_set_in_configuration
+ @configuration.plugin_paths = [File.join(plugin_fixture_root_path, "default")]
+ assert_equal ["acts_as_chunky_bacon", "gemlike", "plugin_with_no_lib_dir", "stubby"].sort, @locator.plugins.map(&:name).sort
- def test_should_not_raise_any_error_and_return_no_plugins_if_the_plugin_path_value_does_not_exist
- @configuration.plugin_paths = ["some_missing_directory"]
- assert_nothing_raised do
- assert @locator.plugins.empty?
- end
- end
+ @configuration.plugin_paths = [File.join(plugin_fixture_root_path, "alternate")]
+ assert_equal ["a"], @locator.plugins.map(&:name)
end
-end # uses_mocha
+ def test_should_not_raise_any_error_and_return_no_plugins_if_the_plugin_path_value_does_not_exist
+ @configuration.plugin_paths = ["some_missing_directory"]
+ assert_nothing_raised do
+ assert @locator.plugins.empty?
+ end
+ end
+end
diff --git a/railties/test/plugin_test.rb b/railties/test/plugin_test.rb
index 50124240a5..5500711df8 100644
--- a/railties/test/plugin_test.rb
+++ b/railties/test/plugin_test.rb
@@ -1,167 +1,162 @@
require 'plugin_test_helper'
-uses_mocha "Plugin Tests" do
+class PluginTest < Test::Unit::TestCase
+ def setup
+ @initializer = Rails::Initializer.new(Rails::Configuration.new)
+ @valid_plugin_path = plugin_fixture_path('default/stubby')
+ @empty_plugin_path = plugin_fixture_path('default/empty')
+ @gemlike_plugin_path = plugin_fixture_path('default/gemlike')
+ end
- class PluginTest < Test::Unit::TestCase
+ def test_should_determine_plugin_name_from_the_directory_of_the_plugin
+ assert_equal 'stubby', plugin_for(@valid_plugin_path).name
+ assert_equal 'empty', plugin_for(@empty_plugin_path).name
+ end
- def setup
- @initializer = Rails::Initializer.new(Rails::Configuration.new)
- @valid_plugin_path = plugin_fixture_path('default/stubby')
- @empty_plugin_path = plugin_fixture_path('default/empty')
- @gemlike_plugin_path = plugin_fixture_path('default/gemlike')
- end
+ def test_should_not_be_loaded_when_created
+ assert !plugin_for(@valid_plugin_path).loaded?
+ end
- def test_should_determine_plugin_name_from_the_directory_of_the_plugin
- assert_equal 'stubby', plugin_for(@valid_plugin_path).name
- assert_equal 'empty', plugin_for(@empty_plugin_path).name
+ def test_should_be_marked_as_loaded_when_load_is_called
+ plugin = plugin_for(@valid_plugin_path)
+ assert !plugin.loaded?
+ plugin.stubs(:evaluate_init_rb)
+ assert_nothing_raised do
+ plugin.send(:load, anything)
end
+ assert plugin.loaded?
+ end
- def test_should_not_be_loaded_when_created
- assert !plugin_for(@valid_plugin_path).loaded?
- end
+ def test_should_determine_validity_of_given_path
+ # This is a plugin path, with a lib dir
+ assert plugin_for(@valid_plugin_path).valid?
+ # This just has an init.rb and no lib dir
+ assert plugin_for(plugin_fixture_path('default/plugin_with_no_lib_dir')).valid?
+ # This would be a plugin path, but the directory is empty
+ assert !plugin_for(plugin_fixture_path('default/empty')).valid?
+ # This is a non sense path
+ assert !plugin_for(plugin_fixture_path('default/this_directory_does_not_exist')).valid?
+ end
- def test_should_be_marked_as_loaded_when_load_is_called
- plugin = plugin_for(@valid_plugin_path)
- assert !plugin.loaded?
- plugin.stubs(:evaluate_init_rb)
- assert_nothing_raised do
- plugin.send(:load, anything)
- end
- assert plugin.loaded?
- end
-
- def test_should_determine_validity_of_given_path
- # This is a plugin path, with a lib dir
- assert plugin_for(@valid_plugin_path).valid?
- # This just has an init.rb and no lib dir
- assert plugin_for(plugin_fixture_path('default/plugin_with_no_lib_dir')).valid?
- # This would be a plugin path, but the directory is empty
- assert !plugin_for(plugin_fixture_path('default/empty')).valid?
- # This is a non sense path
- assert !plugin_for(plugin_fixture_path('default/this_directory_does_not_exist')).valid?
+ def test_should_return_empty_array_for_load_paths_when_plugin_has_no_lib_directory
+ assert_equal [], plugin_for(plugin_fixture_path('default/plugin_with_no_lib_dir')).load_paths
+ end
+
+ def test_should_return_array_with_lib_path_for_load_paths_when_plugin_has_a_lib_directory
+ expected_lib_dir = File.join(plugin_fixture_path('default/stubby'), 'lib')
+ assert_equal [expected_lib_dir], plugin_for(plugin_fixture_path('default/stubby')).load_paths
+ end
+
+ def test_should_raise_a_load_error_when_trying_to_determine_the_load_paths_from_an_invalid_plugin
+ assert_nothing_raised do
+ plugin_for(@valid_plugin_path).load_paths
end
- def test_should_return_empty_array_for_load_paths_when_plugin_has_no_lib_directory
- assert_equal [], plugin_for(plugin_fixture_path('default/plugin_with_no_lib_dir')).load_paths
+ assert_raises(LoadError) do
+ plugin_for(@empty_plugin_path).load_paths
end
- def test_should_return_array_with_lib_path_for_load_paths_when_plugin_has_a_lib_directory
- expected_lib_dir = File.join(plugin_fixture_path('default/stubby'), 'lib')
- assert_equal [expected_lib_dir], plugin_for(plugin_fixture_path('default/stubby')).load_paths
+ assert_raises(LoadError) do
+ plugin_for('this_is_not_a_plugin_directory').load_paths
end
-
- def test_should_raise_a_load_error_when_trying_to_determine_the_load_paths_from_an_invalid_plugin
- assert_nothing_raised do
- plugin_for(@valid_plugin_path).load_paths
- end
-
- assert_raises(LoadError) do
- plugin_for(@empty_plugin_path).load_paths
- end
-
- assert_raises(LoadError) do
- plugin_for('this_is_not_a_plugin_directory').load_paths
- end
+ end
+
+ def test_should_raise_a_load_error_when_trying_to_load_an_invalid_plugin
+ # This path is fine so nothing is raised
+ assert_nothing_raised do
+ plugin = plugin_for(@valid_plugin_path)
+ plugin.stubs(:evaluate_init_rb)
+ plugin.send(:load, @initializer)
end
-
- def test_should_raise_a_load_error_when_trying_to_load_an_invalid_plugin
- # This path is fine so nothing is raised
- assert_nothing_raised do
- plugin = plugin_for(@valid_plugin_path)
- plugin.stubs(:evaluate_init_rb)
- plugin.send(:load, @initializer)
- end
- # This path is fine so nothing is raised
- assert_nothing_raised do
- plugin = plugin_for(@gemlike_plugin_path)
- plugin.stubs(:evaluate_init_rb)
- plugin.send(:load, @initializer)
- end
+ # This path is fine so nothing is raised
+ assert_nothing_raised do
+ plugin = plugin_for(@gemlike_plugin_path)
+ plugin.stubs(:evaluate_init_rb)
+ plugin.send(:load, @initializer)
+ end
- # This is an empty path so it raises
- assert_raises(LoadError) do
- plugin = plugin_for(@empty_plugin_path)
- plugin.stubs(:evaluate_init_rb)
- plugin.send(:load, @initializer)
- end
-
- assert_raises(LoadError) do
- plugin = plugin_for('this_is_not_a_plugin_directory')
- plugin.stubs(:evaluate_init_rb)
- plugin.send(:load, @initializer)
- end
+ # This is an empty path so it raises
+ assert_raises(LoadError) do
+ plugin = plugin_for(@empty_plugin_path)
+ plugin.stubs(:evaluate_init_rb)
+ plugin.send(:load, @initializer)
end
-
- def test_should_raise_a_load_error_when_trying_to_access_load_paths_of_an_invalid_plugin
- # This path is fine so nothing is raised
- assert_nothing_raised do
- plugin_for(@valid_plugin_path).load_paths
- end
-
- # This is an empty path so it raises
- assert_raises(LoadError) do
- plugin_for(@empty_plugin_path).load_paths
- end
-
- assert_raises(LoadError) do
- plugin_for('this_is_not_a_plugin_directory').load_paths
- end
- end
- def test_loading_a_plugin_gives_the_init_file_access_to_all_it_needs
- failure_tip = "Perhaps someone has written another test that loads this same plugin and therefore makes the StubbyMixin constant defined already."
- assert !defined?(StubbyMixin), failure_tip
- plugin = plugin_for(@valid_plugin_path)
- plugin.load_paths.each { |path| $LOAD_PATH.unshift(path) }
- # The init.rb of this plugin raises if it doesn't have access to all the things it needs
- assert_nothing_raised do
- plugin.load(@initializer)
- end
- assert defined?(StubbyMixin)
+ assert_raises(LoadError) do
+ plugin = plugin_for('this_is_not_a_plugin_directory')
+ plugin.stubs(:evaluate_init_rb)
+ plugin.send(:load, @initializer)
end
-
- def test_should_sort_naturally_by_name
- a = plugin_for("path/a")
- b = plugin_for("path/b")
- z = plugin_for("path/z")
- assert_equal [a, b, z], [b, z, a].sort
+ end
+
+ def test_should_raise_a_load_error_when_trying_to_access_load_paths_of_an_invalid_plugin
+ # This path is fine so nothing is raised
+ assert_nothing_raised do
+ plugin_for(@valid_plugin_path).load_paths
end
-
- def test_should_only_be_loaded_once
- plugin = plugin_for(@valid_plugin_path)
- assert !plugin.loaded?
- plugin.expects(:evaluate_init_rb)
- assert_nothing_raised do
- plugin.send(:load, @initializer)
- plugin.send(:load, @initializer)
- end
- assert plugin.loaded?
+
+ # This is an empty path so it raises
+ assert_raises(LoadError) do
+ plugin_for(@empty_plugin_path).load_paths
end
-
- def test_should_make_about_yml_available_as_about_method_on_plugin
- plugin = plugin_for(@valid_plugin_path)
- assert_equal "Plugin Author", plugin.about['author']
- assert_equal "1.0.0", plugin.about['version']
+
+ assert_raises(LoadError) do
+ plugin_for('this_is_not_a_plugin_directory').load_paths
end
-
- def test_should_return_empty_hash_for_about_if_about_yml_is_missing
- assert_equal({}, plugin_for(about_yml_plugin_path('plugin_without_about_yaml')).about)
+ end
+
+ def test_loading_a_plugin_gives_the_init_file_access_to_all_it_needs
+ failure_tip = "Perhaps someone has written another test that loads this same plugin and therefore makes the StubbyMixin constant defined already."
+ assert !defined?(StubbyMixin), failure_tip
+ plugin = plugin_for(@valid_plugin_path)
+ plugin.load_paths.each { |path| $LOAD_PATH.unshift(path) }
+ # The init.rb of this plugin raises if it doesn't have access to all the things it needs
+ assert_nothing_raised do
+ plugin.load(@initializer)
end
-
- def test_should_return_empty_hash_for_about_if_about_yml_is_malformed
- assert_equal({}, plugin_for(about_yml_plugin_path('bad_about_yml')).about)
+ assert defined?(StubbyMixin)
+ end
+
+ def test_should_sort_naturally_by_name
+ a = plugin_for("path/a")
+ b = plugin_for("path/b")
+ z = plugin_for("path/z")
+ assert_equal [a, b, z], [b, z, a].sort
+ end
+
+ def test_should_only_be_loaded_once
+ plugin = plugin_for(@valid_plugin_path)
+ assert !plugin.loaded?
+ plugin.expects(:evaluate_init_rb)
+ assert_nothing_raised do
+ plugin.send(:load, @initializer)
+ plugin.send(:load, @initializer)
end
+ assert plugin.loaded?
+ end
- private
+ def test_should_make_about_yml_available_as_about_method_on_plugin
+ plugin = plugin_for(@valid_plugin_path)
+ assert_equal "Plugin Author", plugin.about['author']
+ assert_equal "1.0.0", plugin.about['version']
+ end
- def about_yml_plugin_path(name)
- File.join(File.dirname(__FILE__), 'fixtures', 'about_yml_plugins', name)
- end
+ def test_should_return_empty_hash_for_about_if_about_yml_is_missing
+ assert_equal({}, plugin_for(about_yml_plugin_path('plugin_without_about_yaml')).about)
+ end
- def plugin_for(path)
- Rails::Plugin.new(path)
- end
+ def test_should_return_empty_hash_for_about_if_about_yml_is_malformed
+ assert_equal({}, plugin_for(about_yml_plugin_path('bad_about_yml')).about)
end
-end # uses_mocha
+ private
+
+ def about_yml_plugin_path(name)
+ File.join(File.dirname(__FILE__), 'fixtures', 'about_yml_plugins', name)
+ end
+
+ def plugin_for(path)
+ Rails::Plugin.new(path)
+ end
+end