diff options
71 files changed, 365 insertions, 730 deletions
@@ -4,7 +4,7 @@ gemspec gem 'arel', github: 'rails/arel', branch: 'master' -gem 'mocha', '>= 0.11.2', :require => false +gem 'mocha', '>= 0.11.2', require: false gem 'rack-test', github: 'brynary/rack-test' gem 'rack-cache', '~> 1.2' gem 'bcrypt-ruby', '~> 3.0.0' @@ -28,7 +28,7 @@ group :doc do # for some weeks unapplied. As a temporary solution # this is our own fork with the fix. gem 'sdoc', github: 'fxn/sdoc' - gem 'redcarpet', '~> 2.1.1', :platforms => :ruby + gem 'redcarpet', '~> 2.2.2', platforms: :ruby gem 'w3c_validators' end diff --git a/actionpack/lib/abstract_controller/rendering.rb b/actionpack/lib/abstract_controller/rendering.rb index 3da2834af0..4b984d0558 100644 --- a/actionpack/lib/abstract_controller/rendering.rb +++ b/actionpack/lib/abstract_controller/rendering.rb @@ -51,7 +51,7 @@ module AbstractController @view_context_class ||= begin routes = respond_to?(:_routes) && _routes helpers = respond_to?(:_helpers) && _helpers - + Class.new(ActionView::Base) do if routes include routes.url_helpers diff --git a/actionpack/lib/action_controller/metal/mime_responds.rb b/actionpack/lib/action_controller/metal/mime_responds.rb index 18ae2c3bfc..d86e8092c4 100644 --- a/actionpack/lib/action_controller/metal/mime_responds.rb +++ b/actionpack/lib/action_controller/metal/mime_responds.rb @@ -259,7 +259,7 @@ module ActionController #:nodoc: # * for other requests - i.e. data formats such as xml, json, csv etc, if # the resource passed to +respond_with+ responds to <code>to_<format></code>, # the method attempts to render the resource in the requested format - # directly, e.g. for an xml request, the response is equivalent to calling + # directly, e.g. for an xml request, the response is equivalent to calling # <code>render :xml => resource</code>. # # === Nested resources diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index 4bd7b69642..ca96ec5f12 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -3,6 +3,7 @@ require 'uri' require 'active_support/core_ext/kernel/singleton_class' require 'active_support/core_ext/object/try' require 'rack/test' +require 'minitest/unit' module ActionDispatch module Integration #:nodoc: diff --git a/actionpack/lib/action_view/renderer/template_renderer.rb b/actionpack/lib/action_view/renderer/template_renderer.rb index 156ad4e547..2a5ea5a711 100644 --- a/actionpack/lib/action_view/renderer/template_renderer.rb +++ b/actionpack/lib/action_view/renderer/template_renderer.rb @@ -29,8 +29,11 @@ module ActionView handler = Template.handler_for_extension(options[:type] || "erb") Template.new(options[:inline], "inline template", handler, :locals => keys) elsif options.key?(:template) - options[:template].respond_to?(:render) ? - options[:template] : find_template(options[:template], options[:prefixes], false, keys, @details) + if options[:template].respond_to?(:render) + options[:template] + else + find_template(options[:template], options[:prefixes], false, keys, @details) + end else raise ArgumentError, "You invoked render but did not give any of :partial, :template, :inline, :file or :text option." end diff --git a/actionpack/test/activerecord/controller_runtime_test.rb b/actionpack/test/activerecord/controller_runtime_test.rb index 2d789395ce..1df826fe2b 100644 --- a/actionpack/test/activerecord/controller_runtime_test.rb +++ b/actionpack/test/activerecord/controller_runtime_test.rb @@ -15,7 +15,7 @@ class ControllerRuntimeLogSubscriberTest < ActionController::TestCase def zero render :inline => "Zero DB runtime" end - + def redirect Project.all redirect_to :action => 'show' @@ -63,18 +63,18 @@ class ControllerRuntimeLogSubscriberTest < ActionController::TestCase assert_equal 2, @logger.logged(:info).size assert_match(/\(Views: [\d.]+ms \| ActiveRecord: 0.0ms\)/, @logger.logged(:info)[1]) end - + def test_log_with_active_record_when_redirecting get :redirect wait assert_equal 3, @logger.logged(:info).size assert_match(/\(ActiveRecord: [\d.]+ms\)/, @logger.logged(:info)[2]) end - + def test_include_time_query_time_after_rendering get :db_after_render wait - + assert_equal 2, @logger.logged(:info).size assert_match(/\(Views: [\d.]+ms \| ActiveRecord: ([1-9][\d.]+)ms\)/, @logger.logged(:info)[1]) end diff --git a/actionpack/test/controller/default_url_options_with_filter_test.rb b/actionpack/test/controller/default_url_options_with_filter_test.rb index ef028e8cdb..9a9ab17fee 100644 --- a/actionpack/test/controller/default_url_options_with_filter_test.rb +++ b/actionpack/test/controller/default_url_options_with_filter_test.rb @@ -16,7 +16,7 @@ class ControllerWithBeforeFilterAndDefaultUrlOptions < ActionController::Base def default_url_options {:locale => "de"} - end + end end class ControllerWithBeforeFilterAndDefaultUrlOptionsTest < ActionController::TestCase diff --git a/actionpack/test/controller/http_basic_authentication_test.rb b/actionpack/test/controller/http_basic_authentication_test.rb index 7286b249c7..2dcfda02a7 100644 --- a/actionpack/test/controller/http_basic_authentication_test.rb +++ b/actionpack/test/controller/http_basic_authentication_test.rb @@ -19,7 +19,7 @@ class HttpBasicAuthenticationTest < ActionController::TestCase def show render :text => 'Only for loooooong credentials' end - + def search render :text => 'All inline' end @@ -118,7 +118,7 @@ class HttpBasicAuthenticationTest < ActionController::TestCase assert assigns(:logged_in) assert_equal 'Definitely Maybe', @response.body end - + test "authenticate with class method" do @request.env['HTTP_AUTHORIZATION'] = encode_credentials('David', 'Goliath') get :search diff --git a/actionpack/test/controller/mime_responds_test.rb b/actionpack/test/controller/mime_responds_test.rb index b21d35c846..d183b0be17 100644 --- a/actionpack/test/controller/mime_responds_test.rb +++ b/actionpack/test/controller/mime_responds_test.rb @@ -240,7 +240,7 @@ class RespondToControllerTest < ActionController::TestCase assert_equal 'HTML', @response.body @request.accept = "text/javascript, text/html" - + assert_raises(ActionController::UnknownFormat) do xhr :get, :just_xml end diff --git a/actionpack/test/controller/new_base/middleware_test.rb b/actionpack/test/controller/new_base/middleware_test.rb index ccef060863..6b7b5e10e3 100644 --- a/actionpack/test/controller/new_base/middleware_test.rb +++ b/actionpack/test/controller/new_base/middleware_test.rb @@ -25,14 +25,14 @@ module MiddlewareTest result end end - + class BlockMiddleware attr_accessor :configurable_message def initialize(app, &block) @app = app yield(self) if block_given? end - + def call(env) result = @app.call(env) result[1]["Configurable-Message"] = configurable_message diff --git a/actionpack/test/controller/new_base/render_partial_test.rb b/actionpack/test/controller/new_base/render_partial_test.rb index b4a25c49c9..2f1aa22208 100644 --- a/actionpack/test/controller/new_base/render_partial_test.rb +++ b/actionpack/test/controller/new_base/render_partial_test.rb @@ -28,7 +28,7 @@ module RenderPartial @test_unchanged = 'hello' end end - + class ChildController < BasicController; end class TestPartial < Rack::TestCase diff --git a/actionpack/test/controller/send_file_test.rb b/actionpack/test/controller/send_file_test.rb index 97ede35317..8bf3096888 100644 --- a/actionpack/test/controller/send_file_test.rb +++ b/actionpack/test/controller/send_file_test.rb @@ -134,7 +134,7 @@ class SendFileTest < ActionController::TestCase @controller.headers = {} assert_raise(ArgumentError){ @controller.send(:send_file_headers!, options) } end - + def test_send_file_headers_guess_type_from_extension { 'image.png' => 'image/png', diff --git a/actionpack/test/template/digestor_test.rb b/actionpack/test/template/digestor_test.rb index b9d26da3af..f493c8201d 100644 --- a/actionpack/test/template/digestor_test.rb +++ b/actionpack/test/template/digestor_test.rb @@ -63,7 +63,7 @@ class TemplateDigestorTest < ActionView::TestCase change_template("comments/_comment") end end - + def test_directory_depth_dependency assert_digest_difference("level/below/index") do change_template("level/below/_header") diff --git a/actionpack/test/template/render_test.rb b/actionpack/test/template/render_test.rb index ddf5c6a1b3..4e6a676fc6 100644 --- a/actionpack/test/template/render_test.rb +++ b/actionpack/test/template/render_test.rb @@ -451,12 +451,12 @@ module RenderTestCases assert_equal %(<title>David</title>), @view.render(:file => "test/layout_render_object") end - + def test_render_with_passing_couple_extensions_to_one_register_template_handler_function_call ActionView::Template.register_template_handler :foo1, :foo2, CustomHandler assert_equal @view.render(:inline => "Hello, World!", :type => :foo1), @view.render(:inline => "Hello, World!", :type => :foo2) end - + def test_render_throws_exception_when_no_extensions_passed_to_register_template_handler_function_call assert_raises(ArgumentError) { ActionView::Template.register_template_handler CustomHandler } end diff --git a/activemodel/lib/active_model/serializers/json.rb b/activemodel/lib/active_model/serializers/json.rb index a4252b995d..9d984b7a18 100644 --- a/activemodel/lib/active_model/serializers/json.rb +++ b/activemodel/lib/active_model/serializers/json.rb @@ -1,8 +1,8 @@ require 'active_support/json' module ActiveModel - # == Active Model JSON Serializer module Serializers + # == Active Model JSON Serializer module JSON extend ActiveSupport::Concern include ActiveModel::Serialization diff --git a/activemodel/lib/active_model/serializers/xml.rb b/activemodel/lib/active_model/serializers/xml.rb index cf742d0569..fb6093cce5 100755 --- a/activemodel/lib/active_model/serializers/xml.rb +++ b/activemodel/lib/active_model/serializers/xml.rb @@ -4,12 +4,16 @@ require 'active_support/core_ext/hash/conversions' require 'active_support/core_ext/hash/slice' module ActiveModel - # == Active Model XML Serializer module Serializers + # == Active Model XML Serializer module Xml extend ActiveSupport::Concern include ActiveModel::Serialization + included do + extend ActiveModel::Naming + end + class Serializer #:nodoc: class Attribute #:nodoc: attr_reader :name, :value, :type diff --git a/activemodel/test/cases/serializers/json_serialization_test.rb b/activemodel/test/cases/serializers/json_serialization_test.rb index e2690f1827..bb5be8cdeb 100644 --- a/activemodel/test/cases/serializers/json_serialization_test.rb +++ b/activemodel/test/cases/serializers/json_serialization_test.rb @@ -4,7 +4,6 @@ require 'models/automobile' require 'active_support/core_ext/object/instance_variables' class Contact - extend ActiveModel::Naming include ActiveModel::Serializers::JSON include ActiveModel::Validations diff --git a/activemodel/test/cases/serializers/xml_serialization_test.rb b/activemodel/test/cases/serializers/xml_serialization_test.rb index e2bb0dda0b..90ddf8ff0c 100755 --- a/activemodel/test/cases/serializers/xml_serialization_test.rb +++ b/activemodel/test/cases/serializers/xml_serialization_test.rb @@ -4,7 +4,6 @@ require 'active_support/core_ext/object/instance_variables' require 'ostruct' class Contact - extend ActiveModel::Naming include ActiveModel::Serializers::Xml attr_accessor :address, :friends @@ -25,7 +24,6 @@ class Customer < Struct.new(:name) end class Address - extend ActiveModel::Naming include ActiveModel::Serializers::Xml attr_accessor :street, :city, :state, :zip, :apt_number diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index f9f30b0d21..c99f09f478 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,5 +1,9 @@ ## Rails 4.0.0 (unreleased) ## +* Decode URI encoded attributes on database connection URLs. + + *Shawn Veader* + * Add `find_or_create_by`, `find_or_create_by!` and `find_or_initialize_by` methods to `Relation`. @@ -38,7 +42,7 @@ *Jon Leighton* -* Fix bug with presence validation of associations. Would incorrectly add duplicated errors +* Fix bug with presence validation of associations. Would incorrectly add duplicated errors when the association was blank. Bug introduced in 1fab518c6a75dac5773654646eb724a59741bc13. *Scott Willson* @@ -926,34 +930,6 @@ *Aaron Patterson* -* Added the `ActiveRecord::Model` module which can be included in a - class as an alternative to inheriting from `ActiveRecord::Base`: - - class Post - include ActiveRecord::Model - end - - Please note: - - * Up until now it has been safe to assume that all AR models are - descendants of `ActiveRecord::Base`. This is no longer a safe - assumption, but it may transpire that there are areas of the - code which still make this assumption. So there may be - 'teething difficulties' with this feature. (But please do try it - and report bugs.) - - * Plugins & libraries etc that add methods to `ActiveRecord::Base` - will not be compatible with `ActiveRecord::Model`. Those libraries - should add to `ActiveRecord::Model` instead (which is included in - `Base`), or better still, avoid monkey-patching AR and instead - provide a module that users can include where they need it. - - * To minimise the risk of conflicts with other code, it is - advisable to include `ActiveRecord::Model` early in your class - definition. - - *Jon Leighton* - * PostgreSQL hstore records can be created. *Aaron Patterson* diff --git a/activerecord/lib/active_record.rb b/activerecord/lib/active_record.rb index 1675127ab0..45122539f1 100644 --- a/activerecord/lib/active_record.rb +++ b/activerecord/lib/active_record.rb @@ -43,7 +43,6 @@ module ActiveRecord autoload :Integration autoload :Migration autoload :Migrator, 'active_record/migration' - autoload :Model autoload :ModelSchema autoload :NestedAttributes autoload :Observer diff --git a/activerecord/lib/active_record/associations/alias_tracker.rb b/activerecord/lib/active_record/associations/alias_tracker.rb index 84540a7000..0c23029981 100644 --- a/activerecord/lib/active_record/associations/alias_tracker.rb +++ b/activerecord/lib/active_record/associations/alias_tracker.rb @@ -8,7 +8,7 @@ module ActiveRecord attr_reader :aliases, :table_joins, :connection # table_joins is an array of arel joins which might conflict with the aliases we assign here - def initialize(connection = ActiveRecord::Model.connection, table_joins = []) + def initialize(connection = Base.connection, table_joins = []) @aliases = Hash.new { |h,k| h[k] = initial_count_for(k) } @table_joins = table_joins @connection = connection diff --git a/activerecord/lib/active_record/attribute_methods.rb b/activerecord/lib/active_record/attribute_methods.rb index 008696f6de..9a4fcdfda3 100644 --- a/activerecord/lib/active_record/attribute_methods.rb +++ b/activerecord/lib/active_record/attribute_methods.rb @@ -59,7 +59,7 @@ module ActiveRecord raise DangerousAttributeError, "#{method_name} is defined by ActiveRecord" end - if [Base, Model].include?(active_record_super) + if superclass == Base super else # If B < A and A defines its own attribute method, then we don't want to overwrite that. diff --git a/activerecord/lib/active_record/attribute_methods/dirty.rb b/activerecord/lib/active_record/attribute_methods/dirty.rb index 59f209cec8..0333605eac 100644 --- a/activerecord/lib/active_record/attribute_methods/dirty.rb +++ b/activerecord/lib/active_record/attribute_methods/dirty.rb @@ -2,11 +2,6 @@ require 'active_support/core_ext/module/attribute_accessors' require 'active_support/deprecation' module ActiveRecord - ActiveSupport.on_load(:active_record_config) do - mattr_accessor :partial_writes, instance_accessor: false - self.partial_writes = true - end - module AttributeMethods module Dirty # :nodoc: extend ActiveSupport::Concern @@ -18,7 +13,8 @@ module ActiveRecord raise "You cannot include Dirty after Timestamp" end - config_attribute :partial_writes + class_attribute :partial_writes, instance_writer: false + self.partial_writes = true def self.partial_updates=(v); self.partial_writes = v; end def self.partial_updates?; partial_writes?; end diff --git a/activerecord/lib/active_record/attribute_methods/read.rb b/activerecord/lib/active_record/attribute_methods/read.rb index 46fd6ebfb3..07c8859496 100644 --- a/activerecord/lib/active_record/attribute_methods/read.rb +++ b/activerecord/lib/active_record/attribute_methods/read.rb @@ -1,8 +1,4 @@ module ActiveRecord - ActiveSupport.on_load(:active_record_config) do - mattr_accessor :attribute_types_cached_by_default, instance_accessor: false - end - module AttributeMethods module Read extend ActiveSupport::Concern @@ -10,7 +6,8 @@ module ActiveRecord ATTRIBUTE_TYPES_CACHED_BY_DEFAULT = [:datetime, :timestamp, :time, :date] included do - config_attribute :attribute_types_cached_by_default + class_attribute :attribute_types_cached_by_default, instance_writer: false + self.attribute_types_cached_by_default = ATTRIBUTE_TYPES_CACHED_BY_DEFAULT end module ClassMethods @@ -79,8 +76,6 @@ module ActiveRecord end end - ActiveRecord::Model.attribute_types_cached_by_default = ATTRIBUTE_TYPES_CACHED_BY_DEFAULT - # Returns the value of the attribute identified by <tt>attr_name</tt> after # it has been typecast (for example, "2004-12-12" in a data column is cast # to a date object, like Date.new(2004, 12, 12)). 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 f36a5806a9..806dc5b1d2 100644 --- a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb +++ b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb @@ -1,13 +1,4 @@ - module ActiveRecord - ActiveSupport.on_load(:active_record_config) do - mattr_accessor :time_zone_aware_attributes, instance_accessor: false - self.time_zone_aware_attributes = false - - mattr_accessor :skip_time_zone_conversion_for_attributes, instance_accessor: false - self.skip_time_zone_conversion_for_attributes = [] - end - module AttributeMethods module TimeZoneConversion class Type # :nodoc: @@ -28,8 +19,11 @@ module ActiveRecord extend ActiveSupport::Concern included do - config_attribute :time_zone_aware_attributes, global: true - config_attribute :skip_time_zone_conversion_for_attributes + mattr_accessor :time_zone_aware_attributes, instance_writer: false + self.time_zone_aware_attributes = false + + class_attribute :skip_time_zone_conversion_for_attributes, instance_writer: false + self.skip_time_zone_conversion_for_attributes = [] end module ClassMethods diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index a4705b24ca..eabbd80f66 100644 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -321,8 +321,48 @@ module ActiveRecord #:nodoc: # So it's possible to assign a logger to the class through <tt>Base.logger=</tt> which will then be used by all # instances in the current object space. class Base - include ActiveRecord::Model + extend ActiveModel::Observing::ClassMethods + extend ActiveModel::Naming + + extend ActiveSupport::Benchmarkable + extend ActiveSupport::DescendantsTracker + + extend ConnectionHandling + extend QueryCache::ClassMethods + extend Querying + extend Translation + extend DynamicMatchers + extend Explain + extend ConnectionHandling + + include Persistence + include ReadonlyAttributes + include ModelSchema + include Inheritance + include Scoping + include Sanitization + include AttributeAssignment + include ActiveModel::Conversion + include Integration + include Validations + include CounterCache + include Locking::Optimistic + include Locking::Pessimistic + include AttributeMethods + include Callbacks + include ActiveModel::Observing + include Timestamp + include Associations + include ActiveModel::SecurePassword + include AutosaveAssociation + include NestedAttributes + include Aggregations + include Transactions + include Reflection + include Serialization + include Store + include Core end -end -ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Model::DeprecationProxy.new) + ActiveSupport.run_load_hooks(:active_record, Base) +end 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 42bd16db80..1da95f451f 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb @@ -441,11 +441,11 @@ module ActiveRecord end def new_connection - ActiveRecord::Model.send(spec.adapter_method, spec.config) + Base.send(spec.adapter_method, spec.config) end def current_connection_id #:nodoc: - ActiveRecord::Model.connection_id ||= Thread.current.object_id + Base.connection_id ||= Thread.current.object_id end def checkout_new_connection @@ -567,10 +567,10 @@ module ActiveRecord class_to_pool[klass] ||= begin until pool = pool_for(klass) klass = klass.superclass - break unless klass < ActiveRecord::Tag + break unless klass <= Base end - class_to_pool[klass] = pool || pool_for(ActiveRecord::Model) + class_to_pool[klass] = pool end end diff --git a/activerecord/lib/active_record/connection_adapters/connection_specification.rb b/activerecord/lib/active_record/connection_adapters/connection_specification.rb index b9a61f7d91..09250d3c01 100644 --- a/activerecord/lib/active_record/connection_adapters/connection_specification.rb +++ b/activerecord/lib/active_record/connection_adapters/connection_specification.rb @@ -73,6 +73,8 @@ module ActiveRecord :database => config.path.sub(%r{^/},""), :host => config.host } spec.reject!{ |_,value| value.blank? } + uri_parser = URI::Parser.new + spec.map { |key,value| spec[key] = uri_parser.unescape(value) if value.is_a?(String) } if config.query options = Hash[config.query.split("&").map{ |pair| pair.split("=") }].symbolize_keys spec.merge!(options) diff --git a/activerecord/lib/active_record/connection_handling.rb b/activerecord/lib/active_record/connection_handling.rb index 3531be05bf..8ce7a7a463 100644 --- a/activerecord/lib/active_record/connection_handling.rb +++ b/activerecord/lib/active_record/connection_handling.rb @@ -1,4 +1,3 @@ - module ActiveRecord module ConnectionHandling # Establishes the connection to the database. Accepts a hash as input where diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb index f97c363871..98032db2ef 100644 --- a/activerecord/lib/active_record/core.rb +++ b/activerecord/lib/active_record/core.rb @@ -4,73 +4,6 @@ require 'thread' module ActiveRecord ActiveSupport.on_load(:active_record_config) do - ## - # :singleton-method: - # - # Accepts a logger conforming to the interface of Log4r 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+. - mattr_accessor :logger, instance_accessor: false - - ## - # :singleton-method: - # Contains the database configuration - as is typically stored in config/database.yml - - # as a Hash. - # - # For example, the following database.yml... - # - # development: - # adapter: sqlite3 - # database: db/development.sqlite3 - # - # production: - # adapter: sqlite3 - # database: db/production.sqlite3 - # - # ...would result in ActiveRecord::Base.configurations to look like this: - # - # { - # 'development' => { - # 'adapter' => 'sqlite3', - # 'database' => 'db/development.sqlite3' - # }, - # 'production' => { - # 'adapter' => 'sqlite3', - # 'database' => 'db/production.sqlite3' - # } - # } - mattr_accessor :configurations, instance_accessor: false - self.configurations = {} - - ## - # :singleton-method: - # Determines whether to use Time.utc (using :utc) or Time.local (using :local) when pulling - # dates and times from the database. This is set to :utc by default. - mattr_accessor :default_timezone, instance_accessor: false - self.default_timezone = :utc - - ## - # :singleton-method: - # Specifies the format to use when dumping the database schema with Rails' - # Rakefile. If :sql, the schema is dumped as (potentially database- - # specific) SQL statements. If :ruby, the schema is dumped as an - # ActiveRecord::Schema file which can be loaded into any database that - # supports migrations. Use :ruby if you want to have different database - # adapters for, e.g., your development and test environments. - mattr_accessor :schema_format, instance_accessor: false - self.schema_format = :ruby - - ## - # :singleton-method: - # Specify whether or not to use timestamps for migration versions - mattr_accessor :timestamped_migrations, instance_accessor: false - self.timestamped_migrations = true - - mattr_accessor :connection_handler, instance_accessor: false - self.connection_handler = ConnectionAdapters::ConnectionHandler.new - - mattr_accessor :dependent_restrict_raises, instance_accessor: false - self.dependent_restrict_raises = true end module Core @@ -79,12 +12,68 @@ module ActiveRecord included do ## # :singleton-method: - # The connection handler - config_attribute :connection_handler + # + # Accepts a logger conforming to the interface of Log4r 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+. + mattr_accessor :logger, instance_writer: false + + ## + # :singleton-method: + # Contains the database configuration - as is typically stored in config/database.yml - + # as a Hash. + # + # For example, the following database.yml... + # + # development: + # adapter: sqlite3 + # database: db/development.sqlite3 + # + # production: + # adapter: sqlite3 + # database: db/production.sqlite3 + # + # ...would result in ActiveRecord::Base.configurations to look like this: + # + # { + # 'development' => { + # 'adapter' => 'sqlite3', + # 'database' => 'db/development.sqlite3' + # }, + # 'production' => { + # 'adapter' => 'sqlite3', + # 'database' => 'db/production.sqlite3' + # } + # } + mattr_accessor :configurations, instance_writer: false + self.configurations = {} - %w(logger configurations default_timezone schema_format timestamped_migrations).each do |name| - config_attribute name, global: true - end + ## + # :singleton-method: + # Determines whether to use Time.utc (using :utc) or Time.local (using :local) when pulling + # dates and times from the database. This is set to :utc by default. + mattr_accessor :default_timezone, instance_writer: false + self.default_timezone = :utc + + ## + # :singleton-method: + # Specifies the format to use when dumping the database schema with Rails' + # Rakefile. If :sql, the schema is dumped as (potentially database- + # specific) SQL statements. If :ruby, the schema is dumped as an + # ActiveRecord::Schema file which can be loaded into any database that + # supports migrations. Use :ruby if you want to have different database + # adapters for, e.g., your development and test environments. + mattr_accessor :schema_format, instance_writer: false + self.schema_format = :ruby + + ## + # :singleton-method: + # Specify whether or not to use timestamps for migration versions + mattr_accessor :timestamped_migrations, instance_writer: false + self.timestamped_migrations = true + + class_attribute :connection_handler, instance_writer: false + self.connection_handler = ConnectionAdapters::ConnectionHandler.new end module ClassMethods @@ -139,7 +128,13 @@ module ActiveRecord # Returns the Arel engine. def arel_engine - @arel_engine ||= connection_handler.retrieve_connection_pool(self) ? self : active_record_super.arel_engine + @arel_engine ||= begin + if Base == self || connection_handler.retrieve_connection_pool(self) + self + else + superclass.arel_engine + end + end end private diff --git a/activerecord/lib/active_record/explain.rb b/activerecord/lib/active_record/explain.rb index 9e0390bed1..af772996f1 100644 --- a/activerecord/lib/active_record/explain.rb +++ b/activerecord/lib/active_record/explain.rb @@ -1,12 +1,10 @@ require 'active_support/lazy_load_hooks' module ActiveRecord - ActiveSupport.on_load(:active_record_config) do - mattr_accessor :auto_explain_threshold_in_seconds, instance_accessor: false - end - module Explain - delegate :auto_explain_threshold_in_seconds, :auto_explain_threshold_in_seconds=, to: 'ActiveRecord::Model' + def self.extended(base) + base.mattr_accessor :auto_explain_threshold_in_seconds, instance_accessor: false + end # If auto explain is enabled, this method triggers EXPLAIN logging for the # queries triggered by the block if it takes more than the threshold as a diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb index 413bd147de..6bc5cd1fb9 100644 --- a/activerecord/lib/active_record/fixtures.rb +++ b/activerecord/lib/active_record/fixtures.rb @@ -553,7 +553,7 @@ module ActiveRecord rows[table_name] = fixtures.map do |label, fixture| row = fixture.to_hash - if model_class && model_class < ActiveRecord::Model + if model_class && model_class < ActiveRecord::Base # fill in timestamp columns if they aren't specified and the model is set to record_timestamps if model_class.record_timestamps timestamp_column_names.each do |c_name| diff --git a/activerecord/lib/active_record/inheritance.rb b/activerecord/lib/active_record/inheritance.rb index 35273b0d81..a448fa1f5c 100644 --- a/activerecord/lib/active_record/inheritance.rb +++ b/activerecord/lib/active_record/inheritance.rb @@ -1,29 +1,22 @@ - module ActiveRecord - ActiveSupport.on_load(:active_record_config) do - # Determine whether to store the full constant name including namespace when using STI - mattr_accessor :store_full_sti_class, instance_accessor: false - self.store_full_sti_class = true - end - module Inheritance extend ActiveSupport::Concern included do - config_attribute :store_full_sti_class + # Determine whether to store the full constant name including namespace when using STI + class_attribute :store_full_sti_class, instance_writer: false + self.store_full_sti_class = true end module ClassMethods # True if this isn't a concrete subclass needing a STI type condition. def descends_from_active_record? - sup = active_record_super - - if sup.abstract_class? - sup.descends_from_active_record? - elsif self == Base + if self == Base false + elsif superclass.abstract_class? + superclass.descends_from_active_record? else - [Base, Model].include?(sup) || !columns_hash.include?(inheritance_column) + superclass == Base || !columns_hash.include?(inheritance_column) end end @@ -40,9 +33,8 @@ module ActiveRecord @symbolized_sti_name ||= sti_name.present? ? sti_name.to_sym : symbolized_base_class end - # Returns the class descending directly from ActiveRecord::Base (or - # that includes ActiveRecord::Model), or an abstract class, if any, in - # the inheritance hierarchy. + # Returns the class descending directly from ActiveRecord::Base, or + # an abstract class, if any, in the inheritance hierarchy. # # If A extends AR::Base, A.base_class will return A. If B descends from A # through some arbitrarily deep hierarchy, B.base_class will return A. @@ -50,15 +42,14 @@ module ActiveRecord # If B < A and C < B and if A is an abstract_class then both B.base_class # and C.base_class would return B as the answer since A is an abstract_class. def base_class - unless self < ActiveRecord::Tag + unless self < Base raise ActiveRecordError, "#{name} doesn't belong in a hierarchy descending from ActiveRecord" end - sup = active_record_super - if sup == Base || sup == Model || sup.abstract_class? + if superclass == Base || superclass.abstract_class? self else - sup.base_class + superclass.base_class end end @@ -97,14 +88,6 @@ module ActiveRecord sti_class.allocate.init_with('attributes' => record, 'column_types' => column_types) end - # For internal use. - # - # If this class includes ActiveRecord::Model then it won't have a - # superclass. So this provides a way to get to the 'root' (ActiveRecord::Model). - def active_record_super #:nodoc: - superclass < Model ? superclass : Model - end - protected # Returns the class type of the record using the current module as a prefix. So descendants of diff --git a/activerecord/lib/active_record/locking/optimistic.rb b/activerecord/lib/active_record/locking/optimistic.rb index e96ed00f9c..035c77c424 100644 --- a/activerecord/lib/active_record/locking/optimistic.rb +++ b/activerecord/lib/active_record/locking/optimistic.rb @@ -1,9 +1,4 @@ module ActiveRecord - ActiveSupport.on_load(:active_record_config) do - mattr_accessor :lock_optimistically, instance_accessor: false - self.lock_optimistically = true - end - module Locking # == What is Optimistic Locking # @@ -56,7 +51,8 @@ module ActiveRecord extend ActiveSupport::Concern included do - config_attribute :lock_optimistically + class_attribute :lock_optimistically, instance_writer: false + self.lock_optimistically = true end def locking_enabled? #:nodoc: diff --git a/activerecord/lib/active_record/model.rb b/activerecord/lib/active_record/model.rb deleted file mode 100644 index f059840f4d..0000000000 --- a/activerecord/lib/active_record/model.rb +++ /dev/null @@ -1,167 +0,0 @@ -require 'active_support/core_ext/module/attribute_accessors' - -module ActiveRecord - module Configuration # :nodoc: - # This just abstracts out how we define configuration options in AR. Essentially we - # have mattr_accessors on the ActiveRecord:Model constant that define global defaults. - # Classes that then use AR get class_attributes defined, which means that when they - # are assigned the default will be overridden for that class and subclasses. (Except - # when options[:global] == true, in which case there is one global value always.) - def config_attribute(name, options = {}) - if options[:global] - class_eval <<-CODE, __FILE__, __LINE__ + 1 - def self.#{name}; ActiveRecord::Model.#{name}; end - def #{name}; ActiveRecord::Model.#{name}; end - def self.#{name}=(val); ActiveRecord::Model.#{name} = val; end - CODE - else - options[:instance_writer] ||= false - class_attribute name, options - - singleton_class.class_eval <<-CODE, __FILE__, __LINE__ + 1 - remove_method :#{name} - def #{name}; ActiveRecord::Model.#{name}; end - CODE - end - end - end - - # This allows us to detect an ActiveRecord::Model while it's in the process of - # being included. - module Tag; end - - # <tt>ActiveRecord::Model</tt> can be included into a class to add Active Record - # persistence. This is an alternative to inheriting from <tt>ActiveRecord::Base</tt>. - # - # class Post - # include ActiveRecord::Model - # end - module Model - extend ActiveSupport::Concern - extend ConnectionHandling - extend ActiveModel::Observing::ClassMethods - - def self.append_features(base) - base.class_eval do - include Tag - extend Configuration - end - - super - end - - included do - extend ActiveModel::Naming - extend ActiveSupport::Benchmarkable - extend ActiveSupport::DescendantsTracker - - extend QueryCache::ClassMethods - extend Querying - extend Translation - extend DynamicMatchers - extend Explain - extend ConnectionHandling - - initialize_generated_modules unless self == Base - end - - include Persistence - include ReadonlyAttributes - include ModelSchema - include Inheritance - include Scoping - include Sanitization - include AttributeAssignment - include ActiveModel::Conversion - include Integration - include Validations - include CounterCache - include Locking::Optimistic - include Locking::Pessimistic - include AttributeMethods - include Callbacks - include ActiveModel::Observing - include Timestamp - include Associations - include ActiveModel::SecurePassword - include AutosaveAssociation - include NestedAttributes - include Aggregations - include Transactions - include Reflection - include Serialization - include Store - include Core - - class << self - def arel_engine - self - end - - def abstract_class? - false - end - - # Defines the name of the table column which will store the class name on single-table - # inheritance situations. - # - # The default inheritance column name is +type+, which means it's a - # reserved word inside Active Record. To be able to use single-table - # inheritance with another column name, or to use the column +type+ in - # your own model for something else, you can set +inheritance_column+: - # - # self.inheritance_column = 'zoink' - def inheritance_column - 'type' - end - end - - class DeprecationProxy < BasicObject #:nodoc: - def initialize(model = Model, base = Base) - @model = model - @base = base - end - - def method_missing(name, *args, &block) - if @model.respond_to?(name, true) - @model.send(name, *args, &block) - else - ::ActiveSupport::Deprecation.warn( - "The object passed to the active_record load hook was previously ActiveRecord::Base " \ - "(a Class). Now it is ActiveRecord::Model (a Module). You have called `#{name}' which " \ - "is only defined on ActiveRecord::Base. Please change your code so that it works with " \ - "a module rather than a class. (Model is included in Base, so anything added to Model " \ - "will be available on Base as well.)" - ) - @base.send(name, *args, &block) - end - end - - alias send method_missing - - def extend(*mods) - ::ActiveSupport::Deprecation.warn( - "The object passed to the active_record load hook was previously ActiveRecord::Base " \ - "(a Class). Now it is ActiveRecord::Model (a Module). You have called `extend' which " \ - "would add singleton methods to Model. This is presumably not what you want, since the " \ - "methods would not be inherited down to Base. Rather than using extend, please use " \ - "ActiveSupport::Concern + include, which will ensure that your class methods are " \ - "inherited." - ) - @base.extend(*mods) - end - end - end - - # This hook is where config accessors on Model get defined. - # - # We don't want to just open the Model module and add stuff to it in other files, because - # that would cause Model to load, which causes all sorts of loading order issues. - # - # We need this hook rather than just using the :active_record one, because users of the - # :active_record hook may need to use config options. - ActiveSupport.run_load_hooks(:active_record_config, Model) - - # Load Base at this point, because the active_record load hook is run in that file. - Base -end diff --git a/activerecord/lib/active_record/model_schema.rb b/activerecord/lib/active_record/model_schema.rb index 99de16cd33..1b95b72c8a 100644 --- a/activerecord/lib/active_record/model_schema.rb +++ b/activerecord/lib/active_record/model_schema.rb @@ -1,18 +1,4 @@ - module ActiveRecord - ActiveSupport.on_load(:active_record_config) do - mattr_accessor :primary_key_prefix_type, instance_accessor: false - - mattr_accessor :table_name_prefix, instance_accessor: false - self.table_name_prefix = "" - - mattr_accessor :table_name_suffix, instance_accessor: false - self.table_name_suffix = "" - - mattr_accessor :pluralize_table_names, instance_accessor: false - self.pluralize_table_names = true - end - module ModelSchema extend ActiveSupport::Concern @@ -24,7 +10,7 @@ module ActiveRecord # 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. - config_attribute :primary_key_prefix_type, global: true + mattr_accessor :primary_key_prefix_type, instance_writer: false ## # :singleton-method: @@ -36,20 +22,25 @@ module ActiveRecord # 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. - config_attribute :table_name_prefix + class_attribute :table_name_prefix, instance_writer: false + self.table_name_prefix = "" ## # :singleton-method: # Works like +table_name_prefix+, but appends instead of prepends (set to "_basecamp" gives "projects_basecamp", # "people_basecamp"). By default, the suffix is the empty string. - config_attribute :table_name_suffix + class_attribute :table_name_suffix, instance_writer: false + self.table_name_suffix = "" ## # :singleton-method: # Indicates whether table names should be the pluralized versions of the corresponding class names. # If true, the default table name for a Product class will be +products+. If false, it would just be +product+. # See table_name for the full rules on table/class naming. This is true, by default. - config_attribute :pluralize_table_names + class_attribute :pluralize_table_names, instance_writer: false + self.pluralize_table_names = true + + self.inheritance_column = 'type' end module ClassMethods @@ -144,9 +135,9 @@ module ActiveRecord # Computes the table name, (re)sets it internally, and returns it. def reset_table_name #:nodoc: self.table_name = if abstract_class? - active_record_super == Base ? nil : active_record_super.table_name - elsif active_record_super.abstract_class? - active_record_super.table_name || compute_table_name + superclass == Base ? nil : superclass.table_name + elsif superclass.abstract_class? + superclass.table_name || compute_table_name else compute_table_name end @@ -156,9 +147,17 @@ module ActiveRecord (parents.detect{ |p| p.respond_to?(:table_name_prefix) } || self).table_name_prefix end - # The name of the column containing the object's class when Single Table Inheritance is used + # Defines the name of the table column which will store the class name on single-table + # inheritance situations. + # + # The default inheritance column name is +type+, which means it's a + # reserved word inside Active Record. To be able to use single-table + # inheritance with another column name, or to use the column +type+ in + # your own model for something else, you can set +inheritance_column+: + # + # self.inheritance_column = 'zoink' def inheritance_column - (@inheritance_column ||= nil) || active_record_super.inheritance_column + (@inheritance_column ||= nil) || superclass.inheritance_column end # Sets the value of inheritance_column @@ -331,7 +330,7 @@ module ActiveRecord base = base_class if self == base # Nested classes are prefixed with singular parent table name. - if parent < ActiveRecord::Model && !parent.abstract_class? + if parent < Base && !parent.abstract_class? contained = parent.table_name contained = contained.singularize if parent.pluralize_table_names contained += '_' diff --git a/activerecord/lib/active_record/nested_attributes.rb b/activerecord/lib/active_record/nested_attributes.rb index 2e7fb3bbb3..d026c50ee6 100644 --- a/activerecord/lib/active_record/nested_attributes.rb +++ b/activerecord/lib/active_record/nested_attributes.rb @@ -3,11 +3,6 @@ require 'active_support/core_ext/object/try' require 'active_support/core_ext/hash/indifferent_access' module ActiveRecord - ActiveSupport.on_load(:active_record_config) do - mattr_accessor :nested_attributes_options, instance_accessor: false - self.nested_attributes_options = {} - end - module NestedAttributes #:nodoc: class TooManyRecords < ActiveRecordError end @@ -15,7 +10,8 @@ module ActiveRecord extend ActiveSupport::Concern included do - config_attribute :nested_attributes_options + class_attribute :nested_attributes_options, instance_writer: false + self.nested_attributes_options = {} end # = Active Record Nested Attributes diff --git a/activerecord/lib/active_record/railtie.rb b/activerecord/lib/active_record/railtie.rb index d7e35fb771..77e41ea927 100644 --- a/activerecord/lib/active_record/railtie.rb +++ b/activerecord/lib/active_record/railtie.rb @@ -80,7 +80,7 @@ module ActiveRecord if File.file?(filename) cache = Marshal.load File.binread filename if cache.version == ActiveRecord::Migrator.current_version - ActiveRecord::Model.connection.schema_cache = cache + self.connection.schema_cache = cache else warn "Ignoring db/schema_cache.dump because it has expired. The current schema version is #{ActiveRecord::Migrator.current_version}, but the one in the cache is #{cache.version}." end @@ -122,8 +122,8 @@ module ActiveRecord ActiveSupport.on_load(:active_record) do ActionDispatch::Reloader.send(hook) do - ActiveRecord::Model.clear_reloadable_connections! - ActiveRecord::Model.clear_cache! + ActiveRecord::Base.clear_reloadable_connections! + ActiveRecord::Base.clear_cache! end end end @@ -135,13 +135,12 @@ module ActiveRecord config.after_initialize do |app| ActiveSupport.on_load(:active_record) do - ActiveRecord::Model.instantiate_observers + instantiate_observers ActionDispatch::Reloader.to_prepare do - ActiveRecord::Model.instantiate_observers + ActiveRecord::Base.instantiate_observers end end - end end end diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index 84aaa39fed..99c2f45bc8 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -159,7 +159,7 @@ module ActiveRecord # Person.exists?(false) # Person.exists? def exists?(conditions = :none) - conditions = conditions.id if ActiveRecord::Model === conditions + conditions = conditions.id if Base === conditions return false if !conditions join_dependency = construct_join_dependency_for_association_find diff --git a/activerecord/lib/active_record/relation/predicate_builder.rb b/activerecord/lib/active_record/relation/predicate_builder.rb index 71030cb5d7..bd7aeb0c4e 100644 --- a/activerecord/lib/active_record/relation/predicate_builder.rb +++ b/activerecord/lib/active_record/relation/predicate_builder.rb @@ -40,7 +40,7 @@ module ActiveRecord # # For polymorphic relationships, find the foreign key and type: # PriceEstimate.where(:estimate_of => treasure) - if klass && value.class < ActiveRecord::Tag && reflection = klass.reflect_on_association(column.to_sym) + if klass && value.class < Base && reflection = klass.reflect_on_association(column.to_sym) if reflection.polymorphic? queries << build(table[reflection.foreign_type], value.class.base_class) end @@ -67,7 +67,7 @@ module ActiveRecord def self.build(attribute, value) case value when Array, ActiveRecord::Associations::CollectionProxy - values = value.to_a.map {|x| x.is_a?(ActiveRecord::Model) ? x.id : x} + values = value.to_a.map {|x| x.is_a?(Base) ? x.id : x} ranges, values = values.partition {|v| v.is_a?(Range)} values_predicate = if values.include?(nil) @@ -93,7 +93,7 @@ module ActiveRecord attribute.in(value.arel.ast) when Range attribute.in(value) - when ActiveRecord::Model + when ActiveRecord::Base attribute.eq(value.id) when Class # FIXME: I think we need to deprecate this behavior diff --git a/activerecord/lib/active_record/result.rb b/activerecord/lib/active_record/result.rb index 425b9b41d8..bea195e9b8 100644 --- a/activerecord/lib/active_record/result.rb +++ b/activerecord/lib/active_record/result.rb @@ -56,7 +56,7 @@ module ActiveRecord @hash_rows ||= begin # We freeze the strings to prevent them getting duped when - # used as keys in ActiveRecord::Model's @attributes hash + # used as keys in ActiveRecord::Base's @attributes hash columns = @columns.map { |c| c.dup.freeze } @rows.map { |row| Hash[columns.zip(row)] diff --git a/activerecord/lib/active_record/serialization.rb b/activerecord/lib/active_record/serialization.rb index e8dd312a47..6a511c307b 100644 --- a/activerecord/lib/active_record/serialization.rb +++ b/activerecord/lib/active_record/serialization.rb @@ -1,19 +1,12 @@ module ActiveRecord #:nodoc: - ActiveSupport.on_load(:active_record_config) do - mattr_accessor :include_root_in_json, instance_accessor: false - self.include_root_in_json = true - end - # = Active Record Serialization module Serialization extend ActiveSupport::Concern include ActiveModel::Serializers::JSON included do - singleton_class.class_eval do - remove_method :include_root_in_json - delegate :include_root_in_json, to: 'ActiveRecord::Model' - end + mattr_accessor :include_root_in_json, instance_accessor: false + self.include_root_in_json = true end def serializable_hash(options = nil) diff --git a/activerecord/lib/active_record/timestamp.rb b/activerecord/lib/active_record/timestamp.rb index ec4588f601..920d6848c1 100644 --- a/activerecord/lib/active_record/timestamp.rb +++ b/activerecord/lib/active_record/timestamp.rb @@ -1,8 +1,6 @@ module ActiveRecord ActiveSupport.on_load(:active_record_config) do - mattr_accessor :record_timestamps, instance_accessor: false - self.record_timestamps = true end # = Active Record Timestamp @@ -37,7 +35,8 @@ module ActiveRecord extend ActiveSupport::Concern included do - config_attribute :record_timestamps, instance_writer: true + class_attribute :record_timestamps + self.record_timestamps = true end def initialize_dup(other) # :nodoc: diff --git a/activerecord/test/cases/adapter_test.rb b/activerecord/test/cases/adapter_test.rb index 93b01a3934..404b492288 100644 --- a/activerecord/test/cases/adapter_test.rb +++ b/activerecord/test/cases/adapter_test.rb @@ -69,16 +69,16 @@ module ActiveRecord def test_not_specifying_database_name_for_cross_database_selects begin assert_nothing_raised do - ActiveRecord::Model.establish_connection(ActiveRecord::Base.configurations['arunit'].except(:database)) + ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['arunit'].except(:database)) config = ARTest.connection_config - ActiveRecord::Model.connection.execute( + ActiveRecord::Base.connection.execute( "SELECT #{config['arunit']['database']}.pirates.*, #{config['arunit2']['database']}.courses.* " \ "FROM #{config['arunit']['database']}.pirates, #{config['arunit2']['database']}.courses" ) end ensure - ActiveRecord::Model.establish_connection 'arunit' + ActiveRecord::Base.establish_connection 'arunit' end end end diff --git a/activerecord/test/cases/adapters/mysql/connection_test.rb b/activerecord/test/cases/adapters/mysql/connection_test.rb index 4bccd2cc59..534dc2c2df 100644 --- a/activerecord/test/cases/adapters/mysql/connection_test.rb +++ b/activerecord/test/cases/adapters/mysql/connection_test.rb @@ -3,13 +3,13 @@ require "cases/helper" class MysqlConnectionTest < ActiveRecord::TestCase def setup super - @connection = ActiveRecord::Model.connection + @connection = ActiveRecord::Base.connection end def test_mysql_reconnect_attribute_after_connection_with_reconnect_true run_without_connection do |orig_connection| - ActiveRecord::Model.establish_connection(orig_connection.merge({:reconnect => true})) - assert ActiveRecord::Model.connection.raw_connection.reconnect + ActiveRecord::Base.establish_connection(orig_connection.merge({:reconnect => true})) + assert ActiveRecord::Base.connection.raw_connection.reconnect end end @@ -25,8 +25,8 @@ class MysqlConnectionTest < ActiveRecord::TestCase def test_mysql_reconnect_attribute_after_connection_with_reconnect_false run_without_connection do |orig_connection| - ActiveRecord::Model.establish_connection(orig_connection.merge({:reconnect => false})) - assert !ActiveRecord::Model.connection.raw_connection.reconnect + ActiveRecord::Base.establish_connection(orig_connection.merge({:reconnect => false})) + assert !ActiveRecord::Base.connection.raw_connection.reconnect end end @@ -117,7 +117,7 @@ class MysqlConnectionTest < ActiveRecord::TestCase # Test that MySQL allows multiple results for stored procedures if defined?(Mysql) && Mysql.const_defined?(:CLIENT_MULTI_RESULTS) def test_multi_results - rows = ActiveRecord::Model.connection.select_rows('CALL ten();') + rows = ActiveRecord::Base.connection.select_rows('CALL ten();') assert_equal 10, rows[0][0].to_i, "ten() did not return 10 as expected: #{rows.inspect}" assert @connection.active?, "Bad connection use by 'MysqlAdapter.select_rows'" end @@ -130,9 +130,9 @@ class MysqlConnectionTest < ActiveRecord::TestCase def test_mysql_strict_mode_disabled_dont_override_global_sql_mode run_without_connection do |orig_connection| - ActiveRecord::Model.establish_connection(orig_connection.merge({:strict => false})) - global_sql_mode = ActiveRecord::Model.connection.exec_query "SELECT @@GLOBAL.sql_mode" - session_sql_mode = ActiveRecord::Model.connection.exec_query "SELECT @@SESSION.sql_mode" + ActiveRecord::Base.establish_connection(orig_connection.merge({:strict => false})) + global_sql_mode = ActiveRecord::Base.connection.exec_query "SELECT @@GLOBAL.sql_mode" + session_sql_mode = ActiveRecord::Base.connection.exec_query "SELECT @@SESSION.sql_mode" assert_equal global_sql_mode.rows, session_sql_mode.rows end end @@ -140,11 +140,11 @@ class MysqlConnectionTest < ActiveRecord::TestCase private def run_without_connection - original_connection = ActiveRecord::Model.remove_connection + original_connection = ActiveRecord::Base.remove_connection begin yield original_connection ensure - ActiveRecord::Model.establish_connection(original_connection) + ActiveRecord::Base.establish_connection(original_connection) end end end diff --git a/activerecord/test/cases/adapters/mysql2/connection_test.rb b/activerecord/test/cases/adapters/mysql2/connection_test.rb index c63e4fe5b6..14c22d2519 100644 --- a/activerecord/test/cases/adapters/mysql2/connection_test.rb +++ b/activerecord/test/cases/adapters/mysql2/connection_test.rb @@ -3,7 +3,7 @@ require "cases/helper" class MysqlConnectionTest < ActiveRecord::TestCase def setup super - @connection = ActiveRecord::Model.connection + @connection = ActiveRecord::Base.connection @connection.extend(LogIntercepter) @connection.intercepted = true end @@ -46,9 +46,9 @@ class MysqlConnectionTest < ActiveRecord::TestCase def test_mysql_strict_mode_disabled_dont_override_global_sql_mode run_without_connection do |orig_connection| - ActiveRecord::Model.establish_connection(orig_connection.merge({:strict => false})) - global_sql_mode = ActiveRecord::Model.connection.exec_query "SELECT @@GLOBAL.sql_mode" - session_sql_mode = ActiveRecord::Model.connection.exec_query "SELECT @@SESSION.sql_mode" + ActiveRecord::Base.establish_connection(orig_connection.merge({:strict => false})) + global_sql_mode = ActiveRecord::Base.connection.exec_query "SELECT @@GLOBAL.sql_mode" + session_sql_mode = ActiveRecord::Base.connection.exec_query "SELECT @@SESSION.sql_mode" assert_equal global_sql_mode.rows, session_sql_mode.rows end end @@ -76,11 +76,11 @@ class MysqlConnectionTest < ActiveRecord::TestCase private def run_without_connection - original_connection = ActiveRecord::Model.remove_connection + original_connection = ActiveRecord::Base.remove_connection begin yield original_connection ensure - ActiveRecord::Model.establish_connection(original_connection) + ActiveRecord::Base.establish_connection(original_connection) end end end diff --git a/activerecord/test/cases/attribute_methods/read_test.rb b/activerecord/test/cases/attribute_methods/read_test.rb index da5d9d8c2a..8d8ff2f952 100644 --- a/activerecord/test/cases/attribute_methods/read_test.rb +++ b/activerecord/test/cases/attribute_methods/read_test.rb @@ -11,10 +11,8 @@ module ActiveRecord def setup @klass = Class.new do def self.superclass; Base; end - def self.active_record_super; Base; end def self.base_class; self; end - extend ActiveRecord::Configuration include ActiveRecord::AttributeMethods def self.define_attribute_methods diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 0f859bf452..203e44857a 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -23,7 +23,6 @@ require 'models/edge' require 'models/joke' require 'models/bulb' require 'models/bird' -require 'models/teapot' require 'rexml/document' require 'active_support/core_ext/exception' @@ -1196,10 +1195,6 @@ class BasicsTest < ActiveRecord::TestCase # Concrete subclasses an abstract class which has a type column. assert !SubStiPost.descends_from_active_record? - - assert Teapot.descends_from_active_record? - assert !OtherTeapot.descends_from_active_record? - assert CoolTeapot.descends_from_active_record? end def test_find_on_abstract_base_class_doesnt_use_type_condition @@ -1453,15 +1448,6 @@ class BasicsTest < ActiveRecord::TestCase assert_equal scope, Bird.uniq end - def test_active_record_super - assert_equal ActiveRecord::Model, ActiveRecord::Base.active_record_super - assert_equal ActiveRecord::Base, Topic.active_record_super - assert_equal Topic, ImportantTopic.active_record_super - assert_equal ActiveRecord::Model, Teapot.active_record_super - assert_equal Teapot, OtherTeapot.active_record_super - assert_equal ActiveRecord::Model, CoolTeapot.active_record_super - end - def test_table_name_with_2_abstract_subclasses assert_equal "photos", Photo.table_name end diff --git a/activerecord/test/cases/connection_adapters/connection_handler_test.rb b/activerecord/test/cases/connection_adapters/connection_handler_test.rb index 4467ddfc39..631bf1aaac 100644 --- a/activerecord/test/cases/connection_adapters/connection_handler_test.rb +++ b/activerecord/test/cases/connection_adapters/connection_handler_test.rb @@ -4,8 +4,8 @@ module ActiveRecord module ConnectionAdapters class ConnectionHandlerTest < ActiveRecord::TestCase def setup - @klass = Class.new { include ActiveRecord::Tag } - @subklass = Class.new(@klass) { include ActiveRecord::Tag } + @klass = Class.new(Base) + @subklass = Class.new(@klass) @handler = ConnectionHandler.new @handler.establish_connection @klass, Base.connection_pool.spec diff --git a/activerecord/test/cases/connection_specification/resolver_test.rb b/activerecord/test/cases/connection_specification/resolver_test.rb index 434d2b7ba5..40c4dc94d1 100644 --- a/activerecord/test/cases/connection_specification/resolver_test.rb +++ b/activerecord/test/cases/connection_specification/resolver_test.rb @@ -36,6 +36,14 @@ module ActiveRecord :host => "foo", :encoding => "utf8" }, spec) end + + def test_encoded_password + skip "only if mysql is available" unless defined?(MysqlAdapter) + password = 'am@z1ng_p@ssw0rd#!' + encoded_password = URI.encode_www_form_component(password) + spec = resolve "mysql://foo:#{encoded_password}@localhost/bar" + assert_equal password, spec[:password] + end end end end diff --git a/activerecord/test/cases/defaults_test.rb b/activerecord/test/cases/defaults_test.rb index 0df872ff10..ed7eedaa27 100644 --- a/activerecord/test/cases/defaults_test.rb +++ b/activerecord/test/cases/defaults_test.rb @@ -52,12 +52,12 @@ if current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter) self.use_transactional_fixtures = false def using_strict(strict) - connection = ActiveRecord::Model.remove_connection - ActiveRecord::Model.establish_connection connection.merge(strict: strict) + connection = ActiveRecord::Base.remove_connection + ActiveRecord::Base.establish_connection connection.merge(strict: strict) yield ensure - ActiveRecord::Model.remove_connection - ActiveRecord::Model.establish_connection connection + ActiveRecord::Base.remove_connection + ActiveRecord::Base.establish_connection connection end # MySQL cannot have defaults on text/blob columns. It reports the diff --git a/activerecord/test/cases/inclusion_test.rb b/activerecord/test/cases/inclusion_test.rb deleted file mode 100644 index 8f095e4953..0000000000 --- a/activerecord/test/cases/inclusion_test.rb +++ /dev/null @@ -1,133 +0,0 @@ -require 'cases/helper' -require 'models/teapot' - -class BasicInclusionModelTest < ActiveRecord::TestCase - def test_basic_model - Teapot.create!(:name => "Ronnie Kemper") - assert_equal "Ronnie Kemper", Teapot.first.name - end - - def test_initialization - t = Teapot.new(:name => "Bob") - assert_equal "Bob", t.name - end - - def test_inherited_model - teapot = CoolTeapot.create!(:name => "Bob") - teapot.reload - - assert_equal "Bob", teapot.name - assert_equal "mmm", teapot.aaahhh - end - - def test_generated_feature_methods - assert Teapot < Teapot::GeneratedFeatureMethods - end - - def test_exists - t = Teapot.create!(:name => "Ronnie Kemper") - assert Teapot.exists?(t) - end - - def test_predicate_builder - t = Teapot.create!(:name => "Bob") - assert_equal "Bob", Teapot.where(:id => [t]).first.name - assert_equal "Bob", Teapot.where(:id => t).first.name - end - - def test_nested_model - assert_equal "ceiling_teapots", Ceiling::Teapot.table_name - end -end - -class InclusionUnitTest < ActiveRecord::TestCase - def setup - @klass = Class.new { include ActiveRecord::Model } - end - - def test_non_abstract_class - assert !@klass.abstract_class? - end - - def test_abstract_class - @klass.abstract_class = true - assert @klass.abstract_class? - end - - def test_establish_connection - assert @klass.respond_to?(:establish_connection) - assert ActiveRecord::Model.respond_to?(:establish_connection) - end - - def test_adapter_connection - name = "#{ActiveRecord::Base.connection_config[:adapter]}_connection" - assert @klass.respond_to?(name) - assert ActiveRecord::Model.respond_to?(name) - end - - def test_connection_handler - assert_equal ActiveRecord::Base.connection_handler, @klass.connection_handler - end - - def test_mirrored_configuration - ActiveRecord::Base.time_zone_aware_attributes = true - assert @klass.time_zone_aware_attributes - ActiveRecord::Base.time_zone_aware_attributes = false - assert !@klass.time_zone_aware_attributes - ensure - ActiveRecord::Base.time_zone_aware_attributes = false - end - - # Doesn't really test anything, but this is here to ensure warnings don't occur - def test_included_twice - @klass.send :include, ActiveRecord::Model - end - - def test_deprecation_proxy - proxy = ActiveRecord::Model::DeprecationProxy.new - - assert_equal ActiveRecord::Model.name, proxy.name - assert_equal ActiveRecord::Base.superclass, assert_deprecated { proxy.superclass } - - sup, sup2 = nil, nil - ActiveSupport.on_load(:__test_active_record_model_deprecation) do - sup = superclass - sup2 = send(:superclass) - end - assert_deprecated do - ActiveSupport.run_load_hooks(:__test_active_record_model_deprecation, proxy) - end - assert_equal ActiveRecord::Base.superclass, sup - assert_equal ActiveRecord::Base.superclass, sup2 - end - - test "including in deprecation proxy" do - model, base = ActiveRecord::Model.dup, ActiveRecord::Base.dup - proxy = ActiveRecord::Model::DeprecationProxy.new(model, base) - - mod = Module.new - proxy.include mod - assert model < mod - end - - test "extending in deprecation proxy" do - model, base = ActiveRecord::Model.dup, ActiveRecord::Base.dup - proxy = ActiveRecord::Model::DeprecationProxy.new(model, base) - - mod = Module.new - assert_deprecated { proxy.extend mod } - assert base.singleton_class < mod - end -end - -class InclusionFixturesTest < ActiveRecord::TestCase - fixtures :teapots - - def test_fixtured_record - assert_equal "Bob", teapots(:bob).name - end - - def test_timestamped_fixture - assert_not_nil teapots(:bob).created_at - end -end diff --git a/activerecord/test/cases/inheritance_test.rb b/activerecord/test/cases/inheritance_test.rb index 8fded9159f..aab7aa51dd 100644 --- a/activerecord/test/cases/inheritance_test.rb +++ b/activerecord/test/cases/inheritance_test.rb @@ -4,7 +4,6 @@ require 'models/person' require 'models/post' require 'models/project' require 'models/subscriber' -require 'models/teapot' require 'models/vegetables' class InheritanceTest < ActiveRecord::TestCase @@ -81,10 +80,6 @@ class InheritanceTest < ActiveRecord::TestCase assert_equal SubStiPost, SubStiPost.base_class end - def test_active_record_model_included_base_class - assert_equal Teapot, Teapot.base_class - end - def test_abstract_inheritance_base_class assert_equal LoosePerson, LoosePerson.base_class assert_equal LooseDescendant, LooseDescendant.base_class @@ -93,11 +88,7 @@ class InheritanceTest < ActiveRecord::TestCase end def test_base_class_activerecord_error - klass = Class.new { - extend ActiveRecord::Configuration - include ActiveRecord::Inheritance - } - + klass = Class.new { include ActiveRecord::Inheritance } assert_raise(ActiveRecord::ActiveRecordError) { klass.base_class } end diff --git a/activerecord/test/cases/multiple_db_test.rb b/activerecord/test/cases/multiple_db_test.rb index 42461e8ecb..2e386a172a 100644 --- a/activerecord/test/cases/multiple_db_test.rb +++ b/activerecord/test/cases/multiple_db_test.rb @@ -96,12 +96,12 @@ class MultipleDbTest < ActiveRecord::TestCase unless in_memory_db? def test_associations_should_work_when_model_has_no_connection begin - ActiveRecord::Model.remove_connection + ActiveRecord::Base.remove_connection assert_nothing_raised ActiveRecord::ConnectionNotEstablished do College.first.courses.first end ensure - ActiveRecord::Model.establish_connection 'arunit' + ActiveRecord::Base.establish_connection 'arunit' end end end diff --git a/activerecord/test/cases/pooled_connections_test.rb b/activerecord/test/cases/pooled_connections_test.rb index 0a6354f5cc..a8a9b06ec4 100644 --- a/activerecord/test/cases/pooled_connections_test.rb +++ b/activerecord/test/cases/pooled_connections_test.rb @@ -7,17 +7,17 @@ class PooledConnectionsTest < ActiveRecord::TestCase def setup @per_test_teardown = [] - @connection = ActiveRecord::Model.remove_connection + @connection = ActiveRecord::Base.remove_connection end def teardown - ActiveRecord::Model.clear_all_connections! - ActiveRecord::Model.establish_connection(@connection) + ActiveRecord::Base.clear_all_connections! + ActiveRecord::Base.establish_connection(@connection) @per_test_teardown.each {|td| td.call } end def checkout_connections - ActiveRecord::Model.establish_connection(@connection.merge({:pool => 2, :checkout_timeout => 0.3})) + ActiveRecord::Base.establish_connection(@connection.merge({:pool => 2, :checkout_timeout => 0.3})) @connections = [] @timed_out = 0 @@ -34,15 +34,15 @@ class PooledConnectionsTest < ActiveRecord::TestCase # Will deadlock due to lack of Monitor timeouts in 1.9 def checkout_checkin_connections(pool_size, threads) - ActiveRecord::Model.establish_connection(@connection.merge({:pool => pool_size, :checkout_timeout => 0.5})) + ActiveRecord::Base.establish_connection(@connection.merge({:pool => pool_size, :checkout_timeout => 0.5})) @connection_count = 0 @timed_out = 0 threads.times do Thread.new do begin - conn = ActiveRecord::Model.connection_pool.checkout + conn = ActiveRecord::Base.connection_pool.checkout sleep 0.1 - ActiveRecord::Model.connection_pool.checkin conn + ActiveRecord::Base.connection_pool.checkin conn @connection_count += 1 rescue ActiveRecord::ConnectionTimeoutError @timed_out += 1 @@ -55,13 +55,13 @@ class PooledConnectionsTest < ActiveRecord::TestCase checkout_checkin_connections 1, 2 assert_equal 2, @connection_count assert_equal 0, @timed_out - assert_equal 1, ActiveRecord::Model.connection_pool.connections.size + assert_equal 1, ActiveRecord::Base.connection_pool.connections.size end private def add_record(name) - ActiveRecord::Model.connection_pool.with_connection { Project.create! :name => name } + ActiveRecord::Base.connection_pool.with_connection { Project.create! :name => name } end end unless current_adapter?(:FrontBase) || in_memory_db? diff --git a/activerecord/test/cases/primary_keys_test.rb b/activerecord/test/cases/primary_keys_test.rb index e6e50a4cd4..bf8aacc363 100644 --- a/activerecord/test/cases/primary_keys_test.rb +++ b/activerecord/test/cases/primary_keys_test.rb @@ -188,14 +188,14 @@ class PrimaryKeyWithNoConnectionTest < ActiveRecord::TestCase def test_set_primary_key_with_no_connection return skip("disconnect wipes in-memory db") if in_memory_db? - connection = ActiveRecord::Model.remove_connection + connection = ActiveRecord::Base.remove_connection model = Class.new(ActiveRecord::Base) model.primary_key = 'foo' assert_equal 'foo', model.primary_key - ActiveRecord::Model.establish_connection(connection) + ActiveRecord::Base.establish_connection(connection) assert_equal 'foo', model.primary_key end diff --git a/activerecord/test/cases/unconnected_test.rb b/activerecord/test/cases/unconnected_test.rb index 5a69054445..e82ca3f93d 100644 --- a/activerecord/test/cases/unconnected_test.rb +++ b/activerecord/test/cases/unconnected_test.rb @@ -7,13 +7,13 @@ class TestUnconnectedAdapter < ActiveRecord::TestCase self.use_transactional_fixtures = false def setup - @underlying = ActiveRecord::Model.connection - @specification = ActiveRecord::Model.remove_connection + @underlying = ActiveRecord::Base.connection + @specification = ActiveRecord::Base.remove_connection end def teardown @underlying = nil - ActiveRecord::Model.establish_connection(@specification) + ActiveRecord::Base.establish_connection(@specification) load_schema if in_memory_db? end diff --git a/activerecord/test/models/teapot.rb b/activerecord/test/models/teapot.rb deleted file mode 100644 index b035b18c1b..0000000000 --- a/activerecord/test/models/teapot.rb +++ /dev/null @@ -1,35 +0,0 @@ -class Teapot - # I'm a little teapot, - # Short and stout, - # Here is my handle - # Here is my spout - # When I get all steamed up, - # Hear me shout, - # Tip me over and pour me out! - # - # HELL YEAH TEAPOT SONG - - include ActiveRecord::Model -end - -class OtherTeapot < Teapot -end - -class OMFGIMATEAPOT - def aaahhh - "mmm" - end -end - -class CoolTeapot < OMFGIMATEAPOT - include ActiveRecord::Model - self.table_name = "teapots" -end - -class Ceiling - include ActiveRecord::Model - - class Teapot - include ActiveRecord::Model - end -end diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index 2e4ec96933..eec06754a5 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -648,12 +648,6 @@ ActiveRecord::Schema.define do t.datetime :ending end - create_table :teapots, :force => true do |t| - t.string :name - t.string :type - t.timestamps - end - create_table :topics, :force => true do |t| t.string :title t.string :author_name diff --git a/activerecord/test/support/connection.rb b/activerecord/test/support/connection.rb index bea894a583..196b3a9493 100644 --- a/activerecord/test/support/connection.rb +++ b/activerecord/test/support/connection.rb @@ -13,9 +13,9 @@ module ARTest def self.connect puts "Using #{connection_name}" - ActiveRecord::Model.logger = ActiveSupport::Logger.new("debug.log", 0, 100 * 1024 * 1024) - ActiveRecord::Model.configurations = connection_config - ActiveRecord::Model.establish_connection 'arunit' + ActiveRecord::Base.logger = ActiveSupport::Logger.new("debug.log", 0, 100 * 1024 * 1024) + ActiveRecord::Base.configurations = connection_config + ActiveRecord::Base.establish_connection 'arunit' ARUnit2Model.establish_connection 'arunit2' end end diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md index 23e2ce0b03..4b06210c4a 100644 --- a/activesupport/CHANGELOG.md +++ b/activesupport/CHANGELOG.md @@ -1,5 +1,7 @@ ## Rails 4.0.0 (unreleased) ## +* Implement HashWithIndifferentAccess#replace so key? works correctly. *David Graham* + * Hash#extract! returns only those keys that present in the receiver. {:a => 1, :b => 2}.extract!(:a, :x) # => {:a => 1} diff --git a/activesupport/lib/active_support/hash_with_indifferent_access.rb b/activesupport/lib/active_support/hash_with_indifferent_access.rb index 0c78f1611f..306d80b2df 100644 --- a/activesupport/lib/active_support/hash_with_indifferent_access.rb +++ b/activesupport/lib/active_support/hash_with_indifferent_access.rb @@ -204,6 +204,14 @@ module ActiveSupport replace(reverse_merge( other_hash )) end + # Replaces the contents of this hash with other_hash. + # + # h = { "a" => 100, "b" => 200 } + # h.replace({ "c" => 300, "d" => 400 }) #=> {"c"=>300, "d"=>400} + def replace(other_hash) + super(self.class.new_from_hash_copying_default(other_hash)) + end + # Removes the specified key from the hash. def delete(key) super(convert_key(key)) diff --git a/activesupport/lib/active_support/queueing.rb b/activesupport/lib/active_support/queueing.rb index c8ba28021d..a89a48d057 100644 --- a/activesupport/lib/active_support/queueing.rb +++ b/activesupport/lib/active_support/queueing.rb @@ -64,9 +64,12 @@ module ActiveSupport # queue and joins the thread, which will ensure that all jobs # are executed before the process finally dies. class ThreadedQueueConsumer + attr_accessor :logger + def initialize(queue, options = {}) @queue = queue @logger = options[:logger] + @fallback_logger = Logger.new($stderr) end def start @@ -80,7 +83,7 @@ module ActiveSupport end def drain - run(@queue.pop) until @queue.empty? + @queue.pop.run until @queue.empty? end def consume @@ -96,8 +99,7 @@ module ActiveSupport end def handle_exception(job, exception) - raise exception unless @logger - @logger.error "Job Error: #{exception.message}\n#{exception.backtrace.join("\n")}" + (logger || @fallback_logger).error "Job Error: #{job.inspect}\n#{exception.message}\n#{exception.backtrace.join("\n")}" end end end diff --git a/activesupport/lib/active_support/test_case.rb b/activesupport/lib/active_support/test_case.rb index 7b9378a7f6..81d97ecb40 100644 --- a/activesupport/lib/active_support/test_case.rb +++ b/activesupport/lib/active_support/test_case.rb @@ -17,7 +17,7 @@ module ActiveSupport # Use AS::TestCase for the base class when describing a model register_spec_type(self) do |desc| - Class === desc && desc < ActiveRecord::Model + Class === desc && desc < ActiveRecord::Base end Assertion = MiniTest::Assertion diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb index 7cfe7b0ea7..6746b58cd3 100644 --- a/activesupport/test/core_ext/hash_ext_test.rb +++ b/activesupport/test/core_ext/hash_ext_test.rb @@ -428,6 +428,18 @@ class HashExtTest < ActiveSupport::TestCase assert_equal 2, hash['b'] end + def test_indifferent_replace + hash = HashWithIndifferentAccess.new + hash[:a] = 42 + + replaced = hash.replace(b: 12) + + assert hash.key?('b') + assert !hash.key?(:a) + assert_equal 12, hash[:b] + assert_same hash, replaced + end + def test_indifferent_merging_with_block hash = HashWithIndifferentAccess.new hash[:a] = 1 diff --git a/activesupport/test/queueing/threaded_consumer_test.rb b/activesupport/test/queueing/threaded_consumer_test.rb index fc43cb555a..a3ca46a261 100644 --- a/activesupport/test/queueing/threaded_consumer_test.rb +++ b/activesupport/test/queueing/threaded_consumer_test.rb @@ -65,10 +65,22 @@ class TestThreadConsumer < ActiveSupport::TestCase job = Job.new { raise "RuntimeError: Error!" } @queue.push job - @queue.drain + consume_queue @queue assert_equal 1, @logger.logged(:error).size - assert_match 'Job Error: RuntimeError: Error!', @logger.logged(:error).last + assert_match "Job Error: #{job.inspect}\nRuntimeError: Error!", @logger.logged(:error).last + end + + test "logger defaults to stderr" do + begin + $stderr, old_stderr = StringIO.new, $stderr + queue = ActiveSupport::Queue.new + queue.push Job.new { raise "RuntimeError: Error!" } + consume_queue queue + assert_match 'Job Error', $stderr.string + ensure + $stderr = old_stderr + end end test "test overriding exception handling" do @@ -85,8 +97,14 @@ class TestThreadConsumer < ActiveSupport::TestCase job = Job.new { raise "RuntimeError: Error!" } @queue.push job - @queue.drain + consume_queue @queue assert_equal "RuntimeError: Error!", @queue.consumer.last_error end + + private + def consume_queue(queue) + queue.push nil + queue.consumer.consume + end end diff --git a/guides/source/4_0_release_notes.md b/guides/source/4_0_release_notes.md index 6b3680aa2d..f24a981c6e 100644 --- a/guides/source/4_0_release_notes.md +++ b/guides/source/4_0_release_notes.md @@ -642,14 +642,6 @@ Active Record * Connections *must* be closed at the end of a thread. If not, your connection pool can fill and an exception will be raised. -* Added the `ActiveRecord::Model` module which can be included in a class as an alternative to inheriting from `ActiveRecord::Base`: - - ```ruby - class Post - include ActiveRecord::Model - end - ``` - * PostgreSQL hstore records can be created. * PostgreSQL hstore types are automatically deserialized from the database. diff --git a/guides/source/documents.yaml b/guides/source/documents.yaml index 0b22423798..19425765b8 100644 --- a/guides/source/documents.yaml +++ b/guides/source/documents.yaml @@ -1,4 +1,4 @@ -- +- name: Start Here documents: - @@ -26,82 +26,87 @@ description: This guide covers the database query interface provided by Active Record. - name: Views - documents: - - + documents: + - name: Layouts and Rendering in Rails url: layouts_and_rendering.html description: This guide covers the basic layout features of Action Controller and Action View, including rendering and redirecting, using content_for blocks, and working with partials. - - + - name: Action View Form Helpers url: form_helpers.html description: Guide to using built-in Form helpers. - name: Controllers documents: - - + - name: Action Controller Overview url: action_controller_overview.html description: This guide covers how controllers work and how they fit into the request cycle in your application. It includes sessions, filters, and cookies, data streaming, and dealing with exceptions raised by a request, among other topics. - - + - name: Rails Routing from the Outside In url: routing.html description: This guide covers the user-facing features of Rails routing. If you want to understand how to use routing in your own Rails applications, start here. - name: Digging Deeper documents: - - + - name: Active Support Core Extensions url: active_support_core_extensions.html description: This guide documents the Ruby core extensions defined in Active Support. - - + - name: Rails Internationalization API url: i18n.html description: This guide covers how to add internationalization to your applications. Your application will be able to translate content to different languages, change pluralization rules, use correct date formats for each country and so on. - - + - name: Action Mailer Basics url: action_mailer_basics.html work_in_progress: true description: This guide describes how to use Action Mailer to send and receive emails. - - + - name: Testing Rails Applications url: testing.html work_in_progress: true description: This is a rather comprehensive guide to doing both unit and functional tests in Rails. It covers everything from 'What is a test?' to the testing APIs. Enjoy. - - + - name: Securing Rails Applications url: security.html description: This guide describes common security problems in web applications and how to avoid them with Rails. - - + - name: Debugging Rails Applications url: debugging_rails_applications.html description: This guide describes how to debug Rails applications. It covers the different ways of achieving this and how to understand what is happening "behind the scenes" of your code. - - + - name: Performance Testing Rails Applications url: performance_testing.html description: This guide covers the various ways of performance testing a Ruby on Rails application. - - + - name: Configuring Rails Applications url: configuring.html description: This guide covers the basic configuration settings for a Rails application. - - + - name: Rails Command Line Tools and Rake Tasks url: command_line.html description: This guide covers the command line tools and rake tasks provided by Rails. - - + - name: Caching with Rails work_in_progress: true url: caching_with_rails.html description: Various caching techniques provided by Rails. - - + - name: Asset Pipeline url: asset_pipeline.html description: This guide documents the asset pipeline. - - + - + name: Working with JavaScript in Rails + work_in_progress: true + url: working_with_javascript_in_rails.html + description: This guide covers the built-in Ajax/JavaScript functionality of Rails. + - name: Getting Started with Engines url: engines.html description: This guide explains how to write a mountable engine. work_in_progress: true - - + - name: The Rails Initialization Process work_in_progress: true url: initialization.html @@ -109,38 +114,38 @@ - name: Extending Rails documents: - - + - name: The Basics of Creating Rails Plugins work_in_progress: true url: plugins.html description: This guide covers how to build a plugin to extend the functionality of Rails. - - + - name: Rails on Rack url: rails_on_rack.html description: This guide covers Rails integration with Rack and interfacing with other Rack components. - - + - name: Creating and Customizing Rails Generators url: generators.html description: This guide covers the process of adding a brand new generator to your extension or providing an alternative to an element of a built-in Rails generator (such as providing alternative test stubs for the scaffold generator). - name: Contributing to Ruby on Rails documents: - - + - name: Contributing to Ruby on Rails url: contributing_to_ruby_on_rails.html description: Rails is not 'somebody else's framework.' This guide covers a variety of ways that you can get involved in the ongoing development of Rails. - - + - name: API Documentation Guidelines url: api_documentation_guidelines.html description: This guide documents the Ruby on Rails API documentation guidelines. - - + - name: Ruby on Rails Guides Guidelines url: ruby_on_rails_guides_guidelines.html description: This guide documents the Ruby on Rails guides guidelines. - name: Release Notes documents: - - + - name: Upgrading Ruby on Rails url: upgrading_ruby_on_rails.html work_in_progress: true @@ -157,15 +162,15 @@ name: Ruby on Rails 3.1 Release Notes url: 3_1_release_notes.html description: Release notes for Rails 3.1. - - + - name: Ruby on Rails 3.0 Release Notes url: 3_0_release_notes.html description: Release notes for Rails 3.0. - - + - name: Ruby on Rails 2.3 Release Notes url: 2_3_release_notes.html description: Release notes for Rails 2.3. - - + - name: Ruby on Rails 2.2 Release Notes url: 2_2_release_notes.html description: Release notes for Rails 2.2. diff --git a/railties/lib/rails/application/finisher.rb b/railties/lib/rails/application/finisher.rb index c520f7af9d..2d87b8594a 100644 --- a/railties/lib/rails/application/finisher.rb +++ b/railties/lib/rails/application/finisher.rb @@ -99,6 +99,7 @@ module Rails initializer :activate_queue_consumer do |app| if config.queue.class == ActiveSupport::Queue app.queue_consumer = config.queue_consumer || config.queue.consumer + app.queue_consumer.logger ||= Rails.logger if app.queue_consumer.respond_to?(:logger=) app.queue_consumer.start at_exit { app.queue_consumer.shutdown } end diff --git a/railties/test/application/queue_test.rb b/railties/test/application/queue_test.rb index b0b3cf18e9..219a35da35 100644 --- a/railties/test/application/queue_test.rb +++ b/railties/test/application/queue_test.rb @@ -78,6 +78,7 @@ module ApplicationTests assert_nil Rails.application.config.queue_consumer assert_kind_of ActiveSupport::ThreadedQueueConsumer, Rails.application.queue_consumer + assert_equal Rails.logger, Rails.application.queue_consumer.logger end test "attempting to marshal a queue will raise an exception" do diff --git a/tools/profile b/tools/profile index d4cfa13f0a..665efe049d 100755 --- a/tools/profile +++ b/tools/profile @@ -1,12 +1,9 @@ #!/usr/bin/env ruby # Example: # tools/profile activesupport/lib/active_support.rb -abort 'Use REE so you can profile memory and object allocation' unless GC.respond_to?(:enable_stats) - ENV['NO_RELOAD'] ||= '1' ENV['RAILS_ENV'] ||= 'development' -GC.enable_stats Gem.source_index require 'benchmark' @@ -23,23 +20,18 @@ module RequireProfiler def profile(file) stats << [file, depth] self.depth += 1 - heap_before, objects_before = GC.allocated_size, ObjectSpace.allocated_objects result = nil elapsed = Benchmark.realtime { result = yield } - heap_after, objects_after = GC.allocated_size, ObjectSpace.allocated_objects self.depth -= 1 stats.pop if stats.last.first == file - stats << [file, depth, elapsed, heap_after - heap_before, objects_after - objects_before] if result + stats << [file, depth, elapsed] if result result end end end GC.start -before = GC.allocated_size -before_gctime, before_gcruns = GC.time, GC.collections before_rss = `ps -o rss= -p #{Process.pid}`.to_i -before_live_objects = ObjectSpace.live_objects path = ARGV.shift if mode = ARGV.shift @@ -53,12 +45,8 @@ end elapsed = Benchmark.realtime { require path } results = RubyProf.stop if mode -after_gctime, after_gcruns = GC.time, GC.collections GC.start -after_live_objects = ObjectSpace.live_objects after_rss = `ps -o rss= -p #{Process.pid}`.to_i -after = GC.allocated_size -usage = (after - before) / 1024.0 if mode if printer = ARGV.shift @@ -74,11 +62,11 @@ if mode end end -RequireProfiler.stats.each do |file, depth, sec, bytes, objects| +RequireProfiler.stats.each do |file, depth, sec| if sec - puts "%10.2f KB %10d obj %8.1f ms %s%s" % [bytes / 1024.0, objects, sec * 1000, ' ' * depth, file] + puts "%8.1f ms %s%s" % [sec * 1000, ' ' * depth, file] else - puts "#{' ' * (42 + depth)}#{file}" + puts "#{' ' * (13 + depth)}#{file}" end end -puts "%10.2f KB %10d obj %8.1f ms %d KB RSS %8.1f ms GC time %d GC runs" % [usage, after_live_objects - before_live_objects, elapsed * 1000, after_rss - before_rss, (after_gctime - before_gctime) / 1000.0, after_gcruns - before_gcruns] +puts "%8.1f ms %d KB RSS" % [elapsed * 1000, after_rss - before_rss] |