aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Gemfile2
-rw-r--r--Rakefile28
-rw-r--r--actionmailer/lib/action_mailer/deprecated_api.rb2
-rw-r--r--actionmailer/test/base_test.rb12
-rw-r--r--actionpack/README.rdoc2
-rw-r--r--actionpack/lib/abstract_controller/base.rb12
-rw-r--r--actionpack/lib/action_dispatch/middleware/best_standards_support.rb13
-rw-r--r--actionpack/lib/action_dispatch/routing/deprecated_mapper.rb1
-rw-r--r--actionpack/lib/action_dispatch/routing/mapper.rb5
-rw-r--r--actionpack/lib/action_dispatch/routing/route_set.rb9
-rw-r--r--actionpack/lib/action_dispatch/testing/integration.rb1
-rw-r--r--actionpack/lib/action_view/helpers/form_tag_helper.rb2
-rw-r--r--actionpack/lib/action_view/helpers/sanitize_helper.rb2
-rw-r--r--actionpack/lib/action_view/helpers/text_helper.rb3
-rw-r--r--actionpack/test/abstract/abstract_controller_test.rb14
-rw-r--r--actionpack/test/controller/resources_test.rb1
-rw-r--r--actionpack/test/dispatch/routing_test.rb55
-rw-r--r--actionpack/test/template/form_helper_test.rb2
-rw-r--r--actionpack/test/template/form_tag_helper_test.rb2
-rw-r--r--activemodel/lib/active_model/attribute_methods.rb2
-rw-r--r--activemodel/lib/active_model/dirty.rb9
-rw-r--r--activemodel/lib/active_model/errors.rb10
-rw-r--r--activemodel/lib/active_model/serialization.rb2
-rw-r--r--activemodel/lib/active_model/serializers/json.rb18
-rw-r--r--activemodel/lib/active_model/validations.rb6
-rw-r--r--activemodel/lib/active_model/validations/length.rb11
-rw-r--r--activemodel/lib/active_model/validator.rb2
-rw-r--r--activemodel/test/cases/dirty_test.rb90
-rw-r--r--activemodel/test/cases/errors_test.rb65
-rw-r--r--activemodel/test/cases/validations/length_validation_test.rb14
-rw-r--r--activerecord/lib/active_record/aggregations.rb115
-rw-r--r--activerecord/lib/active_record/association_preload.rb16
-rw-r--r--activerecord/lib/active_record/associations.rb464
-rw-r--r--activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb7
-rw-r--r--activerecord/lib/active_record/associations/has_many_association.rb2
-rw-r--r--activerecord/lib/active_record/associations/has_many_through_association.rb7
-rw-r--r--activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb3
-rw-r--r--activerecord/lib/active_record/attribute_methods/write.rb4
-rw-r--r--activerecord/lib/active_record/autosave_association.rb34
-rw-r--r--activerecord/lib/active_record/base.rb247
-rw-r--r--activerecord/lib/active_record/callbacks.rb66
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb9
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/database_limits.rb2
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/quoting.rb2
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb12
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb2
-rw-r--r--activerecord/lib/active_record/connection_adapters/mysql_adapter.rb3
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb12
-rw-r--r--activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb4
-rw-r--r--activerecord/lib/active_record/dynamic_finder_match.rb4
-rw-r--r--activerecord/lib/active_record/errors.rb14
-rw-r--r--activerecord/lib/active_record/fixtures.rb50
-rw-r--r--activerecord/lib/active_record/named_scope.rb21
-rw-r--r--activerecord/lib/active_record/observer.rb4
-rw-r--r--activerecord/lib/active_record/persistence.rb6
-rw-r--r--activerecord/lib/active_record/railties/databases.rake2
-rw-r--r--activerecord/lib/active_record/relation.rb18
-rw-r--r--activerecord/lib/active_record/relation/batches.rb8
-rw-r--r--activerecord/lib/active_record/relation/calculations.rb80
-rw-r--r--activerecord/lib/active_record/relation/finder_methods.rb27
-rw-r--r--activerecord/lib/active_record/relation/query_methods.rb6
-rw-r--r--activerecord/lib/active_record/schema.rb2
-rw-r--r--activerecord/lib/active_record/schema_dumper.rb18
-rw-r--r--activerecord/lib/active_record/timestamp.rb3
-rw-r--r--activerecord/lib/active_record/validations/associated.rb7
-rw-r--r--activerecord/lib/active_record/validations/uniqueness.rb22
-rw-r--r--activerecord/test/cases/associations_test.rb22
-rw-r--r--activerecord/test/cases/attribute_methods_test.rb278
-rw-r--r--activerecord/test/cases/base_test.rb542
-rw-r--r--activerecord/test/cases/finder_test.rb8
-rw-r--r--activerecord/test/cases/method_scoping_test.rb7
-rw-r--r--activerecord/test/cases/named_scope_test.rb6
-rw-r--r--activerecord/test/cases/persistence_test.rb113
-rw-r--r--activerecord/test/cases/relations_test.rb18
-rw-r--r--activerecord/test/cases/serialization_test.rb134
-rw-r--r--activeresource/lib/active_resource/http_mock.rb6
-rw-r--r--activesupport/lib/active_support/callbacks.rb18
-rw-r--r--activesupport/lib/active_support/concern.rb35
-rw-r--r--activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb22
-rw-r--r--activesupport/lib/active_support/dependencies.rb22
-rw-r--r--activesupport/lib/active_support/ordered_hash.rb11
-rw-r--r--activesupport/lib/active_support/ordered_options.rb16
-rw-r--r--activesupport/test/core_ext/date_time_ext_test.rb31
-rw-r--r--railties/guides/source/action_controller_overview.textile35
-rw-r--r--railties/guides/source/active_record_querying.textile2
-rw-r--r--railties/guides/source/active_support_core_extensions.textile149
-rw-r--r--railties/guides/source/api_documentation_guidelines.textile2
-rw-r--r--railties/guides/source/form_helpers.textile2
-rw-r--r--railties/guides/source/getting_started.textile4
-rw-r--r--railties/guides/source/routing.textile6
-rw-r--r--railties/lib/rails/application.rb2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/databases/oracle.yml2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt4
-rw-r--r--railties/lib/rails/rack/log_tailer.rb7
-rw-r--r--railties/lib/rails/railtie.rb42
-rw-r--r--railties/test/application/routing_test.rb96
-rw-r--r--railties/test/generators/app_generator_test.rb2
97 files changed, 2061 insertions, 1283 deletions
diff --git a/Gemfile b/Gemfile
index b42723aaae..d594d20fac 100644
--- a/Gemfile
+++ b/Gemfile
@@ -11,7 +11,7 @@ gem "rails", :path => File.dirname(__FILE__)
gem "rake", ">= 0.8.7"
gem "mocha", ">= 0.9.8"
gem "rdoc", ">= 2.5.9"
-gem "horo"
+gem "horo", ">= 1.0.1"
# AS
gem "memcache-client", ">= 1.8.5"
diff --git a/Rakefile b/Rakefile
index 4e56da5ab3..ceb0e832b3 100644
--- a/Rakefile
+++ b/Rakefile
@@ -5,6 +5,31 @@ require 'rake'
require 'rdoc/task'
require 'rake/gempackagetask'
+# RDoc skips some files in the Rails tree due to its binary? predicate. This is a quick
+# hack for edge docs, until we decide which is the correct way to address this issue.
+# If not fixed in RDoc itself, via an option or something, we should probably move this
+# to railties and use it also in doc:rails.
+def hijack_rdoc!
+ require "rdoc/parser"
+ class << RDoc::Parser
+ def binary?(file)
+ s = File.read(file, 1024) or return false
+
+ if s[0, 2] == Marshal.dump('')[0, 2] then
+ true
+ elsif file =~ /erb\.rb$/ then
+ false
+ elsif s.index("\x00") then # ORIGINAL is s.scan(/<%|%>/).length >= 4 || s.index("\x00")
+ true
+ elsif 0.respond_to? :fdiv then
+ s.count("^ -~\t\r\n").fdiv(s.size) > 0.3
+ else # HACK 1.8.6
+ (s.count("^ -~\t\r\n").to_f / s.size) > 0.3
+ end
+ end
+ end
+end
+
PROJECTS = %w(activesupport activemodel actionpack actionmailer activeresource activerecord railties)
desc 'Run all tests by default'
@@ -63,6 +88,8 @@ end
desc "Generate documentation for the Rails framework"
RDoc::Task.new do |rdoc|
+ hijack_rdoc!
+
rdoc.rdoc_dir = 'doc/rdoc'
rdoc.title = "Ruby on Rails Documentation"
@@ -90,6 +117,7 @@ RDoc::Task.new do |rdoc|
rdoc.rdoc_files.include('actionpack/README.rdoc')
rdoc.rdoc_files.include('actionpack/CHANGELOG')
+ rdoc.rdoc_files.include('actionpack/lib/abstract_controller/**/*.rb')
rdoc.rdoc_files.include('actionpack/lib/action_controller/**/*.rb')
rdoc.rdoc_files.include('actionpack/lib/action_dispatch/**/*.rb')
rdoc.rdoc_files.include('actionpack/lib/action_view/**/*.rb')
diff --git a/actionmailer/lib/action_mailer/deprecated_api.rb b/actionmailer/lib/action_mailer/deprecated_api.rb
index 0070d8e016..7d57feba04 100644
--- a/actionmailer/lib/action_mailer/deprecated_api.rb
+++ b/actionmailer/lib/action_mailer/deprecated_api.rb
@@ -1,3 +1,5 @@
+require 'active_support/core_ext/object/try'
+
module ActionMailer
# This is the API which is deprecated and is going to be removed on Rails 3.1 release.
# Part of the old API will be deprecated after 3.1, for a smoother deprecation process.
diff --git a/actionmailer/test/base_test.rb b/actionmailer/test/base_test.rb
index e2b9df5d02..fec0ecf477 100644
--- a/actionmailer/test/base_test.rb
+++ b/actionmailer/test/base_test.rb
@@ -507,6 +507,18 @@ class BaseTest < ActiveSupport::TestCase
assert_equal("Thanks for signing up this afternoon", mail.subject)
end
+ test "action methods should be refreshed after defining new method" do
+ class FooMailer < ActionMailer::Base
+ # this triggers action_methods
+ self.respond_to?(:foo)
+
+ def notify
+ end
+ end
+
+ assert_equal ["notify"], FooMailer.action_methods
+ end
+
protected
# Execute the block setting the given values and restoring old values after
diff --git a/actionpack/README.rdoc b/actionpack/README.rdoc
index 0e7d164623..b297ceb0e2 100644
--- a/actionpack/README.rdoc
+++ b/actionpack/README.rdoc
@@ -1,6 +1,6 @@
= Action Pack -- From request to response
-Action Pack is a framework for handling and responding to web requests. It it
+Action Pack is a framework for handling and responding to web requests. It
provides mechanisms for *routing* (mapping request URLs to actions), defining
*controllers* that implement actions, and generating responses by rendering
*views*, which are templates of various formats. In short, Action Pack
diff --git a/actionpack/lib/abstract_controller/base.rb b/actionpack/lib/abstract_controller/base.rb
index 8a8337858b..db0a6736e0 100644
--- a/actionpack/lib/abstract_controller/base.rb
+++ b/actionpack/lib/abstract_controller/base.rb
@@ -72,6 +72,13 @@ module AbstractController
end
end
+ # action_methods are cached and there is sometimes need to refresh
+ # them. clear_action_methods! allows you to do that, so next time
+ # you run action_methods, they will be recalculated
+ def clear_action_methods!
+ @action_methods = nil
+ end
+
# Returns the full controller name, underscored, without the ending Controller.
# For instance, MyApp::MyPostsController would return "my_app/my_posts" for
# controller_name.
@@ -81,6 +88,11 @@ module AbstractController
def controller_path
@controller_path ||= name.sub(/Controller$/, '').underscore unless anonymous?
end
+
+ def method_added(name)
+ super
+ clear_action_methods!
+ end
end
abstract!
diff --git a/actionpack/lib/action_dispatch/middleware/best_standards_support.rb b/actionpack/lib/action_dispatch/middleware/best_standards_support.rb
index df8f7766bb..69adcc419f 100644
--- a/actionpack/lib/action_dispatch/middleware/best_standards_support.rb
+++ b/actionpack/lib/action_dispatch/middleware/best_standards_support.rb
@@ -1,12 +1,21 @@
module ActionDispatch
class BestStandardsSupport
- def initialize(app)
+ def initialize(app, type = true)
@app = app
+
+ @header = case type
+ when true
+ "IE=Edge,chrome=1"
+ when :builtin
+ "IE=Edge"
+ when false
+ nil
+ end
end
def call(env)
status, headers, body = @app.call(env)
- headers["X-UA-Compatible"] = "IE=Edge,chrome=1"
+ headers["X-UA-Compatible"] = @header
[status, headers, body]
end
end
diff --git a/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb b/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb
index 4904f0633d..e04062ce8b 100644
--- a/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb
+++ b/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb
@@ -1,5 +1,6 @@
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/object/with_options'
+require 'active_support/core_ext/object/try'
module ActionDispatch
module Routing
diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb
index 526c97ff8e..c118c72440 100644
--- a/actionpack/lib/action_dispatch/routing/mapper.rb
+++ b/actionpack/lib/action_dispatch/routing/mapper.rb
@@ -1,3 +1,4 @@
+require 'erb'
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/object/blank'
@@ -277,7 +278,6 @@ module ActionDispatch
path = args.shift || block
path_proc = path.is_a?(Proc) ? path : proc { |params| path % params }
status = options[:status] || 301
- body = 'Moved Permanently'
lambda do |env|
req = Request.new(env)
@@ -290,11 +290,14 @@ module ActionDispatch
uri.host ||= req.host
uri.port ||= req.port unless req.port == 80
+ body = %(<html><body>You are being <a href="#{ERB::Util.h(uri.to_s)}">redirected</a>.</body></html>)
+
headers = {
'Location' => uri.to_s,
'Content-Type' => 'text/html',
'Content-Length' => body.length.to_s
}
+
[ status, headers, [body] ]
end
end
diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb
index 77688fe397..d23b580d97 100644
--- a/actionpack/lib/action_dispatch/routing/route_set.rb
+++ b/actionpack/lib/action_dispatch/routing/route_set.rb
@@ -392,10 +392,9 @@ module ActionDispatch
end
def generate
- error = ActionController::RoutingError.new("No route matches #{options.inspect}")
path, params = @set.set.generate(:path_info, named_route, options, recall, opts)
- raise error unless path
+ raise_routing_error unless path
params.reject! {|k,v| !v }
@@ -404,7 +403,7 @@ module ActionDispatch
path << "?#{params.to_query}" if params.any?
"#{script_name}#{path}"
rescue Rack::Mount::RoutingError
- raise error
+ raise_routing_error
end
def opts
@@ -421,6 +420,10 @@ module ActionDispatch
{:parameterize => parameterize}
end
+ def raise_routing_error
+ raise ActionController::RoutingError.new("No route matches #{options.inspect}")
+ end
+
def different_controller?
return false unless current_controller
controller.to_param != current_controller.to_param
diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb
index 8e58adaf59..b52795c575 100644
--- a/actionpack/lib/action_dispatch/testing/integration.rb
+++ b/actionpack/lib/action_dispatch/testing/integration.rb
@@ -1,6 +1,7 @@
require 'stringio'
require 'uri'
require 'active_support/core_ext/kernel/singleton_class'
+require 'active_support/core_ext/object/try'
require 'rack/test'
require 'test/unit/assertions'
diff --git a/actionpack/lib/action_view/helpers/form_tag_helper.rb b/actionpack/lib/action_view/helpers/form_tag_helper.rb
index 9dac2d4538..1ea870426a 100644
--- a/actionpack/lib/action_view/helpers/form_tag_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_tag_helper.rb
@@ -538,7 +538,7 @@ module ActionView
def extra_tags_for_form(html_options)
snowman_tag = tag(:input, :type => "hidden",
- :name => "_snowman", :value => "&#9731;".html_safe)
+ :name => "_e", :value => "&#9731;".html_safe)
method = html_options.delete("method").to_s
diff --git a/actionpack/lib/action_view/helpers/sanitize_helper.rb b/actionpack/lib/action_view/helpers/sanitize_helper.rb
index 63f6154ec4..d82005fa24 100644
--- a/actionpack/lib/action_view/helpers/sanitize_helper.rb
+++ b/actionpack/lib/action_view/helpers/sanitize_helper.rb
@@ -1,3 +1,4 @@
+require 'active_support/core_ext/object/try'
require 'action_controller/vendor/html-scanner'
require 'action_view/helpers/tag_helper'
@@ -7,6 +8,7 @@ module ActionView
# The SanitizeHelper module provides a set of methods for scrubbing text of undesired HTML elements.
# These helper methods extend Action View making them callable within your template files.
module SanitizeHelper
+ extend ActiveSupport::Concern
# This +sanitize+ helper will html encode all tags and strip all attributes that
# aren't specifically allowed.
#
diff --git a/actionpack/lib/action_view/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb
index 52a016c9c1..c1de5c8cb3 100644
--- a/actionpack/lib/action_view/helpers/text_helper.rb
+++ b/actionpack/lib/action_view/helpers/text_helper.rb
@@ -10,6 +10,9 @@ module ActionView
# your views. These helper methods extend Action View making them callable
# within your template files.
module TextHelper
+ extend ActiveSupport::Concern
+
+ include SanitizeHelper
# The preferred method of outputting text in your views is to use the
# <%= "text" %> eRuby syntax. The regular _puts_ and _print_ methods
# do not operate as expected in an eRuby code block. If you absolutely must
diff --git a/actionpack/test/abstract/abstract_controller_test.rb b/actionpack/test/abstract/abstract_controller_test.rb
index 3b5013a47a..19855490b4 100644
--- a/actionpack/test/abstract/abstract_controller_test.rb
+++ b/actionpack/test/abstract/abstract_controller_test.rb
@@ -250,5 +250,19 @@ module AbstractController
end
end
+ class Me6 < AbstractController::Base
+ self.action_methods
+
+ def index
+ end
+ end
+
+ class TestActionMethodsReloading < ActiveSupport::TestCase
+
+ test "action_methods should be reloaded after defining a new method" do
+ assert_equal ["index"], Me6.action_methods
+ end
+ end
+
end
end
diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb
index a9d1c55c05..6c8f470fba 100644
--- a/actionpack/test/controller/resources_test.rb
+++ b/actionpack/test/controller/resources_test.rb
@@ -1,3 +1,4 @@
+require 'active_support/core_ext/object/try'
require 'abstract_unit'
class ResourcesController < ActionController::Base
diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb
index 4808663aa9..3f090b7254 100644
--- a/actionpack/test/dispatch/routing_test.rb
+++ b/actionpack/test/dispatch/routing_test.rb
@@ -1,3 +1,4 @@
+require 'erb'
require 'abstract_unit'
require 'controller/fake_controllers'
@@ -56,7 +57,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
match 'account/proc/:name', :to => redirect {|params| "/#{params[:name].pluralize}" }
match 'account/proc_req' => redirect {|params, req| "/#{req.method}" }
- match 'account/google' => redirect('http://www.google.com/')
+ match 'account/google' => redirect('http://www.google.com/', :status => 302)
match 'openid/login', :via => [:get, :post], :to => "openid#login"
@@ -501,9 +502,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
def test_login_redirect
with_test_routes do
get '/account/login'
- assert_equal 301, @response.status
- assert_equal 'http://www.example.com/login', @response.headers['Location']
- assert_equal 'Moved Permanently', @response.body
+ verify_redirect 'http://www.example.com/login'
end
end
@@ -511,18 +510,14 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
with_test_routes do
assert_equal '/account/logout', logout_redirect_path
get '/account/logout'
- assert_equal 301, @response.status
- assert_equal 'http://www.example.com/logout', @response.headers['Location']
- assert_equal 'Moved Permanently', @response.body
+ verify_redirect 'http://www.example.com/logout'
end
end
def test_namespace_redirect
with_test_routes do
get '/private'
- assert_equal 301, @response.status
- assert_equal 'http://www.example.com/private/index', @response.headers['Location']
- assert_equal 'Moved Permanently', @response.body
+ verify_redirect 'http://www.example.com/private/index'
end
end
@@ -586,27 +581,21 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
def test_redirect_modulo
with_test_routes do
get '/account/modulo/name'
- assert_equal 301, @response.status
- assert_equal 'http://www.example.com/names', @response.headers['Location']
- assert_equal 'Moved Permanently', @response.body
+ verify_redirect 'http://www.example.com/names'
end
end
def test_redirect_proc
with_test_routes do
get '/account/proc/person'
- assert_equal 301, @response.status
- assert_equal 'http://www.example.com/people', @response.headers['Location']
- assert_equal 'Moved Permanently', @response.body
+ verify_redirect 'http://www.example.com/people'
end
end
def test_redirect_proc_with_request
with_test_routes do
get '/account/proc_req'
- assert_equal 301, @response.status
- assert_equal 'http://www.example.com/GET', @response.headers['Location']
- assert_equal 'Moved Permanently', @response.body
+ verify_redirect 'http://www.example.com/GET'
end
end
@@ -1203,12 +1192,10 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
end
- def test_redirect_with_complete_url
+ def test_redirect_with_complete_url_and_status
with_test_routes do
get '/account/google'
- assert_equal 301, @response.status
- assert_equal 'http://www.google.com/', @response.headers['Location']
- assert_equal 'Moved Permanently', @response.body
+ verify_redirect 'http://www.google.com/', 302
end
end
@@ -1216,9 +1203,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
previous_host, self.host = self.host, 'www.example.com:3000'
with_test_routes do
get '/account/login'
- assert_equal 301, @response.status
- assert_equal 'http://www.example.com:3000/login', @response.headers['Location']
- assert_equal 'Moved Permanently', @response.body
+ verify_redirect 'http://www.example.com:3000/login'
end
ensure
self.host = previous_host
@@ -1899,8 +1884,18 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
end
- private
- def with_test_routes
- yield
- end
+private
+ def with_test_routes
+ yield
+ end
+
+ def verify_redirect(url, status=301)
+ assert_equal status, @response.status
+ assert_equal url, @response.headers['Location']
+ assert_equal expected_redirect_body(url), @response.body
+ end
+
+ def expected_redirect_body(url)
+ %(<html><body>You are being <a href="#{ERB::Util.h(url)}">redirected</a>.</body></html>)
+ end
end
diff --git a/actionpack/test/template/form_helper_test.rb b/actionpack/test/template/form_helper_test.rb
index 9086a23345..be66710ae5 100644
--- a/actionpack/test/template/form_helper_test.rb
+++ b/actionpack/test/template/form_helper_test.rb
@@ -1513,7 +1513,7 @@ class FormHelperTest < ActionView::TestCase
def snowman(method = nil)
txt = %{<div style="margin:0;padding:0;display:inline">}
- txt << %{<input name="_snowman" type="hidden" value="&#9731;" />}
+ txt << %{<input name="_e" type="hidden" value="&#9731;" />}
txt << %{<input name="_method" type="hidden" value="#{method}" />} if method
txt << %{</div>}
end
diff --git a/actionpack/test/template/form_tag_helper_test.rb b/actionpack/test/template/form_tag_helper_test.rb
index 8a0f352bc0..6c85952d40 100644
--- a/actionpack/test/template/form_tag_helper_test.rb
+++ b/actionpack/test/template/form_tag_helper_test.rb
@@ -12,7 +12,7 @@ class FormTagHelperTest < ActionView::TestCase
method = options[:method]
txt = %{<div style="margin:0;padding:0;display:inline">}
- txt << %{<input name="_snowman" type="hidden" value="&#9731;" />}
+ txt << %{<input name="_e" type="hidden" value="&#9731;" />}
txt << %{<input name="_method" type="hidden" value="#{method}" />} if method
txt << %{</div>}
end
diff --git a/activemodel/lib/active_model/attribute_methods.rb b/activemodel/lib/active_model/attribute_methods.rb
index 817640b178..a43436e008 100644
--- a/activemodel/lib/active_model/attribute_methods.rb
+++ b/activemodel/lib/active_model/attribute_methods.rb
@@ -283,7 +283,7 @@ module ActiveModel
@attribute_methods_generated = true
end
- # Removes all the preiously dynamically defined methods from the class
+ # Removes all the previously dynamically defined methods from the class
def undefine_attribute_methods
generated_attribute_methods.module_eval do
instance_methods.each { |m| undef_method(m) }
diff --git a/activemodel/lib/active_model/dirty.rb b/activemodel/lib/active_model/dirty.rb
index 5ea7636427..2516377afd 100644
--- a/activemodel/lib/active_model/dirty.rb
+++ b/activemodel/lib/active_model/dirty.rb
@@ -37,12 +37,13 @@ module ActiveModel
# end
#
# def name=(val)
- # name_will_change!
+ # name_will_change! unless val == @name
# @name = val
# end
#
# def save
# @previously_changed = changes
+ # @changed_attributes.clear
# end
#
# end
@@ -77,12 +78,6 @@ module ActiveModel
# person.changed # => ['name']
# person.changes # => { 'name' => ['Bill', 'Bob'] }
#
- # Resetting an attribute returns it to its original state:
- # person.reset_name! # => 'Bill'
- # person.changed? # => false
- # person.name_changed? # => false
- # person.name # => 'Bill'
- #
# If an attribute is modified in-place then make use of <tt>[attribute_name]_will_change!</tt>
# to mark that the attribute is changing. Otherwise ActiveModel can't track changes to
# in-place attributes.
diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb
index f39678db83..272ddb1554 100644
--- a/activemodel/lib/active_model/errors.rb
+++ b/activemodel/lib/active_model/errors.rb
@@ -37,11 +37,11 @@ module ActiveModel
# send(attr)
# end
#
- # def ErrorsPerson.human_attribute_name(attr, options = {})
+ # def Person.human_attribute_name(attr, options = {})
# attr
# end
#
- # def ErrorsPerson.lookup_ancestors
+ # def Person.lookup_ancestors
# [self]
# end
#
@@ -86,11 +86,7 @@ module ActiveModel
# p.errors[:name] # => ["can not be nil"]
# p.errors['name'] # => ["can not be nil"]
def [](attribute)
- if errors = get(attribute.to_sym)
- errors
- else
- set(attribute.to_sym, [])
- end
+ get(attribute.to_sym) || set(attribute.to_sym, [])
end
# Adds to the supplied attribute the supplied error message.
diff --git a/activemodel/lib/active_model/serialization.rb b/activemodel/lib/active_model/serialization.rb
index 5670ec74cb..e675937f4d 100644
--- a/activemodel/lib/active_model/serialization.rb
+++ b/activemodel/lib/active_model/serialization.rb
@@ -61,6 +61,8 @@ module ActiveModel
# person.serializable_hash # => {"name"=>"Bob"}
# person.to_json # => "{\"name\":\"Bob\"}"
# person.to_xml # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<serial-person...
+ #
+ # Valid options are <tt>:only</tt>, <tt>:except</tt> and <tt>:methods</tt> .
module Serialization
def serializable_hash(options = nil)
options ||= {}
diff --git a/activemodel/lib/active_model/serializers/json.rb b/activemodel/lib/active_model/serializers/json.rb
index 500b2399a3..e1dbc522de 100644
--- a/activemodel/lib/active_model/serializers/json.rb
+++ b/activemodel/lib/active_model/serializers/json.rb
@@ -19,8 +19,8 @@ module ActiveModel
# passed through +options+.
#
# The option <tt>ActiveModel::Base.include_root_in_json</tt> controls the
- # top-level behavior of <tt>to_json</tt>. It is <tt>true</tt> by default. When it is <tt>true</tt>,
- # <tt>to_json</tt> will emit a single root node named after the object's type. For example:
+ # top-level behavior of +to_json+. If true (the default) +to_json+ will
+ # emit a single root node named after the object's type. For example:
#
# konata = User.find(1)
# konata.to_json
@@ -32,11 +32,11 @@ module ActiveModel
# # => {"id": 1, "name": "Konata Izumi", "age": 16,
# "created_at": "2006/08/01", "awesome": true}
#
- # The remainder of the examples in this section assume include_root_in_json is set to
- # <tt>false</tt>.
+ # The remainder of the examples in this section assume +include_root_in_json+
+ # is false.
#
- # Without any +options+, the returned JSON string will include all
- # the model's attributes. For example:
+ # Without any +options+, the returned JSON string will include all the model's
+ # attributes. For example:
#
# konata = User.find(1)
# konata.to_json
@@ -52,14 +52,14 @@ module ActiveModel
# konata.to_json(:except => [ :id, :created_at, :age ])
# # => {"name": "Konata Izumi", "awesome": true}
#
- # To include any methods on the model, use <tt>:methods</tt>.
+ # To include the result of some method calls on the model use <tt>:methods</tt>:
#
# konata.to_json(:methods => :permalink)
# # => {"id": 1, "name": "Konata Izumi", "age": 16,
# "created_at": "2006/08/01", "awesome": true,
# "permalink": "1-konata-izumi"}
#
- # To include associations, use <tt>:include</tt>.
+ # To include associations use <tt>:include</tt>:
#
# konata.to_json(:include => :posts)
# # => {"id": 1, "name": "Konata Izumi", "age": 16,
@@ -67,7 +67,7 @@ module ActiveModel
# "posts": [{"id": 1, "author_id": 1, "title": "Welcome to the weblog"},
# {"id": 2, author_id: 1, "title": "So I was thinking"}]}
#
- # 2nd level and higher order associations work as well:
+ # Second level and higher order associations work as well:
#
# konata.to_json(:include => { :posts => {
# :include => { :comments => {
diff --git a/activemodel/lib/active_model/validations.rb b/activemodel/lib/active_model/validations.rb
index 1a58d4c4fb..3407c59e7a 100644
--- a/activemodel/lib/active_model/validations.rb
+++ b/activemodel/lib/active_model/validations.rb
@@ -118,11 +118,13 @@ module ActiveModel
# end
#
def validate(*args, &block)
- options = args.last
- if options.is_a?(Hash) && options.key?(:on)
+ options = args.extract_options!
+ if options.key?(:on)
+ options = options.dup
options[:if] = Array.wrap(options[:if])
options[:if] << "validation_context == :#{options[:on]}"
end
+ args << options
set_callback(:validate, *args, &block)
end
diff --git a/activemodel/lib/active_model/validations/length.rb b/activemodel/lib/active_model/validations/length.rb
index c8a77ad666..a7af4f2b4d 100644
--- a/activemodel/lib/active_model/validations/length.rb
+++ b/activemodel/lib/active_model/validations/length.rb
@@ -40,8 +40,6 @@ module ActiveModel
CHECKS.each do |key, validity_check|
next unless check_value = options[key]
- default_message = options[MESSAGES[key]]
- options[:message] ||= default_message if default_message
valid_value = if key == :maximum
value.nil? || value.size.send(validity_check, check_value)
@@ -51,8 +49,13 @@ module ActiveModel
next if valid_value
- record.errors.add(attribute, MESSAGES[key],
- options.except(*RESERVED_OPTIONS).merge!(:count => check_value))
+ errors_options = options.except(*RESERVED_OPTIONS)
+ errors_options[:count] = check_value
+
+ default_message = options[MESSAGES[key]]
+ errors_options[:message] ||= default_message if default_message
+
+ record.errors.add(attribute, MESSAGES[key], errors_options)
end
end
end
diff --git a/activemodel/lib/active_model/validator.rb b/activemodel/lib/active_model/validator.rb
index 52192d5988..163124d531 100644
--- a/activemodel/lib/active_model/validator.rb
+++ b/activemodel/lib/active_model/validator.rb
@@ -111,7 +111,7 @@ module ActiveModel #:nodoc:
# Accepts options that will be made available through the +options+ reader.
def initialize(options)
- @options = options
+ @options = options.freeze
end
# Return the kind for this validator.
diff --git a/activemodel/test/cases/dirty_test.rb b/activemodel/test/cases/dirty_test.rb
index e1a35be384..858ae9cb69 100644
--- a/activemodel/test/cases/dirty_test.rb
+++ b/activemodel/test/cases/dirty_test.rb
@@ -3,10 +3,11 @@ require "cases/helper"
class DirtyTest < ActiveModel::TestCase
class DirtyModel
include ActiveModel::Dirty
- define_attribute_methods [:name]
+ define_attribute_methods [:name, :color]
def initialize
@name = nil
+ @color = nil
end
def name
@@ -17,13 +18,92 @@ class DirtyTest < ActiveModel::TestCase
name_will_change!
@name = val
end
+
+ def color
+ @color
+ end
+
+ def color=(val)
+ color_will_change! unless val == @color
+ @color = val
+ end
+
+ def save
+ @previously_changed = changes
+ @changed_attributes.clear
+ end
+ end
+
+ setup do
+ @model = DirtyModel.new
+ end
+
+ test "setting attribute will result in change" do
+ assert !@model.changed?
+ assert !@model.name_changed?
+ @model.name = "Ringo"
+ assert @model.changed?
+ assert @model.name_changed?
+ end
+
+ test "list of changed attributes" do
+ assert_equal [], @model.changed
+ @model.name = "Paul"
+ assert_equal ['name'], @model.changed
+ end
+
+ test "changes to attribute values" do
+ assert !@model.changes['name']
+ @model.name = "John"
+ assert_equal [nil, "John"], @model.changes['name']
end
test "changes accessible through both strings and symbols" do
- model = DirtyModel.new
- model.name = "David"
- assert_not_nil model.changes[:name]
- assert_not_nil model.changes['name']
+ @model.name = "David"
+ assert_not_nil @model.changes[:name]
+ assert_not_nil @model.changes['name']
+ end
+
+ test "attribute mutation" do
+ @model.instance_variable_set("@name", "Yam")
+ assert !@model.name_changed?
+ @model.name.replace("Hadad")
+ assert !@model.name_changed?
+ @model.name_will_change!
+ @model.name.replace("Baal")
+ assert @model.name_changed?
+ end
+
+ test "resetting attribute" do
+ @model.name = "Bob"
+ @model.reset_name!
+ assert_nil @model.name
+ #assert !@model.name_changed #Doesn't work yet
+ end
+
+ test "setting color to same value should not result in change being recorded" do
+ @model.color = "red"
+ assert @model.color_changed?
+ @model.save
+ assert !@model.color_changed?
+ assert !@model.changed?
+ @model.color = "red"
+ assert !@model.color_changed?
+ assert !@model.changed?
+ end
+
+ test "saving should reset model's changed status" do
+ @model.name = "Alf"
+ assert @model.changed?
+ @model.save
+ assert !@model.changed?
+ assert !@model.name_changed?
+ end
+
+ test "saving should preserve previous changes" do
+ @model.name = "Jericho Cane"
+ @model.save
+ assert_equal [nil, "Jericho Cane"], @model.previous_changes['name']
end
end
diff --git a/activemodel/test/cases/errors_test.rb b/activemodel/test/cases/errors_test.rb
new file mode 100644
index 0000000000..79b45bb298
--- /dev/null
+++ b/activemodel/test/cases/errors_test.rb
@@ -0,0 +1,65 @@
+require "cases/helper"
+
+class ErrorsTest < ActiveModel::TestCase
+ class Person
+ extend ActiveModel::Naming
+ def initialize
+ @errors = ActiveModel::Errors.new(self)
+ end
+
+ attr_accessor :name
+ attr_reader :errors
+
+ def validate!
+ errors.add(:name, "can not be nil") if name == nil
+ end
+
+ def read_attribute_for_validation(attr)
+ send(attr)
+ end
+
+ def self.human_attribute_name(attr, options = {})
+ attr
+ end
+
+ def self.lookup_ancestors
+ [self]
+ end
+
+ end
+
+ test "method validate! should work" do
+ person = Person.new
+ person.validate!
+ assert_equal ["name can not be nil"], person.errors.full_messages
+ assert_equal ["can not be nil"], person.errors[:name]
+
+ end
+
+ test 'should be able to assign error' do
+ person = Person.new
+ person.errors[:name] = 'should not be nil'
+ assert_equal ["should not be nil"], person.errors[:name]
+ end
+
+ test 'should be able to add an error on an attribute' do
+ person = Person.new
+ person.errors.add(:name, "can not be blank")
+ assert_equal ["can not be blank"], person.errors[:name]
+ end
+
+ test 'should respond to size' do
+ person = Person.new
+ person.errors.add(:name, "can not be blank")
+ assert_equal 1, person.errors.size
+ end
+
+ test 'to_a should return an array' do
+ person = Person.new
+ person.errors.add(:name, "can not be blank")
+ person.errors.add(:name, "can not be nil")
+ assert_equal ["name can not be blank", "name can not be nil"], person.errors.to_a
+
+ end
+
+end
diff --git a/activemodel/test/cases/validations/length_validation_test.rb b/activemodel/test/cases/validations/length_validation_test.rb
index 012c5a2f37..1e6180a938 100644
--- a/activemodel/test/cases/validations/length_validation_test.rb
+++ b/activemodel/test/cases/validations/length_validation_test.rb
@@ -229,6 +229,20 @@ class LengthValidationTest < ActiveModel::TestCase
assert_equal ["hoo 5"], t.errors["title"]
end
+ def test_validates_length_of_custom_errors_for_both_too_short_and_too_long
+ Topic.validates_length_of :title, :minimum => 3, :maximum => 5, :too_short => 'too short', :too_long => 'too long'
+
+ t = Topic.new(:title => 'a')
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ['too short'], t.errors['title']
+
+ t = Topic.new(:title => 'aaaaaa')
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ['too long'], t.errors['title']
+ end
+
def test_validates_length_of_custom_errors_for_is_with_message
Topic.validates_length_of( :title, :is=>5, :message=>"boo %{count}" )
t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
diff --git a/activerecord/lib/active_record/aggregations.rb b/activerecord/lib/active_record/aggregations.rb
index c45400d3d9..83a9ab46c5 100644
--- a/activerecord/lib/active_record/aggregations.rb
+++ b/activerecord/lib/active_record/aggregations.rb
@@ -9,11 +9,13 @@ module ActiveRecord
end unless self.new_record?
end
- # Active Record implements aggregation through a macro-like class method called +composed_of+ for representing attributes
- # as value objects. It expresses relationships like "Account [is] composed of Money [among other things]" or "Person [is]
- # composed of [an] address". Each call to the macro adds a description of how the value objects are created from the
- # attributes of the entity object (when the entity is initialized either as a new object or from finding an existing object)
- # and how it can be turned back into attributes (when the entity is saved to the database). Example:
+ # Active Record implements aggregation through a macro-like class method called +composed_of+
+ # for representing attributes as value objects. It expresses relationships like "Account [is]
+ # composed of Money [among other things]" or "Person [is] composed of [an] address". Each call
+ # to the macro adds a description of how the value objects are created from the attributes of
+ # the entity object (when the entity is initialized either as a new object or from finding an
+ # existing object) and how it can be turned back into attributes (when the entity is saved to
+ # the database).
#
# class Customer < ActiveRecord::Base
# composed_of :balance, :class_name => "Money", :mapping => %w(balance amount)
@@ -68,9 +70,10 @@ module ActiveRecord
# end
# end
#
- # Now it's possible to access attributes from the database through the value objects instead. If you choose to name the
- # composition the same as the attribute's name, it will be the only way to access that attribute. That's the case with our
- # +balance+ attribute. You interact with the value objects just like you would any other attribute, though:
+ # Now it's possible to access attributes from the database through the value objects instead. If
+ # you choose to name the composition the same as the attribute's name, it will be the only way to
+ # access that attribute. That's the case with our +balance+ attribute. You interact with the value
+ # objects just like you would any other attribute, though:
#
# customer.balance = Money.new(20) # sets the Money value object and the attribute
# customer.balance # => Money value object
@@ -79,8 +82,8 @@ module ActiveRecord
# customer.balance == Money.new(20) # => true
# customer.balance < Money.new(5) # => false
#
- # Value objects can also be composed of multiple attributes, such as the case of Address. The order of the mappings will
- # determine the order of the parameters. Example:
+ # Value objects can also be composed of multiple attributes, such as the case of Address. The order
+ # of the mappings will determine the order of the parameters.
#
# customer.address_street = "Hyancintvej"
# customer.address_city = "Copenhagen"
@@ -91,38 +94,43 @@ module ActiveRecord
#
# == Writing value objects
#
- # Value objects are immutable and interchangeable objects that represent a given value, such as a Money object representing
- # $5. Two Money objects both representing $5 should be equal (through methods such as <tt>==</tt> and <tt><=></tt> from Comparable if ranking
- # makes sense). This is unlike entity objects where equality is determined by identity. An entity class such as Customer can
- # easily have two different objects that both have an address on Hyancintvej. Entity identity is determined by object or
- # relational unique identifiers (such as primary keys). Normal ActiveRecord::Base classes are entity objects.
+ # Value objects are immutable and interchangeable objects that represent a given value, such as
+ # a Money object representing $5. Two Money objects both representing $5 should be equal (through
+ # methods such as <tt>==</tt> and <tt><=></tt> from Comparable if ranking makes sense). This is
+ # unlike entity objects where equality is determined by identity. An entity class such as Customer can
+ # easily have two different objects that both have an address on Hyancintvej. Entity identity is
+ # determined by object or relational unique identifiers (such as primary keys). Normal
+ # ActiveRecord::Base classes are entity objects.
#
- # It's also important to treat the value objects as immutable. Don't allow the Money object to have its amount changed after
- # creation. Create a new Money object with the new value instead. This is exemplified by the Money#exchange_to method that
- # returns a new value object instead of changing its own values. Active Record won't persist value objects that have been
- # changed through means other than the writer method.
+ # It's also important to treat the value objects as immutable. Don't allow the Money object to have
+ # its amount changed after creation. Create a new Money object with the new value instead. This
+ # is exemplified by the Money#exchange_to method that returns a new value object instead of changing
+ # its own values. Active Record won't persist value objects that have been changed through means
+ # other than the writer method.
#
- # The immutable requirement is enforced by Active Record by freezing any object assigned as a value object. Attempting to
- # change it afterwards will result in a ActiveSupport::FrozenObjectError.
+ # The immutable requirement is enforced by Active Record by freezing any object assigned as a value
+ # object. Attempting to change it afterwards will result in a ActiveSupport::FrozenObjectError.
#
- # Read more about value objects on http://c2.com/cgi/wiki?ValueObject and on the dangers of not keeping value objects
- # immutable on http://c2.com/cgi/wiki?ValueObjectsShouldBeImmutable
+ # Read more about value objects on http://c2.com/cgi/wiki?ValueObject and on the dangers of not
+ # keeping value objects immutable on http://c2.com/cgi/wiki?ValueObjectsShouldBeImmutable
#
# == Custom constructors and converters
#
- # By default value objects are initialized by calling the <tt>new</tt> constructor of the value class passing each of the
- # mapped attributes, in the order specified by the <tt>:mapping</tt> option, as arguments. If the value class doesn't support
- # this convention then +composed_of+ allows a custom constructor to be specified.
+ # By default value objects are initialized by calling the <tt>new</tt> constructor of the value
+ # class passing each of the mapped attributes, in the order specified by the <tt>:mapping</tt>
+ # option, as arguments. If the value class doesn't support this convention then +composed_of+ allows
+ # a custom constructor to be specified.
#
- # When a new value is assigned to the value object the default assumption is that the new value is an instance of the value
- # class. Specifying a custom converter allows the new value to be automatically converted to an instance of value class if
- # necessary.
+ # When a new value is assigned to the value object the default assumption is that the new value
+ # is an instance of the value class. Specifying a custom converter allows the new value to be automatically
+ # converted to an instance of value class if necessary.
#
- # For example, the NetworkResource model has +network_address+ and +cidr_range+ attributes that should be aggregated using the
- # NetAddr::CIDR value class (http://netaddr.rubyforge.org). The constructor for the value class is called +create+ and it
- # expects a CIDR address string as a parameter. New values can be assigned to the value object using either another
- # NetAddr::CIDR object, a string or an array. The <tt>:constructor</tt> and <tt>:converter</tt> options can be used to
- # meet these requirements:
+ # For example, the NetworkResource model has +network_address+ and +cidr_range+ attributes that
+ # should be aggregated using the NetAddr::CIDR value class (http://netaddr.rubyforge.org). The constructor
+ # for the value class is called +create+ and it expects a CIDR address string as a parameter. New
+ # values can be assigned to the value object using either another NetAddr::CIDR object, a string
+ # or an array. The <tt>:constructor</tt> and <tt>:converter</tt> options can be used to meet
+ # these requirements:
#
# class NetworkResource < ActiveRecord::Base
# composed_of :cidr,
@@ -149,9 +157,9 @@ module ActiveRecord
#
# == Finding records by a value object
#
- # Once a +composed_of+ relationship is specified for a model, records can be loaded from the database by specifying an instance
- # of the value object in the conditions hash. The following example finds all customers with +balance_amount+ equal to 20 and
- # +balance_currency+ equal to "USD":
+ # Once a +composed_of+ relationship is specified for a model, records can be loaded from the database
+ # by specifying an instance of the value object in the conditions hash. The following example
+ # finds all customers with +balance_amount+ equal to 20 and +balance_currency+ equal to "USD":
#
# Customer.find(:all, :conditions => {:balance => Money.new(20, "USD")})
#
@@ -160,23 +168,28 @@ module ActiveRecord
# <tt>composed_of :address</tt> adds <tt>address</tt> and <tt>address=(new_address)</tt> methods.
#
# Options are:
- # * <tt>:class_name</tt> - Specifies the class name of the association. Use it only if that name can't be inferred
- # from the part id. So <tt>composed_of :address</tt> will by default be linked to the Address class, but
- # if the real class name is CompanyAddress, you'll have to specify it with this option.
- # * <tt>:mapping</tt> - Specifies the mapping of entity attributes to attributes of the value object. Each mapping
- # is represented as an array where the first item is the name of the entity attribute and the second item is the
- # name the attribute in the value object. The order in which mappings are defined determine the order in which
- # attributes are sent to the value class constructor.
+ # * <tt>:class_name</tt> - Specifies the class name of the association. Use it only if that name
+ # can't be inferred from the part id. So <tt>composed_of :address</tt> will by default be linked
+ # to the Address class, but if the real class name is CompanyAddress, you'll have to specify it
+ # with this option.
+ # * <tt>:mapping</tt> - Specifies the mapping of entity attributes to attributes of the value
+ # object. Each mapping is represented as an array where the first item is the name of the
+ # entity attribute and the second item is the name the attribute in the value object. The
+ # order in which mappings are defined determine the order in which attributes are sent to the
+ # value class constructor.
# * <tt>:allow_nil</tt> - Specifies that the value object will not be instantiated when all mapped
- # attributes are +nil+. Setting the value object to +nil+ has the effect of writing +nil+ to all mapped attributes.
+ # attributes are +nil+. Setting the value object to +nil+ has the effect of writing +nil+ to all
+ # mapped attributes.
# This defaults to +false+.
- # * <tt>:constructor</tt> - A symbol specifying the name of the constructor method or a Proc that is called to
- # initialize the value object. The constructor is passed all of the mapped attributes, in the order that they
- # are defined in the <tt>:mapping option</tt>, as arguments and uses them to instantiate a <tt>:class_name</tt> object.
+ # * <tt>:constructor</tt> - A symbol specifying the name of the constructor method or a Proc that
+ # is called to initialize the value object. The constructor is passed all of the mapped attributes,
+ # in the order that they are defined in the <tt>:mapping option</tt>, as arguments and uses them
+ # to instantiate a <tt>:class_name</tt> object.
# The default is <tt>:new</tt>.
- # * <tt>:converter</tt> - A symbol specifying the name of a class method of <tt>:class_name</tt> or a Proc that is
- # called when a new value is assigned to the value object. The converter is passed the single value that is used
- # in the assignment and is only called if the new value is not an instance of <tt>:class_name</tt>.
+ # * <tt>:converter</tt> - A symbol specifying the name of a class method of <tt>:class_name</tt>
+ # or a Proc that is called when a new value is assigned to the value object. The converter is
+ # passed the single value that is used in the assignment and is only called if the new value is
+ # not an instance of <tt>:class_name</tt>.
#
# Option examples:
# composed_of :temperature, :mapping => %w(reading celsius)
diff --git a/activerecord/lib/active_record/association_preload.rb b/activerecord/lib/active_record/association_preload.rb
index 08601f8ef9..0f0fdc2e21 100644
--- a/activerecord/lib/active_record/association_preload.rb
+++ b/activerecord/lib/active_record/association_preload.rb
@@ -9,8 +9,8 @@ module ActiveRecord
# Implements the details of eager loading of Active Record associations.
# Application developers should not use this module directly.
#
- # ActiveRecord::Base is extended with this module. The source code in
- # ActiveRecord::Base references methods defined in this module.
+ # <tt>ActiveRecord::Base</tt> is extended with this module. The source code in
+ # <tt>ActiveRecord::Base</tt> references methods defined in this module.
#
# Note that 'eager loading' and 'preloading' are actually the same thing.
# However, there are two different eager loading strategies.
@@ -55,7 +55,7 @@ module ActiveRecord
# == Parameters
# +records+ is an array of ActiveRecord::Base. This array needs not be flat,
# i.e. +records+ itself may also contain arrays of records. In any case,
- # +preload_associations+ will preload the associations all records by
+ # +preload_associations+ will preload the all associations records by
# flattening +records+.
#
# +associations+ specifies one or more associations that you want to
@@ -110,8 +110,8 @@ module ActiveRecord
def preload_one_association(records, association, preload_options={})
class_to_reflection = {}
# Not all records have the same class, so group then preload
- # group on the reflection itself so that if various subclass share the same association then we do not split them
- # unnecessarily
+ # group on the reflection itself so that if various subclass share the same association then
+ # we do not split them unnecessarily
records.group_by { |record| class_to_reflection[record.class] ||= record.class.reflections[association]}.each do |reflection, _records|
raise ConfigurationError, "Association named '#{ association }' was not found; perhaps you misspelled it?" unless reflection
@@ -149,7 +149,8 @@ module ActiveRecord
seen_keys = {}
associated_records.each do |associated_record|
#this is a has_one or belongs_to: there should only be one record.
- #Unfortunately we can't (in portable way) ask the database for 'all records where foo_id in (x,y,z), but please
+ #Unfortunately we can't (in portable way) ask the database for
+ #'all records where foo_id in (x,y,z), but please
# only one row per distinct foo_id' so this where we enforce that
next if seen_keys[associated_record[key].to_s]
seen_keys[associated_record[key].to_s] = true
@@ -304,7 +305,8 @@ module ActiveRecord
polymorph_type = options[:foreign_type]
klasses_and_ids = {}
- # Construct a mapping from klass to a list of ids to load and a mapping of those ids back to their parent_records
+ # Construct a mapping from klass to a list of ids to load and a mapping of those ids back
+ # to their parent_records
records.each do |record|
if klass = record.send(polymorph_type)
klass_id = record.send(primary_key_name)
diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb
index fdc203e298..73c0900c8b 100644
--- a/activerecord/lib/active_record/associations.rb
+++ b/activerecord/lib/active_record/associations.rb
@@ -114,7 +114,7 @@ module ActiveRecord
autoload :HasOneAssociation, 'active_record/associations/has_one_association'
autoload :HasOneThroughAssociation, 'active_record/associations/has_one_through_association'
- # Clears out the association cache
+ # Clears out the association cache.
def clear_association_cache #:nodoc:
self.class.reflect_on_all_associations.to_a.each do |assoc|
instance_variable_set "@#{assoc.name}", nil
@@ -122,7 +122,7 @@ module ActiveRecord
end
private
- # Gets the specified association instance if it responds to :loaded?, nil otherwise.
+ # Returns the specified association instance if it responds to :loaded?, nil otherwise.
def association_instance_get(name)
ivar = "@#{name}"
if instance_variable_defined?(ivar)
@@ -136,10 +136,12 @@ module ActiveRecord
instance_variable_set("@#{name}", association)
end
- # Associations are a set of macro-like class methods for tying objects together through foreign keys. They express relationships like
- # "Project has one Project Manager" or "Project belongs to a Portfolio". Each macro adds a number of methods to the class which are
- # specialized according to the collection or association symbol and the options hash. It works much the same way as Ruby's own <tt>attr*</tt>
- # methods. Example:
+ # Associations are a set of macro-like class methods for tying objects together through
+ # foreign keys. They express relationships like "Project has one Project Manager"
+ # or "Project belongs to a Portfolio". Each macro adds a number of methods to the
+ # class which are specialized according to the collection or association symbol and the
+ # options hash. It works much the same way as Ruby's own <tt>attr*</tt>
+ # methods.
#
# class Project < ActiveRecord::Base
# belongs_to :portfolio
@@ -148,7 +150,8 @@ module ActiveRecord
# has_and_belongs_to_many :categories
# end
#
- # The project class now has the following methods (and more) to ease the traversal and manipulation of its relationships:
+ # The project class now has the following methods (and more) to ease the traversal and
+ # manipulation of its relationships:
# * <tt>Project#portfolio, Project#portfolio=(portfolio), Project#portfolio.nil?</tt>
# * <tt>Project#project_manager, Project#project_manager=(project_manager), Project#project_manager.nil?,</tt>
# * <tt>Project#milestones.empty?, Project#milestones.size, Project#milestones, Project#milestones<<(milestone),</tt>
@@ -159,8 +162,9 @@ module ActiveRecord
#
# === A word of warning
#
- # Don't create associations that have the same name as instance methods of ActiveRecord::Base. Since the association
- # adds a method with that name to its model, it will override the inherited method and break things.
+ # Don't create associations that have the same name as instance methods of
+ # <tt>ActiveRecord::Base</tt>. Since the association adds a method with that name to
+ # its model, it will override the inherited method and break things.
# For instance, +attributes+ and +connection+ would be bad choices for association names.
#
# == Auto-generated methods
@@ -270,8 +274,8 @@ module ActiveRecord
#
# == Is it a +belongs_to+ or +has_one+ association?
#
- # Both express a 1-1 relationship. The difference is mostly where to place the foreign key, which goes on the table for the class
- # declaring the +belongs_to+ relationship. Example:
+ # Both express a 1-1 relationship. The difference is mostly where to place the foreign
+ # key, which goes on the table for the class declaring the +belongs_to+ relationship.
#
# class User < ActiveRecord::Base
# # I reference an account.
@@ -300,8 +304,9 @@ module ActiveRecord
#
# == Unsaved objects and associations
#
- # You can manipulate objects and associations before they are saved to the database, but there is some special behavior you should be
- # aware of, mostly involving the saving of associated objects.
+ # You can manipulate objects and associations before they are saved to the database, but
+ # there is some special behavior you should be aware of, mostly involving the saving of
+ # associated objects.
#
# You can set the :autosave option on a <tt>has_one</tt>, <tt>belongs_to</tt>,
# <tt>has_many</tt>, or <tt>has_and_belongs_to_many</tt> association. Setting it
@@ -310,26 +315,33 @@ module ActiveRecord
#
# === One-to-one associations
#
- # * Assigning an object to a +has_one+ association automatically saves that object and the object being replaced (if there is one), in
- # order to update their primary keys - except if the parent object is unsaved (<tt>new_record? == true</tt>).
- # * If either of these saves fail (due to one of the objects being invalid) the assignment statement returns +false+ and the assignment
- # is cancelled.
- # * If you wish to assign an object to a +has_one+ association without saving it, use the <tt>association.build</tt> method (documented below).
- # * Assigning an object to a +belongs_to+ association does not save the object, since the foreign key field belongs on the parent. It
- # does not save the parent either.
+ # * Assigning an object to a +has_one+ association automatically saves that object and
+ # the object being replaced (if there is one), in order to update their primary
+ # keys - except if the parent object is unsaved (<tt>new_record? == true</tt>).
+ # * If either of these saves fail (due to one of the objects being invalid) the assignment
+ # statement returns +false+ and the assignment is cancelled.
+ # * If you wish to assign an object to a +has_one+ association without saving it,
+ # use the <tt>association.build</tt> method (documented below).
+ # * Assigning an object to a +belongs_to+ association does not save the object, since
+ # the foreign key field belongs on the parent. It does not save the parent either.
#
# === Collections
#
- # * Adding an object to a collection (+has_many+ or +has_and_belongs_to_many+) automatically saves that object, except if the parent object
- # (the owner of the collection) is not yet stored in the database.
- # * If saving any of the objects being added to a collection (via <tt>push</tt> or similar) fails, then <tt>push</tt> returns +false+.
- # * You can add an object to a collection without automatically saving it by using the <tt>collection.build</tt> method (documented below).
- # * All unsaved (<tt>new_record? == true</tt>) members of the collection are automatically saved when the parent is saved.
+ # * Adding an object to a collection (+has_many+ or +has_and_belongs_to_many+) automatically
+ # saves that object, except if the parent object (the owner of the collection) is not yet
+ # stored in the database.
+ # * If saving any of the objects being added to a collection (via <tt>push</tt> or similar)
+ # fails, then <tt>push</tt> returns +false+.
+ # * You can add an object to a collection without automatically saving it by using the
+ # <tt>collection.build</tt> method (documented below).
+ # * All unsaved (<tt>new_record? == true</tt>) members of the collection are automatically
+ # saved when the parent is saved.
#
# === Association callbacks
#
- # Similar to the normal callbacks that hook into the lifecycle of an Active Record object, you can also define callbacks that get
- # triggered when you add an object to or remove an object from an association collection. Example:
+ # Similar to the normal callbacks that hook into the lifecycle of an Active Record object,
+ # you can also define callbacks that get triggered when you add an object to or remove an
+ # object from an association collection.
#
# class Project
# has_and_belongs_to_many :developers, :after_add => :evaluate_velocity
@@ -342,19 +354,21 @@ module ActiveRecord
# It's possible to stack callbacks by passing them as an array. Example:
#
# class Project
- # has_and_belongs_to_many :developers, :after_add => [:evaluate_velocity, Proc.new { |p, d| p.shipping_date = Time.now}]
+ # has_and_belongs_to_many :developers,
+ # :after_add => [:evaluate_velocity, Proc.new { |p, d| p.shipping_date = Time.now}]
# end
#
# Possible callbacks are: +before_add+, +after_add+, +before_remove+ and +after_remove+.
#
- # Should any of the +before_add+ callbacks throw an exception, the object does not get added to the collection. Same with
- # the +before_remove+ callbacks; if an exception is thrown the object doesn't get removed.
+ # Should any of the +before_add+ callbacks throw an exception, the object does not get
+ # added to the collection. Same with the +before_remove+ callbacks; if an exception is
+ # thrown the object doesn't get removed.
#
# === Association extensions
#
- # The proxy objects that control the access to associations can be extended through anonymous modules. This is especially
- # beneficial for adding new finders, creators, and other factory-type methods that are only used as part of this association.
- # Example:
+ # The proxy objects that control the access to associations can be extended through anonymous
+ # modules. This is especially beneficial for adding new finders, creators, and other
+ # factory-type methods that are only used as part of this association.
#
# class Account < ActiveRecord::Base
# has_many :people do
@@ -369,7 +383,8 @@ module ActiveRecord
# person.first_name # => "David"
# person.last_name # => "Heinemeier Hansson"
#
- # If you need to share the same extensions between many associations, you can use a named extension module. Example:
+ # If you need to share the same extensions between many associations, you can use a named
+ # extension module.
#
# module FindOrCreateByNameExtension
# def find_or_create_by_name(name)
@@ -386,9 +401,10 @@ module ActiveRecord
# has_many :people, :extend => FindOrCreateByNameExtension
# end
#
- # If you need to use multiple named extension modules, you can specify an array of modules with the <tt>:extend</tt> option.
- # In the case of name conflicts between methods in the modules, methods in modules later in the array supercede
- # those earlier in the array. Example:
+ # If you need to use multiple named extension modules, you can specify an array of modules
+ # with the <tt>:extend</tt> option.
+ # In the case of name conflicts between methods in the modules, methods in modules later
+ # in the array supercede those earlier in the array.
#
# class Account < ActiveRecord::Base
# has_many :people, :extend => [FindOrCreateByNameExtension, FindRecentExtension]
@@ -399,12 +415,14 @@ module ActiveRecord
#
# * +proxy_owner+ - Returns the object the association is part of.
# * +proxy_reflection+ - Returns the reflection object that describes the association.
- # * +proxy_target+ - Returns the associated object for +belongs_to+ and +has_one+, or the collection of associated objects for +has_many+ and +has_and_belongs_to_many+.
+ # * +proxy_target+ - Returns the associated object for +belongs_to+ and +has_one+, or
+ # the collection of associated objects for +has_many+ and +has_and_belongs_to_many+.
#
# === Association Join Models
#
- # Has Many associations can be configured with the <tt>:through</tt> option to use an explicit join model to retrieve the data. This
- # operates similarly to a +has_and_belongs_to_many+ association. The advantage is that you're able to add validations,
+ # Has Many associations can be configured with the <tt>:through</tt> option to use an
+ # explicit join model to retrieve the data. This operates similarly to a
+ # +has_and_belongs_to_many+ association. The advantage is that you're able to add validations,
# callbacks, and extra attributes on the join model. Consider the following schema:
#
# class Author < ActiveRecord::Base
@@ -418,7 +436,7 @@ module ActiveRecord
# end
#
# @author = Author.find :first
- # @author.authorships.collect { |a| a.book } # selects all books that the author's authorships belong to.
+ # @author.authorships.collect { |a| a.book } # selects all books that the author's authorships belong to
# @author.books # selects all books by using the Authorship join model
#
# You can also go through a +has_many+ association on the join model:
@@ -439,7 +457,7 @@ module ActiveRecord
#
# @firm = Firm.find :first
# @firm.clients.collect { |c| c.invoices }.flatten # select all invoices for all clients of the firm
- # @firm.invoices # selects all invoices by going through the Client join model.
+ # @firm.invoices # selects all invoices by going through the Client join model
#
# Similarly you can go through a +has_one+ association on the join model:
#
@@ -461,16 +479,18 @@ module ActiveRecord
# @group.users.collect { |u| u.avatar }.flatten # select all avatars for all users in the group
# @group.avatars # selects all avatars by going through the User join model.
#
- # An important caveat with going through +has_one+ or +has_many+ associations on the join model is that these associations are
- # *read-only*. For example, the following would not work following the previous example:
+ # An important caveat with going through +has_one+ or +has_many+ associations on the
+ # join model is that these associations are *read-only*. For example, the following
+ # would not work following the previous example:
#
- # @group.avatars << Avatar.new # this would work if User belonged_to Avatar rather than the other way around.
+ # @group.avatars << Avatar.new # this would work if User belonged_to Avatar rather than the other way around
# @group.avatars.delete(@group.avatars.last) # so would this
#
# === Polymorphic Associations
#
- # Polymorphic associations on models are not restricted on what types of models they can be associated with. Rather, they
- # specify an interface that a +has_many+ association must adhere to.
+ # Polymorphic associations on models are not restricted on what types of models they
+ # can be associated with. Rather, they specify an interface that a +has_many+ association
+ # must adhere to.
#
# class Asset < ActiveRecord::Base
# belongs_to :attachable, :polymorphic => true
@@ -482,13 +502,16 @@ module ActiveRecord
#
# @asset.attachable = @post
#
- # This works by using a type column in addition to a foreign key to specify the associated record. In the Asset example, you'd need
- # an +attachable_id+ integer column and an +attachable_type+ string column.
+ # This works by using a type column in addition to a foreign key to specify the associated
+ # record. In the Asset example, you'd need an +attachable_id+ integer column and an
+ # +attachable_type+ string column.
#
- # Using polymorphic associations in combination with single table inheritance (STI) is a little tricky. In order
- # for the associations to work as expected, ensure that you store the base model for the STI models in the
- # type column of the polymorphic association. To continue with the asset example above, suppose there are guest posts
- # and member posts that use the posts table for STI. In this case, there must be a +type+ column in the posts table.
+ # Using polymorphic associations in combination with single table inheritance (STI) is
+ # a little tricky. In order for the associations to work as expected, ensure that you
+ # store the base model for the STI models in the type column of the polymorphic
+ # association. To continue with the asset example above, suppose there are guest posts
+ # and member posts that use the posts table for STI. In this case, there must be a +type+
+ # column in the posts table.
#
# class Asset < ActiveRecord::Base
# belongs_to :attachable, :polymorphic => true
@@ -511,9 +534,10 @@ module ActiveRecord
#
# == Caching
#
- # All of the methods are built on a simple caching principle that will keep the result of the last query around unless specifically
- # instructed not to. The cache is even shared across methods to make it even cheaper to use the macro-added methods without
- # worrying too much about performance at the first go. Example:
+ # All of the methods are built on a simple caching principle that will keep the result
+ # of the last query around unless specifically instructed not to. The cache is even
+ # shared across methods to make it even cheaper to use the macro-added methods without
+ # worrying too much about performance at the first go.
#
# project.milestones # fetches milestones from the database
# project.milestones.size # uses the milestone cache
@@ -523,9 +547,10 @@ module ActiveRecord
#
# == Eager loading of associations
#
- # Eager loading is a way to find objects of a certain class and a number of named associations. This is
- # one of the easiest ways of to prevent the dreaded 1+N problem in which fetching 100 posts that each need to display their author
- # triggers 101 database queries. Through the use of eager loading, the 101 queries can be reduced to 2. Example:
+ # Eager loading is a way to find objects of a certain class and a number of named associations.
+ # This is one of the easiest ways of to prevent the dreaded 1+N problem in which fetching 100
+ # posts that each need to display their author triggers 101 database queries. Through the
+ # use of eager loading, the 101 queries can be reduced to 2.
#
# class Post < ActiveRecord::Base
# belongs_to :author
@@ -540,44 +565,55 @@ module ActiveRecord
# puts "Last comment on: " + post.comments.first.created_on
# end
#
- # To iterate over these one hundred posts, we'll generate 201 database queries. Let's first just optimize it for retrieving the author:
+ # To iterate over these one hundred posts, we'll generate 201 database queries. Let's
+ # first just optimize it for retrieving the author:
#
# for post in Post.find(:all, :include => :author)
#
- # This references the name of the +belongs_to+ association that also used the <tt>:author</tt> symbol. After loading the posts, find
- # will collect the +author_id+ from each one and load all the referenced authors with one query. Doing so will cut down the number of queries from 201 to 102.
+ # This references the name of the +belongs_to+ association that also used the <tt>:author</tt>
+ # symbol. After loading the posts, find will collect the +author_id+ from each one and load
+ # all the referenced authors with one query. Doing so will cut down the number of queries
+ # from 201 to 102.
#
# We can improve upon the situation further by referencing both associations in the finder with:
#
# for post in Post.find(:all, :include => [ :author, :comments ])
#
- # This will load all comments with a single query. This reduces the total number of queries to 3. More generally the number of queries
- # will be 1 plus the number of associations named (except if some of the associations are polymorphic +belongs_to+ - see below).
+ # This will load all comments with a single query. This reduces the total number of queries
+ # to 3. More generally the number of queries will be 1 plus the number of associations
+ # named (except if some of the associations are polymorphic +belongs_to+ - see below).
#
# To include a deep hierarchy of associations, use a hash:
#
# for post in Post.find(:all, :include => [ :author, { :comments => { :author => :gravatar } } ])
#
- # That'll grab not only all the comments but all their authors and gravatar pictures. You can mix and match
- # symbols, arrays and hashes in any combination to describe the associations you want to load.
+ # That'll grab not only all the comments but all their authors and gravatar pictures.
+ # You can mix and match symbols, arrays and hashes in any combination to describe the
+ # associations you want to load.
#
- # All of this power shouldn't fool you into thinking that you can pull out huge amounts of data with no performance penalty just because you've reduced
- # the number of queries. The database still needs to send all the data to Active Record and it still needs to be processed. So it's no
- # catch-all for performance problems, but it's a great way to cut down on the number of queries in a situation as the one described above.
+ # All of this power shouldn't fool you into thinking that you can pull out huge amounts
+ # of data with no performance penalty just because you've reduced the number of queries.
+ # The database still needs to send all the data to Active Record and it still needs to
+ # be processed. So it's no catch-all for performance problems, but it's a great way to
+ # cut down on the number of queries in a situation as the one described above.
#
- # Since only one table is loaded at a time, conditions or orders cannot reference tables other than the main one. If this is the case
- # Active Record falls back to the previously used LEFT OUTER JOIN based strategy. For example
+ # Since only one table is loaded at a time, conditions or orders cannot reference tables
+ # other than the main one. If this is the case Active Record falls back to the previously
+ # used LEFT OUTER JOIN based strategy. For example
#
# Post.find(:all, :include => [ :author, :comments ], :conditions => ['comments.approved = ?', true])
#
- # This will result in a single SQL query with joins along the lines of: <tt>LEFT OUTER JOIN comments ON comments.post_id = posts.id</tt> and
- # <tt>LEFT OUTER JOIN authors ON authors.id = posts.author_id</tt>. Note that using conditions like this can have unintended consequences.
- # In the above example posts with no approved comments are not returned at all, because the conditions apply to the SQL statement as a whole
- # and not just to the association. You must disambiguate column references for this fallback to happen, for example
+ # This will result in a single SQL query with joins along the lines of:
+ # <tt>LEFT OUTER JOIN comments ON comments.post_id = posts.id</tt> and
+ # <tt>LEFT OUTER JOIN authors ON authors.id = posts.author_id</tt>. Note that using conditions
+ # like this can have unintended consequences.
+ # In the above example posts with no approved comments are not returned at all, because
+ # the conditions apply to the SQL statement as a whole and not just to the association.
+ # You must disambiguate column references for this fallback to happen, for example
# <tt>:order => "author.name DESC"</tt> will work but <tt>:order => "name DESC"</tt> will not.
#
- # If you do want eager load only some members of an association it is usually more natural to <tt>:include</tt> an association
- # which has conditions defined on it:
+ # If you do want eager load only some members of an association it is usually more natural
+ # to <tt>:include</tt> an association which has conditions defined on it:
#
# class Post < ActiveRecord::Base
# has_many :approved_comments, :class_name => 'Comment', :conditions => ['approved = ?', true]
@@ -585,9 +621,11 @@ module ActiveRecord
#
# Post.find(:all, :include => :approved_comments)
#
- # This will load posts and eager load the +approved_comments+ association, which contains only those comments that have been approved.
+ # This will load posts and eager load the +approved_comments+ association, which contains
+ # only those comments that have been approved.
#
- # If you eager load an association with a specified <tt>:limit</tt> option, it will be ignored, returning all the associated objects:
+ # If you eager load an association with a specified <tt>:limit</tt> option, it will be ignored,
+ # returning all the associated objects:
#
# class Picture < ActiveRecord::Base
# has_many :most_recent_comments, :class_name => 'Comment', :order => 'id DESC', :limit => 10
@@ -595,8 +633,8 @@ module ActiveRecord
#
# Picture.find(:first, :include => :most_recent_comments).most_recent_comments # => returns all associated comments.
#
- # When eager loaded, conditions are interpolated in the context of the model class, not the model instance. Conditions are lazily interpolated
- # before the actual model exists.
+ # When eager loaded, conditions are interpolated in the context of the model class, not
+ # the model instance. Conditions are lazily interpolated before the actual model exists.
#
# Eager loading is supported with polymorphic associations.
#
@@ -608,17 +646,21 @@ module ActiveRecord
#
# Address.find(:all, :include => :addressable)
#
- # This will execute one query to load the addresses and load the addressables with one query per addressable type.
- # For example if all the addressables are either of class Person or Company then a total of 3 queries will be executed. The list of
- # addressable types to load is determined on the back of the addresses loaded. This is not supported if Active Record has to fallback
- # to the previous implementation of eager loading and will raise ActiveRecord::EagerLoadPolymorphicError. The reason is that the parent
- # model's type is a column value so its corresponding table name cannot be put in the +FROM+/+JOIN+ clauses of that query.
+ # This will execute one query to load the addresses and load the addressables with one
+ # query per addressable type.
+ # For example if all the addressables are either of class Person or Company then a total
+ # of 3 queries will be executed. The list of addressable types to load is determined on
+ # the back of the addresses loaded. This is not supported if Active Record has to fallback
+ # to the previous implementation of eager loading and will raise ActiveRecord::EagerLoadPolymorphicError.
+ # The reason is that the parent model's type is a column value so its corresponding table
+ # name cannot be put in the +FROM+/+JOIN+ clauses of that query.
#
# == Table Aliasing
#
- # Active Record uses table aliasing in the case that a table is referenced multiple times in a join. If a table is referenced only once,
- # the standard table name is used. The second time, the table is aliased as <tt>#{reflection_name}_#{parent_table_name}</tt>. Indexes are appended
- # for any more successive uses of the table name.
+ # Active Record uses table aliasing in the case that a table is referenced multiple times
+ # in a join. If a table is referenced only once, the standard table name is used. The
+ # second time, the table is aliased as <tt>#{reflection_name}_#{parent_table_name}</tt>.
+ # Indexes are appended for any more successive uses of the table name.
#
# Post.find :all, :joins => :comments
# # => SELECT ... FROM posts INNER JOIN comments ON ...
@@ -651,7 +693,8 @@ module ActiveRecord
# INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories
# INNER JOIN categories_posts categories_posts_join INNER JOIN categories categories_posts_2
#
- # If you wish to specify your own custom joins using a <tt>:joins</tt> option, those table names will take precedence over the eager associations:
+ # If you wish to specify your own custom joins using a <tt>:joins</tt> option, those table
+ # names will take precedence over the eager associations:
#
# Post.find :all, :joins => :comments, :joins => "inner join comments ..."
# # => SELECT ... FROM posts INNER JOIN comments_posts ON ... INNER JOIN comments ...
@@ -660,7 +703,8 @@ module ActiveRecord
# INNER JOIN comments special_comments_posts ...
# INNER JOIN comments ...
#
- # Table aliases are automatically truncated according to the maximum length of table identifiers according to the specific database.
+ # Table aliases are automatically truncated according to the maximum length of table identifiers
+ # according to the specific database.
#
# == Modules
#
@@ -676,9 +720,10 @@ module ActiveRecord
# end
# end
#
- # When <tt>Firm#clients</tt> is called, it will in turn call <tt>MyApplication::Business::Client.find_all_by_firm_id(firm.id)</tt>.
- # If you want to associate with a class in another module scope, this can be done by specifying the complete class name.
- # Example:
+ # When <tt>Firm#clients</tt> is called, it will in turn call
+ # <tt>MyApplication::Business::Client.find_all_by_firm_id(firm.id)</tt>.
+ # If you want to associate with a class in another module scope, this can be done by
+ # specifying the complete class name.
#
# module MyApplication
# module Business
@@ -694,8 +739,8 @@ module ActiveRecord
#
# == Bi-directional associations
#
- # When you specify an association there is usually an association on the associated model that specifies the same
- # relationship in reverse. For example, with the following models:
+ # When you specify an association there is usually an association on the associated model
+ # that specifies the same relationship in reverse. For example, with the following models:
#
# class Dungeon < ActiveRecord::Base
# has_many :traps
@@ -710,9 +755,11 @@ module ActiveRecord
# belongs_to :dungeon
# end
#
- # The +traps+ association on +Dungeon+ and the the +dungeon+ association on +Trap+ are the inverse of each other and the
- # inverse of the +dungeon+ association on +EvilWizard+ is the +evil_wizard+ association on +Dungeon+ (and vice-versa). By default,
- # Active Record doesn't know anything about these inverse relationships and so no object loading optimisation is possible. For example:
+ # The +traps+ association on +Dungeon+ and the the +dungeon+ association on +Trap+ are
+ # the inverse of each other and the inverse of the +dungeon+ association on +EvilWizard+
+ # is the +evil_wizard+ association on +Dungeon+ (and vice-versa). By default,
+ # Active Record doesn't know anything about these inverse relationships and so no object
+ # loading optimisation is possible. For example:
#
# d = Dungeon.first
# t = d.traps.first
@@ -720,9 +767,11 @@ module ActiveRecord
# d.level = 10
# d.level == t.dungeon.level # => false
#
- # The +Dungeon+ instances +d+ and <tt>t.dungeon</tt> in the above example refer to the same object data from the database, but are
- # actually different in-memory copies of that data. Specifying the <tt>:inverse_of</tt> option on associations lets you tell
- # Active Record about inverse relationships and it will optimise object loading. For example, if we changed our model definitions to:
+ # The +Dungeon+ instances +d+ and <tt>t.dungeon</tt> in the above example refer to
+ # the same object data from the database, but are actually different in-memory copies
+ # of that data. Specifying the <tt>:inverse_of</tt> option on associations lets you tell
+ # Active Record about inverse relationships and it will optimise object loading. For
+ # example, if we changed our model definitions to:
#
# class Dungeon < ActiveRecord::Base
# has_many :traps, :inverse_of => :dungeon
@@ -737,8 +786,8 @@ module ActiveRecord
# belongs_to :dungeon, :inverse_of => :evil_wizard
# end
#
- # Then, from our code snippet above, +d+ and <tt>t.dungeon</tt> are actually the same in-memory instance and our final <tt>d.level == t.dungeon.level</tt>
- # will return +true+.
+ # Then, from our code snippet above, +d+ and <tt>t.dungeon</tt> are actually the same
+ # in-memory instance and our final <tt>d.level == t.dungeon.level</tt> will return +true+.
#
# There are limitations to <tt>:inverse_of</tt> support:
#
@@ -748,13 +797,13 @@ module ActiveRecord
#
# == Type safety with <tt>ActiveRecord::AssociationTypeMismatch</tt>
#
- # If you attempt to assign an object to an association that doesn't match the inferred or specified <tt>:class_name</tt>, you'll
- # get an <tt>ActiveRecord::AssociationTypeMismatch</tt>.
+ # If you attempt to assign an object to an association that doesn't match the inferred
+ # or specified <tt>:class_name</tt>, you'll get an <tt>ActiveRecord::AssociationTypeMismatch</tt>.
#
# == Options
#
- # All of the association macros can be specialized through options. This makes cases more complex than the simple and guessable ones
- # possible.
+ # All of the association macros can be specialized through options. This makes cases
+ # more complex than the simple and guessable ones possible.
module ClassMethods
# Specifies a one-to-many association. The following methods for retrieval and query of
# collections of associated objects will be added:
@@ -828,20 +877,22 @@ module ActiveRecord
# === Supported options
# [:class_name]
# Specify the class name of the association. Use it only if that name can't be inferred
- # from the association name. So <tt>has_many :products</tt> will by default be linked to the Product class, but
- # if the real class name is SpecialProduct, you'll have to specify it with this option.
+ # from the association name. So <tt>has_many :products</tt> will by default be linked
+ # to the Product class, but if the real class name is SpecialProduct, you'll have to
+ # specify it with this option.
# [:conditions]
# Specify the conditions that the associated objects must meet in order to be included as a +WHERE+
- # SQL fragment, such as <tt>price > 5 AND name LIKE 'B%'</tt>. Record creations from the association are scoped if a hash
- # is used. <tt>has_many :posts, :conditions => {:published => true}</tt> will create published posts with <tt>@blog.posts.create</tt>
- # or <tt>@blog.posts.build</tt>.
+ # SQL fragment, such as <tt>price > 5 AND name LIKE 'B%'</tt>. Record creations from
+ # the association are scoped if a hash is used.
+ # <tt>has_many :posts, :conditions => {:published => true}</tt> will create published
+ # posts with <tt>@blog.posts.create</tt> or <tt>@blog.posts.build</tt>.
# [:order]
# Specify the order in which the associated objects are returned as an <tt>ORDER BY</tt> SQL fragment,
# such as <tt>last_name, first_name DESC</tt>.
# [:foreign_key]
# Specify the foreign key used for the association. By default this is guessed to be the name
- # of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_many+ association will use "person_id"
- # as the default <tt>:foreign_key</tt>.
+ # of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_many+
+ # association will use "person_id" as the default <tt>:foreign_key</tt>.
# [:primary_key]
# Specify the method that returns the primary key used for the association. By default this is +id+.
# [:dependent]
@@ -855,10 +906,12 @@ module ActiveRecord
#
# [:finder_sql]
# Specify a complete SQL statement to fetch the association. This is a good way to go for complex
- # associations that depend on multiple tables. Note: When this option is used, +find_in_collection+ is _not_ added.
+ # associations that depend on multiple tables. Note: When this option is used, +find_in_collection+
+ # is _not_ added.
# [:counter_sql]
# Specify a complete SQL statement to fetch the size of the association. If <tt>:finder_sql</tt> is
- # specified but not <tt>:counter_sql</tt>, <tt>:counter_sql</tt> will be generated by replacing <tt>SELECT ... FROM</tt> with <tt>SELECT COUNT(*) FROM</tt>.
+ # specified but not <tt>:counter_sql</tt>, <tt>:counter_sql</tt> will be generated by
+ # replacing <tt>SELECT ... FROM</tt> with <tt>SELECT COUNT(*) FROM</tt>.
# [:extend]
# Specify a named module for extending the proxy. See "Association extensions".
# [:include]
@@ -866,25 +919,31 @@ module ActiveRecord
# [:group]
# An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
# [:having]
- # Combined with +:group+ this can be used to filter the records that a <tt>GROUP BY</tt> returns. Uses the <tt>HAVING</tt> SQL-clause.
+ # Combined with +:group+ this can be used to filter the records that a <tt>GROUP BY</tt>
+ # returns. Uses the <tt>HAVING</tt> SQL-clause.
# [:limit]
# An integer determining the limit on the number of rows that should be returned.
# [:offset]
- # An integer determining the offset from where the rows should be fetched. So at 5, it would skip the first 4 rows.
+ # An integer determining the offset from where the rows should be fetched. So at 5,
+ # it would skip the first 4 rows.
# [:select]
- # By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if you, for example, want to do a join
- # but not include the joined columns. Do not forget to include the primary and foreign keys, otherwise it will raise an error.
+ # By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if
+ # you, for example, want to do a join but not include the joined columns. Do not forget
+ # to include the primary and foreign keys, otherwise it will raise an error.
# [:as]
# Specifies a polymorphic interface (See <tt>belongs_to</tt>).
# [:through]
- # Specifies a join model through which to perform the query. Options for <tt>:class_name</tt> and <tt>:foreign_key</tt>
- # are ignored, as the association uses the source reflection. You can only use a <tt>:through</tt> query through a <tt>belongs_to</tt>
- # <tt>has_one</tt> or <tt>has_many</tt> association on the join model. The collection of join models can be managed via the collection
- # API. For example, new join models are created for newly associated objects, and if some are gone their rows are deleted (directly,
+ # Specifies a join model through which to perform the query. Options for <tt>:class_name</tt>
+ # and <tt>:foreign_key</tt> are ignored, as the association uses the source reflection. You
+ # can only use a <tt>:through</tt> query through a <tt>belongs_to</tt>, <tt>has_one</tt>
+ # or <tt>has_many</tt> association on the join model. The collection of join models
+ # can be managed via the collection API. For example, new join models are created for
+ # newly associated objects, and if some are gone their rows are deleted (directly,
# no destroy callbacks are triggered).
# [:source]
- # Specifies the source association name used by <tt>has_many :through</tt> queries. Only use it if the name cannot be
- # inferred from the association. <tt>has_many :subscribers, :through => :subscriptions</tt> will look for either <tt>:subscribers</tt> or
+ # Specifies the source association name used by <tt>has_many :through</tt> queries.
+ # Only use it if the name cannot be inferred from the association.
+ # <tt>has_many :subscribers, :through => :subscriptions</tt> will look for either <tt>:subscribers</tt> or
# <tt>:subscriber</tt> on Subscription, unless a <tt>:source</tt> is given.
# [:source_type]
# Specifies type of the source association used by <tt>has_many :through</tt> queries where the source
@@ -896,12 +955,14 @@ module ActiveRecord
# [:validate]
# If false, don't validate the associated objects when saving the parent object. true by default.
# [:autosave]
- # If true, always save the associated objects or destroy them if marked for destruction, when saving the parent object.
+ # If true, always save the associated objects or destroy them if marked for destruction,
+ # when saving the parent object.
# If false, never save or destroy the associated objects.
# By default, only save associated objects that are new records.
# [:inverse_of]
- # Specifies the name of the <tt>belongs_to</tt> association on the associated object that is the inverse of this <tt>has_many</tt>
- # association. Does not work in combination with <tt>:through</tt> or <tt>:as</tt> options.
+ # Specifies the name of the <tt>belongs_to</tt> association on the associated object
+ # that is the inverse of this <tt>has_many</tt> association. Does not work in combination
+ # with <tt>:through</tt> or <tt>:as</tt> options.
# See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
#
# Option examples:
@@ -975,19 +1036,20 @@ module ActiveRecord
# [:conditions]
# Specify the conditions that the associated object must meet in order to be included as a +WHERE+
# SQL fragment, such as <tt>rank = 5</tt>. Record creation from the association is scoped if a hash
- # is used. <tt>has_one :account, :conditions => {:enabled => true}</tt> will create an enabled account with <tt>@company.create_account</tt>
- # or <tt>@company.build_account</tt>.
+ # is used. <tt>has_one :account, :conditions => {:enabled => true}</tt> will create
+ # an enabled account with <tt>@company.create_account</tt> or <tt>@company.build_account</tt>.
# [:order]
# Specify the order in which the associated objects are returned as an <tt>ORDER BY</tt> SQL fragment,
# such as <tt>last_name, first_name DESC</tt>.
# [:dependent]
# If set to <tt>:destroy</tt>, the associated object is destroyed when this object is. If set to
- # <tt>:delete</tt>, the associated object is deleted *without* calling its destroy method. If set to <tt>:nullify</tt>, the associated
- # object's foreign key is set to +NULL+. Also, association is assigned.
+ # <tt>:delete</tt>, the associated object is deleted *without* calling its destroy method.
+ # If set to <tt>:nullify</tt>, the associated object's foreign key is set to +NULL+.
+ # Also, association is assigned.
# [:foreign_key]
# Specify the foreign key used for the association. By default this is guessed to be the name
- # of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_one+ association will use "person_id"
- # as the default <tt>:foreign_key</tt>.
+ # of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_one+ association
+ # will use "person_id" as the default <tt>:foreign_key</tt>.
# [:primary_key]
# Specify the method that returns the primary key used for the association. By default this is +id+.
# [:include]
@@ -995,15 +1057,18 @@ module ActiveRecord
# [:as]
# Specifies a polymorphic interface (See <tt>belongs_to</tt>).
# [:select]
- # By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if, for example, you want to do a join
- # but not include the joined columns. Do not forget to include the primary and foreign keys, otherwise it will raise an error.
+ # By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if, for example,
+ # you want to do a join but not include the joined columns. Do not forget to include the
+ # primary and foreign keys, otherwise it will raise an error.
# [:through]
- # Specifies a Join Model through which to perform the query. Options for <tt>:class_name</tt> and <tt>:foreign_key</tt>
- # are ignored, as the association uses the source reflection. You can only use a <tt>:through</tt> query through a
- # <tt>has_one</tt> or <tt>belongs_to</tt> association on the join model.
+ # Specifies a Join Model through which to perform the query. Options for <tt>:class_name</tt>
+ # and <tt>:foreign_key</tt> are ignored, as the association uses the source reflection. You
+ # can only use a <tt>:through</tt> query through a <tt>has_one</tt> or <tt>belongs_to</tt>
+ # association on the join model.
# [:source]
- # Specifies the source association name used by <tt>has_one :through</tt> queries. Only use it if the name cannot be
- # inferred from the association. <tt>has_one :favorite, :through => :favorites</tt> will look for a
+ # Specifies the source association name used by <tt>has_one :through</tt> queries.
+ # Only use it if the name cannot be inferred from the association.
+ # <tt>has_one :favorite, :through => :favorites</tt> will look for a
# <tt>:favorite</tt> on Favorite, unless a <tt>:source</tt> is given.
# [:source_type]
# Specifies type of the source association used by <tt>has_one :through</tt> queries where the source
@@ -1013,17 +1078,19 @@ module ActiveRecord
# [:validate]
# If false, don't validate the associated object when saving the parent object. +false+ by default.
# [:autosave]
- # If true, always save the associated object or destroy it if marked for destruction, when saving the parent object.
- # If false, never save or destroy the associated object.
+ # If true, always save the associated object or destroy it if marked for destruction,
+ # when saving the parent object. If false, never save or destroy the associated object.
# By default, only save the associated object if it's a new record.
# [:inverse_of]
- # Specifies the name of the <tt>belongs_to</tt> association on the associated object that is the inverse of this <tt>has_one</tt>
- # association. Does not work in combination with <tt>:through</tt> or <tt>:as</tt> options.
+ # Specifies the name of the <tt>belongs_to</tt> association on the associated object
+ # that is the inverse of this <tt>has_one</tt> association. Does not work in combination
+ # with <tt>:through</tt> or <tt>:as</tt> options.
# See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
#
# Option examples:
# has_one :credit_card, :dependent => :destroy # destroys the associated credit card
- # has_one :credit_card, :dependent => :nullify # updates the associated records foreign key value to NULL rather than destroying it
+ # has_one :credit_card, :dependent => :nullify # updates the associated records foreign
+ # # key value to NULL rather than destroying it
# has_one :last_comment, :class_name => "Comment", :order => "posted_on"
# has_one :project_manager, :class_name => "Person", :conditions => "role = 'project_manager'"
# has_one :attachment, :as => :attachable
@@ -1085,27 +1152,34 @@ module ActiveRecord
# Specify the conditions that the associated object must meet in order to be included as a +WHERE+
# SQL fragment, such as <tt>authorized = 1</tt>.
# [:select]
- # By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if, for example, you want to do a join
- # but not include the joined columns. Do not forget to include the primary and foreign keys, otherwise it will raise an error.
+ # By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed
+ # if, for example, you want to do a join but not include the joined columns. Do not
+ # forget to include the primary and foreign keys, otherwise it will raise an error.
# [:foreign_key]
# Specify the foreign key used for the association. By default this is guessed to be the name
- # of the association with an "_id" suffix. So a class that defines a <tt>belongs_to :person</tt> association will use
- # "person_id" as the default <tt>:foreign_key</tt>. Similarly, <tt>belongs_to :favorite_person, :class_name => "Person"</tt>
- # will use a foreign key of "favorite_person_id".
+ # of the association with an "_id" suffix. So a class that defines a <tt>belongs_to :person</tt>
+ # association will use "person_id" as the default <tt>:foreign_key</tt>. Similarly,
+ # <tt>belongs_to :favorite_person, :class_name => "Person"</tt> will use a foreign key
+ # of "favorite_person_id".
# [:primary_key]
- # Specify the method that returns the primary key of associated object used for the association. By default this is id.
+ # Specify the method that returns the primary key of associated object used for the association.
+ # By default this is id.
# [:dependent]
# If set to <tt>:destroy</tt>, the associated object is destroyed when this object is. If set to
- # <tt>:delete</tt>, the associated object is deleted *without* calling its destroy method. This option should not be specified when
- # <tt>belongs_to</tt> is used in conjunction with a <tt>has_many</tt> relationship on another class because of the potential to leave
+ # <tt>:delete</tt>, the associated object is deleted *without* calling its destroy method.
+ # This option should not be specified when <tt>belongs_to</tt> is used in conjunction with
+ # a <tt>has_many</tt> relationship on another class because of the potential to leave
# orphaned records behind.
# [:counter_cache]
# Caches the number of belonging objects on the associate class through the use of +increment_counter+
- # and +decrement_counter+. The counter cache is incremented when an object of this class is created and decremented when it's
- # destroyed. This requires that a column named <tt>#{table_name}_count</tt> (such as +comments_count+ for a belonging Comment class)
- # is used on the associate class (such as a Post class). You can also specify a custom counter cache column by providing
- # a column name instead of a +true+/+false+ value to this option (e.g., <tt>:counter_cache => :my_custom_counter</tt>.)
- # Note: Specifying a counter cache will add it to that model's list of readonly attributes using +attr_readonly+.
+ # and +decrement_counter+. The counter cache is incremented when an object of this
+ # class is created and decremented when it's destroyed. This requires that a column
+ # named <tt>#{table_name}_count</tt> (such as +comments_count+ for a belonging Comment class)
+ # is used on the associate class (such as a Post class). You can also specify a custom counter
+ # cache column by providing a column name instead of a +true+/+false+ value to this
+ # option (e.g., <tt>:counter_cache => :my_custom_counter</tt>.)
+ # Note: Specifying a counter cache will add it to that model's list of readonly attributes
+ # using +attr_readonly+.
# [:include]
# Specify second-order associations that should be eager loaded when this object is loaded.
# [:polymorphic]
@@ -1117,15 +1191,18 @@ module ActiveRecord
# [:validate]
# If false, don't validate the associated objects when saving the parent object. +false+ by default.
# [:autosave]
- # If true, always save the associated object or destroy it if marked for destruction, when saving the parent object.
+ # If true, always save the associated object or destroy it if marked for destruction, when
+ # saving the parent object.
# If false, never save or destroy the associated object.
# By default, only save the associated object if it's a new record.
# [:touch]
- # If true, the associated object will be touched (the updated_at/on attributes set to now) when this record is either saved or
- # destroyed. If you specify a symbol, that attribute will be updated with the current time instead of the updated_at/on attribute.
+ # If true, the associated object will be touched (the updated_at/on attributes set to now)
+ # when this record is either saved or destroyed. If you specify a symbol, that attribute
+ # will be updated with the current time instead of the updated_at/on attribute.
# [:inverse_of]
- # Specifies the name of the <tt>has_one</tt> or <tt>has_many</tt> association on the associated object that is the inverse of this <tt>belongs_to</tt>
- # association. Does not work in combination with the <tt>:polymorphic</tt> options.
+ # Specifies the name of the <tt>has_one</tt> or <tt>has_many</tt> association on the associated
+ # object that is the inverse of this <tt>belongs_to</tt> association. Does not work in
+ # combination with the <tt>:polymorphic</tt> options.
# See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
#
# Option examples:
@@ -1159,9 +1236,10 @@ module ActiveRecord
# Specifies a many-to-many relationship with another class. This associates two classes via an
# intermediate join table. Unless the join table is explicitly specified as an option, it is
# guessed using the lexical order of the class names. So a join between Developer and Project
- # will give the default join table name of "developers_projects" because "D" outranks "P". Note that this precedence
- # is calculated using the <tt><</tt> 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
+ # will give the default join table name of "developers_projects" because "D" outranks "P".
+ # Note that this precedence is calculated using the <tt><</tt> 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". Be aware of this caveat, and use the
@@ -1183,9 +1261,10 @@ module ActiveRecord
# end
# end
#
- # Deprecated: Any additional fields added to the join table will be placed as attributes when pulling records out through
- # +has_and_belongs_to_many+ associations. Records returned from join tables with additional attributes will be marked as
- # readonly (because we can't save changes to the additional attributes). It's strongly recommended that you upgrade any
+ # Deprecated: Any additional fields added to the join table will be placed as attributes when
+ # pulling records out through +has_and_belongs_to_many+ associations. Records returned from join
+ # tables with additional attributes will be marked as readonly (because we can't save changes
+ # to the additional attributes). It's strongly recommended that you upgrade any
# associations with attributes to a real join model (see introduction).
#
# Adds the following methods for retrieval and query:
@@ -1225,7 +1304,8 @@ module ActiveRecord
# with +attributes+ and linked to this object through the join table, but has not yet been saved.
# [collection.create(attributes = {})]
# Returns a new object of the collection type that has been instantiated
- # with +attributes+, linked to this object through the join table, and that has already been saved (if it passed the validation).
+ # with +attributes+, linked to this object through the join table, and that has already been
+ # saved (if it passed the validation).
#
# (+collection+ is replaced with the symbol passed as the first argument, so
# <tt>has_and_belongs_to_many :categories</tt> would add among others <tt>categories.empty?</tt>.)
@@ -1260,8 +1340,9 @@ module ActiveRecord
# MUST be declared underneath any +has_and_belongs_to_many+ declaration in order to work.
# [:foreign_key]
# Specify the foreign key used for the association. By default this is guessed to be the name
- # of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_and_belongs_to_many+ association
- # to Project will use "person_id" as the default <tt>:foreign_key</tt>.
+ # of this class in lower-case and "_id" suffixed. So a Person class that makes
+ # a +has_and_belongs_to_many+ association to Project will use "person_id" as the
+ # default <tt>:foreign_key</tt>.
# [:association_foreign_key]
# Specify the foreign key used for the association on the receiving side of the association.
# By default this is guessed to be the name of the associated class in lower-case and "_id" suffixed.
@@ -1269,7 +1350,8 @@ module ActiveRecord
# the association will use "project_id" as the default <tt>:association_foreign_key</tt>.
# [:conditions]
# Specify the conditions that the associated object must meet in order to be included as a +WHERE+
- # SQL fragment, such as <tt>authorized = 1</tt>. Record creations from the association are scoped if a hash is used.
+ # SQL fragment, such as <tt>authorized = 1</tt>. Record creations from the association are
+ # scoped if a hash is used.
# <tt>has_many :posts, :conditions => {:published => true}</tt> will create published posts with <tt>@blog.posts.create</tt>
# or <tt>@blog.posts.build</tt>.
# [:order]
@@ -1281,7 +1363,8 @@ module ActiveRecord
# Overwrite the default generated SQL statement used to fetch the association with a manual statement
# [:counter_sql]
# Specify a complete SQL statement to fetch the size of the association. If <tt>:finder_sql</tt> is
- # specified but not <tt>:counter_sql</tt>, <tt>:counter_sql</tt> will be generated by replacing <tt>SELECT ... FROM</tt> with <tt>SELECT COUNT(*) FROM</tt>.
+ # specified but not <tt>:counter_sql</tt>, <tt>:counter_sql</tt> will be generated by
+ # replacing <tt>SELECT ... FROM</tt> with <tt>SELECT COUNT(*) FROM</tt>.
# [:delete_sql]
# Overwrite the default generated SQL statement used to remove links between the associated
# classes with a manual statement.
@@ -1295,20 +1378,24 @@ module ActiveRecord
# [:group]
# An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
# [:having]
- # Combined with +:group+ this can be used to filter the records that a <tt>GROUP BY</tt> returns. Uses the <tt>HAVING</tt> SQL-clause.
+ # Combined with +:group+ this can be used to filter the records that a <tt>GROUP BY</tt> returns.
+ # Uses the <tt>HAVING</tt> SQL-clause.
# [:limit]
# An integer determining the limit on the number of rows that should be returned.
# [:offset]
- # An integer determining the offset from where the rows should be fetched. So at 5, it would skip the first 4 rows.
+ # An integer determining the offset from where the rows should be fetched. So at 5,
+ # it would skip the first 4 rows.
# [:select]
- # By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if, for example, you want to do a join
- # but not include the joined columns. Do not forget to include the primary and foreign keys, otherwise it will raise an error.
+ # By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if, for example,
+ # you want to do a join but not include the joined columns. Do not forget to include the primary
+ # and foreign keys, otherwise it will raise an error.
# [:readonly]
# If true, all the associated objects are readonly through the association.
# [:validate]
# If false, don't validate the associated objects when saving the parent object. +true+ by default.
# [:autosave]
- # If true, always save the associated objects or destroy them if marked for destruction, when saving the parent object.
+ # If true, always save the associated objects or destroy them if marked for destruction, when
+ # saving the parent object.
# If false, never save or destroy the associated objects.
# By default, only save associated objects that are new records.
#
@@ -1506,15 +1593,12 @@ module ActiveRecord
# Creates before_destroy callback methods that nullify, delete or destroy
# has_many associated objects, according to the defined :dependent rule.
- # If the association is marked as :dependent => :restrict, create a callback
- # that prevents deleting entirely.
#
- # See HasManyAssociation#delete_records. Dependent associations
- # delete children, otherwise foreign key is set to NULL.
- # See HasManyAssociation#delete_records. Dependent associations
- # delete children if the option is set to :destroy or :delete_all, set the
- # foreign key to NULL if the option is set to :nullify, and do not touch the
- # child records if the option is set to :restrict.
+ # See HasManyAssociation#delete_records for more information. In general
+ # - delete children if the option is set to :destroy or :delete_all
+ # - set the foreign key to NULL if the option is set to :nullify
+ # - do not delete the parent record if there is any child record if the
+ # option is set to :restrict
#
# The +extra_conditions+ parameter, which is not used within the main
# Active Record codebase, is meant to allow plugins to define extra
diff --git a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb
index e61af93d1e..bec123e7a2 100644
--- a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb
+++ b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb
@@ -106,9 +106,10 @@ module ActiveRecord
:limit => @reflection.options[:limit] } }
end
- # Join tables with additional columns on top of the two foreign keys must be considered ambiguous unless a select
- # clause has been explicitly defined. Otherwise you can get broken records back, if, for example, the join column also has
- # an id column. This will then overwrite the id column of the records coming back.
+ # Join tables with additional columns on top of the two foreign keys must be considered
+ # ambiguous unless a select clause has been explicitly defined. Otherwise you can get
+ # broken records back, if, for example, the join column also has an id column. This will
+ # then overwrite the id column of the records coming back.
def finding_with_ambiguous_select?(select_clause)
!select_clause && columns.size != 2
end
diff --git a/activerecord/lib/active_record/associations/has_many_association.rb b/activerecord/lib/active_record/associations/has_many_association.rb
index d74fb7c702..c33bc6aa47 100644
--- a/activerecord/lib/active_record/associations/has_many_association.rb
+++ b/activerecord/lib/active_record/associations/has_many_association.rb
@@ -24,7 +24,7 @@ module ActiveRecord
# If the association has a counter cache it gets that value. Otherwise
# it will attempt to do a count via SQL, bounded to <tt>:limit</tt> if
# there's one. Some configuration options like :group make it impossible
- # to do a SQL count, in those cases the array count will be used.
+ # to do an SQL count, in those cases the array count will be used.
#
# That does not depend on whether the collection has already been loaded
# or not. The +size+ method is the one that takes the loaded flag into
diff --git a/activerecord/lib/active_record/associations/has_many_through_association.rb b/activerecord/lib/active_record/associations/has_many_through_association.rb
index 17f850756f..608b1c741a 100644
--- a/activerecord/lib/active_record/associations/has_many_through_association.rb
+++ b/activerecord/lib/active_record/associations/has_many_through_association.rb
@@ -24,9 +24,10 @@ module ActiveRecord
end
end
- # Returns the size of the collection by executing a SELECT COUNT(*) query if the collection hasn't been loaded and
- # calling collection.size if it has. If it's more likely than not that the collection does have a size larger than zero,
- # and you need to fetch that collection afterwards, it'll take one fewer SELECT query if you use #length.
+ # Returns the size of the collection by executing a SELECT COUNT(*) query if the collection hasn't been
+ # loaded and calling collection.size if it has. If it's more likely than not that the collection does
+ # have a size larger than zero, and you need to fetch that collection afterwards, it'll take one fewer
+ # SELECT query if you use #length.
def size
return @owner.send(:read_attribute, cached_counter_attribute_name) if has_cached_counter?
return @target.size if loaded?
diff --git a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
index 783d61383b..8f0aacba42 100644
--- a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
+++ b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
@@ -14,7 +14,8 @@ module ActiveRecord
module ClassMethods
protected
# Defined for all +datetime+ and +timestamp+ attributes when +time_zone_aware_attributes+ are enabled.
- # This enhanced read method automatically converts the UTC time stored in the database to the time zone stored in Time.zone.
+ # This enhanced read method automatically converts the UTC time stored in the database to the time
+ # zone stored in Time.zone.
def define_method_attribute(attr_name)
if create_time_zone_conversion_attribute?(attr_name, columns_hash[attr_name])
method_body, line = <<-EOV, __LINE__ + 1
diff --git a/activerecord/lib/active_record/attribute_methods/write.rb b/activerecord/lib/active_record/attribute_methods/write.rb
index e31acac050..7a2de3bf80 100644
--- a/activerecord/lib/active_record/attribute_methods/write.rb
+++ b/activerecord/lib/active_record/attribute_methods/write.rb
@@ -14,8 +14,8 @@ module ActiveRecord
end
end
- # Updates the attribute identified by <tt>attr_name</tt> with the specified +value+. Empty strings for fixnum and float
- # columns are turned into +nil+.
+ # Updates the attribute identified by <tt>attr_name</tt> with the specified +value+. Empty strings
+ # for fixnum and float columns are turned into +nil+.
def write_attribute(attr_name, value)
attr_name = attr_name.to_s
attr_name = self.class.primary_key if attr_name == 'id'
diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb
index 062b010436..2c7afe3c9f 100644
--- a/activerecord/lib/active_record/autosave_association.rb
+++ b/activerecord/lib/active_record/autosave_association.rb
@@ -4,14 +4,13 @@ module ActiveRecord
# = Active Record Autosave Association
#
# AutosaveAssociation is a module that takes care of automatically saving
- # your associations when the parent is saved. In addition to saving, it
- # also destroys any associations that were marked for destruction.
+ # associacted records when parent is saved. In addition to saving, it
+ # also destroys any associated records that were marked for destruction.
# (See mark_for_destruction and marked_for_destruction?)
#
# Saving of the parent, its associations, and the destruction of marked
# associations, all happen inside 1 transaction. This should never leave the
- # database in an inconsistent state after, for instance, mass assigning
- # attributes and saving them.
+ # database in an inconsistent state.
#
# If validations for any of the associations fail, their error messages will
# be applied to the parent.
@@ -21,8 +20,6 @@ module ActiveRecord
#
# === One-to-one Example
#
- # Consider a Post model with one Author:
- #
# class Post
# has_one :author, :autosave => true
# end
@@ -155,11 +152,12 @@ module ActiveRecord
CODE
end
- # Adds a validate and save callback for the association as specified by
+ # Adds validation and save callbacks for the association as specified by
# the +reflection+.
#
- # For performance reasons, we don't check whether to validate at runtime,
- # but instead only define the method and callback when needed. However,
+ # For performance reasons, we don't check whether to validate at runtime.
+ # However the validation and callback methods are lazy and those methods
+ # get created when they are invoked for the very first time. However,
# this can change, for instance, when using nested attributes, which is
# called _after_ the association has been defined. Since we don't want
# the callbacks to get defined multiple times, there are guards that
@@ -197,14 +195,15 @@ module ActiveRecord
end
end
- # Reloads the attributes of the object as usual and removes a mark for destruction.
+ # Reloads the attributes of the object as usual and clears <tt>marked_for_destruction</tt> flag.
def reload(options = nil)
@marked_for_destruction = false
super
end
# Marks this record to be destroyed as part of the parents save transaction.
- # This does _not_ actually destroy the record yet, rather it will be destroyed when <tt>parent.save</tt> is called.
+ # This does _not_ actually destroy the record instantly, rather child record will be destroyed
+ # when <tt>parent.save</tt> is called.
#
# Only useful if the <tt>:autosave</tt> option on the parent is enabled for this associated model.
def mark_for_destruction
@@ -249,7 +248,7 @@ module ActiveRecord
end
# Validate the association if <tt>:validate</tt> or <tt>:autosave</tt> is
- # turned on for the association specified by +reflection+.
+ # turned on for the association.
def validate_single_association(reflection)
if (association = association_instance_get(reflection.name)) && !association.target.nil?
association_valid?(reflection, association)
@@ -357,14 +356,9 @@ module ActiveRecord
end
end
- # Saves the associated record if it's new or <tt>:autosave</tt> is enabled
- # on the association.
- #
- # In addition, it will destroy the association if it was marked for
- # destruction with mark_for_destruction.
+ # Saves the associated record if it's new or <tt>:autosave</tt> is enabled.
#
- # This all happens inside a transaction, _if_ the Transactions module is included into
- # ActiveRecord::Base after the AutosaveAssociation module, which it does by default.
+ # In addition, it will destroy the association if it was marked for destruction.
def save_belongs_to_association(reflection)
if (association = association_instance_get(reflection.name)) && !association.destroyed?
autosave = reflection.options[:autosave]
@@ -384,4 +378,4 @@ module ActiveRecord
end
end
end
-end \ No newline at end of file
+end
diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb
index 391c287fe4..8da4fbcba7 100644
--- a/activerecord/lib/active_record/base.rb
+++ b/activerecord/lib/active_record/base.rb
@@ -26,17 +26,19 @@ require 'active_record/log_subscriber'
module ActiveRecord #:nodoc:
# = Active Record
#
- # Active Record objects don't specify their attributes directly, but rather infer them from the table definition with
- # which they're linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change
- # is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain
+ # Active Record objects don't specify their attributes directly, but rather infer them from
+ # the table definition with which they're linked. Adding, removing, and changing attributes
+ # and their type is done directly in the database. Any change is instantly reflected in the
+ # Active Record objects. The mapping that binds a given Active Record class to a certain
# database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.
#
# See the mapping rules in table_name and the full example in link:files/README.html for more insight.
#
# == Creation
#
- # Active Records accept constructor parameters either in a hash or as a block. The hash method is especially useful when
- # you're receiving the data from somewhere else, like an HTTP request. It works like this:
+ # Active Records accept constructor parameters either in a hash or as a block. The hash
+ # method is especially useful when you're receiving the data from somewhere else, like an
+ # HTTP request. It works like this:
#
# user = User.new(:name => "David", :occupation => "Code Artist")
# user.name # => "David"
@@ -75,14 +77,17 @@ module ActiveRecord #:nodoc:
# end
# end
#
- # The <tt>authenticate_unsafely</tt> method inserts the parameters directly into the query and is thus susceptible to SQL-injection
- # attacks if the <tt>user_name</tt> and +password+ parameters come directly from an HTTP request. The <tt>authenticate_safely</tt> and
- # <tt>authenticate_safely_simply</tt> both will sanitize the <tt>user_name</tt> and +password+ before inserting them in the query,
- # which will ensure that an attacker can't escape the query and fake the login (or worse).
+ # The <tt>authenticate_unsafely</tt> method inserts the parameters directly into the query
+ # and is thus susceptible to SQL-injection attacks if the <tt>user_name</tt> and +password+
+ # parameters come directly from an HTTP request. The <tt>authenticate_safely</tt> and
+ # <tt>authenticate_safely_simply</tt> both will sanitize the <tt>user_name</tt> and +password+
+ # before inserting them in the query, which will ensure that an attacker can't escape the
+ # query and fake the login (or worse).
#
- # When using multiple parameters in the conditions, it can easily become hard to read exactly what the fourth or fifth
- # question mark is supposed to represent. In those cases, you can resort to named bind variables instead. That's done by replacing
- # the question marks with symbols and supplying a hash with values for the matching symbol keys:
+ # When using multiple parameters in the conditions, it can easily become hard to read exactly
+ # what the fourth or fifth question mark is supposed to represent. In those cases, you can
+ # resort to named bind variables instead. That's done by replacing the question marks with
+ # symbols and supplying a hash with values for the matching symbol keys:
#
# Company.where(
# "id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
@@ -103,18 +108,19 @@ module ActiveRecord #:nodoc:
#
# Student.where(:grade => [9,11,12])
#
- # When joining tables, nested hashes or keys written in the form 'table_name.column_name' can be used to qualify the table name of a
- # particular condition. For instance:
+ # When joining tables, nested hashes or keys written in the form 'table_name.column_name'
+ # can be used to qualify the table name of a particular condition. For instance:
#
# Student.joins(:schools).where(:schools => { :type => 'public' })
# Student.joins(:schools).where('schools.type' => 'public' )
#
# == Overwriting default accessors
#
- # All column values are automatically available through basic accessors on the Active Record object, but sometimes you
- # want to specialize this behavior. This can be done by overwriting the default accessors (using the same
- # name as the attribute) and calling <tt>read_attribute(attr_name)</tt> and <tt>write_attribute(attr_name, value)</tt> to actually change things.
- # Example:
+ # All column values are automatically available through basic accessors on the Active Record
+ # object, but sometimes you want to specialize this behavior. This can be done by overwriting
+ # the default accessors (using the same name as the attribute) and calling
+ # <tt>read_attribute(attr_name)</tt> and <tt>write_attribute(attr_name, value)</tt> to actually
+ # change things.
#
# class Song < ActiveRecord::Base
# # Uses an integer of seconds to hold the length of the song
@@ -128,8 +134,8 @@ module ActiveRecord #:nodoc:
# end
# end
#
- # You can alternatively use <tt>self[:attribute]=(value)</tt> and <tt>self[:attribute]</tt> instead of <tt>write_attribute(:attribute, value)</tt> and
- # <tt>read_attribute(:attribute)</tt> as a shorter form.
+ # You can alternatively use <tt>self[:attribute]=(value)</tt> and <tt>self[:attribute]</tt>
+ # instead of <tt>write_attribute(:attribute, value)</tt> and <tt>read_attribute(:attribute)</tt>.
#
# == Attribute query methods
#
@@ -147,34 +153,43 @@ module ActiveRecord #:nodoc:
#
# == Accessing attributes before they have been typecasted
#
- # Sometimes you want to be able to read the raw attribute data without having the column-determined typecast run its course first.
- # That can be done by using the <tt><attribute>_before_type_cast</tt> accessors that all attributes have. For example, if your Account model
- # has a <tt>balance</tt> attribute, you can call <tt>account.balance_before_type_cast</tt> or <tt>account.id_before_type_cast</tt>.
+ # Sometimes you want to be able to read the raw attribute data without having the column-determined
+ # typecast run its course first. That can be done by using the <tt><attribute>_before_type_cast</tt>
+ # accessors that all attributes have. For example, if your Account model has a <tt>balance</tt> attribute,
+ # you can call <tt>account.balance_before_type_cast</tt> or <tt>account.id_before_type_cast</tt>.
#
- # This is especially useful in validation situations where the user might supply a string for an integer field and you want to display
- # the original string back in an error message. Accessing the attribute normally would typecast the string to 0, which isn't what you
- # want.
+ # This is especially useful in validation situations where the user might supply a string for an
+ # integer field and you want to display the original string back in an error message. Accessing the
+ # attribute normally would typecast the string to 0, which isn't what you want.
#
# == Dynamic attribute-based finders
#
- # Dynamic attribute-based finders are a cleaner way of getting (and/or creating) objects by simple queries without turning to SQL. They work by
- # appending the name of an attribute to <tt>find_by_</tt>, <tt>find_last_by_</tt>, or <tt>find_all_by_</tt>, so you get finders like <tt>Person.find_by_user_name</tt>,
- # <tt>Person.find_all_by_last_name</tt>, and <tt>Payment.find_by_transaction_id</tt>. So instead of writing
+ # Dynamic attribute-based finders are a cleaner way of getting (and/or creating) objects
+ # by simple queries without turning to SQL. They work by appending the name of an attribute
+ # to <tt>find_by_</tt>, <tt>find_last_by_</tt>, or <tt>find_all_by_</tt> and thus produces finders
+ # like <tt>Person.find_by_user_name</tt>, <tt>Person.find_all_by_last_name</tt>, and
+ # <tt>Payment.find_by_transaction_id</tt>. Instead of writing
# <tt>Person.where(:user_name => user_name).first</tt>, you just do <tt>Person.find_by_user_name(user_name)</tt>.
- # And instead of writing <tt>Person.where(:last_name => last_name).all</tt>, you just do <tt>Person.find_all_by_last_name(last_name)</tt>.
+ # And instead of writing <tt>Person.where(:last_name => last_name).all</tt>, you just do
+ # <tt>Person.find_all_by_last_name(last_name)</tt>.
#
- # It's also possible to use multiple attributes in the same find by separating them with "_and_", so you get finders like
- # <tt>Person.find_by_user_name_and_password</tt> or even <tt>Payment.find_by_purchaser_and_state_and_country</tt>. So instead of writing
- # <tt>Person.where(:user_name => user_name, :password => password).first</tt>, you just do
- # <tt>Person.find_by_user_name_and_password(user_name, password)</tt>.
+ # It's also possible to use multiple attributes in the same find by separating them with "_and_".
+ #
+ # Person.where(:user_name => user_name, :password => password).first
+ # Person.find_by_user_name_and_password #with dynamic finder
+ #
+ # Person.where(:user_name => user_name, :password => password, :gender => 'male').first
+ # Payment.find_by_user_name_and_password_and_gender
#
- # It's even possible to call these dynamic finder methods on relations and named scopes. For example :
+ # It's even possible to call these dynamic finder methods on relations and named scopes.
#
# Payment.order("created_on").find_all_by_amount(50)
# Payment.pending.find_last_by_amount(100)
#
- # The same dynamic finder style can be used to create the object if it doesn't already exist. This dynamic finder is called with
- # <tt>find_or_create_by_</tt> and will return the object if it already exists and otherwise creates it, then returns it. Protected attributes won't be set unless they are given in a block. For example:
+ # The same dynamic finder style can be used to create the object if it doesn't already exist.
+ # This dynamic finder is called with <tt>find_or_create_by_</tt> and will return the object if
+ # it already exists and otherwise creates it, then returns it. Protected attributes won't be set
+ # unless they are given in a block.
#
# # No 'Summer' tag exists
# Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer")
@@ -185,23 +200,33 @@ module ActiveRecord #:nodoc:
# # Now 'Bob' exist and is an 'admin'
# User.find_or_create_by_name('Bob', :age => 40) { |u| u.admin = true }
#
- # Use the <tt>find_or_initialize_by_</tt> finder if you want to return a new record without saving it first. Protected attributes won't be set unless they are given in a block. For example:
+ # Use the <tt>find_or_initialize_by_</tt> finder if you want to return a new record without
+ # saving it first. Protected attributes won't be set unless they are given in a block.
#
# # No 'Winter' tag exists
# winter = Tag.find_or_initialize_by_name("Winter")
# winter.new_record? # true
#
# To find by a subset of the attributes to be used for instantiating a new object, pass a hash instead of
- # a list of parameters. For example:
+ # a list of parameters.
#
# Tag.find_or_create_by_name(:name => "rails", :creator => current_user)
#
- # That will either find an existing tag named "rails", or create a new one while setting the user that created it.
+ # That will either find an existing tag named "rails", or create a new one while setting the
+ # user that created it.
+ #
+ # Just like <tt>find_by_*</tt>, you can also use <tt>scoped_by_*</tt> to retrieve data. The good thing about
+ # using this feature is that the very first time result is returned using <tt>method_missing</tt> technique
+ # but after that the method is declared on the class. Henceforth <tt>method_missing</tt> will not be hit.
+ #
+ # User.scoped_by_user_name('David')
#
# == Saving arrays, hashes, and other non-mappable objects in text columns
#
- # Active Record can serialize any object in text columns using YAML. To do so, you must specify this with a call to the class method +serialize+.
- # This makes it possible to store arrays, hashes, and other non-mappable objects without doing any additional work. Example:
+ # Active Record can serialize any object in text columns using YAML. To do so, you must
+ # specify this with a call to the class method +serialize+.
+ # This makes it possible to store arrays, hashes, and other non-mappable objects without doing
+ # any additional work.
#
# class User < ActiveRecord::Base
# serialize :preferences
@@ -210,8 +235,8 @@ module ActiveRecord #:nodoc:
# user = User.create(:preferences => { "background" => "black", "display" => large })
# User.find(user.id).preferences # => { "background" => "black", "display" => large }
#
- # You can also specify a class option as the second parameter that'll raise an exception if a serialized object is retrieved as a
- # descendant of a class not in the hierarchy. Example:
+ # You can also specify a class option as the second parameter that'll raise an exception
+ # if a serialized object is retrieved as a descendant of a class not in the hierarchy.
#
# class User < ActiveRecord::Base
# serialize :preferences, Hash
@@ -222,52 +247,63 @@ module ActiveRecord #:nodoc:
#
# == Single table inheritance
#
- # Active Record allows inheritance by storing the name of the class in a column that by default is named "type" (can be changed
- # by overwriting <tt>Base.inheritance_column</tt>). This means that an inheritance looking like this:
+ # Active Record allows inheritance by storing the name of the class in a column that by
+ # default is named "type" (can be changed by overwriting <tt>Base.inheritance_column</tt>).
+ # This means that an inheritance looking like this:
#
# class Company < ActiveRecord::Base; end
# class Firm < Company; end
# class Client < Company; end
# class PriorityClient < Client; end
#
- # When you do <tt>Firm.create(:name => "37signals")</tt>, this record will be saved in the companies table with type = "Firm". You can then
- # fetch this row again using <tt>Company.where(:name => '37signals').first</tt> and it will return a Firm object.
+ # When you do <tt>Firm.create(:name => "37signals")</tt>, this record will be saved in
+ # the companies table with type = "Firm". You can then fetch this row again using
+ # <tt>Company.where(:name => '37signals').first</tt> and it will return a Firm object.
#
- # If you don't have a type column defined in your table, single-table inheritance won't be triggered. In that case, it'll work just
- # like normal subclasses with no special magic for differentiating between them or reloading the right type with find.
+ # If you don't have a type column defined in your table, single-table inheritance won't
+ # be triggered. In that case, it'll work just like normal subclasses with no special magic
+ # for differentiating between them or reloading the right type with find.
#
# Note, all the attributes for all the cases are kept in the same table. Read more:
# http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html
#
# == Connection to multiple databases in different models
#
- # Connections are usually created through ActiveRecord::Base.establish_connection and retrieved by ActiveRecord::Base.connection.
- # All classes inheriting from ActiveRecord::Base will use this connection. But you can also set a class-specific connection.
- # For example, if Course is an ActiveRecord::Base, but resides in a different database, you can just say <tt>Course.establish_connection</tt>
+ # Connections are usually created through ActiveRecord::Base.establish_connection and retrieved
+ # by ActiveRecord::Base.connection. All classes inheriting from ActiveRecord::Base will use this
+ # connection. But you can also set a class-specific connection. For example, if Course is an
+ # ActiveRecord::Base, but resides in a different database, you can just say <tt>Course.establish_connection</tt>
# and Course and all of its subclasses will use this connection instead.
#
- # This feature is implemented by keeping a connection pool in ActiveRecord::Base that is a Hash indexed by the class. If a connection is
- # requested, the retrieve_connection method will go up the class-hierarchy until a connection is found in the connection pool.
+ # This feature is implemented by keeping a connection pool in ActiveRecord::Base that is
+ # a Hash indexed by the class. If a connection is requested, the retrieve_connection method
+ # will go up the class-hierarchy until a connection is found in the connection pool.
#
# == Exceptions
#
# * ActiveRecordError - Generic error class and superclass of all other errors raised by Active Record.
# * AdapterNotSpecified - The configuration hash used in <tt>establish_connection</tt> didn't include an
# <tt>:adapter</tt> key.
- # * AdapterNotFound - The <tt>:adapter</tt> key used in <tt>establish_connection</tt> specified a non-existent adapter
+ # * AdapterNotFound - The <tt>:adapter</tt> key used in <tt>establish_connection</tt> specified a
+ # non-existent adapter
# (or a bad spelling of an existing one).
- # * AssociationTypeMismatch - The object assigned to the association wasn't of the type specified in the association definition.
+ # * AssociationTypeMismatch - The object assigned to the association wasn't of the type
+ # specified in the association definition.
# * SerializationTypeMismatch - The serialized object wasn't of the class specified as the second parameter.
- # * ConnectionNotEstablished+ - No connection has been established. Use <tt>establish_connection</tt> before querying.
+ # * ConnectionNotEstablished+ - No connection has been established. Use <tt>establish_connection</tt>
+ # before querying.
# * RecordNotFound - No record responded to the +find+ method. Either the row with the given ID doesn't exist
# or the row didn't meet the additional restrictions. Some +find+ calls do not raise this exception to signal
# nothing was found, please check its documentation for further details.
# * StatementInvalid - The database server rejected the SQL statement. The precise error is added in the message.
# * MultiparameterAssignmentErrors - Collection of errors that occurred during a mass assignment using the
- # <tt>attributes=</tt> method. The +errors+ property of this exception contains an array of AttributeAssignmentError
+ # <tt>attributes=</tt> method. The +errors+ property of this exception contains an array of
+ # AttributeAssignmentError
# objects that should be inspected to determine which attributes triggered the errors.
- # * AttributeAssignmentError - An error occurred while doing a mass assignment through the <tt>attributes=</tt> method.
- # You can inspect the +attribute+ property of the exception object to determine which attribute triggered the error.
+ # * AttributeAssignmentError - An error occurred while doing a mass assignment through the
+ # <tt>attributes=</tt> method.
+ # You can inspect the +attribute+ property of the exception object to determine which attribute
+ # triggered the error.
#
# *Note*: The attributes listed are class-level attributes (accessible from both the class and instance level).
# So it's possible to assign a logger to the class through <tt>Base.logger=</tt> which will then be used by all
@@ -275,8 +311,9 @@ module ActiveRecord #:nodoc:
class Base
##
# :singleton-method:
- # Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then passed
- # on to any new database connections made and which can be retrieved on both a class and instance level by calling +logger+.
+ # Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class,
+ # which is then passed on to any new database connections made and which can be retrieved on both
+ # a class and instance level by calling +logger+.
cattr_accessor :logger, :instance_writer => false
class << self
@@ -323,21 +360,24 @@ module ActiveRecord #:nodoc:
##
# :singleton-method:
- # Accessor for the prefix type that will be prepended to every primary key column name. The options are :table_name and
- # :table_name_with_underscore. If the first is specified, the Product class will look for "productid" instead of "id" as
- # the primary column. If the latter is specified, the Product class will look for "product_id" instead of "id". Remember
+ # Accessor for the prefix type that will be prepended to every primary key column name.
+ # The options are :table_name and :table_name_with_underscore. If the first is specified,
+ # the Product class will look for "productid" instead of "id" as the primary column. If the
+ # latter is specified, the Product class will look for "product_id" instead of "id". Remember
# that this is a global setting for all Active Records.
cattr_accessor :primary_key_prefix_type, :instance_writer => false
@@primary_key_prefix_type = nil
##
# :singleton-method:
- # Accessor for the name of the prefix string to prepend to every table name. So if set to "basecamp_", all
- # table names will be named like "basecamp_projects", "basecamp_people", etc. This is a convenient way of creating a namespace
- # for tables in a shared database. By default, the prefix is the empty string.
+ # Accessor for the name of the prefix string to prepend to every table name. So if set
+ # to "basecamp_", all table names will be named like "basecamp_projects", "basecamp_people",
+ # etc. This is a convenient way of creating a namespace for tables in a shared database.
+ # By default, the prefix is the empty string.
#
- # If you are organising your models within modules you can add a prefix to the models within a namespace by defining
- # a singleton method in the parent module called table_name_prefix which returns your chosen prefix.
+ # If you are organising your models within modules you can add a prefix to the models within
+ # a namespace by defining a singleton method in the parent module called table_name_prefix which
+ # returns your chosen prefix.
class_attribute :table_name_prefix, :instance_writer => false
self.table_name_prefix = ""
@@ -358,8 +398,8 @@ module ActiveRecord #:nodoc:
##
# :singleton-method:
- # Determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling dates and times from the database.
- # This is set to :local by default.
+ # Determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling
+ # dates and times from the database. This is set to :local by default.
cattr_accessor :default_timezone, :instance_writer => false
@@default_timezone = :local
@@ -476,7 +516,8 @@ module ActiveRecord #:nodoc:
connection.select_value(sql, "#{name} Count").to_i
end
- # Attributes listed as readonly can be set for a new record, but will be ignored in database updates afterwards.
+ # Attributes listed as readonly will be used to create a new record but update operations will
+ # ignore these fields.
def attr_readonly(*attributes)
write_inheritable_attribute(:attr_readonly, Set.new(attributes.map(&:to_s)) + (readonly_attributes || []))
end
@@ -505,15 +546,18 @@ module ActiveRecord #:nodoc:
serialized_attributes[attr_name.to_s] = class_name
end
- # Returns a hash of all the attributes that have been specified for serialization as keys and their class restriction as values.
+ # Returns a hash of all the attributes that have been specified for serialization as
+ # keys and their class restriction as values.
def serialized_attributes
read_inheritable_attribute(:attr_serialized) or write_inheritable_attribute(:attr_serialized, {})
end
- # Guesses the table name (in forced lower-case) based on the name of the class in the inheritance hierarchy descending
- # directly from ActiveRecord::Base. So if the hierarchy looks like: Reply < Message < ActiveRecord::Base, then Message is used
- # to guess the table name even when called on Reply. The rules used to do the guess are handled by the Inflector class
- # in Active Support, which knows almost all common English inflections. You can add new inflections in config/initializers/inflections.rb.
+ # Guesses the table name (in forced lower-case) based on the name of the class in the
+ # inheritance hierarchy descending directly from ActiveRecord::Base. So if the hierarchy
+ # looks like: Reply < Message < ActiveRecord::Base, then Message is used
+ # to guess the table name even when called on Reply. The rules used to do the guess
+ # are handled by the Inflector class in Active Support, which knows almost all common
+ # English inflections. You can add new inflections in config/initializers/inflections.rb.
#
# Nested classes are given table names prefixed by the singular form of
# the parent's table name. Enclosing modules are not considered.
@@ -561,8 +605,8 @@ module ActiveRecord #:nodoc:
(parents.detect{ |p| p.respond_to?(:table_name_prefix) } || self).table_name_prefix
end
- # Defines the column name for use with single table inheritance
- # -- can be set in subclasses like so: self.inheritance_column = "type_id"
+ # Defines the column name for use with single table inheritance. Use
+ # <tt>set_inheritance_column</tt> to set a different value.
def inheritance_column
@inheritance_column ||= "type".freeze
end
@@ -579,8 +623,8 @@ module ActiveRecord #:nodoc:
default
end
- # Sets the table name to use to the given value, or (if the value
- # is nil or false) to the value returned by the given block.
+ # Sets the table name. If the value is nil or false then the value returned by the given
+ # block is used.
#
# class Project < ActiveRecord::Base
# set_table_name "project"
@@ -923,15 +967,15 @@ module ActiveRecord #:nodoc:
end
end
- # Enables dynamic finders like <tt>find_by_user_name(user_name)</tt> and <tt>find_by_user_name_and_password(user_name, password)</tt>
- # that are turned into <tt>where(:user_name => user_name).first</tt> and <tt>where(:user_name => user_name, :password => :password).first</tt>
- # respectively. Also works for <tt>all</tt> by using <tt>find_all_by_amount(50)</tt> that is turned into <tt>where(:amount => 50).all</tt>.
+ # Enables dynamic finders like <tt>User.find_by_user_name(user_name)</tt> and
+ # <tt>User.scoped_by_user_name(user_name). Refer to Dynamic attribute-based finders
+ # section at the top of this file for more detailed information.
#
- # It's even possible to use all the additional parameters to +find+. For example, the full interface for +find_all_by_amount+
- # is actually <tt>find_all_by_amount(amount, options)</tt>.
+ # It's even possible to use all the additional parameters to +find+. For example, the
+ # full interface for +find_all_by_amount+ is actually <tt>find_all_by_amount(amount, options)</tt>.
#
- # Each dynamic finder, scope or initializer/creator is also defined in the class after it is first invoked, so that future
- # attempts to use it do not run through method_missing.
+ # Each dynamic finder using <tt>scoped_by_*</tt> is also defined in the class after it
+ # is first invoked, so that future attempts to use it do not run through method_missing.
def method_missing(method_id, *arguments, &block)
if match = DynamicFinderMatch.match(method_id)
attribute_names = match.attribute_names
@@ -991,8 +1035,8 @@ module ActiveRecord #:nodoc:
end
protected
- # Scope parameters to method calls within the block. Takes a hash of method_name => parameters hash.
- # method_name may be <tt>:find</tt> or <tt>:create</tt>. <tt>:find</tt> parameter is <tt>Relation</tt> while
+ # with_scope lets you apply options to inner block incrementally. It takes a hash and the keys must be
+ # <tt>:find</tt> or <tt>:create</tt>. <tt>:find</tt> parameter is <tt>Relation</tt> while
# <tt>:create</tt> parameters are an attributes hash.
#
# class Article < ActiveRecord::Base
@@ -1037,8 +1081,7 @@ module ActiveRecord #:nodoc:
# end
# end
#
- # *Note*: the +:find+ scope also has effect on update and deletion methods,
- # like +update_all+ and +delete_all+.
+ # *Note*: the +:find+ scope also has effect on update and deletion methods, like +update_all+ and +delete_all+.
def with_scope(method_scoping = {}, action = :merge, &block)
method_scoping = method_scoping.method_scoping if method_scoping.respond_to?(:method_scoping)
@@ -1357,7 +1400,7 @@ MSG
# as it copies the object's attributes only, not its associations. The extent of a "deep" clone is
# application specific and is therefore left to the application to implement according to its need.
def initialize_copy(other)
- callback(:after_initialize) if respond_to_without_attributes?(:after_initialize)
+ _run_after_initialize_callbacks if respond_to?(:_run_after_initialize_callbacks)
cloned_attributes = other.clone_attributes(:read_attribute_before_type_cast)
cloned_attributes.delete(self.class.primary_key)
@@ -1607,10 +1650,11 @@ MSG
private
- # Sets the attribute used for single table inheritance to this class name if this is not the ActiveRecord::Base descendant.
- # Considering the hierarchy Reply < Message < ActiveRecord::Base, this makes it possible to do Reply.new without having to
- # set <tt>Reply[Reply.inheritance_column] = "Reply"</tt> yourself. No such attribute would be set for objects of the
- # Message class in that example.
+ # Sets the attribute used for single table inheritance to this class name if this is not the
+ # ActiveRecord::Base descendant.
+ # Considering the hierarchy Reply < Message < ActiveRecord::Base, this makes it possible to
+ # do Reply.new without having to set <tt>Reply[Reply.inheritance_column] = "Reply"</tt> yourself.
+ # No such attribute would be set for objects of the Message class in that example.
def ensure_proper_type
unless self.class.descends_from_active_record?
write_attribute(self.class.inheritance_column, self.class.sti_name)
@@ -1659,8 +1703,9 @@ MSG
# by calling new on the column type or aggregation type (through composed_of) object with these parameters.
# So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate
# written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the
- # parentheses to have the parameters typecasted before they're used in the constructor. Use i for Fixnum, f for Float,
- # s for String, and a for Array. If all the values for a given attribute are empty, the attribute will be set to nil.
+ # parentheses to have the parameters typecasted before they're used in the constructor. Use i for Fixnum,
+ # f for Float, s for String, and a for Array. If all the values for a given attribute are empty, the
+ # attribute will be set to nil.
def assign_multiparameter_attributes(pairs)
execute_callstack_for_multiparameter_attributes(
extract_callstack_for_multiparameter_attributes(pairs)
diff --git a/activerecord/lib/active_record/callbacks.rb b/activerecord/lib/active_record/callbacks.rb
index 82c45a41b0..aa92bf999f 100644
--- a/activerecord/lib/active_record/callbacks.rb
+++ b/activerecord/lib/active_record/callbacks.rb
@@ -26,8 +26,8 @@ module ActiveRecord
# <tt>after_rollback</tt>.
#
# That's a total of ten callbacks, which gives you immense power to react and prepare for each state in the
- # Active Record lifecycle. The sequence for calling <tt>Base#save</tt> for an existing record is similar, except that each
- # <tt>_on_create</tt> callback is replaced by the corresponding <tt>_on_update</tt> callback.
+ # Active Record lifecycle. The sequence for calling <tt>Base#save</tt> for an existing record is similar,
+ # except that each <tt>_on_create</tt> callback is replaced by the corresponding <tt>_on_update</tt> callback.
#
# Examples:
# class CreditCard < ActiveRecord::Base
@@ -55,9 +55,9 @@ module ActiveRecord
#
# == Inheritable callback queues
#
- # Besides the overwritable callback methods, it's also possible to register callbacks through the use of the callback macros.
- # Their main advantage is that the macros add behavior into a callback queue that is kept intact down through an inheritance
- # hierarchy. Example:
+ # Besides the overwritable callback methods, it's also possible to register callbacks through the
+ # use of the callback macros. Their main advantage is that the macros add behavior into a callback
+ # queue that is kept intact down through an inheritance hierarchy.
#
# class Topic < ActiveRecord::Base
# before_destroy :destroy_author
@@ -67,9 +67,9 @@ module ActiveRecord
# before_destroy :destroy_readers
# end
#
- # Now, when <tt>Topic#destroy</tt> is run only +destroy_author+ is called. When <tt>Reply#destroy</tt> is run, both +destroy_author+ and
- # +destroy_readers+ are called. Contrast this to the situation where we've implemented the save behavior through overwriteable
- # methods:
+ # Now, when <tt>Topic#destroy</tt> is run only +destroy_author+ is called. When <tt>Reply#destroy</tt> is
+ # run, both +destroy_author+ and +destroy_readers+ are called. Contrast this to the following situation
+ # where the +before_destroy+ methis is overriden:
#
# class Topic < ActiveRecord::Base
# def before_destroy() destroy_author end
@@ -79,20 +79,21 @@ module ActiveRecord
# def before_destroy() destroy_readers end
# end
#
- # In that case, <tt>Reply#destroy</tt> would only run +destroy_readers+ and _not_ +destroy_author+. So, use the callback macros when
- # you want to ensure that a certain callback is called for the entire hierarchy, and use the regular overwriteable methods
- # when you want to leave it up to each descendant to decide whether they want to call +super+ and trigger the inherited callbacks.
+ # In that case, <tt>Reply#destroy</tt> would only run +destroy_readers+ and _not_ +destroy_author+.
+ # So, use the callback macros when you want to ensure that a certain callback is called for the entire
+ # hierarchy, and use the regular overwriteable methods when you want to leave it up to each descendant
+ # to decide whether they want to call +super+ and trigger the inherited callbacks.
#
- # *IMPORTANT:* In order for inheritance to work for the callback queues, you must specify the callbacks before specifying the
- # associations. Otherwise, you might trigger the loading of a child before the parent has registered the callbacks and they won't
- # be inherited.
+ # *IMPORTANT:* In order for inheritance to work for the callback queues, you must specify the
+ # callbacks before specifying the associations. Otherwise, you might trigger the loading of a
+ # child before the parent has registered the callbacks and they won't be inherited.
#
# == Types of callbacks
#
# There are four types of callbacks accepted by the callback macros: Method references (symbol), callback objects,
- # inline methods (using a proc), and inline eval methods (using a string). Method references and callback objects are the
- # recommended approaches, inline methods using a proc are sometimes appropriate (such as for creating mix-ins), and inline
- # eval methods are deprecated.
+ # inline methods (using a proc), and inline eval methods (using a string). Method references and callback objects
+ # are the recommended approaches, inline methods using a proc are sometimes appropriate (such as for
+ # creating mix-ins), and inline eval methods are deprecated.
#
# The method reference callbacks work by specifying a protected or private method available in the object, like this:
#
@@ -169,15 +170,15 @@ module ActiveRecord
# end
# end
#
- # The callback macros usually accept a symbol for the method they're supposed to run, but you can also pass a "method string",
- # which will then be evaluated within the binding of the callback. Example:
+ # The callback macros usually accept a symbol for the method they're supposed to run, but you can also
+ # pass a "method string", which will then be evaluated within the binding of the callback. Example:
#
# class Topic < ActiveRecord::Base
# before_destroy 'self.class.delete_all "parent_id = #{id}"'
# end
#
- # Notice that single quotes (') are used so the <tt>#{id}</tt> part isn't evaluated until the callback is triggered. Also note that these
- # inline callbacks can be stacked just like the regular ones:
+ # Notice that single quotes (') are used so the <tt>#{id}</tt> part isn't evaluated until the callback
+ # is triggered. Also note that these inline callbacks can be stacked just like the regular ones:
#
# class Topic < ActiveRecord::Base
# before_destroy 'self.class.delete_all "parent_id = #{id}"',
@@ -186,22 +187,24 @@ module ActiveRecord
#
# == The +after_find+ and +after_initialize+ exceptions
#
- # Because +after_find+ and +after_initialize+ are called for each object found and instantiated by a finder, such as <tt>Base.find(:all)</tt>, we've had
- # to implement a simple performance constraint (50% more speed on a simple test case). Unlike all the other callbacks, +after_find+ and
- # +after_initialize+ will only be run if an explicit implementation is defined (<tt>def after_find</tt>). In that case, all of the
+ # Because +after_find+ and +after_initialize+ are called for each object found and instantiated by a finder,
+ # such as <tt>Base.find(:all)</tt>, we've had to implement a simple performance constraint (50% more speed
+ # on a simple test case). Unlike all the other callbacks, +after_find+ and +after_initialize+ will only be
+ # run if an explicit implementation is defined (<tt>def after_find</tt>). In that case, all of the
# callback types will be called.
#
# == <tt>before_validation*</tt> returning statements
#
- # If the returning value of a +before_validation+ callback can be evaluated to +false+, the process will be aborted and <tt>Base#save</tt> will return +false+.
- # If Base#save! is called it will raise a ActiveRecord::RecordInvalid exception.
- # Nothing will be appended to the errors object.
+ # If the returning value of a +before_validation+ callback can be evaluated to +false+, the process will be
+ # aborted and <tt>Base#save</tt> will return +false+. If Base#save! is called it will raise a
+ # ActiveRecord::RecordInvalid exception. Nothing will be appended to the errors object.
#
# == Canceling callbacks
#
- # If a <tt>before_*</tt> callback returns +false+, all the later callbacks and the associated action are cancelled. If an <tt>after_*</tt> callback returns
- # +false+, all the later callbacks are cancelled. Callbacks are generally run in the order they are defined, with the exception of callbacks
- # defined as methods on the model, which are called last.
+ # If a <tt>before_*</tt> callback returns +false+, all the later callbacks and the associated action are
+ # cancelled. If an <tt>after_*</tt> callback returns +false+, all the later callbacks are cancelled.
+ # Callbacks are generally run in the order they are defined, with the exception of callbacks defined as
+ # methods on the model, which are called last.
#
# == Transactions
#
@@ -217,7 +220,8 @@ module ActiveRecord
#
# == Debugging callbacks
#
- # To list the methods and procs registered with a particular callback, append <tt>_callback_chain</tt> to the callback name that you wish to list and send that to your class from the Rails console:
+ # To list the methods and procs registered with a particular callback, append <tt>_callback_chain</tt> to
+ # the callback name that you wish to list and send that to your class from the Rails console:
#
# >> Topic.after_save_callback_chain
# => [#<ActiveSupport::Callbacks::Callback:0x3f6a448
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
index 9d0251dda3..02a8f4e214 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
@@ -103,8 +103,8 @@ module ActiveRecord
# Signal that the thread is finished with the current connection.
# #release_connection releases the connection-thread association
# and returns the connection to the pool.
- def release_connection
- conn = @reserved_connections.delete(current_connection_id)
+ def release_connection(with_id = current_connection_id)
+ conn = @reserved_connections.delete(with_id)
checkin conn if conn
end
@@ -112,10 +112,11 @@ module ActiveRecord
# exists checkout a connection, yield it to the block, and checkin the
# connection when finished.
def with_connection
- fresh_connection = true unless @reserved_connections[current_connection_id]
+ connection_id = current_connection_id
+ fresh_connection = true unless @reserved_connections[connection_id]
yield connection
ensure
- release_connection if fresh_connection
+ release_connection(connection_id) if fresh_connection
end
# Returns true if a connection has already been opened.
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/database_limits.rb b/activerecord/lib/active_record/connection_adapters/abstract/database_limits.rb
index 4118ea7b31..a130c330dd 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/database_limits.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/database_limits.rb
@@ -42,7 +42,7 @@ module ActiveRecord
65535
end
- # the maximum length of a SQL query
+ # the maximum length of an SQL query
def sql_query_length
1048575
end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb b/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb
index d7b5bf8e31..e2b3773a99 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb
@@ -30,7 +30,7 @@ module ActiveRecord
if value.acts_like?(:date) || value.acts_like?(:time)
"'#{quoted_date(value)}'"
else
- "'#{quote_string(value.to_yaml)}'"
+ "'#{quote_string(value.to_s)}'"
end
end
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 7691b6a788..9118ceb33c 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
@@ -23,7 +23,8 @@ module ActiveRecord
#
# +name+ is the column's name, such as <tt>supplier_id</tt> in <tt>supplier_id int(11)</tt>.
# +default+ is the type-casted default value, such as +new+ in <tt>sales_stage varchar(20) default 'new'</tt>.
- # +sql_type+ is used to extract the column's length, if necessary. For example +60+ in <tt>company_name varchar(60)</tt>.
+ # +sql_type+ is used to extract the column's length, if necessary. For example +60+ in
+ # <tt>company_name varchar(60)</tt>.
# It will be mapped to one of the standard Rails SQL types in the <tt>type</tt> attribute.
# +null+ determines if this column allows +NULL+ values.
def initialize(name, default, sql_type = nil, null = true)
@@ -359,7 +360,8 @@ module ActiveRecord
#
# Available options are (none of these exists by default):
# * <tt>:limit</tt> -
- # Requests a maximum column length. This is number of characters for <tt>:string</tt> and <tt>:text</tt> columns and number of bytes for :binary and :integer columns.
+ # Requests a maximum column length. This is number of characters for <tt>:string</tt> and
+ # <tt>:text</tt> columns and number of bytes for :binary and :integer columns.
# * <tt>:default</tt> -
# The column's default value. Use nil for NULL.
# * <tt>:null</tt> -
@@ -462,8 +464,8 @@ module ActiveRecord
# TableDefinition#timestamps that'll add created_at and +updated_at+ as datetimes.
#
# TableDefinition#references will add an appropriately-named _id column, plus a corresponding _type
- # column if the <tt>:polymorphic</tt> option is supplied. If <tt>:polymorphic</tt> is a hash of options, these will be
- # used when creating the <tt>_type</tt> column. So what can be written like this:
+ # column if the <tt>:polymorphic</tt> option is supplied. If <tt>:polymorphic</tt> is a hash of
+ # options, these will be used when creating the <tt>_type</tt> column. So what can be written like this:
#
# create_table :taggings do |t|
# t.integer :tag_id, :tagger_id, :taggable_id
@@ -535,7 +537,7 @@ module ActiveRecord
end
end
- # Represents a SQL table in an abstract way for updating a table.
+ # Represents an SQL table in an abstract way for updating a table.
# Also see TableDefinition and SchemaStatements#create_table
#
# Available transformations are:
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
index ffc3847a31..7dee68502f 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
@@ -327,6 +327,8 @@ module ActiveRecord
#
# Note: SQLite doesn't support index length
def add_index(table_name, column_name, options = {})
+ options[:name] = options[:name].to_s if options.key?(:name)
+
column_names = Array.wrap(column_name)
index_name = index_name(table_name, :column => column_names)
diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
index b403443d8e..ba0051de05 100644
--- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
@@ -278,7 +278,8 @@ module ActiveRecord
rows
end
- # Executes a SQL query and returns a MySQL::Result object. Note that you have to free the Result object after you're done using it.
+ # Executes an SQL query and returns a MySQL::Result object. Note that you have to free
+ # the Result object after you're done using it.
def execute(sql, name = nil) #:nodoc:
if name == :skip_logging
@connection.query(sql)
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
index 37e94502a4..6fae899e87 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
@@ -183,10 +183,14 @@ module ActiveRecord
# * <tt>:username</tt> - Defaults to nothing.
# * <tt>:password</tt> - Defaults to nothing.
# * <tt>:database</tt> - The name of the database. No default, must be provided.
- # * <tt>:schema_search_path</tt> - An optional schema search path for the connection given as a string of comma-separated schema names. This is backward-compatible with the <tt>:schema_order</tt> option.
- # * <tt>:encoding</tt> - An optional client encoding that is used in a <tt>SET client_encoding TO <encoding></tt> call on the connection.
- # * <tt>:min_messages</tt> - An optional client min messages that is used in a <tt>SET client_min_messages TO <min_messages></tt> call on the connection.
- # * <tt>:allow_concurrency</tt> - If true, use async query methods so Ruby threads don't deadlock; otherwise, use blocking query methods.
+ # * <tt>:schema_search_path</tt> - An optional schema search path for the connection given
+ # as a string of comma-separated schema names. This is backward-compatible with the <tt>:schema_order</tt> option.
+ # * <tt>:encoding</tt> - An optional client encoding that is used in a <tt>SET client_encoding TO
+ # <encoding></tt> call on the connection.
+ # * <tt>:min_messages</tt> - An optional client min messages that is used in a
+ # <tt>SET client_min_messages TO <min_messages></tt> call on the connection.
+ # * <tt>:allow_concurrency</tt> - If true, use async query methods so Ruby threads don't deadlock;
+ # otherwise, use blocking query methods.
class PostgreSQLAdapter < AbstractAdapter
ADAPTER_NAME = 'PostgreSQL'.freeze
diff --git a/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb
index e812a0371b..82ad0a3b8e 100644
--- a/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb
@@ -29,8 +29,8 @@ module ActiveRecord
end
end
- # The SQLite adapter works with both the 2.x and 3.x series of SQLite with the sqlite-ruby drivers (available both as gems and
- # from http://rubyforge.org/projects/sqlite-ruby/).
+ # The SQLite adapter works with both the 2.x and 3.x series of SQLite with the sqlite-ruby
+ # drivers (available both as gems and from http://rubyforge.org/projects/sqlite-ruby/).
#
# Options:
#
diff --git a/activerecord/lib/active_record/dynamic_finder_match.rb b/activerecord/lib/active_record/dynamic_finder_match.rb
index dfb8a3ba60..0dc965bd26 100644
--- a/activerecord/lib/active_record/dynamic_finder_match.rb
+++ b/activerecord/lib/active_record/dynamic_finder_match.rb
@@ -2,8 +2,8 @@ module ActiveRecord
# = Active Record Dynamic Finder Match
#
- # Provides dynamic attribute-based finders such as <tt>find_by_country</tt>
- # if, for example, the <tt>Person</tt> has an attribute with that name.
+ # Refer to ActiveRecord::Base documentation for Dynamic attribute-based finders for detailed info
+ #
class DynamicFinderMatch
def self.match(method)
df_match = self.new(method)
diff --git a/activerecord/lib/active_record/errors.rb b/activerecord/lib/active_record/errors.rb
index 7aa725d095..e9ac5516ec 100644
--- a/activerecord/lib/active_record/errors.rb
+++ b/activerecord/lib/active_record/errors.rb
@@ -30,7 +30,8 @@ module ActiveRecord
class SerializationTypeMismatch < ActiveRecordError
end
- # Raised when adapter not specified on connection (or configuration file <tt>config/database.yml</tt> misses adapter field).
+ # Raised when adapter not specified on connection (or configuration file <tt>config/database.yml</tt>
+ # misses adapter field).
class AdapterNotSpecified < ActiveRecordError
end
@@ -38,7 +39,8 @@ module ActiveRecord
class AdapterNotFound < ActiveRecordError
end
- # Raised when connection to the database could not been established (for example when <tt>connection=</tt> is given a nil object).
+ # Raised when connection to the database could not been established (for example when <tt>connection=</tt>
+ # is given a nil object).
class ConnectionNotEstablished < ActiveRecordError
end
@@ -51,7 +53,8 @@ module ActiveRecord
class RecordNotSaved < ActiveRecordError
end
- # Raised when SQL statement cannot be executed by the database (for example, it's often the case for MySQL when Ruby driver used is too old).
+ # Raised when SQL statement cannot be executed by the database (for example, it's often the case for
+ # MySQL when Ruby driver used is too old).
class StatementInvalid < ActiveRecordError
end
@@ -78,7 +81,8 @@ module ActiveRecord
class InvalidForeignKey < WrappedDatabaseException
end
- # Raised when number of bind variables in statement given to <tt>:condition</tt> key (for example, when using +find+ method)
+ # Raised when number of bind variables in statement given to <tt>:condition</tt> key (for example,
+ # when using +find+ method)
# does not match number of expected variables.
#
# For example, in
@@ -165,4 +169,4 @@ module ActiveRecord
@errors = errors
end
end
-end \ No newline at end of file
+end
diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb
index 657303fd14..e44102b538 100644
--- a/activerecord/lib/active_record/fixtures.rb
+++ b/activerecord/lib/active_record/fixtures.rb
@@ -39,9 +39,10 @@ end
# This type of fixture is in YAML format and the preferred default. YAML is a file format which describes data structures
# in a non-verbose, human-readable format. It ships with Ruby 1.8.1+.
#
-# Unlike single-file fixtures, YAML fixtures are stored in a single file per model, which are placed in the directory appointed
-# by <tt>ActiveSupport::TestCase.fixture_path=(path)</tt> (this is automatically configured for Rails, so you can just
-# put your files in <tt><your-rails-app>/test/fixtures/</tt>). The fixture file ends with the <tt>.yml</tt> file extension (Rails example:
+# Unlike single-file fixtures, YAML fixtures are stored in a single file per model, which are placed
+# in the directory appointed by <tt>ActiveSupport::TestCase.fixture_path=(path)</tt> (this is
+# automatically configured for Rails, so you can just put your files in <tt><your-rails-app>/test/fixtures/</tt>).
+# The fixture file ends with the <tt>.yml</tt> file extension (Rails example:
# <tt><your-rails-app>/test/fixtures/web_sites.yml</tt>). The format of a YAML fixture file looks like this:
#
# rubyonrails:
@@ -58,7 +59,8 @@ end
# indented list of key/value pairs in the "key: value" format. Records are separated by a blank line for your viewing
# pleasure.
#
-# Note that YAML fixtures are unordered. If you want ordered fixtures, use the omap YAML type. See http://yaml.org/type/omap.html
+# Note that YAML fixtures are unordered. If you want ordered fixtures, use the omap YAML type.
+# See http://yaml.org/type/omap.html
# for the specification. You will need ordered fixtures when you have foreign key constraints on keys in the same table.
# This is commonly needed for tree structures. Example:
#
@@ -79,7 +81,8 @@ end
# (Rails example: <tt><your-rails-app>/test/fixtures/web_sites.csv</tt>).
#
# The format of this type of fixture file is much more compact than the others, but also a little harder to read by us
-# humans. The first line of the CSV file is a comma-separated list of field names. The rest of the file is then comprised
+# humans. The first line of the CSV file is a comma-separated list of field names. The rest of the
+# file is then comprised
# of the actual data (1 per line). Here's an example:
#
# id, name, url
@@ -99,15 +102,16 @@ end
#
# == Single-file fixtures
#
-# This type of fixture was the original format for Active Record that has since been deprecated in favor of the YAML and CSV formats.
-# Fixtures for this format are created by placing text files in a sub-directory (with the name of the model) to the directory
-# appointed by <tt>ActiveSupport::TestCase.fixture_path=(path)</tt> (this is automatically configured for Rails, so you can just
-# put your files in <tt><your-rails-app>/test/fixtures/<your-model-name>/</tt> --
+# This type of fixture was the original format for Active Record that has since been deprecated in
+# favor of the YAML and CSV formats.
+# Fixtures for this format are created by placing text files in a sub-directory (with the name of the model)
+# to the directory appointed by <tt>ActiveSupport::TestCase.fixture_path=(path)</tt> (this is automatically
+# configured for Rails, so you can just put your files in <tt><your-rails-app>/test/fixtures/<your-model-name>/</tt> --
# like <tt><your-rails-app>/test/fixtures/web_sites/</tt> for the WebSite model).
#
# Each text file placed in this directory represents a "record". Usually these types of fixtures are named without
-# extensions, but if you are on a Windows machine, you might consider adding <tt>.txt</tt> as the extension. Here's what the
-# above example might look like:
+# extensions, but if you are on a Windows machine, you might consider adding <tt>.txt</tt> as the extension.
+# Here's what the above example might look like:
#
# web_sites/google
# web_sites/yahoo.txt
@@ -133,7 +137,8 @@ end
# end
# end
#
-# By default, the <tt>test_helper module</tt> will load all of your fixtures into your test database, so this test will succeed.
+# By default, the <tt>test_helper module</tt> will load all of your fixtures into your test database,
+# so this test will succeed.
# The testing environment will automatically load the all fixtures into the database before each test.
# To ensure consistent data, the environment deletes the fixtures before running the load.
#
@@ -182,13 +187,15 @@ end
# This will create 1000 very simple YAML fixtures.
#
# Using ERb, you can also inject dynamic values into your fixtures with inserts like <tt><%= Date.today.strftime("%Y-%m-%d") %></tt>.
-# This is however a feature to be used with some caution. The point of fixtures are that they're stable units of predictable
-# sample data. If you feel that you need to inject dynamic values, then perhaps you should reexamine whether your application
-# is properly testable. Hence, dynamic values in fixtures are to be considered a code smell.
+# This is however a feature to be used with some caution. The point of fixtures are that they're
+# stable units of predictable sample data. If you feel that you need to inject dynamic values, then
+# perhaps you should reexamine whether your application is properly testable. Hence, dynamic values
+# in fixtures are to be considered a code smell.
#
# = Transactional fixtures
#
-# TestCases can use begin+rollback to isolate their changes to the database instead of having to delete+insert for every test case.
+# TestCases can use begin+rollback to isolate their changes to the database instead of having to
+# delete+insert for every test case.
#
# class FooTest < ActiveSupport::TestCase
# self.use_transactional_fixtures = true
@@ -205,15 +212,18 @@ end
# end
#
# If you preload your test database with all fixture data (probably in the Rakefile task) and use transactional fixtures,
-# then you may omit all fixtures declarations in your test cases since all the data's already there and every case rolls back its changes.
+# then you may omit all fixtures declarations in your test cases since all the data's already there
+# and every case rolls back its changes.
#
# In order to use instantiated fixtures with preloaded data, set +self.pre_loaded_fixtures+ to true. This will provide
-# access to fixture data for every table that has been loaded through fixtures (depending on the value of +use_instantiated_fixtures+)
+# access to fixture data for every table that has been loaded through fixtures (depending on the
+# value of +use_instantiated_fixtures+)
#
# When *not* to use transactional fixtures:
#
-# 1. You're testing whether a transaction works correctly. Nested transactions don't commit until all parent transactions commit,
-# particularly, the fixtures transaction which is begun in setup and rolled back in teardown. Thus, you won't be able to verify
+# 1. You're testing whether a transaction works correctly. Nested transactions don't commit until
+# all parent transactions commit, particularly, the fixtures transaction which is begun in setup
+# and rolled back in teardown. Thus, you won't be able to verify
# the results of your transaction until Active Record supports nested transactions or savepoints (in progress).
# 2. Your database does not support transactions. Every Active Record database supports transactions except MySQL MyISAM.
# Use InnoDB, MaxDB, or NDB instead.
diff --git a/activerecord/lib/active_record/named_scope.rb b/activerecord/lib/active_record/named_scope.rb
index 417ff4b5eb..0e560418dc 100644
--- a/activerecord/lib/active_record/named_scope.rb
+++ b/activerecord/lib/active_record/named_scope.rb
@@ -48,18 +48,21 @@ module ActiveRecord
# The above calls to <tt>scope</tt> define class methods Shirt.red and Shirt.dry_clean_only. Shirt.red,
# in effect, represents the query <tt>Shirt.where(:color => 'red')</tt>.
#
- # Unlike <tt>Shirt.find(...)</tt>, however, the object returned by Shirt.red is not an Array; it resembles the association object
- # constructed by a <tt>has_many</tt> declaration. For instance, you can invoke <tt>Shirt.red.first</tt>, <tt>Shirt.red.count</tt>,
- # <tt>Shirt.red.where(:size => 'small')</tt>. Also, just as with the association objects, named \scopes act like an Array,
- # implementing Enumerable; <tt>Shirt.red.each(&block)</tt>, <tt>Shirt.red.first</tt>, and <tt>Shirt.red.inject(memo, &block)</tt>
+ # Unlike <tt>Shirt.find(...)</tt>, however, the object returned by Shirt.red is not an Array; it
+ # resembles the association object constructed by a <tt>has_many</tt> declaration. For instance,
+ # you can invoke <tt>Shirt.red.first</tt>, <tt>Shirt.red.count</tt>, <tt>Shirt.red.where(:size => 'small')</tt>.
+ # Also, just as with the association objects, named \scopes act like an Array, implementing Enumerable;
+ # <tt>Shirt.red.each(&block)</tt>, <tt>Shirt.red.first</tt>, and <tt>Shirt.red.inject(memo, &block)</tt>
# all behave as if Shirt.red really was an Array.
#
- # These named \scopes are composable. For instance, <tt>Shirt.red.dry_clean_only</tt> will produce all shirts that are both red and dry clean only.
- # Nested finds and calculations also work with these compositions: <tt>Shirt.red.dry_clean_only.count</tt> returns the number of garments
- # for which these criteria obtain. Similarly with <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>.
+ # These named \scopes are composable. For instance, <tt>Shirt.red.dry_clean_only</tt> will produce
+ # all shirts that are both red and dry clean only.
+ # Nested finds and calculations also work with these compositions: <tt>Shirt.red.dry_clean_only.count</tt>
+ # returns the number of garments for which these criteria obtain. Similarly with
+ # <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>.
#
- # All \scopes are available as class methods on the ActiveRecord::Base descendant upon which the \scopes were defined. But they are also available to
- # <tt>has_many</tt> associations. If,
+ # All \scopes are available as class methods on the ActiveRecord::Base descendant upon which
+ # the \scopes were defined. But they are also available to <tt>has_many</tt> associations. If,
#
# class Person < ActiveRecord::Base
# has_many :shirts
diff --git a/activerecord/lib/active_record/observer.rb b/activerecord/lib/active_record/observer.rb
index ce002f5e1a..78bac55bf2 100644
--- a/activerecord/lib/active_record/observer.rb
+++ b/activerecord/lib/active_record/observer.rb
@@ -67,8 +67,8 @@ module ActiveRecord
#
# == Configuration
#
- # In order to activate an observer, list it in the <tt>config.active_record.observers</tt> configuration setting in your
- # <tt>config/application.rb</tt> file.
+ # In order to activate an observer, list it in the <tt>config.active_record.observers</tt> configuration
+ # setting in your <tt>config/application.rb</tt> file.
#
# config.active_record.observers = :comment_observer, :signup_observer
#
diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb
index cbc2220e96..71b46beaef 100644
--- a/activerecord/lib/active_record/persistence.rb
+++ b/activerecord/lib/active_record/persistence.rb
@@ -60,7 +60,7 @@ module ActiveRecord
# reflect that no changes should be made (since they can't be
# persisted). Returns the frozen instance.
#
- # The row is simply removed with a SQL +DELETE+ statement on the
+ # The row is simply removed with an SQL +DELETE+ statement on the
# record's primary key, and no callbacks are executed.
#
# To enforce the object's +before_destroy+ and +after_destroy+
@@ -91,8 +91,8 @@ module ActiveRecord
# like render <tt>:partial => @client.becomes(Company)</tt> to render that
# instance using the companies/company partial instead of clients/client.
#
- # Note: The new instance will share a link to the same attributes as the original class. So any change to the attributes in either
- # instance will affect the other.
+ # Note: The new instance will share a link to the same attributes as the original class.
+ # So any change to the attributes in either instance will affect the other.
def becomes(klass)
became = klass.new
became.instance_variable_set("@attributes", @attributes)
diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake
index 2c17c74ab4..ae605d3e7a 100644
--- a/activerecord/lib/active_record/railties/databases.rake
+++ b/activerecord/lib/active_record/railties/databases.rake
@@ -339,7 +339,7 @@ namespace :db do
end
namespace :structure do
- desc "Dump the database structure to a SQL file"
+ desc "Dump the database structure to an SQL file"
task :dump => :environment do
abcs = ActiveRecord::Base.configurations
case abcs[Rails.env]["adapter"]
diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb
index 7962f52738..30be723291 100644
--- a/activerecord/lib/active_record/relation.rb
+++ b/activerecord/lib/active_record/relation.rb
@@ -67,7 +67,8 @@ module ActiveRecord
preload += @includes_values unless eager_loading?
preload.each {|associations| @klass.send(:preload_associations, @records, associations) }
- # @readonly_value is true only if set explicitly. @implicit_readonly is true if there are JOINS and no explicit SELECT.
+ # @readonly_value is true only if set explicitly. @implicit_readonly is true if there
+ # are JOINS and no explicit SELECT.
readonly = @readonly_value.nil? ? @implicit_readonly : @readonly_value
@records.each { |record| record.readonly! } if readonly
@@ -130,7 +131,8 @@ module ActiveRecord
# ==== Parameters
#
# * +updates+ - A string, array, or hash representing the SET part of an SQL statement.
- # * +conditions+ - A string, array, or hash representing the WHERE part of an SQL statement. See conditions in the intro.
+ # * +conditions+ - A string, array, or hash representing the WHERE part of an SQL statement.
+ # See conditions in the intro.
# * +options+ - Additional options are <tt>:limit</tt> and <tt>:order</tt>, see the examples for usage.
#
# ==== Examples
@@ -144,7 +146,7 @@ module ActiveRecord
# # Update all avatars migrated more than a week ago
# Avatar.update_all ['migrated_at = ?', Time.now.utc], ['migrated_at > ?', 1.week.ago]
#
- # # Update all books that match our conditions, but limit it to 5 ordered by date
+ # # Update all books that match conditions, but limit it to 5 ordered by date
# Book.update_all "author = 'David'", "title LIKE '%Rails%'", :order => 'created_at', :limit => 5
def update_all(updates, conditions = nil, options = {})
if conditions || options.present?
@@ -165,14 +167,14 @@ module ActiveRecord
# ==== Parameters
#
# * +id+ - This should be the id or an array of ids to be updated.
- # * +attributes+ - This should be a hash of attributes to be set on the object, or an array of hashes.
+ # * +attributes+ - This should be a hash of attributes or an array of hashes.
#
# ==== Examples
#
- # # Updating one record:
+ # # Updates one record
# Person.update(15, :user_name => 'Samuel', :group => 'expert')
#
- # # Updating multiple records:
+ # # Updates multiple records
# people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
# Person.update(people.keys, people.values)
def update(id, attributes)
@@ -317,7 +319,9 @@ module ActiveRecord
def scope_for_create
@scope_for_create ||= begin
@create_with_value || Hash[
- @where_values.grep(Arel::Predicates::Equality).map { |where|
+ @where_values.find_all { |w|
+ w.respond_to?(:operator) && w.operator == :==
+ }.map { |where|
[where.operand1.name,
where.operand2.respond_to?(:value) ?
where.operand2.value : where.operand2]
diff --git a/activerecord/lib/active_record/relation/batches.rb b/activerecord/lib/active_record/relation/batches.rb
index 412be895c4..d7494ebb5a 100644
--- a/activerecord/lib/active_record/relation/batches.rb
+++ b/activerecord/lib/active_record/relation/batches.rb
@@ -50,9 +50,9 @@ module ActiveRecord
def find_in_batches(options = {})
relation = self
- if orders.present? || taken.present?
- ActiveRecord::Base.logger.warn("Scoped order and limit are ignored, it's forced to be batch order and batch size")
- end
+ if orders.present? || taken.present?
+ ActiveRecord::Base.logger.warn("Scoped order and limit are ignored, it's forced to be batch order and batch size")
+ end
if (finder_options = options.except(:start, :batch_size)).present?
raise "You can't specify an order, it's forced to be #{batch_order}" if options[:order].present?
@@ -73,7 +73,7 @@ module ActiveRecord
break if records.size < batch_size
if primary_key_offset = records.last.id
- records = relation.where(primary_key.gt(primary_key_offset)).all
+ records = relation.where(primary_key.gt(primary_key_offset)).to_a
else
raise "Primary key not included in the custom select clause"
end
diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb
index 44baeb6c84..a679c444cf 100644
--- a/activerecord/lib/active_record/relation/calculations.rb
+++ b/activerecord/lib/active_record/relation/calculations.rb
@@ -1,30 +1,38 @@
require 'active_support/core_ext/object/blank'
+require 'active_support/core_ext/object/try'
module ActiveRecord
module Calculations
# Count operates using three different approaches.
#
# * Count all: By not passing any parameters to count, it will return a count of all the rows for the model.
- # * Count using column: By passing a column name to count, it will return a count of all the rows for the model with supplied column present
+ # * Count using column: By passing a column name to count, it will return a count of all the
+ # rows for the model with supplied column present
# * Count using options will find the row count matched by the options used.
#
# The third approach, count using options, accepts an option hash as the only parameter. The options are:
#
- # * <tt>:conditions</tt>: An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. See conditions in the intro to ActiveRecord::Base.
+ # * <tt>:conditions</tt>: An SQL fragment like "administrator = 1" or [ "user_name = ?", username ].
+ # See conditions in the intro to ActiveRecord::Base.
# * <tt>:joins</tt>: Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed)
- # or named associations in the same form used for the <tt>:include</tt> option, which will perform an INNER JOIN on the associated table(s).
- # If the value is a string, then the records will be returned read-only since they will have attributes that do not correspond to the table's columns.
+ # or named associations in the same form used for the <tt>:include</tt> option, which will
+ # perform an INNER JOIN on the associated table(s).
+ # If the value is a string, then the records will be returned read-only since they will have
+ # attributes that do not correspond to the table's columns.
# Pass <tt>:readonly => false</tt> to override.
- # * <tt>:include</tt>: Named associations that should be loaded alongside using LEFT OUTER JOINs. The symbols named refer
- # to already defined associations. When using named associations, count returns the number of DISTINCT items for the model you're counting.
+ # * <tt>:include</tt>: Named associations that should be loaded alongside using LEFT OUTER JOINs.
+ # The symbols named refer to already defined associations. When using named associations, count
+ # returns the number of DISTINCT items for the model you're counting.
# See eager loading under Associations.
# * <tt>:order</tt>: An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations).
# * <tt>:group</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
- # * <tt>:select</tt>: By default, this is * as in SELECT * FROM, but can be changed if you, for example, want to do a join but not
+ # * <tt>:select</tt>: By default, this is * as in SELECT * FROM, but can be changed if you, for example,
+ # want to do a join but not
# include the joined columns.
- # * <tt>:distinct</tt>: Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) ...
- # * <tt>:from</tt> - By default, this is the table name of the class, but can be changed to an alternate table name (or even the name
- # of a database view).
+ # * <tt>:distinct</tt>: Set this to true to make this a distinct calculation, such as
+ # SELECT COUNT(DISTINCT posts.id) ...
+ # * <tt>:from</tt> - By default, this is the table name of the class, but can be changed to an
+ # alternate table name (or even the name of a database view).
#
# Examples for counting all:
# Person.count # returns the total count of all people
@@ -34,12 +42,19 @@ module ActiveRecord
#
# Examples for count with options:
# Person.count(:conditions => "age > 26")
- # Person.count(:conditions => "age > 26 AND job.salary > 60000", :include => :job) # because of the named association, it finds the DISTINCT count using LEFT OUTER JOIN.
- # Person.count(:conditions => "age > 26 AND job.salary > 60000", :joins => "LEFT JOIN jobs on jobs.person_id = person.id") # finds the number of rows matching the conditions and joins.
+ #
+ # # because of the named association, it finds the DISTINCT count using LEFT OUTER JOIN.
+ # Person.count(:conditions => "age > 26 AND job.salary > 60000", :include => :job)
+ #
+ # # finds the number of rows matching the conditions and joins.
+ # Person.count(:conditions => "age > 26 AND job.salary > 60000",
+ # :joins => "LEFT JOIN jobs on jobs.person_id = person.id")
+ #
# Person.count('id', :conditions => "age > 26") # Performs a COUNT(id)
# Person.count(:all, :conditions => "age > 26") # Performs a COUNT(*) (:all is an alias for '*')
#
- # Note: <tt>Person.count(:all)</tt> will not work because it will use <tt>:all</tt> as the condition. Use Person.count instead.
+ # Note: <tt>Person.count(:all)</tt> will not work because it will use <tt>:all</tt> as the condition.
+ # Use Person.count instead.
def count(column_name = nil, options = {})
column_name, options = nil, column_name if column_name.is_a?(Hash)
calculate(:count, column_name, options)
@@ -80,13 +95,15 @@ module ActiveRecord
calculate(:sum, column_name, options)
end
- # This calculates aggregate values in the given column. Methods for count, sum, average, minimum, and maximum have been added as shortcuts.
- # Options such as <tt>:conditions</tt>, <tt>:order</tt>, <tt>:group</tt>, <tt>:having</tt>, and <tt>:joins</tt> can be passed to customize the query.
+ # This calculates aggregate values in the given column. Methods for count, sum, average,
+ # minimum, and maximum have been added as shortcuts. Options such as <tt>:conditions</tt>,
+ # <tt>:order</tt>, <tt>:group</tt>, <tt>:having</tt>, and <tt>:joins</tt> can be passed to customize the query.
#
# There are two basic forms of output:
- # * Single aggregate value: The single value is type cast to Fixnum for COUNT, Float for AVG, and the given column's type for everything else.
- # * Grouped values: This returns an ordered hash of the values and groups them by the <tt>:group</tt> option. It takes either a column name, or the name
- # of a belongs_to association.
+ # * Single aggregate value: The single value is type cast to Fixnum for COUNT, Float
+ # for AVG, and the given column's type for everything else.
+ # * Grouped values: This returns an ordered hash of the values and groups them by the
+ # <tt>:group</tt> option. It takes either a column name, or the name of a belongs_to association.
#
# values = Person.maximum(:age, :group => 'last_name')
# puts values["Drake"]
@@ -102,21 +119,30 @@ module ActiveRecord
# end
#
# Options:
- # * <tt>:conditions</tt> - An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. See conditions in the intro to ActiveRecord::Base.
- # * <tt>:include</tt>: Eager loading, see Associations for details. Since calculations don't load anything, the purpose of this is to access fields on joined tables in your conditions, order, or group clauses.
- # * <tt>:joins</tt> - An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id". (Rarely needed).
- # The records will be returned read-only since they will have attributes that do not correspond to the table's columns.
+ # * <tt>:conditions</tt> - An SQL fragment like "administrator = 1" or [ "user_name = ?", username ].
+ # See conditions in the intro to ActiveRecord::Base.
+ # * <tt>:include</tt>: Eager loading, see Associations for details. Since calculations don't load anything,
+ # the purpose of this is to access fields on joined tables in your conditions, order, or group clauses.
+ # * <tt>:joins</tt> - An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id".
+ # (Rarely needed).
+ # The records will be returned read-only since they will have attributes that do not correspond to the
+ # table's columns.
# * <tt>:order</tt> - An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations).
# * <tt>:group</tt> - An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
- # * <tt>:select</tt> - By default, this is * as in SELECT * FROM, but can be changed if you for example want to do a join, but not
- # include the joined columns.
- # * <tt>:distinct</tt> - Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) ...
+ # * <tt>:select</tt> - By default, this is * as in SELECT * FROM, but can be changed if you for example
+ # want to do a join, but not include the joined columns.
+ # * <tt>:distinct</tt> - Set this to true to make this a distinct calculation, such as
+ # SELECT COUNT(DISTINCT posts.id) ...
#
# Examples:
# Person.calculate(:count, :all) # The same as Person.count
# Person.average(:age) # SELECT AVG(age) FROM people...
- # Person.minimum(:age, :conditions => ['last_name != ?', 'Drake']) # Selects the minimum age for everyone with a last name other than 'Drake'
- # Person.minimum(:age, :having => 'min(age) > 17', :group => :last_name) # Selects the minimum age for any family without any minors
+ # Person.minimum(:age, :conditions => ['last_name != ?', 'Drake']) # Selects the minimum age for
+ # # everyone with a last name other than 'Drake'
+ #
+ # # Selects the minimum age for any family without any minors
+ # Person.minimum(:age, :having => 'min(age) > 17', :group => :last_name)
+ #
# Person.sum("2 * age")
def calculate(operation, column_name, options = {})
if options.except(:distinct).present?
diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb
index 3bf4c5bdd1..b34c11973b 100644
--- a/activerecord/lib/active_record/relation/finder_methods.rb
+++ b/activerecord/lib/active_record/relation/finder_methods.rb
@@ -21,23 +21,28 @@ module ActiveRecord
#
# ==== Parameters
#
- # * <tt>:conditions</tt> - An SQL fragment like "administrator = 1", <tt>[ "user_name = ?", username ]</tt>, or <tt>["user_name = :user_name", { :user_name => user_name }]</tt>. See conditions in the intro.
+ # * <tt>:conditions</tt> - An SQL fragment like "administrator = 1", <tt>[ "user_name = ?", username ]</tt>,
+ # or <tt>["user_name = :user_name", { :user_name => user_name }]</tt>. See conditions in the intro.
# * <tt>:order</tt> - An SQL fragment like "created_at DESC, name".
# * <tt>:group</tt> - An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
- # * <tt>:having</tt> - Combined with +:group+ this can be used to filter the records that a <tt>GROUP BY</tt> returns. Uses the <tt>HAVING</tt> SQL-clause.
+ # * <tt>:having</tt> - Combined with +:group+ this can be used to filter the records that a
+ # <tt>GROUP BY</tt> returns. Uses the <tt>HAVING</tt> SQL-clause.
# * <tt>:limit</tt> - An integer determining the limit on the number of rows that should be returned.
- # * <tt>:offset</tt> - An integer determining the offset from where the rows should be fetched. So at 5, it would skip rows 0 through 4.
+ # * <tt>:offset</tt> - An integer determining the offset from where the rows should be fetched. So at 5,
+ # it would skip rows 0 through 4.
# * <tt>:joins</tt> - Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed),
- # named associations in the same form used for the <tt>:include</tt> option, which will perform an <tt>INNER JOIN</tt> on the associated table(s),
+ # named associations in the same form used for the <tt>:include</tt> option, which will perform an
+ # <tt>INNER JOIN</tt> on the associated table(s),
# or an array containing a mixture of both strings and named associations.
- # If the value is a string, then the records will be returned read-only since they will have attributes that do not correspond to the table's columns.
+ # If the value is a string, then the records will be returned read-only since they will
+ # have attributes that do not correspond to the table's columns.
# Pass <tt>:readonly => false</tt> to override.
# * <tt>:include</tt> - Names associations that should be loaded alongside. The symbols named refer
# to already defined associations. See eager loading under Associations.
- # * <tt>:select</tt> - By default, this is "*" as in "SELECT * FROM", but can be changed if you, for example, want to do a join but not
- # include the joined columns. Takes a string with the SELECT SQL fragment (e.g. "id, name").
- # * <tt>:from</tt> - By default, this is the table name of the class, but can be changed to an alternate table name (or even the name
- # of a database view).
+ # * <tt>:select</tt> - By default, this is "*" as in "SELECT * FROM", but can be changed if you,
+ # for example, want to do a join but not include the joined columns. Takes a string with the SELECT SQL fragment (e.g. "id, name").
+ # * <tt>:from</tt> - By default, this is the table name of the class, but can be changed
+ # to an alternate table name (or even the name of a database view).
# * <tt>:readonly</tt> - Mark the returned records read-only so they cannot be saved or updated.
# * <tt>:lock</tt> - An SQL fragment like "FOR UPDATE" or "LOCK IN SHARE MODE".
# <tt>:lock => true</tt> gives connection's default exclusive lock, usually "FOR UPDATE".
@@ -164,6 +169,8 @@ module ActiveRecord
# Person.exists?(['name LIKE ?', "%#{query}%"])
# Person.exists?
def exists?(id = nil)
+ id = id.id if ActiveRecord::Base === id
+
case id
when Array, Hash
where(id).exists?
@@ -279,6 +286,8 @@ module ActiveRecord
end
def find_one(id)
+ id = id.id if ActiveRecord::Base === id
+
record = where(primary_key.eq(id)).first
unless record
diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb
index a92d180442..e71f1cca72 100644
--- a/activerecord/lib/active_record/relation/query_methods.rb
+++ b/activerecord/lib/active_record/relation/query_methods.rb
@@ -31,7 +31,7 @@ module ActiveRecord
end
def group(*args)
- clone.tap {|r| r.group_values += args if args.present? }
+ clone.tap {|r| r.group_values += args.flatten if args.present? }
end
def order(*args)
@@ -95,7 +95,7 @@ module ActiveRecord
order_clause = arel.send(:order_clauses).join(', ')
relation = except(:order)
- if order_clause.present?
+ unless order_clauses.blank?
relation.order(reverse_sql_order(order_clause))
else
relation.order("#{@klass.table_name}.#{@klass.primary_key} DESC")
@@ -238,7 +238,7 @@ module ActiveRecord
end
def reverse_sql_order(order_query)
- order_query.to_s.split(/,/).each { |s|
+ order_query.split(',').each { |s|
if s.match(/\s(asc|ASC)$/)
s.gsub!(/\s(asc|ASC)$/, ' DESC')
elsif s.match(/\s(desc|DESC)$/)
diff --git a/activerecord/lib/active_record/schema.rb b/activerecord/lib/active_record/schema.rb
index e2783087ec..c1bc3214ea 100644
--- a/activerecord/lib/active_record/schema.rb
+++ b/activerecord/lib/active_record/schema.rb
@@ -2,7 +2,7 @@ require 'active_support/core_ext/object/blank'
module ActiveRecord
# = Active Record Schema
- #
+ #
# Allows programmers to programmatically define a schema in a portable
# DSL. This means you can define tables, indexes, etc. without using SQL
# directly, so your applications can more easily support multiple
diff --git a/activerecord/lib/active_record/schema_dumper.rb b/activerecord/lib/active_record/schema_dumper.rb
index a4757773d8..e9af20e1b6 100644
--- a/activerecord/lib/active_record/schema_dumper.rb
+++ b/activerecord/lib/active_record/schema_dumper.rb
@@ -8,13 +8,13 @@ module ActiveRecord
# output format (i.e., ActiveRecord::Schema).
class SchemaDumper #:nodoc:
private_class_method :new
-
+
##
# :singleton-method:
- # A list of tables which should not be dumped to the schema.
+ # A list of tables which should not be dumped to the schema.
# Acceptable values are strings as well as regexp.
# This setting is only used if ActiveRecord::Base.schema_format == :ruby
- cattr_accessor :ignore_tables
+ cattr_accessor :ignore_tables
@@ignore_tables = []
def self.dump(connection=ActiveRecord::Base.connection, stream=STDOUT)
@@ -71,7 +71,7 @@ HEADER
else
raise StandardError, 'ActiveRecord::SchemaDumper.ignore_tables accepts an array of String and / or Regexp values.'
end
- end
+ end
table(tbl, stream)
end
end
@@ -87,7 +87,7 @@ HEADER
elsif @connection.respond_to?(:primary_key)
pk = @connection.primary_key(table)
end
-
+
tbl.print " create_table #{table.inspect}"
if columns.detect { |c| c.name == pk }
if pk != 'id'
@@ -105,7 +105,7 @@ HEADER
next if column.name == pk
spec = {}
spec[:name] = column.name.inspect
-
+
# AR has an optimisation which handles zero-scale decimals as integers. This
# code ensures that the dumper still dumps the column as a decimal.
spec[:type] = if column.type == :integer && [/^numeric/, /^decimal/].any? { |e| e.match(column.sql_type) }
@@ -148,7 +148,7 @@ HEADER
tbl.puts " end"
tbl.puts
-
+
indexes(table, tbl)
tbl.rewind
@@ -158,7 +158,7 @@ HEADER
stream.puts "# #{e.message}"
stream.puts
end
-
+
stream
end
@@ -172,7 +172,7 @@ HEADER
value.inspect
end
end
-
+
def indexes(table, stream)
if (indexes = @connection.indexes(table)).any?
add_index_statements = indexes.map do |index|
diff --git a/activerecord/lib/active_record/timestamp.rb b/activerecord/lib/active_record/timestamp.rb
index 32b3f03f13..5531d12a41 100644
--- a/activerecord/lib/active_record/timestamp.rb
+++ b/activerecord/lib/active_record/timestamp.rb
@@ -21,7 +21,8 @@ module ActiveRecord
#
# This feature can easily be turned off by assigning value <tt>false</tt> .
#
- # If your attributes are time zone aware and you desire to skip time zone conversion for certain attributes then you can do following:
+ # If your attributes are time zone aware and you desire to skip time zone conversion for certain
+ # attributes then you can do following:
#
# Topic.skip_time_zone_conversion_for_attributes = [:written_on]
module Timestamp
diff --git a/activerecord/lib/active_record/validations/associated.rb b/activerecord/lib/active_record/validations/associated.rb
index 0b0f5682aa..15b587de45 100644
--- a/activerecord/lib/active_record/validations/associated.rb
+++ b/activerecord/lib/active_record/validations/associated.rb
@@ -27,8 +27,9 @@ module ActiveRecord
#
# this would specify a circular dependency and cause infinite recursion.
#
- # NOTE: This validation will not fail if the association hasn't been assigned. If you want to ensure that the association
- # is both present and guaranteed to be valid, you also need to use +validates_presence_of+.
+ # NOTE: This validation will not fail if the association hasn't been assigned. If you want to
+ # ensure that the association is both present and guaranteed to be valid, you also need to
+ # use +validates_presence_of+.
#
# Configuration options:
# * <tt>:message</tt> - A custom error message (default is: "is invalid")
@@ -44,4 +45,4 @@ module ActiveRecord
end
end
end
-end \ No newline at end of file
+end
diff --git a/activerecord/lib/active_record/validations/uniqueness.rb b/activerecord/lib/active_record/validations/uniqueness.rb
index 1c9ecc7b1b..bf863c7063 100644
--- a/activerecord/lib/active_record/validations/uniqueness.rb
+++ b/activerecord/lib/active_record/validations/uniqueness.rb
@@ -78,22 +78,25 @@ module ActiveRecord
end
module ClassMethods
- # Validates whether the value of the specified attributes are unique across the system. Useful for making sure that only one user
+ # Validates whether the value of the specified attributes are unique across the system.
+ # Useful for making sure that only one user
# can be named "davidhh".
#
# class Person < ActiveRecord::Base
# validates_uniqueness_of :user_name, :scope => :account_id
# end
#
- # It can also validate whether the value of the specified attributes are unique based on multiple scope parameters. For example,
- # making sure that a teacher can only be on the schedule once per semester for a particular class.
+ # It can also validate whether the value of the specified attributes are unique based on multiple
+ # scope parameters. For example, making sure that a teacher can only be on the schedule once
+ # per semester for a particular class.
#
# class TeacherSchedule < ActiveRecord::Base
# validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
# end
#
- # When the record is created, a check is performed to make sure that no record exists in the database with the given value for the specified
- # attribute (that maps to a column). When the record is updated, the same check is made but disregarding the record itself.
+ # When the record is created, a check is performed to make sure that no record exists in the database
+ # with the given value for the specified attribute (that maps to a column). When the record is updated,
+ # the same check is made but disregarding the record itself.
#
# Configuration options:
# * <tt>:message</tt> - Specifies a custom error message (default is: "has already been taken").
@@ -102,11 +105,12 @@ module ActiveRecord
# * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
- # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
- # method, proc or string should return or evaluate to a true or false value.
+ # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).
+ # The method, proc or string should return or evaluate to a true or false value.
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
- # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
- # method, proc or string should return or evaluate to a true or false value.
+ # not occur (e.g. <tt>:unless => :skip_validation</tt>, or
+ # <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The method, proc or string should
+ # return or evaluate to a true or false value.
#
# === Concurrency and integrity
#
diff --git a/activerecord/test/cases/associations_test.rb b/activerecord/test/cases/associations_test.rb
index d328ca630b..b31611e27a 100644
--- a/activerecord/test/cases/associations_test.rb
+++ b/activerecord/test/cases/associations_test.rb
@@ -32,6 +32,28 @@ class AssociationsTest < ActiveRecord::TestCase
assert_equal 1, liquids[0].molecules.length
end
+ def test_clear_association_cache_stored
+ firm = Firm.find(1)
+ assert_kind_of Firm, firm
+
+ firm.clear_association_cache
+ assert_equal Firm.find(1).clients.collect{ |x| x.name }.sort, firm.clients.collect{ |x| x.name }.sort
+ end
+
+ def test_clear_association_cache_new_record
+ firm = Firm.new
+ client_stored = Client.find(3)
+ client_new = Client.new
+ client_new.name = "The Joneses"
+ clients = [ client_stored, client_new ]
+
+ firm.clients << clients
+ assert_equal clients.map(&:name).to_set, firm.clients.map(&:name).to_set
+
+ firm.clear_association_cache
+ assert_equal clients.map(&:name).to_set, firm.clients.map(&:name).to_set
+ end
+
def test_loading_the_association_target_should_keep_child_records_marked_for_destruction
ship = Ship.create!(:name => "The good ship Dollypop")
part = ship.parts.create!(:name => "Mast")
diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb
index d59fa0a632..d20b762853 100644
--- a/activerecord/test/cases/attribute_methods_test.rb
+++ b/activerecord/test/cases/attribute_methods_test.rb
@@ -1,9 +1,15 @@
require "cases/helper"
-require 'models/topic'
require 'models/minimalistic'
+require 'models/developer'
+require 'models/auto_id'
+require 'models/computer'
+require 'models/topic'
+require 'models/company'
+require 'models/category'
+require 'models/reply'
class AttributeMethodsTest < ActiveRecord::TestCase
- fixtures :topics
+ fixtures :topics, :developers, :companies, :computers
def setup
@old_matchers = ActiveRecord::Base.send(:attribute_method_matchers).dup
@@ -16,6 +22,274 @@ class AttributeMethodsTest < ActiveRecord::TestCase
ActiveRecord::Base.send(:attribute_method_matchers).concat(@old_matchers)
end
+ def test_attribute_present
+ t = Topic.new
+ t.title = "hello there!"
+ t.written_on = Time.now
+ assert t.attribute_present?("title")
+ assert t.attribute_present?("written_on")
+ assert !t.attribute_present?("content")
+ end
+
+ def test_attribute_keys_on_new_instance
+ t = Topic.new
+ assert_equal nil, t.title, "The topics table has a title column, so it should be nil"
+ assert_raise(NoMethodError) { t.title2 }
+ end
+
+ def test_boolean_attributes
+ assert ! Topic.find(1).approved?
+ assert Topic.find(2).approved?
+ end
+
+ def test_set_attributes
+ topic = Topic.find(1)
+ topic.attributes = { "title" => "Budget", "author_name" => "Jason" }
+ topic.save
+ assert_equal("Budget", topic.title)
+ assert_equal("Jason", topic.author_name)
+ assert_equal(topics(:first).author_email_address, Topic.find(1).author_email_address)
+ end
+
+ def test_set_attributes_without_hash
+ topic = Topic.new
+ assert_nothing_raised { topic.attributes = '' }
+ end
+
+ def test_integers_as_nil
+ test = AutoId.create('value' => '')
+ assert_nil AutoId.find(test.id).value
+ end
+
+ def test_set_attributes_with_block
+ topic = Topic.new do |t|
+ t.title = "Budget"
+ t.author_name = "Jason"
+ end
+
+ assert_equal("Budget", topic.title)
+ assert_equal("Jason", topic.author_name)
+ end
+
+ def test_respond_to?
+ topic = Topic.find(1)
+ assert_respond_to topic, "title"
+ assert_respond_to topic, "title?"
+ assert_respond_to topic, "title="
+ assert_respond_to topic, :title
+ assert_respond_to topic, :title?
+ assert_respond_to topic, :title=
+ assert_respond_to topic, "author_name"
+ assert_respond_to topic, "attribute_names"
+ assert !topic.respond_to?("nothingness")
+ assert !topic.respond_to?(:nothingness)
+ end
+
+ def test_array_content
+ topic = Topic.new
+ topic.content = %w( one two three )
+ topic.save
+
+ assert_equal(%w( one two three ), Topic.find(topic.id).content)
+ end
+
+ def test_read_attributes_before_type_cast
+ category = Category.new({:name=>"Test categoty", :type => nil})
+ category_attrs = {"name"=>"Test categoty", "type" => nil, "categorizations_count" => nil}
+ assert_equal category_attrs , category.attributes_before_type_cast
+ end
+
+ if current_adapter?(:MysqlAdapter)
+ def test_read_attributes_before_type_cast_on_boolean
+ bool = Booleantest.create({ "value" => false })
+ assert_equal "0", bool.reload.attributes_before_type_cast["value"]
+ end
+ end
+
+ def test_read_attributes_before_type_cast_on_datetime
+ developer = Developer.find(:first)
+ # Oracle adapter returns Time before type cast
+ unless current_adapter?(:OracleAdapter)
+ assert_equal developer.created_at.to_s(:db) , developer.attributes_before_type_cast["created_at"]
+ else
+ assert_equal developer.created_at.to_s(:db) , developer.attributes_before_type_cast["created_at"].to_s(:db)
+
+ developer.created_at = "345643456"
+ assert_equal developer.created_at_before_type_cast, "345643456"
+ assert_equal developer.created_at, nil
+
+ developer.created_at = "2010-03-21T21:23:32+01:00"
+ assert_equal developer.created_at_before_type_cast, "2010-03-21T21:23:32+01:00"
+ assert_equal developer.created_at, Time.parse("2010-03-21T21:23:32+01:00")
+ end
+ end
+
+ def test_hash_content
+ topic = Topic.new
+ topic.content = { "one" => 1, "two" => 2 }
+ topic.save
+
+ assert_equal 2, Topic.find(topic.id).content["two"]
+
+ topic.content_will_change!
+ topic.content["three"] = 3
+ topic.save
+
+ assert_equal 3, Topic.find(topic.id).content["three"]
+ end
+
+ def test_update_array_content
+ topic = Topic.new
+ topic.content = %w( one two three )
+
+ topic.content.push "four"
+ assert_equal(%w( one two three four ), topic.content)
+
+ topic.save
+
+ topic = Topic.find(topic.id)
+ topic.content << "five"
+ assert_equal(%w( one two three four five ), topic.content)
+ end
+
+ def test_case_sensitive_attributes_hash
+ # DB2 is not case-sensitive
+ return true if current_adapter?(:DB2Adapter)
+
+ assert_equal @loaded_fixtures['computers']['workstation'].to_hash, Computer.find(:first).attributes
+ end
+
+ def test_hashes_not_mangled
+ new_topic = { :title => "New Topic" }
+ new_topic_values = { :title => "AnotherTopic" }
+
+ topic = Topic.new(new_topic)
+ assert_equal new_topic[:title], topic.title
+
+ topic.attributes= new_topic_values
+ assert_equal new_topic_values[:title], topic.title
+ end
+
+ def test_create_through_factory
+ topic = Topic.create("title" => "New Topic")
+ topicReloaded = Topic.find(topic.id)
+ assert_equal(topic, topicReloaded)
+ end
+
+ def test_write_attribute
+ topic = Topic.new
+ topic.send(:write_attribute, :title, "Still another topic")
+ assert_equal "Still another topic", topic.title
+
+ topic.send(:write_attribute, "title", "Still another topic: part 2")
+ assert_equal "Still another topic: part 2", topic.title
+ end
+
+ def test_read_attribute
+ topic = Topic.new
+ topic.title = "Don't change the topic"
+ assert_equal "Don't change the topic", topic.send(:read_attribute, "title")
+ assert_equal "Don't change the topic", topic["title"]
+
+ assert_equal "Don't change the topic", topic.send(:read_attribute, :title)
+ assert_equal "Don't change the topic", topic[:title]
+ end
+
+ def test_read_attribute_when_false
+ topic = topics(:first)
+ topic.approved = false
+ assert !topic.approved?, "approved should be false"
+ topic.approved = "false"
+ assert !topic.approved?, "approved should be false"
+ end
+
+ def test_read_attribute_when_true
+ topic = topics(:first)
+ topic.approved = true
+ assert topic.approved?, "approved should be true"
+ topic.approved = "true"
+ assert topic.approved?, "approved should be true"
+ end
+
+ def test_read_write_boolean_attribute
+ topic = Topic.new
+ # puts ""
+ # puts "New Topic"
+ # puts topic.inspect
+ topic.approved = "false"
+ # puts "Expecting false"
+ # puts topic.inspect
+ assert !topic.approved?, "approved should be false"
+ topic.approved = "false"
+ # puts "Expecting false"
+ # puts topic.inspect
+ assert !topic.approved?, "approved should be false"
+ topic.approved = "true"
+ # puts "Expecting true"
+ # puts topic.inspect
+ assert topic.approved?, "approved should be true"
+ topic.approved = "true"
+ # puts "Expecting true"
+ # puts topic.inspect
+ assert topic.approved?, "approved should be true"
+ # puts ""
+ end
+
+ def test_query_attribute_string
+ [nil, "", " "].each do |value|
+ assert_equal false, Topic.new(:author_name => value).author_name?
+ end
+
+ assert_equal true, Topic.new(:author_name => "Name").author_name?
+ end
+
+ def test_query_attribute_number
+ [nil, 0, "0"].each do |value|
+ assert_equal false, Developer.new(:salary => value).salary?
+ end
+
+ assert_equal true, Developer.new(:salary => 1).salary?
+ assert_equal true, Developer.new(:salary => "1").salary?
+ end
+
+ def test_query_attribute_boolean
+ [nil, "", false, "false", "f", 0].each do |value|
+ assert_equal false, Topic.new(:approved => value).approved?
+ end
+
+ [true, "true", "1", 1].each do |value|
+ assert_equal true, Topic.new(:approved => value).approved?
+ end
+ end
+
+ def test_query_attribute_with_custom_fields
+ object = Company.find_by_sql(<<-SQL).first
+ SELECT c1.*, c2.ruby_type as string_value, c2.rating as int_value
+ FROM companies c1, companies c2
+ WHERE c1.firm_id = c2.id
+ AND c1.id = 2
+ SQL
+
+ assert_equal "Firm", object.string_value
+ assert object.string_value?
+
+ object.string_value = " "
+ assert !object.string_value?
+
+ assert_equal 1, object.int_value.to_i
+ assert object.int_value?
+
+ object.int_value = "0"
+ assert !object.int_value?
+ end
+
+ def test_non_attribute_access_and_assignment
+ topic = Topic.new
+ assert !topic.respond_to?("mumbo")
+ assert_raise(NoMethodError) { topic.mumbo }
+ assert_raise(NoMethodError) { topic.mumbo = 5 }
+ end
+
def test_undeclared_attribute_method_does_not_affect_respond_to_and_method_missing
topic = @target.new(:title => 'Budget')
assert topic.respond_to?('title')
diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb
index 0992b2fefb..ca397d3847 100644
--- a/activerecord/test/cases/base_test.rb
+++ b/activerecord/test/cases/base_test.rb
@@ -52,264 +52,6 @@ class BasicsTest < ActiveRecord::TestCase
assert Topic.table_exists?
end
- def test_set_attributes
- topic = Topic.find(1)
- topic.attributes = { "title" => "Budget", "author_name" => "Jason" }
- topic.save
- assert_equal("Budget", topic.title)
- assert_equal("Jason", topic.author_name)
- assert_equal(topics(:first).author_email_address, Topic.find(1).author_email_address)
- end
-
- def test_set_attributes_without_hash
- topic = Topic.new
- assert_nothing_raised { topic.attributes = '' }
- end
-
- def test_integers_as_nil
- test = AutoId.create('value' => '')
- assert_nil AutoId.find(test.id).value
- end
-
- def test_set_attributes_with_block
- topic = Topic.new do |t|
- t.title = "Budget"
- t.author_name = "Jason"
- end
-
- assert_equal("Budget", topic.title)
- assert_equal("Jason", topic.author_name)
- end
-
- def test_respond_to?
- topic = Topic.find(1)
- assert_respond_to topic, "title"
- assert_respond_to topic, "title?"
- assert_respond_to topic, "title="
- assert_respond_to topic, :title
- assert_respond_to topic, :title?
- assert_respond_to topic, :title=
- assert_respond_to topic, "author_name"
- assert_respond_to topic, "attribute_names"
- assert !topic.respond_to?("nothingness")
- assert !topic.respond_to?(:nothingness)
- end
-
- def test_array_content
- topic = Topic.new
- topic.content = %w( one two three )
- topic.save
-
- assert_equal(%w( one two three ), Topic.find(topic.id).content)
- end
-
- def test_read_attributes_before_type_cast
- category = Category.new({:name=>"Test categoty", :type => nil})
- category_attrs = {"name"=>"Test categoty", "type" => nil, "categorizations_count" => nil}
- assert_equal category_attrs , category.attributes_before_type_cast
- end
-
- if current_adapter?(:MysqlAdapter)
- def test_read_attributes_before_type_cast_on_boolean
- bool = Booleantest.create({ "value" => false })
- assert_equal "0", bool.reload.attributes_before_type_cast["value"]
- end
- end
-
- if current_adapter?(:Mysql2Adapter)
- def test_read_attributes_before_type_cast_on_boolean
- bool = Booleantest.create({ "value" => false })
- assert_equal 0, bool.reload.attributes_before_type_cast["value"]
- end
- end
-
- unless current_adapter?(:Mysql2Adapter)
- def test_read_attributes_before_type_cast_on_datetime
- developer = Developer.find(:first)
- # Oracle adapter returns Time before type cast
- if current_adapter?(:OracleAdapter)
- assert_equal developer.created_at.to_s(:db) , developer.attributes_before_type_cast["created_at"].to_s(:db)
-
- developer.created_at = "345643456"
- assert_equal developer.created_at_before_type_cast, "345643456"
- assert_equal developer.created_at, nil
-
- developer.created_at = "2010-03-21T21:23:32+01:00"
- assert_equal developer.created_at_before_type_cast, "2010-03-21T21:23:32+01:00"
- assert_equal developer.created_at, Time.parse("2010-03-21T21:23:32+01:00")
- assert_equal developer.created_at.to_s(:db) , developer.attributes_before_type_cast["created_at"].to_s(:db)
- else
- assert_equal developer.created_at.to_s(:db) , developer.attributes_before_type_cast["created_at"]
- end
- end
- end
-
- def test_hash_content
- topic = Topic.new
- topic.content = { "one" => 1, "two" => 2 }
- topic.save
-
- assert_equal 2, Topic.find(topic.id).content["two"]
-
- topic.content_will_change!
- topic.content["three"] = 3
- topic.save
-
- assert_equal 3, Topic.find(topic.id).content["three"]
- end
-
- def test_update_array_content
- topic = Topic.new
- topic.content = %w( one two three )
-
- topic.content.push "four"
- assert_equal(%w( one two three four ), topic.content)
-
- topic.save
-
- topic = Topic.find(topic.id)
- topic.content << "five"
- assert_equal(%w( one two three four five ), topic.content)
- end
-
- def test_case_sensitive_attributes_hash
- # DB2 is not case-sensitive
- return true if current_adapter?(:DB2Adapter)
-
- assert_equal @loaded_fixtures['computers']['workstation'].to_hash, Computer.find(:first).attributes
- end
-
- def test_hashes_not_mangled
- new_topic = { :title => "New Topic" }
- new_topic_values = { :title => "AnotherTopic" }
-
- topic = Topic.new(new_topic)
- assert_equal new_topic[:title], topic.title
-
- topic.attributes= new_topic_values
- assert_equal new_topic_values[:title], topic.title
- end
-
- def test_create_through_factory
- topic = Topic.create("title" => "New Topic")
- topicReloaded = Topic.find(topic.id)
- assert_equal(topic, topicReloaded)
- end
-
- def test_write_attribute
- topic = Topic.new
- topic.send(:write_attribute, :title, "Still another topic")
- assert_equal "Still another topic", topic.title
-
- topic.send(:write_attribute, "title", "Still another topic: part 2")
- assert_equal "Still another topic: part 2", topic.title
- end
-
- def test_read_attribute
- topic = Topic.new
- topic.title = "Don't change the topic"
- assert_equal "Don't change the topic", topic.send(:read_attribute, "title")
- assert_equal "Don't change the topic", topic["title"]
-
- assert_equal "Don't change the topic", topic.send(:read_attribute, :title)
- assert_equal "Don't change the topic", topic[:title]
- end
-
- def test_read_attribute_when_false
- topic = topics(:first)
- topic.approved = false
- assert !topic.approved?, "approved should be false"
- topic.approved = "false"
- assert !topic.approved?, "approved should be false"
- end
-
- def test_read_attribute_when_true
- topic = topics(:first)
- topic.approved = true
- assert topic.approved?, "approved should be true"
- topic.approved = "true"
- assert topic.approved?, "approved should be true"
- end
-
- def test_read_write_boolean_attribute
- topic = Topic.new
- # puts ""
- # puts "New Topic"
- # puts topic.inspect
- topic.approved = "false"
- # puts "Expecting false"
- # puts topic.inspect
- assert !topic.approved?, "approved should be false"
- topic.approved = "false"
- # puts "Expecting false"
- # puts topic.inspect
- assert !topic.approved?, "approved should be false"
- topic.approved = "true"
- # puts "Expecting true"
- # puts topic.inspect
- assert topic.approved?, "approved should be true"
- topic.approved = "true"
- # puts "Expecting true"
- # puts topic.inspect
- assert topic.approved?, "approved should be true"
- # puts ""
- end
-
- def test_query_attribute_string
- [nil, "", " "].each do |value|
- assert_equal false, Topic.new(:author_name => value).author_name?
- end
-
- assert_equal true, Topic.new(:author_name => "Name").author_name?
- end
-
- def test_query_attribute_number
- [nil, 0, "0"].each do |value|
- assert_equal false, Developer.new(:salary => value).salary?
- end
-
- assert_equal true, Developer.new(:salary => 1).salary?
- assert_equal true, Developer.new(:salary => "1").salary?
- end
-
- def test_query_attribute_boolean
- [nil, "", false, "false", "f", 0].each do |value|
- assert_equal false, Topic.new(:approved => value).approved?
- end
-
- [true, "true", "1", 1].each do |value|
- assert_equal true, Topic.new(:approved => value).approved?
- end
- end
-
- def test_query_attribute_with_custom_fields
- object = Company.find_by_sql(<<-SQL).first
- SELECT c1.*, c2.ruby_type as string_value, c2.rating as int_value
- FROM companies c1, companies c2
- WHERE c1.firm_id = c2.id
- AND c1.id = 2
- SQL
-
- assert_equal "Firm", object.string_value
- assert object.string_value?
-
- object.string_value = " "
- assert !object.string_value?
-
- assert_equal 1, object.int_value.to_i
- assert object.int_value?
-
- object.int_value = "0"
- assert !object.int_value?
- end
-
- def test_non_attribute_access_and_assignment
- topic = Topic.new
- assert !topic.respond_to?("mumbo")
- assert_raise(NoMethodError) { topic.mumbo }
- assert_raise(NoMethodError) { topic.mumbo = 5 }
- end
-
def test_preserving_date_objects
if current_adapter?(:SybaseAdapter)
# Sybase ctlib does not (yet?) support the date type; use datetime instead.
@@ -541,38 +283,6 @@ class BasicsTest < ActiveRecord::TestCase
GUESSED_CLASSES.each(&:reset_table_name)
end
- def test_destroy_all
- conditions = "author_name = 'Mary'"
- topics_by_mary = Topic.all(:conditions => conditions, :order => 'id')
- assert ! topics_by_mary.empty?
-
- assert_difference('Topic.count', -topics_by_mary.size) do
- destroyed = Topic.destroy_all(conditions).sort_by(&:id)
- assert_equal topics_by_mary, destroyed
- assert destroyed.all? { |topic| topic.frozen? }, "destroyed topics should be frozen"
- end
- end
-
- def test_destroy_many
- clients = Client.find([2, 3], :order => 'id')
-
- assert_difference('Client.count', -2) do
- destroyed = Client.destroy([2, 3]).sort_by(&:id)
- assert_equal clients, destroyed
- assert destroyed.all? { |client| client.frozen? }, "destroyed clients should be frozen"
- end
- end
-
- def test_delete_many
- original_count = Topic.count
- Topic.delete(deleting = [1, 2])
- assert_equal original_count - deleting.size, Topic.count
- end
-
- def test_boolean_attributes
- assert ! Topic.find(1).approved?
- assert Topic.find(2).approved?
- end
if current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter)
def test_update_all_with_order_and_limit
@@ -580,63 +290,6 @@ class BasicsTest < ActiveRecord::TestCase
end
end
- # Oracle UPDATE does not support ORDER BY
- unless current_adapter?(:OracleAdapter)
- def test_update_all_ignores_order_without_limit_from_association
- author = authors(:david)
- assert_nothing_raised do
- assert_equal author.posts_with_comments_and_categories.length, author.posts_with_comments_and_categories.update_all([ "body = ?", "bulk update!" ])
- end
- end
-
- def test_update_all_with_order_and_limit_updates_subset_only
- author = authors(:david)
- assert_nothing_raised do
- assert_equal 1, author.posts_sorted_by_id_limited.size
- assert_equal 2, author.posts_sorted_by_id_limited.find(:all, :limit => 2).size
- assert_equal 1, author.posts_sorted_by_id_limited.update_all([ "body = ?", "bulk update!" ])
- assert_equal "bulk update!", posts(:welcome).body
- assert_not_equal "bulk update!", posts(:thinking).body
- end
- end
- end
-
- def test_update_many
- topic_data = { 1 => { "content" => "1 updated" }, 2 => { "content" => "2 updated" } }
- updated = Topic.update(topic_data.keys, topic_data.values)
-
- assert_equal 2, updated.size
- assert_equal "1 updated", Topic.find(1).content
- assert_equal "2 updated", Topic.find(2).content
- end
-
- def test_delete_all
- assert Topic.count > 0
-
- assert_equal Topic.count, Topic.delete_all
- end
-
- def test_update_by_condition
- Topic.update_all "content = 'bulk updated!'", ["approved = ?", true]
- assert_equal "Have a nice day", Topic.find(1).content
- assert_equal "bulk updated!", Topic.find(2).content
- end
-
- def test_attribute_present
- t = Topic.new
- t.title = "hello there!"
- t.written_on = Time.now
- assert t.attribute_present?("title")
- assert t.attribute_present?("written_on")
- assert !t.attribute_present?("content")
- end
-
- def test_attribute_keys_on_new_instance
- t = Topic.new
- assert_equal nil, t.title, "The topics table has a title column, so it should be nil"
- assert_raise(NoMethodError) { t.title2 }
- end
-
def test_null_fields
assert_nil Topic.find(1).parent_id
assert_nil Topic.create("title" => "Hey you").parent_id
@@ -720,8 +373,6 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal [ Topic.find(1) ], [ Topic.find(2).topic ] & [ Topic.find(1) ]
end
-
-
def test_readonly_attributes
assert_equal Set.new([ 'title' , 'comments_count' ]), ReadonlyTitlePost.readonly_attributes
@@ -1323,49 +974,6 @@ class BasicsTest < ActiveRecord::TestCase
end
end
- def test_increment_attribute
- assert_equal 50, accounts(:signals37).credit_limit
- accounts(:signals37).increment! :credit_limit
- assert_equal 51, accounts(:signals37, :reload).credit_limit
-
- accounts(:signals37).increment(:credit_limit).increment!(:credit_limit)
- assert_equal 53, accounts(:signals37, :reload).credit_limit
- end
-
- def test_increment_nil_attribute
- assert_nil topics(:first).parent_id
- topics(:first).increment! :parent_id
- assert_equal 1, topics(:first).parent_id
- end
-
- def test_increment_attribute_by
- assert_equal 50, accounts(:signals37).credit_limit
- accounts(:signals37).increment! :credit_limit, 5
- assert_equal 55, accounts(:signals37, :reload).credit_limit
-
- accounts(:signals37).increment(:credit_limit, 1).increment!(:credit_limit, 3)
- assert_equal 59, accounts(:signals37, :reload).credit_limit
- end
-
- def test_decrement_attribute
- assert_equal 50, accounts(:signals37).credit_limit
-
- accounts(:signals37).decrement!(:credit_limit)
- assert_equal 49, accounts(:signals37, :reload).credit_limit
-
- accounts(:signals37).decrement(:credit_limit).decrement!(:credit_limit)
- assert_equal 47, accounts(:signals37, :reload).credit_limit
- end
-
- def test_decrement_attribute_by
- assert_equal 50, accounts(:signals37).credit_limit
- accounts(:signals37).decrement! :credit_limit, 5
- assert_equal 45, accounts(:signals37, :reload).credit_limit
-
- accounts(:signals37).decrement(:credit_limit, 1).decrement!(:credit_limit, 3)
- assert_equal 41, accounts(:signals37, :reload).credit_limit
- end
-
def test_toggle_attribute
assert !topics(:first).approved?
topics(:first).toggle!(:approved)
@@ -1492,28 +1100,6 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal res6, res7
end
- def test_clear_association_cache_stored
- firm = Firm.find(1)
- assert_kind_of Firm, firm
-
- firm.clear_association_cache
- assert_equal Firm.find(1).clients.collect{ |x| x.name }.sort, firm.clients.collect{ |x| x.name }.sort
- end
-
- def test_clear_association_cache_new_record
- firm = Firm.new
- client_stored = Client.find(3)
- client_new = Client.new
- client_new.name = "The Joneses"
- clients = [ client_stored, client_new ]
-
- firm.clients << clients
- assert_equal clients.map(&:name).to_set, firm.clients.map(&:name).to_set
-
- firm.clear_association_cache
- assert_equal clients.map(&:name).to_set, firm.clients.map(&:name).to_set
- end
-
def test_interpolate_sql
assert_nothing_raised { Category.new.send(:interpolate_sql, 'foo@bar') }
assert_nothing_raised { Category.new.send(:interpolate_sql, 'foo bar) baz') }
@@ -1713,134 +1299,6 @@ class BasicsTest < ActiveRecord::TestCase
assert_no_queries { assert true }
end
- def test_to_xml
- xml = REXML::Document.new(topics(:first).to_xml(:indent => 0))
- bonus_time_in_current_timezone = topics(:first).bonus_time.xmlschema
- written_on_in_current_timezone = topics(:first).written_on.xmlschema
- last_read_in_current_timezone = topics(:first).last_read.xmlschema
-
- assert_equal "topic", xml.root.name
- assert_equal "The First Topic" , xml.elements["//title"].text
- assert_equal "David" , xml.elements["//author-name"].text
- assert_match "Have a nice day", xml.elements["//content"].text
-
- assert_equal "1", xml.elements["//id"].text
- assert_equal "integer" , xml.elements["//id"].attributes['type']
-
- assert_equal "1", xml.elements["//replies-count"].text
- assert_equal "integer" , xml.elements["//replies-count"].attributes['type']
-
- assert_equal written_on_in_current_timezone, xml.elements["//written-on"].text
- assert_equal "datetime" , xml.elements["//written-on"].attributes['type']
-
- assert_equal "david@loudthinking.com", xml.elements["//author-email-address"].text
-
- assert_equal nil, xml.elements["//parent-id"].text
- assert_equal "integer", xml.elements["//parent-id"].attributes['type']
- assert_equal "true", xml.elements["//parent-id"].attributes['nil']
-
- if current_adapter?(:SybaseAdapter)
- assert_equal last_read_in_current_timezone, xml.elements["//last-read"].text
- assert_equal "datetime" , xml.elements["//last-read"].attributes['type']
- else
- # Oracle enhanced adapter allows to define Date attributes in model class (see topic.rb)
- assert_equal "2004-04-15", xml.elements["//last-read"].text
- assert_equal "date" , xml.elements["//last-read"].attributes['type']
- end
-
- # Oracle and DB2 don't have true boolean or time-only fields
- unless current_adapter?(:OracleAdapter, :DB2Adapter)
- assert_equal "false", xml.elements["//approved"].text
- assert_equal "boolean" , xml.elements["//approved"].attributes['type']
-
- assert_equal bonus_time_in_current_timezone, xml.elements["//bonus-time"].text
- assert_equal "datetime" , xml.elements["//bonus-time"].attributes['type']
- end
- end
-
- def test_to_xml_skipping_attributes
- xml = topics(:first).to_xml(:indent => 0, :skip_instruct => true, :except => [:title, :replies_count])
- assert_equal "<topic>", xml.first(7)
- assert !xml.include?(%(<title>The First Topic</title>))
- assert xml.include?(%(<author-name>David</author-name>))
-
- xml = topics(:first).to_xml(:indent => 0, :skip_instruct => true, :except => [:title, :author_name, :replies_count])
- assert !xml.include?(%(<title>The First Topic</title>))
- assert !xml.include?(%(<author-name>David</author-name>))
- end
-
- def test_to_xml_including_has_many_association
- xml = topics(:first).to_xml(:indent => 0, :skip_instruct => true, :include => :replies, :except => :replies_count)
- assert_equal "<topic>", xml.first(7)
- assert xml.include?(%(<replies type="array"><reply>))
- assert xml.include?(%(<title>The Second Topic of the day</title>))
- end
-
- def test_array_to_xml_including_has_many_association
- xml = [ topics(:first), topics(:second) ].to_xml(:indent => 0, :skip_instruct => true, :include => :replies)
- assert xml.include?(%(<replies type="array"><reply>))
- end
-
- def test_array_to_xml_including_methods
- xml = [ topics(:first), topics(:second) ].to_xml(:indent => 0, :skip_instruct => true, :methods => [ :topic_id ])
- assert xml.include?(%(<topic-id type="integer">#{topics(:first).topic_id}</topic-id>)), xml
- assert xml.include?(%(<topic-id type="integer">#{topics(:second).topic_id}</topic-id>)), xml
- end
-
- def test_array_to_xml_including_has_one_association
- xml = [ companies(:first_firm), companies(:rails_core) ].to_xml(:indent => 0, :skip_instruct => true, :include => :account)
- assert xml.include?(companies(:first_firm).account.to_xml(:indent => 0, :skip_instruct => true))
- assert xml.include?(companies(:rails_core).account.to_xml(:indent => 0, :skip_instruct => true))
- end
-
- def test_array_to_xml_including_belongs_to_association
- xml = [ companies(:first_client), companies(:second_client), companies(:another_client) ].to_xml(:indent => 0, :skip_instruct => true, :include => :firm)
- assert xml.include?(companies(:first_client).to_xml(:indent => 0, :skip_instruct => true))
- assert xml.include?(companies(:second_client).firm.to_xml(:indent => 0, :skip_instruct => true))
- assert xml.include?(companies(:another_client).firm.to_xml(:indent => 0, :skip_instruct => true))
- end
-
- def test_to_xml_including_belongs_to_association
- xml = companies(:first_client).to_xml(:indent => 0, :skip_instruct => true, :include => :firm)
- assert !xml.include?("<firm>")
-
- xml = companies(:second_client).to_xml(:indent => 0, :skip_instruct => true, :include => :firm)
- assert xml.include?("<firm>")
- end
-
- def test_to_xml_including_multiple_associations
- xml = companies(:first_firm).to_xml(:indent => 0, :skip_instruct => true, :include => [ :clients, :account ])
- assert_equal "<firm>", xml.first(6)
- assert xml.include?(%(<account>))
- assert xml.include?(%(<clients type="array"><client>))
- end
-
- def test_to_xml_including_multiple_associations_with_options
- xml = companies(:first_firm).to_xml(
- :indent => 0, :skip_instruct => true,
- :include => { :clients => { :only => :name } }
- )
-
- assert_equal "<firm>", xml.first(6)
- assert xml.include?(%(<client><name>Summit</name></client>))
- assert xml.include?(%(<clients type="array"><client>))
- end
-
- def test_to_xml_including_methods
- xml = Company.new.to_xml(:methods => :arbitrary_method, :skip_instruct => true)
- assert_equal "<company>", xml.first(9)
- assert xml.include?(%(<arbitrary-method>I am Jack's profound disappointment</arbitrary-method>))
- end
-
- def test_to_xml_with_block
- value = "Rockin' the block"
- xml = Company.new.to_xml(:skip_instruct => true) do |_xml|
- _xml.tag! "arbitrary-element", value
- end
- assert_equal "<company>", xml.first(9)
- assert xml.include?(%(<arbitrary-element>#{value}</arbitrary-element>))
- end
-
def test_to_param_should_return_string
assert_kind_of String, Client.find(:first).to_param
end
diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb
index a107c1a474..4f3e43d77d 100644
--- a/activerecord/test/cases/finder_test.rb
+++ b/activerecord/test/cases/finder_test.rb
@@ -693,6 +693,14 @@ class FinderTest < ActiveRecord::TestCase
assert_equal [], Topic.find_all_by_title("The First Topic!!")
end
+ def test_find_all_by_one_attribute_which_is_a_symbol
+ topics = Topic.find_all_by_content("Have a nice day".to_sym)
+ assert_equal 2, topics.size
+ assert topics.include?(topics(:first))
+
+ assert_equal [], Topic.find_all_by_title("The First Topic!!")
+ end
+
def test_find_all_by_one_attribute_that_is_an_aggregate
balance = customers(:david).balance
assert_kind_of Money, balance
diff --git a/activerecord/test/cases/method_scoping_test.rb b/activerecord/test/cases/method_scoping_test.rb
index 774b50e2e4..5256ab8d11 100644
--- a/activerecord/test/cases/method_scoping_test.rb
+++ b/activerecord/test/cases/method_scoping_test.rb
@@ -208,6 +208,13 @@ class MethodScopingTest < ActiveRecord::TestCase
end
end
+ def test_scope_for_create_only_uses_equal
+ table = VerySpecialComment.arel_table
+ relation = VerySpecialComment.scoped
+ relation.where_values << table[:id].not_eq(1)
+ assert_equal({:type => "VerySpecialComment"}, relation.send(:scope_for_create))
+ end
+
def test_scoped_create
new_comment = nil
diff --git a/activerecord/test/cases/named_scope_test.rb b/activerecord/test/cases/named_scope_test.rb
index 7c037b20c5..c42dda2ccb 100644
--- a/activerecord/test/cases/named_scope_test.rb
+++ b/activerecord/test/cases/named_scope_test.rb
@@ -478,4 +478,10 @@ class DynamicScopeTest < ActiveRecord::TestCase
assert_equal Post.scoped_by_author_id(1).find(1), Post.find(1)
assert_equal Post.scoped_by_author_id_and_title(1, "Welcome to the weblog").first, Post.find(:first, :conditions => { :author_id => 1, :title => "Welcome to the weblog"})
end
+
+ def test_dynamic_scope_should_create_methods_after_hitting_method_missing
+ assert Developer.methods.grep(/scoped_by_created_at/).blank?
+ Developer.scoped_by_created_at(nil)
+ assert Developer.methods.grep(/scoped_by_created_at/).present?
+ end
end
diff --git a/activerecord/test/cases/persistence_test.rb b/activerecord/test/cases/persistence_test.rb
index 1cc3a337c3..d7666b19f6 100644
--- a/activerecord/test/cases/persistence_test.rb
+++ b/activerecord/test/cases/persistence_test.rb
@@ -19,6 +19,119 @@ class PersistencesTest < ActiveRecord::TestCase
fixtures :topics, :companies, :developers, :projects, :computers, :accounts, :minimalistics, 'warehouse-things', :authors, :categorizations, :categories, :posts, :minivans
+ # Oracle UPDATE does not support ORDER BY
+ unless current_adapter?(:OracleAdapter)
+ def test_update_all_ignores_order_without_limit_from_association
+ author = authors(:david)
+ assert_nothing_raised do
+ assert_equal author.posts_with_comments_and_categories.length, author.posts_with_comments_and_categories.update_all([ "body = ?", "bulk update!" ])
+ end
+ end
+
+ def test_update_all_with_order_and_limit_updates_subset_only
+ author = authors(:david)
+ assert_nothing_raised do
+ assert_equal 1, author.posts_sorted_by_id_limited.size
+ assert_equal 2, author.posts_sorted_by_id_limited.find(:all, :limit => 2).size
+ assert_equal 1, author.posts_sorted_by_id_limited.update_all([ "body = ?", "bulk update!" ])
+ assert_equal "bulk update!", posts(:welcome).body
+ assert_not_equal "bulk update!", posts(:thinking).body
+ end
+ end
+ end
+
+ def test_update_many
+ topic_data = { 1 => { "content" => "1 updated" }, 2 => { "content" => "2 updated" } }
+ updated = Topic.update(topic_data.keys, topic_data.values)
+
+ assert_equal 2, updated.size
+ assert_equal "1 updated", Topic.find(1).content
+ assert_equal "2 updated", Topic.find(2).content
+ end
+
+ def test_delete_all
+ assert Topic.count > 0
+
+ assert_equal Topic.count, Topic.delete_all
+ end
+
+ def test_update_by_condition
+ Topic.update_all "content = 'bulk updated!'", ["approved = ?", true]
+ assert_equal "Have a nice day", Topic.find(1).content
+ assert_equal "bulk updated!", Topic.find(2).content
+ end
+
+ def test_increment_attribute
+ assert_equal 50, accounts(:signals37).credit_limit
+ accounts(:signals37).increment! :credit_limit
+ assert_equal 51, accounts(:signals37, :reload).credit_limit
+
+ accounts(:signals37).increment(:credit_limit).increment!(:credit_limit)
+ assert_equal 53, accounts(:signals37, :reload).credit_limit
+ end
+
+ def test_increment_nil_attribute
+ assert_nil topics(:first).parent_id
+ topics(:first).increment! :parent_id
+ assert_equal 1, topics(:first).parent_id
+ end
+
+ def test_increment_attribute_by
+ assert_equal 50, accounts(:signals37).credit_limit
+ accounts(:signals37).increment! :credit_limit, 5
+ assert_equal 55, accounts(:signals37, :reload).credit_limit
+
+ accounts(:signals37).increment(:credit_limit, 1).increment!(:credit_limit, 3)
+ assert_equal 59, accounts(:signals37, :reload).credit_limit
+ end
+
+ def test_destroy_all
+ conditions = "author_name = 'Mary'"
+ topics_by_mary = Topic.all(:conditions => conditions, :order => 'id')
+ assert ! topics_by_mary.empty?
+
+ assert_difference('Topic.count', -topics_by_mary.size) do
+ destroyed = Topic.destroy_all(conditions).sort_by(&:id)
+ assert_equal topics_by_mary, destroyed
+ assert destroyed.all? { |topic| topic.frozen? }, "destroyed topics should be frozen"
+ end
+ end
+
+ def test_destroy_many
+ clients = Client.find([2, 3], :order => 'id')
+
+ assert_difference('Client.count', -2) do
+ destroyed = Client.destroy([2, 3]).sort_by(&:id)
+ assert_equal clients, destroyed
+ assert destroyed.all? { |client| client.frozen? }, "destroyed clients should be frozen"
+ end
+ end
+
+ def test_delete_many
+ original_count = Topic.count
+ Topic.delete(deleting = [1, 2])
+ assert_equal original_count - deleting.size, Topic.count
+ end
+
+ def test_decrement_attribute
+ assert_equal 50, accounts(:signals37).credit_limit
+
+ accounts(:signals37).decrement!(:credit_limit)
+ assert_equal 49, accounts(:signals37, :reload).credit_limit
+
+ accounts(:signals37).decrement(:credit_limit).decrement!(:credit_limit)
+ assert_equal 47, accounts(:signals37, :reload).credit_limit
+ end
+
+ def test_decrement_attribute_by
+ assert_equal 50, accounts(:signals37).credit_limit
+ accounts(:signals37).decrement! :credit_limit, 5
+ assert_equal 45, accounts(:signals37, :reload).credit_limit
+
+ accounts(:signals37).decrement(:credit_limit, 1).decrement!(:credit_limit, 3)
+ assert_equal 41, accounts(:signals37, :reload).credit_limit
+ end
+
def test_create
topic = Topic.new
topic.title = "New Topic"
diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb
index c9313fe7b6..ac7b501bb7 100644
--- a/activerecord/test/cases/relations_test.rb
+++ b/activerecord/test/cases/relations_test.rb
@@ -192,11 +192,23 @@ class RelationTest < ActiveRecord::TestCase
end
end
- def test_respond_to_private_arel_methods
+ def test_respond_to_delegates_to_relation
relation = Topic.scoped
+ fake_arel = Struct.new(:responds) {
+ def respond_to? method, access = false
+ responds << [method, access]
+ end
+ }.new []
+
+ relation.extend(Module.new { attr_accessor :arel })
+ relation.arel = fake_arel
+
+ relation.respond_to?(:matching_attributes)
+ assert_equal [:matching_attributes, false], fake_arel.responds.first
- assert ! relation.respond_to?(:matching_attributes)
- assert relation.respond_to?(:matching_attributes, true)
+ fake_arel.responds = []
+ relation.respond_to?(:matching_attributes, true)
+ assert_equal [:matching_attributes, true], fake_arel.responds.first
end
def test_respond_to_dynamic_finders
diff --git a/activerecord/test/cases/serialization_test.rb b/activerecord/test/cases/serialization_test.rb
index 8c385af97c..dab81530af 100644
--- a/activerecord/test/cases/serialization_test.rb
+++ b/activerecord/test/cases/serialization_test.rb
@@ -1,7 +1,13 @@
require "cases/helper"
require 'models/contact'
+require 'models/topic'
+require 'models/reply'
+require 'models/company'
class SerializationTest < ActiveRecord::TestCase
+
+ fixtures :topics, :companies, :accounts
+
FORMATS = [ :xml, :json ]
def setup
@@ -17,6 +23,134 @@ class SerializationTest < ActiveRecord::TestCase
@contact = Contact.new(@contact_attributes)
end
+ def test_to_xml
+ xml = REXML::Document.new(topics(:first).to_xml(:indent => 0))
+ bonus_time_in_current_timezone = topics(:first).bonus_time.xmlschema
+ written_on_in_current_timezone = topics(:first).written_on.xmlschema
+ last_read_in_current_timezone = topics(:first).last_read.xmlschema
+
+ assert_equal "topic", xml.root.name
+ assert_equal "The First Topic" , xml.elements["//title"].text
+ assert_equal "David" , xml.elements["//author-name"].text
+ assert_match "Have a nice day", xml.elements["//content"].text
+
+ assert_equal "1", xml.elements["//id"].text
+ assert_equal "integer" , xml.elements["//id"].attributes['type']
+
+ assert_equal "1", xml.elements["//replies-count"].text
+ assert_equal "integer" , xml.elements["//replies-count"].attributes['type']
+
+ assert_equal written_on_in_current_timezone, xml.elements["//written-on"].text
+ assert_equal "datetime" , xml.elements["//written-on"].attributes['type']
+
+ assert_equal "david@loudthinking.com", xml.elements["//author-email-address"].text
+
+ assert_equal nil, xml.elements["//parent-id"].text
+ assert_equal "integer", xml.elements["//parent-id"].attributes['type']
+ assert_equal "true", xml.elements["//parent-id"].attributes['nil']
+
+ if current_adapter?(:SybaseAdapter)
+ assert_equal last_read_in_current_timezone, xml.elements["//last-read"].text
+ assert_equal "datetime" , xml.elements["//last-read"].attributes['type']
+ else
+ # Oracle enhanced adapter allows to define Date attributes in model class (see topic.rb)
+ assert_equal "2004-04-15", xml.elements["//last-read"].text
+ assert_equal "date" , xml.elements["//last-read"].attributes['type']
+ end
+
+ # Oracle and DB2 don't have true boolean or time-only fields
+ unless current_adapter?(:OracleAdapter, :DB2Adapter)
+ assert_equal "false", xml.elements["//approved"].text
+ assert_equal "boolean" , xml.elements["//approved"].attributes['type']
+
+ assert_equal bonus_time_in_current_timezone, xml.elements["//bonus-time"].text
+ assert_equal "datetime" , xml.elements["//bonus-time"].attributes['type']
+ end
+ end
+
+ def test_to_xml_skipping_attributes
+ xml = topics(:first).to_xml(:indent => 0, :skip_instruct => true, :except => [:title, :replies_count])
+ assert_equal "<topic>", xml.first(7)
+ assert !xml.include?(%(<title>The First Topic</title>))
+ assert xml.include?(%(<author-name>David</author-name>))
+
+ xml = topics(:first).to_xml(:indent => 0, :skip_instruct => true, :except => [:title, :author_name, :replies_count])
+ assert !xml.include?(%(<title>The First Topic</title>))
+ assert !xml.include?(%(<author-name>David</author-name>))
+ end
+
+ def test_to_xml_including_has_many_association
+ xml = topics(:first).to_xml(:indent => 0, :skip_instruct => true, :include => :replies, :except => :replies_count)
+ assert_equal "<topic>", xml.first(7)
+ assert xml.include?(%(<replies type="array"><reply>))
+ assert xml.include?(%(<title>The Second Topic of the day</title>))
+ end
+
+ def test_array_to_xml_including_has_many_association
+ xml = [ topics(:first), topics(:second) ].to_xml(:indent => 0, :skip_instruct => true, :include => :replies)
+ assert xml.include?(%(<replies type="array"><reply>))
+ end
+
+ def test_array_to_xml_including_methods
+ xml = [ topics(:first), topics(:second) ].to_xml(:indent => 0, :skip_instruct => true, :methods => [ :topic_id ])
+ assert xml.include?(%(<topic-id type="integer">#{topics(:first).topic_id}</topic-id>)), xml
+ assert xml.include?(%(<topic-id type="integer">#{topics(:second).topic_id}</topic-id>)), xml
+ end
+
+ def test_array_to_xml_including_has_one_association
+ xml = [ companies(:first_firm), companies(:rails_core) ].to_xml(:indent => 0, :skip_instruct => true, :include => :account)
+ assert xml.include?(companies(:first_firm).account.to_xml(:indent => 0, :skip_instruct => true))
+ assert xml.include?(companies(:rails_core).account.to_xml(:indent => 0, :skip_instruct => true))
+ end
+
+ def test_array_to_xml_including_belongs_to_association
+ xml = [ companies(:first_client), companies(:second_client), companies(:another_client) ].to_xml(:indent => 0, :skip_instruct => true, :include => :firm)
+ assert xml.include?(companies(:first_client).to_xml(:indent => 0, :skip_instruct => true))
+ assert xml.include?(companies(:second_client).firm.to_xml(:indent => 0, :skip_instruct => true))
+ assert xml.include?(companies(:another_client).firm.to_xml(:indent => 0, :skip_instruct => true))
+ end
+
+ def test_to_xml_including_belongs_to_association
+ xml = companies(:first_client).to_xml(:indent => 0, :skip_instruct => true, :include => :firm)
+ assert !xml.include?("<firm>")
+
+ xml = companies(:second_client).to_xml(:indent => 0, :skip_instruct => true, :include => :firm)
+ assert xml.include?("<firm>")
+ end
+
+ def test_to_xml_including_multiple_associations
+ xml = companies(:first_firm).to_xml(:indent => 0, :skip_instruct => true, :include => [ :clients, :account ])
+ assert_equal "<firm>", xml.first(6)
+ assert xml.include?(%(<account>))
+ assert xml.include?(%(<clients type="array"><client>))
+ end
+
+ def test_to_xml_including_multiple_associations_with_options
+ xml = companies(:first_firm).to_xml(
+ :indent => 0, :skip_instruct => true,
+ :include => { :clients => { :only => :name } }
+ )
+
+ assert_equal "<firm>", xml.first(6)
+ assert xml.include?(%(<client><name>Summit</name></client>))
+ assert xml.include?(%(<clients type="array"><client>))
+ end
+
+ def test_to_xml_including_methods
+ xml = Company.new.to_xml(:methods => :arbitrary_method, :skip_instruct => true)
+ assert_equal "<company>", xml.first(9)
+ assert xml.include?(%(<arbitrary-method>I am Jack's profound disappointment</arbitrary-method>))
+ end
+
+ def test_to_xml_with_block
+ value = "Rockin' the block"
+ xml = Company.new.to_xml(:skip_instruct => true) do |_xml|
+ _xml.tag! "arbitrary-element", value
+ end
+ assert_equal "<company>", xml.first(9)
+ assert xml.include?(%(<arbitrary-element>#{value}</arbitrary-element>))
+ end
+
def test_serialize_should_be_reversible
for format in FORMATS
@serialized = Contact.new.send("to_#{format}")
diff --git a/activeresource/lib/active_resource/http_mock.rb b/activeresource/lib/active_resource/http_mock.rb
index f192c53b4f..75425c01c0 100644
--- a/activeresource/lib/active_resource/http_mock.rb
+++ b/activeresource/lib/active_resource/http_mock.rb
@@ -123,7 +123,11 @@ module ActiveResource
# def post(path, body, headers)
# request = ActiveResource::Request.new(:post, path, body, headers)
# self.class.requests << request
- # self.class.responses.assoc(request).try(:second) || raise(InvalidRequestError.new("No response recorded for #{request}"))
+ # if response = self.class.responses.assoc(request)
+ # response[1]
+ # else
+ # raise InvalidRequestError.new("No response recorded for #{request}")
+ # end
# end
module_eval <<-EOE, __FILE__, __LINE__ + 1
def #{method}(path, #{'body, ' if has_body}headers)
diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb
index 1c7802f7de..24e407c253 100644
--- a/activesupport/lib/active_support/callbacks.rb
+++ b/activesupport/lib/active_support/callbacks.rb
@@ -419,7 +419,10 @@ module ActiveSupport
@_keyed_callbacks ||= {}
@_keyed_callbacks[name] ||= begin
str = send("_#{kind}_callbacks").compile(name, object)
- class_eval "def #{name}() #{str} end", __FILE__, __LINE__
+ class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
+ def #{name}() #{str} end
+ protected :#{name}
+ RUBY_EVAL
true
end
end
@@ -483,7 +486,11 @@ module ActiveSupport
end
end
- # Skip a previously defined callback for a given type.
+ # Skip a previously defined callback.
+ #
+ # class Writer < Person
+ # skip_callback :validate, :before, :check_membership, :if => lambda { self.age > 18 }
+ # end
#
def skip_callback(name, *filter_list, &block)
__update_callbacks(name, filter_list, block) do |chain, type, filters, options|
@@ -523,7 +530,8 @@ module ActiveSupport
# This macro accepts the following options:
#
# * <tt>:terminator</tt> - Indicates when a before filter is considered
- # to be halted.
+ # to halted. This is a string to be eval'ed and has the result of the
+ # very filter available in the <tt>result</tt> variable:
#
# define_callbacks :validate, :terminator => "result == false"
#
@@ -568,7 +576,9 @@ module ActiveSupport
#
# would trigger <tt>Audit#before_save</tt> instead. That's constructed by calling
# <tt>"#{kind}_#{name}"</tt> on the given instance. In this case "kind" is "before" and
- # "name" is "save".
+ # "name" is "save". In this context ":kind" and ":name" have special meanings: ":kind"
+ # refers to the kind of callback (before/after/around) and ":name" refers to the
+ # method on which callbacks are being defined.
#
# A declaration like
#
diff --git a/activesupport/lib/active_support/concern.rb b/activesupport/lib/active_support/concern.rb
index eb31f7cad4..2d87e8d0e5 100644
--- a/activesupport/lib/active_support/concern.rb
+++ b/activesupport/lib/active_support/concern.rb
@@ -1,3 +1,38 @@
+# A typical module looks like this
+#
+# module M
+# def self.included(base)
+# base.send(:extend, ClassMethods)
+# base.send(:include, InstanceMethods)
+# scope :foo, :conditions => { :created_at => nil }
+# end
+#
+# module ClassMethods
+# def cm; puts 'I am a class method'; end
+# end
+#
+# module InstanceMethods
+# def im; puts 'I am an instance method'; end
+# end
+# end
+#
+# By using <tt>ActiveSupport::Concern</tt> the above module could instead be written as:
+#
+# module M
+# extend ActiveSupport::Concern
+#
+# included do
+# scope :foo, :conditions => { :created_at => nil }
+# end
+#
+# module ClassMethods
+# def cm; puts 'I am a class method'; end
+# end
+#
+# module InstanceMethods
+# def im; puts 'I am an instance method'; end
+# end
+# end
module ActiveSupport
module Concern
def self.extended(base)
diff --git a/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb b/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb
index 92d6dbadd4..e844cf50d1 100644
--- a/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb
+++ b/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb
@@ -5,6 +5,10 @@ require 'active_support/core_ext/array/extract_options'
module ClassInheritableAttributes # :nodoc:
end
+# It is recommend to use <tt>class_attribute</tt> over methods defined in this file. Please
+# refer to documentation for <tt>class_attribute</tt> for more information. Officially it is not
+# deprected but <tt>class_attribute</tt> is faster.
+#
# Allows attributes to be shared within an inheritance hierarchy. Each descendant gets a copy of
# their parents' attributes, instead of just a pointer to the same. This means that the child can add elements
# to, for example, an array without those additions being shared with either their parent, siblings, or
@@ -12,6 +16,24 @@ end
#
# The copies of inheritable parent attributes are added to subclasses when they are created, via the
# +inherited+ hook.
+#
+# class Person
+# class_inheritable_accessor :hair_colors
+# end
+#
+# Person.hair_colors = [:brown, :black, :blonde, :red]
+# Person.hair_colors #=> [:brown, :black, :blonde, :red]
+# Person.new.hair_colors #=> [:brown, :black, :blonde, :red]
+#
+# To opt out of the instance writer method, pass :instance_writer => false.
+# To opt out of the instance reader method, pass :instance_reader => false.
+#
+# class Person
+# class_inheritable_accessor :hair_colors :instance_writer => false, :instance_reader => false
+# end
+#
+# Person.new.hair_colors = [:brown] # => NoMethodError
+# Person.new.hair_colors # => NoMethodError
class Class # :nodoc:
def class_inheritable_reader(*syms)
options = syms.extract_options!
diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb
index 2b80bd214f..1b93eac7ee 100644
--- a/activesupport/lib/active_support/dependencies.rb
+++ b/activesupport/lib/active_support/dependencies.rb
@@ -276,14 +276,22 @@ module ActiveSupport #:nodoc:
end
def depend_on(file_name, swallow_load_errors = false, message = "No such file to load -- %s.rb")
- path = search_for_file(file_name)
- require_or_load(path || file_name)
- rescue LoadError => load_error
- unless swallow_load_errors
- if file_name = load_error.message[/ -- (.*?)(\.rb)?$/, 1]
- raise LoadError.new(message % file_name).copy_blame!(load_error)
+ #path = search_for_file(file_name)
+ require_or_load(file_name)
+ rescue LoadError
+ begin
+ if path = search_for_file(file_name)
+ require_or_load(path)
+ else
+ raise
+ end
+ rescue LoadError => load_error
+ unless swallow_load_errors
+ if file_name = load_error.message[/ -- (.*?)(\.rb)?$/, 1]
+ raise LoadError.new(message % file_name).copy_blame!(load_error)
+ end
+ raise
end
- raise
end
end
diff --git a/activesupport/lib/active_support/ordered_hash.rb b/activesupport/lib/active_support/ordered_hash.rb
index 6b563b9063..2e8d538d0b 100644
--- a/activesupport/lib/active_support/ordered_hash.rb
+++ b/activesupport/lib/active_support/ordered_hash.rb
@@ -4,8 +4,17 @@ YAML.add_builtin_type("omap") do |type, val|
ActiveSupport::OrderedHash[val.map(&:to_a).map(&:first)]
end
-# OrderedHash is namespaced to prevent conflicts with other implementations
module ActiveSupport
+ # The order of iteration over hashes in Ruby 1.8 is undefined. For example, you do not know the
+ # order in which +keys+ will return keys, or +each+ yield pairs. <tt>ActiveSupport::OrderedHash</tt>
+ # implements a hash that preserves insertion order, as in Ruby 1.9:
+ #
+ # oh = ActiveSupport::OrderedHash.new
+ # oh[:a] = 1
+ # oh[:b] = 2
+ # oh.keys # => [:a, :b], this order is guaranteed
+ #
+ # <tt>ActiveSupport::OrderedHash</tt> is namespaced to prevent conflicts with other implementations.
class OrderedHash < ::Hash #:nodoc:
def to_yaml_type
"!tag:yaml.org,2002:omap"
diff --git a/activesupport/lib/active_support/ordered_options.rb b/activesupport/lib/active_support/ordered_options.rb
index 61ccb79211..7fc2b45b51 100644
--- a/activesupport/lib/active_support/ordered_options.rb
+++ b/activesupport/lib/active_support/ordered_options.rb
@@ -1,5 +1,21 @@
require 'active_support/ordered_hash'
+# Usually key value pairs are handled something like this:
+#
+# h = ActiveSupport::OrderedOptions.new
+# h[:boy] = 'John'
+# h[:girl] = 'Mary'
+# h[:boy] # => 'John'
+# h[:girl] # => 'Mary'
+#
+# Using <tt>OrderedOptions</tt> above code could be reduced to:
+#
+# h = ActiveSupport::OrderedOptions.new
+# h.boy = 'John'
+# h.girl = 'Mary'
+# h.boy # => 'John'
+# h.girl # => 'Mary'
+#
module ActiveSupport #:nodoc:
class OrderedOptions < OrderedHash
def []=(key, value)
diff --git a/activesupport/test/core_ext/date_time_ext_test.rb b/activesupport/test/core_ext/date_time_ext_test.rb
index 19d7935211..e8506f5222 100644
--- a/activesupport/test/core_ext/date_time_ext_test.rb
+++ b/activesupport/test/core_ext/date_time_ext_test.rb
@@ -171,22 +171,29 @@ class DateTimeExtCalculationsTest < Test::Unit::TestCase
end
def test_advance
- assert_equal DateTime.civil(2006,2,28,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:years => 1)
- assert_equal DateTime.civil(2005,6,28,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:months => 4)
- assert_equal DateTime.civil(2005,3,21,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:weeks => 3)
- assert_equal DateTime.civil(2005,3,5,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:days => 5)
- assert_equal DateTime.civil(2012,9,28,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:years => 7, :months => 7)
- assert_equal DateTime.civil(2013,10,3,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:years => 7, :months => 19, :days => 5)
+ assert_equal DateTime.civil(2006,2,28,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:years => 1)
+ assert_equal DateTime.civil(2005,6,28,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:months => 4)
+ assert_equal DateTime.civil(2005,3,21,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:weeks => 3)
+ assert_equal DateTime.civil(2005,3,5,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:days => 5)
+ assert_equal DateTime.civil(2012,9,28,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:years => 7, :months => 7)
+ assert_equal DateTime.civil(2013,10,3,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:years => 7, :months => 19, :days => 5)
assert_equal DateTime.civil(2013,10,17,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:years => 7, :months => 19, :weeks => 2, :days => 5)
assert_equal DateTime.civil(2001,12,27,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:years => -3, :months => -2, :days => -1)
- assert_equal DateTime.civil(2005,2,28,15,15,10), DateTime.civil(2004,2,29,15,15,10).advance(:years => 1) #leap day plus one year
- assert_equal DateTime.civil(2005,2,28,20,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:hours => 5)
- assert_equal DateTime.civil(2005,2,28,15,22,10), DateTime.civil(2005,2,28,15,15,10).advance(:minutes => 7)
- assert_equal DateTime.civil(2005,2,28,15,15,19), DateTime.civil(2005,2,28,15,15,10).advance(:seconds => 9)
- assert_equal DateTime.civil(2005,2,28,20,22,19), DateTime.civil(2005,2,28,15,15,10).advance(:hours => 5, :minutes => 7, :seconds => 9)
- assert_equal DateTime.civil(2005,2,28,10,8,1), DateTime.civil(2005,2,28,15,15,10).advance(:hours => -5, :minutes => -7, :seconds => -9)
+ assert_equal DateTime.civil(2005,2,28,15,15,10), DateTime.civil(2004,2,29,15,15,10).advance(:years => 1) #leap day plus one year
+ assert_equal DateTime.civil(2005,2,28,20,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:hours => 5)
+ assert_equal DateTime.civil(2005,2,28,15,22,10), DateTime.civil(2005,2,28,15,15,10).advance(:minutes => 7)
+ assert_equal DateTime.civil(2005,2,28,15,15,19), DateTime.civil(2005,2,28,15,15,10).advance(:seconds => 9)
+ assert_equal DateTime.civil(2005,2,28,20,22,19), DateTime.civil(2005,2,28,15,15,10).advance(:hours => 5, :minutes => 7, :seconds => 9)
+ assert_equal DateTime.civil(2005,2,28,10,8,1), DateTime.civil(2005,2,28,15,15,10).advance(:hours => -5, :minutes => -7, :seconds => -9)
assert_equal DateTime.civil(2013,10,17,20,22,19), DateTime.civil(2005,2,28,15,15,10).advance(:years => 7, :months => 19, :weeks => 2, :days => 5, :hours => 5, :minutes => 7, :seconds => 9)
+ end
+ def test_advanced_processes_first_the_date_deltas_and_then_the_time_deltas
+ # If the time deltas were processed first, the following datetimes would be advanced to 2010/04/01 instead.
+ assert_equal DateTime.civil(2010, 3, 29), DateTime.civil(2010, 2, 28, 23, 59, 59).advance(:months => 1, :seconds => 1)
+ assert_equal DateTime.civil(2010, 3, 29), DateTime.civil(2010, 2, 28, 23, 59).advance(:months => 1, :minutes => 1)
+ assert_equal DateTime.civil(2010, 3, 29), DateTime.civil(2010, 2, 28, 23).advance(:months => 1, :hours => 1)
+ assert_equal DateTime.civil(2010, 3, 29), DateTime.civil(2010, 2, 28, 22, 58, 59).advance(:months => 1, :hours => 1, :minutes => 1, :seconds => 1)
end
def test_next_week
diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile
index 038ca903c1..ec2d5b2787 100644
--- a/railties/guides/source/action_controller_overview.textile
+++ b/railties/guides/source/action_controller_overview.textile
@@ -162,23 +162,38 @@ If you need a different session storage mechanism, you can change it in the +con
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rake db:sessions:create")
-# ActionController::Base.session_store = :active_record_store
+# YourApp::Application.config.session_store :active_record_store
</ruby>
-Rails sets up a session key (the name of the cookie) and (for the CookieStore) a secret key used when signing the session data. These can also be changed in +config/initializers/session_store.rb+:
+Rails sets up a session key (the name of the cookie) when signing the session data. These can also be changed in +config/initializers/session_store.rb+:
<ruby>
-# Your secret key for verifying cookie session data integrity.
-# If you change this key, all old sessions will become invalid!
-# Make sure the secret is at least 30 characters and all random,
+# Be sure to restart your server when you modify this file.
+
+YourApp::Application.config.session_store :cookie_store, :key => '_your_app_session'
+</ruby>
+
+You can also pass a +:domain+ key and specify the domain name for the cookie:
+
+<ruby>
+# Be sure to restart your server when you modify this file.
+
+YourApp::Application.config.session_store :cookie_store, :key => '_your_app_session', :domain => ".example.com"
+</ruby>
+
+Rails sets up (for the CookieStore) a secret key used for signing the session data. This can be changed in +config/initializers/secret_token.rb+
+
+<ruby>
+# Be sure to restart your server when you modify this file.
+
+# Your secret key for verifying the integrity of signed cookies.
+# If you change this key, all old signed cookies will become invalid!
+# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
-ActionController::Base.session = {
- :key => '_yourappname_session',
- :secret => '4f50711b8f0f49572...'
-}
+YourApp::Application.config.secret_token = '49d3f3de9ed86c74b94ad6bd0...'
</ruby>
-NOTE: Changing the secret when using the CookieStore will invalidate all existing sessions.
+NOTE: Changing the secret when using the +CookieStore+ will invalidate all existing sessions.
h4. Accessing the Session
diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile
index 5c4ed3a803..53095a2bd3 100644
--- a/railties/guides/source/active_record_querying.textile
+++ b/railties/guides/source/active_record_querying.textile
@@ -764,7 +764,7 @@ This loads all the posts and the associated category and comments for each post.
h5. Nested Associations Hash
<ruby>
-Category.find(1).includes(:posts => [{:comments => :guest}, :tags])
+Category.includes(:posts => [{:comments => :guest}, :tags]).find(1)
</ruby>
This will find the category with id 1 and eager load all of the associated posts, the associated posts' tags and comments, and every comment's guest association.
diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile
index 136fcde82a..9a449debae 100644
--- a/railties/guides/source/active_support_core_extensions.textile
+++ b/railties/guides/source/active_support_core_extensions.textile
@@ -2979,11 +2979,11 @@ Note in the previous example that increments may be negative.
To perform the computation the method first increments years, then months, then weeks, and finally days. This order is important towards the end of months. Say for example we are at the end of February of 2010, and we want to move one month and one day forward.
-The method +advance+ advances first one month, and the one day, the result is:
+The method +advance+ advances first one month, and then one day, the result is:
<ruby>
-Date.new(2010, 2, 28).advance(:months => 1, :day => 1)
-# => Sun, 28 Mar 2010
+Date.new(2010, 2, 28).advance(:months => 1, :days => 1)
+# => Sun, 29 Mar 2010
</ruby>
While if it did it the other way around the result would be different:
@@ -3053,30 +3053,30 @@ h4(#date-conversions). Conversions
h3. Extensions to +DateTime+
-NOTE: All the following methods are defined in +active_support/core_ext/date_time/calculations.rb+.
-
WARNING: +DateTime+ is not aware of DST rules and so some of these methods have edge cases when a DST change is going on. For example +seconds_since_midnight+ might not return the real amount in such a day.
h4(#calculations-datetime). Calculations
+NOTE: All the following methods are defined in +active_support/core_ext/date_time/calculations.rb+.
+
The class +DateTime+ is a subclass of +Date+ so by loading +active_support/core_ext/date/calculations.rb+ you inherit these methods and their aliases, except that they will always return datetimes:
<ruby>
yesterday
tomorrow
-beginning_of_week
-end_on_week
+beginning_of_week (monday, at_beginning_of_week)
+end_on_week (at_end_of_week)
next_week
months_ago
months_since
-beginning_of_month
-end_of_month
+beginning_of_month (at_beginning_of_month)
+end_of_month (at_end_of_month)
prev_month
next_month
-beginning_of_quarter
-end_of_quarter
-beginning_of_year
-end_of_year
+beginning_of_quarter (at_beginning_of_quarter)
+end_of_quarter (at_end_of_quarter)
+beginning_of_year (at_beginning_of_year)
+end_of_year (at_end_of_year)
years_ago
years_since
prev_year
@@ -3086,10 +3086,10 @@ next_year
The following methods are reimplemented so you do *not* need to load +active_support/core_ext/date/calculations.rb+ for these ones:
<ruby>
-beginning_of_day
+beginning_of_day (midnight, at_midnight, at_beginning_of_day)
end_of_day
ago
-since
+since (in)
</ruby>
On the other hand, +advance+ and +change+ are also defined and support more options, they are documented below.
@@ -3132,6 +3132,37 @@ now.utc? # => false
now.utc.utc? # => true
</ruby>
+h6(#datetime-advance). +advance+
+
+The most generic way to jump to another datetime is +advance+. This method receives a hash with keys +:years+, +:months+, +:weeks+, +:days+, +:hours+, +:minutes+, and +:seconds+, and returns a datetime advanced as much as the present keys indicate.
+
+<ruby>
+d = DateTime.current
+# => Thu, 05 Aug 2010 11:33:31 +0000
+d.advance(:years => 1, :months => 1, :days => 1, :hours => 1, :minutes => 1, :seconds => 1)
+# => Tue, 06 Sep 2011 12:34:32 +0000
+</ruby>
+
+This method first computes the destination date passing +:years+, +:months+, +:weeks+, and +:days+ to +Date#advance+ documented above. After that, it adjusts the time calling +since+ with the number of seconds to advance. This order is relevant, a different ordering would give different datetimes in some edge-cases. The example in +Date#advance+ applies, and we can extend it to show order relevance related to the time bits.
+
+If we first move the date bits (that have also a relative order of processing, as documented before), and then the time bits we get for example the following computation:
+
+<ruby>
+d = DateTime.new(2010, 2, 28, 23, 59, 59)
+# => Sun, 28 Feb 2010 23:59:59 +0000
+d.advance(:months => 1, :seconds => 1)
+# => Mon, 29 Mar 2010 00:00:00 +0000
+</ruby>
+
+but if we computed them the other way around, the result would be different:
+
+<ruby>
+d.advance(:seconds => 1).advance(:months => 1)
+# => Thu, 01 Apr 2010 00:00:00 +0000
+</ruby>
+
+WARNING: Since +DateTime+ is not DST-aware you can end up in a non-existing point in time with no warning or error telling you so.
+
h5(#datetime-changing-components). Changing Components
The method +change+ allows you to get a new datetime which is the same as the receiver except for the given options, which may include +:year+, +:month+, +:day+, +:hour+, +:min+, +:sec+, +:offset+, +:start+:
@@ -3168,7 +3199,93 @@ h4(#datetime-conversions). Conversions
h3. Extensions to +Time+
-...
+h4(#time-calculations). Calculations
+
+NOTE: All the following methods are defined in +active_support/core_ext/time/calculations.rb+.
+
+Active Support adds to +Time+ many of the methods available for +DateTime+:
+
+<ruby>
+past?
+today?
+future?
+yesterday
+tomorrow
+seconds_since_midnight
+change
+advance
+ago
+since (in)
+beginning_of_day (midnight, at_midnight, at_beginning_of_day)
+end_of_day
+beginning_of_week (monday, at_beginning_of_week)
+end_on_week (at_end_of_week)
+next_week
+months_ago
+months_since
+beginning_of_month (at_beginning_of_month)
+end_of_month (at_end_of_month)
+prev_month
+next_month
+beginning_of_quarter (at_beginning_of_quarter)
+end_of_quarter (at_end_of_quarter)
+beginning_of_year (at_beginning_of_year)
+end_of_year (at_end_of_year)
+years_ago
+years_since
+prev_year
+next_year
+</ruby>
+
+They are analogous. Please refer to their documentation above and take into account the following differences:
+
+* +change+ accepts an additional +:usec+ option.
+* +Time+ understands DST, so you get correct DST calculations as in
+
+<ruby>
+# In Barcelona, 2010/03/28 02:00 +0100 becomes 2010/03/28 03:00 +0200 due to DST.
+t = Time.local_time(2010, 3, 28, 1, 59, 59)
+# => Sun Mar 28 01:59:59 +0100 2010
+t.advance(:seconds => 1)
+# => Sun Mar 28 03:00:00 +0200 2010
+</ruby>
+
+* If +since+ or +ago+ jump to a time that can't be expressed with +Time+ a +DateTime+ object is returned instead.
+
+h4. Time Constructors
+
+Active Support defines +Time.current+ to be +Time.zone.now+ if there's a user time zone defined, with fallback to +Time.now+:
+
+<ruby>
+Time.zone_default
+# => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...>
+Time.current
+# => Fri, 06 Aug 2010 17:11:58 CEST +02:00
+</ruby>
+
+Analogously to +DateTime+, the predicates +past?+, and +future?+ are relative to +Time.current+.
+
+Use the +local_time+ class method to create time objects honoring the user time zone:
+
+<ruby>
+Time.zone_default
+# => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...>
+Time.local_time(2010, 8, 15)
+# => Sun Aug 15 00:00:00 +0200 2010
+</ruby>
+
+The +utc_time+ class method returns a time in UTC:
+
+<ruby>
+Time.zone_default
+# => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...>
+Time.utc_time(2010, 8, 15)
+# => Sun Aug 15 00:00:00 UTC 2010
+</ruby>
+
+Both +local_time+ and +utc_time+ accept up to seven positional arguments: year, month, day, hour, min, sec, usec. Year is mandatory, month and day default to 1, and the rest default to 0.
+
+If the time to be constructed lies beyond the range supported by +Time+ in the runtime platform, usecs are discarded and a +DateTime+ object is returned instead.
h3. Extensions to +Process+
diff --git a/railties/guides/source/api_documentation_guidelines.textile b/railties/guides/source/api_documentation_guidelines.textile
index d9a0d39d9d..9f201de49b 100644
--- a/railties/guides/source/api_documentation_guidelines.textile
+++ b/railties/guides/source/api_documentation_guidelines.textile
@@ -29,7 +29,7 @@ Documentation has to be concise but comprehensive. Explore and document edge cas
The proper names of Rails components have a space in between the words, like "Active Support". +ActiveRecord+ is a Ruby module, whereas Active Record is an ORM. Historically there has been lack of consistency regarding this, but we checked with David when docrails started. All Rails documentation consistently refer to Rails components by their proper name, and if in your next blog post or presentation you remember this tidbit and take it into account that'd be fenomenal :).
-Spell names correctly: HTML, MySQL, JavaScript, ERb.
+Spell names correctly: HTML, MySQL, JavaScript, ERb. Use the article "an" for "SQL", as in "an SQL statement". Also "an SQLite database".
h3. Example Code
diff --git a/railties/guides/source/form_helpers.textile b/railties/guides/source/form_helpers.textile
index 1f1b7d076e..146b75da3f 100644
--- a/railties/guides/source/form_helpers.textile
+++ b/railties/guides/source/form_helpers.textile
@@ -647,7 +647,7 @@ the +params+ hash will contain
{'person' => {'name' => 'Henry'}}
</erb>
-and +params["name"]+ will retrieve the submitted value in the controller.
+and +params[:person][:name]+ will retrieve the submitted value in the controller.
Hashes can be nested as many levels as required, for example
diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile
index 12f2bb146b..ffb0310816 100644
--- a/railties/guides/source/getting_started.textile
+++ b/railties/guides/source/getting_started.textile
@@ -213,9 +213,9 @@ If you open this file in a new Rails application, you'll see a default database
* The +test+ environment is used to run automated tests
* The +production+ environment is used when you deploy your application for the world to use.
-h5. Configuring a SQLite3 Database
+h5. Configuring an SQLite3 Database
-Rails comes with built-in support for "SQLite3":http://www.sqlite.org, which is a lightweight serverless database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails defaults to using a SQLite database when creating a new project, but you can always change it later.
+Rails comes with built-in support for "SQLite3":http://www.sqlite.org, which is a lightweight serverless database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails defaults to using an SQLite database when creating a new project, but you can always change it later.
Here's the section of the default configuration file (<tt>config/database.yml</tt>) with connection information for the development environment:
diff --git a/railties/guides/source/routing.textile b/railties/guides/source/routing.textile
index 7b665d81e7..625941ba31 100644
--- a/railties/guides/source/routing.textile
+++ b/railties/guides/source/routing.textile
@@ -762,6 +762,12 @@ formatted_users GET /users.:format {:controller=>"users", :action=>"index"}
POST /users.:format {:controller=>"users", :action=>"create"}
</pre>
+You may restrict the listing to the routes that map to a particular controller setting the +CONTROLLER+ environment variable:
+
+<shell>
+$ CONTROLLER=users rake routes
+</shell>
+
TIP: You'll find that the output from +rake routes+ is much more readable if you widen your terminal window until the output lines don't wrap.
h4. Testing Routes
diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb
index 6622cfdd2f..5b26333486 100644
--- a/railties/lib/rails/application.rb
+++ b/railties/lib/rails/application.rb
@@ -205,7 +205,7 @@ module Rails
middleware.use ::ActionDispatch::ParamsParser
middleware.use ::Rack::MethodOverride
middleware.use ::ActionDispatch::Head
- middleware.use ::ActionDispatch::BestStandardsSupport if config.action_dispatch.best_standards_support
+ middleware.use ::ActionDispatch::BestStandardsSupport, config.action_dispatch.best_standards_support if config.action_dispatch.best_standards_support
end
end
diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/oracle.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/oracle.yml
index f99ee937f3..fddf8b8144 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/databases/oracle.yml
+++ b/railties/lib/rails/generators/rails/app/templates/config/databases/oracle.yml
@@ -4,7 +4,7 @@
# http://rubyforge.org/projects/ruby-oci8/
#
# Specify your database using any valid connection syntax, such as a
-# tnsnames.ora service name, or a SQL connect url string of the form:
+# tnsnames.ora service name, or an SQL connect string of the form:
#
# //host:[port][/service name]
#
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
index 99758dfcf7..7616614aff 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
@@ -19,4 +19,8 @@
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
+
+ # Only use best-standards-support built into browsers
+ config.action_dispatch.best_standards_support = :builtin
end
+
diff --git a/railties/lib/rails/rack/log_tailer.rb b/railties/lib/rails/rack/log_tailer.rb
index 3fa45156c3..011ac6cecc 100644
--- a/railties/lib/rails/rack/log_tailer.rb
+++ b/railties/lib/rails/rack/log_tailer.rb
@@ -6,7 +6,6 @@ module Rails
path = Pathname.new(log || "#{File.expand_path(Rails.root)}/log/#{Rails.env}.log").cleanpath
@cursor = ::File.size(path)
- @last_checked = Time.now.to_f
@file = ::File.open(path, 'r')
end
@@ -20,11 +19,9 @@ module Rails
def tail!
@file.seek @cursor
- mod = @file.mtime.to_f
- if mod > @last_checked
+ if !@file.eof?
contents = @file.read
- @last_checked = mod
- @cursor += contents.size
+ @cursor = @file.tell
$stdout.print contents
end
end
diff --git a/railties/lib/rails/railtie.rb b/railties/lib/rails/railtie.rb
index f0d9d95fc4..8a6e2716dc 100644
--- a/railties/lib/rails/railtie.rb
+++ b/railties/lib/rails/railtie.rb
@@ -6,53 +6,53 @@ require 'active_support/deprecation'
module Rails
# Railtie is the core of the Rails Framework and provides several hooks to extend
# Rails and/or modify the initialization process.
- #
+ #
# Every major component of Rails (Action Mailer, Action Controller,
# Action View, Active Record and Active Resource) are all Railties, so each of
# them is responsible to set their own initialization. This makes, for example,
# Rails absent of any Active Record hook, allowing any other ORM framework to hook in.
- #
+ #
# Developing a Rails extension does _not_ require any implementation of
# Railtie, but if you need to interact with the Rails framework during
# or after boot, then Railtie is what you need to do that interaction.
- #
+ #
# For example, the following would need you to implement Railtie in your
# plugin:
- #
+ #
# * creating initializers
# * configuring a Rails framework or the Application, like setting a generator
# * adding Rails config.* keys to the environment
# * setting up a subscriber to the Rails +ActiveSupport::Notifications+
# * adding rake tasks into rails
- #
+ #
# == Creating your Railtie
#
# Implementing Railtie in your Rails extension is done by creating a class
# Railtie that has your extension name and making sure that this gets loaded
# during boot time of the Rails stack.
- #
+ #
# You can do this however you wish, but here is an example if you want to provide
# it for a gem that can be used with or without Rails:
- #
+ #
# * Create a file (say, lib/my_gem/railtie.rb) which contains class Railtie inheriting from
# Rails::Railtie and is namespaced to your gem:
#
- # # lib/my_gem/railtie.rb
- # module MyGem
- # class Railtie < Rails::Railtie
+ # # lib/my_gem/railtie.rb
+ # module MyGem
+ # class Railtie < Rails::Railtie
+ # end
# end
- # end
- #
+ #
# * Require your own gem as well as rails in this file:
- #
- # # lib/my_gem/railtie.rb
- # require 'my_gem'
- # require 'rails'
- #
- # module MyGem
- # class Railtie < Rails::Railtie
+ #
+ # # lib/my_gem/railtie.rb
+ # require 'my_gem'
+ # require 'rails'
+ #
+ # module MyGem
+ # class Railtie < Rails::Railtie
+ # end
# end
- # end
#
# == Initializers
#
@@ -65,7 +65,7 @@ module Rails
# end
# end
#
- # If specified, the block can also receive the application object, in case you
+ # If specified, the block can also receive the application object, in case you
# need to access some application specific configuration, like middleware:
#
# class MyRailtie < Rails::Railtie
diff --git a/railties/test/application/routing_test.rb b/railties/test/application/routing_test.rb
index a10a39ef40..febc53bac9 100644
--- a/railties/test/application/routing_test.rb
+++ b/railties/test/application/routing_test.rb
@@ -11,19 +11,19 @@ module ApplicationTests
extend Rack::Test::Methods
end
- def app
+ def app(env = "production")
+ old_env = ENV["RAILS_ENV"]
+
@app ||= begin
+ ENV["RAILS_ENV"] = env
require "#{app_path}/config/environment"
Rails.application
end
+ ensure
+ ENV["RAILS_ENV"] = old_env
end
- test "rails/info/properties" do
- get "/rails/info/properties"
- assert_equal 200, last_response.status
- end
-
- test "simple controller" do
+ def simple_controller
controller :foo, <<-RUBY
class FooController < ApplicationController
def index
@@ -37,12 +37,42 @@ module ApplicationTests
match ':controller(/:action)'
end
RUBY
+ end
+
+ test "rails/info/properties in development" do
+ app("development")
+ get "/rails/info/properties"
+ assert_equal 200, last_response.status
+ end
+
+ test "rails/info/properties in production" do
+ app("production")
+ get "/rails/info/properties"
+ assert_equal 404, last_response.status
+ end
+
+ test "simple controller" do
+ simple_controller
get '/foo'
assert_equal 'foo', last_response.body
+ end
+
+ test "simple controller in production mode returns best standards" do
+ simple_controller
+
+ get '/foo'
assert_equal "IE=Edge,chrome=1", last_response.headers["X-UA-Compatible"]
end
+ test "simple controller in development mode leaves out Chrome" do
+ simple_controller
+ app("development")
+
+ get "/foo"
+ assert_equal "IE=Edge", last_response.headers["X-UA-Compatible"]
+ end
+
test "simple controller with helper" do
controller :foo, <<-RUBY
class FooController < ApplicationController
@@ -147,38 +177,42 @@ module ApplicationTests
assert_equal 'admin::foo', last_response.body
end
- test "reloads routes when configuration is changed" do
- controller :foo, <<-RUBY
- class FooController < ApplicationController
- def bar
- render :text => "bar"
+ {"development" => "baz", "production" => "bar"}.each do |mode, expected|
+ test "reloads routes when configuration is changed in #{mode}" do
+ controller :foo, <<-RUBY
+ class FooController < ApplicationController
+ def bar
+ render :text => "bar"
+ end
+
+ def baz
+ render :text => "baz"
+ end
end
+ RUBY
- def baz
- render :text => "baz"
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do |map|
+ match 'foo', :to => 'foo#bar'
end
- end
- RUBY
+ RUBY
- app_file 'config/routes.rb', <<-RUBY
- AppTemplate::Application.routes.draw do |map|
- match 'foo', :to => 'foo#bar'
- end
- RUBY
+ app(mode)
- get '/foo'
- assert_equal 'bar', last_response.body
+ get '/foo'
+ assert_equal 'bar', last_response.body
- app_file 'config/routes.rb', <<-RUBY
- AppTemplate::Application.routes.draw do |map|
- match 'foo', :to => 'foo#baz'
- end
- RUBY
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do |map|
+ match 'foo', :to => 'foo#baz'
+ end
+ RUBY
- sleep 0.1
+ sleep 0.1
- get '/foo'
- assert_equal 'baz', last_response.body
+ get '/foo'
+ assert_equal expected, last_response.body
+ end
end
test 'resource routing with irrigular inflection' do
diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb
index 21725a380c..08cfb585f9 100644
--- a/railties/test/generators/app_generator_test.rb
+++ b/railties/test/generators/app_generator_test.rb
@@ -114,7 +114,7 @@ class AppGeneratorTest < Rails::Generators::TestCase
Rails.application.config.root = app_moved_root
Rails.application.class.stubs(:name).returns("Myapp")
- Rails.application.stubs(:instance_of?).returns(Rails::Application)
+ Rails.application.stubs(:is_a?).returns(Rails::Application)
FileUtils.mv(app_root, app_moved_root)