diff options
37 files changed, 341 insertions, 179 deletions
@@ -8,11 +8,6 @@ pattern. Understanding the MVC pattern is key to understanding Rails. MVC divides your application into three layers, each with a specific responsibility. -The _View layer_ is composed of "templates" that are responsible for providing -appropriate representations of your application's resources. Templates can -come in a variety of formats, but most view templates are HTML with embedded -Ruby code (ERB files). - The _Model layer_ represents your domain model (such as Account, Product, Person, Post, etc.) and encapsulates the business logic that is specific to your application. In Rails, database-backed model classes are derived from @@ -24,16 +19,26 @@ as provided by the Active Model module. You can read more about Active Record in its [README](activerecord/README.rdoc). The _Controller layer_ is responsible for handling incoming HTTP requests and -providing a suitable response. Usually this means returning HTML, but Rails -controllers can also generate XML, JSON, PDFs, mobile-specific views, and -more. Controllers manipulate models and render view templates in order to -generate the appropriate HTTP response. - -In Rails, the Controller and View layers are handled together by Action Pack. -These two layers are bundled in a single package due to their heavy interdependence. -This is unlike the relationship between Active Record and Action Pack, which are -independent. Each of these packages can be used independently outside of Rails. You -can read more about Action Pack in its [README](actionpack/README.rdoc). +providing a suitable response. Usually this means returning HTML, but Rails controllers +can also generate XML, JSON, PDFs, mobile-specific views, and more. Controllers load and +manipulate models, and render view templates in order to generate the appropriate HTTP response. +In Rails, incoming requests are routed by Action Dispatch to an appropriate controller, and +controller classes are derived from `ActionController::Base`. Action Dispatch and Action Controller +are bundled together in Action Pack. You can read more about Action Pack in its +[README](actionpack/README.rdoc). + +The _View layer_ is composed of "templates" that are responsible for providing +appropriate representations of your application's resources. Templates can +come in a variety of formats, but most view templates are HTML with embedded +Ruby code (ERB files). Views are typically rendered to generate a controller response, +or to generate the body of an email. In Rails, View generation is handled by Action View. +You can read more about Action View in its [README](actionview/README.rdoc). + +Active Record, Action Pack, and Action View can each be used independently outside Rails. +In addition to them, Rails also comes with Action Mailer ([README](actionmailer/README.rdoc)), a library +to generate and send emails; and Active Support ([README](activesupport/README.rdoc)), a collection of +utility classes and standard library extensions that are useful for Rails, and may also be used +independently outside Rails. ## Getting Started diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md index e7621270dd..8b78e0f801 100644 --- a/actionpack/CHANGELOG.md +++ b/actionpack/CHANGELOG.md @@ -1,9 +1,9 @@ * Introduce `BasicRendering` which is the most basic rendering implementation. It - allows to `render :text` and `render :nothing` without need of having ActionView. + allows to `render :text` and `render :nothing` without depending on Action View. *Łukasz Strzałkowski* -* Separate ActionView completely from ActionPack. +* Separate Action View completely from Action Pack. *Łukasz Strzałkowski* diff --git a/actionview/CHANGELOG.md b/actionview/CHANGELOG.md index 98b78a7114..6240dc6ac6 100644 --- a/actionview/CHANGELOG.md +++ b/actionview/CHANGELOG.md @@ -1,3 +1,7 @@ +* Only cache template digests if `config.cache_template_loading` id true. + + *Josh Lauer*, *Justin Ridgewell* + * Added an `extname` hash option for `javascript_include_tag` method. Before: diff --git a/actionview/lib/action_view/digestor.rb b/actionview/lib/action_view/digestor.rb index 64239c81b2..95c3200c81 100644 --- a/actionview/lib/action_view/digestor.rb +++ b/actionview/lib/action_view/digestor.rb @@ -32,9 +32,13 @@ module ActionView Digestor end - @@cache[cache_key] = digest = klass.new(name, format, finder, options).digest # Store the actual digest - ensure - @@cache.delete_pair(cache_key, false) if pre_stored && !digest # something went wrong, make sure not to corrupt the @@cache + # Store the actual digest if config.cache_template_loading is true + klass.new(name, format, finder, options).digest.tap do |digest| + @@cache[cache_key] = digest if ActionView::Resolver.caching? + end + rescue Exception + @@cache.delete_pair(cache_key, false) if pre_stored # something went wrong, make sure not to corrupt the @@cache + raise end end diff --git a/actionview/test/template/digestor_test.rb b/actionview/test/template/digestor_test.rb index 67e3775f28..c6608e214a 100644 --- a/actionview/test/template/digestor_test.rb +++ b/actionview/test/template/digestor_test.rb @@ -184,6 +184,15 @@ class TemplateDigestorTest < ActionView::TestCase assert_not_equal digest_phone, digest_fridge_phone end + def test_cache_template_loading + resolver_before = ActionView::Resolver.caching + ActionView::Resolver.caching = false + assert_digest_difference("messages/edit", true) do + change_template("comments/_comment") + end + ActionView::Resolver.caching = resolver_before + end + private def assert_logged(message) old_logger = ActionView::Base.logger @@ -200,9 +209,9 @@ class TemplateDigestorTest < ActionView::TestCase end end - def assert_digest_difference(template_name) + def assert_digest_difference(template_name, persistent = false) previous_digest = digest(template_name) - ActionView::Digestor.cache.clear + ActionView::Digestor.cache.clear unless persistent yield diff --git a/activemodel/lib/active_model/secure_password.rb b/activemodel/lib/active_model/secure_password.rb index cc9483e67b..8b9ac97bbb 100644 --- a/activemodel/lib/active_model/secure_password.rb +++ b/activemodel/lib/active_model/secure_password.rb @@ -2,7 +2,9 @@ module ActiveModel module SecurePassword extend ActiveSupport::Concern - class << self; attr_accessor :min_cost; end + class << self + attr_accessor :min_cost # :nodoc: + end self.min_cost = false module ClassMethods diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index a485feaf47..503a029aac 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,13 @@ +* Test that PostgreSQL adapter includes `usec` when quoting `DateTime` objects + + *Ben Cherry* + +* Fix PredicateBuilder so polymorhic association keys in `where` clause can + also accept not only `ActiveRecord::Base` direct descendances (decorated + models, for example). + + *Mikhail Dieterle* + * PostgreSQL adapter recognizes negative money values formatted with parentheses (eg. `($1.25) # => -1.25`)). Fixes #11899. diff --git a/activerecord/RUNNING_UNIT_TESTS.rdoc b/activerecord/RUNNING_UNIT_TESTS.rdoc index c3ee34da55..ca1f2fd665 100644 --- a/activerecord/RUNNING_UNIT_TESTS.rdoc +++ b/activerecord/RUNNING_UNIT_TESTS.rdoc @@ -24,6 +24,7 @@ Simply executing <tt>bundle exec rake test</tt> is equivalent to the following: $ bundle exec rake test_mysql2 $ bundle exec rake test_postgresql $ bundle exec rake test_sqlite3 + $ bundle exec rake test_sqlite3_mem There should be tests available for each database backend listed in the {Config File}[rdoc-label:label-Config+File]. (the exact set of available tests is diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index 5ceda933f2..33cbafc6aa 100644 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -164,7 +164,7 @@ module ActiveRecord private # Returns the specified association instance if it responds to :loaded?, nil otherwise. def association_instance_get(name) - @association_cache[name.to_sym] + @association_cache[name] end # Set the specified association instance. diff --git a/activerecord/lib/active_record/associations/preloader/association.rb b/activerecord/lib/active_record/associations/preloader/association.rb index 0cc836f991..928da71eed 100644 --- a/activerecord/lib/active_record/associations/preloader/association.rb +++ b/activerecord/lib/active_record/associations/preloader/association.rb @@ -29,6 +29,10 @@ module ActiveRecord end def records_for(ids) + query_scope(ids) + end + + def query_scope(ids) scope.where(association_key.in(ids)) end @@ -52,12 +56,9 @@ module ActiveRecord raise NotImplementedError end - # We're converting to a string here because postgres will return the aliased association - # key in a habtm as a string (for whatever reason) def owners_by_key @owners_by_key ||= owners.group_by do |owner| - key = owner[owner_key_name] - key && key.to_s + owner[owner_key_name] end end @@ -71,27 +72,34 @@ module ActiveRecord owners_map = owners_by_key owner_keys = owners_map.keys.compact - if klass.nil? || owner_keys.empty? - records = [] - else + # Each record may have multiple owners, and vice-versa + records_by_owner = Hash[owners.map { |owner| [owner, []] }] + + if klass && owner_keys.any? # Some databases impose a limit on the number of ids in a list (in Oracle it's 1000) # Make several smaller queries if necessary or make one query if the adapter supports it sliced = owner_keys.each_slice(klass.connection.in_clause_length || owner_keys.size) - records = sliced.flat_map { |slice| records_for(slice).to_a } + sliced.each { |slice| + records = records_for(slice) + caster = type_caster(records, association_key_name) + records.each do |record| + owner_key = caster.call record[association_key_name] + + owners_map[owner_key].each do |owner| + records_by_owner[owner] << record + end + end + } end - # Each record may have multiple owners, and vice-versa - records_by_owner = Hash[owners.map { |owner| [owner, []] }] - records.each do |record| - owner_key = record[association_key_name].to_s - - owners_map[owner_key].each do |owner| - records_by_owner[owner] << record - end - end records_by_owner end + IDENTITY = lambda { |value| value } + def type_caster(results, name) + IDENTITY + end + def reflection_scope @reflection_scope ||= reflection.scope ? klass.unscoped.instance_exec(nil, &reflection.scope) : klass.unscoped end diff --git a/activerecord/lib/active_record/associations/preloader/has_and_belongs_to_many.rb b/activerecord/lib/active_record/associations/preloader/has_and_belongs_to_many.rb index 9a3fada380..c042a44b21 100644 --- a/activerecord/lib/active_record/associations/preloader/has_and_belongs_to_many.rb +++ b/activerecord/lib/active_record/associations/preloader/has_and_belongs_to_many.rb @@ -12,7 +12,7 @@ module ActiveRecord # Unlike the other associations, we want to get a raw array of rows so that we can # access the aliased column on the join table def records_for(ids) - scope = super + scope = query_scope ids klass.connection.select_all(scope.arel, 'SQL', scope.bind_values) end @@ -40,6 +40,11 @@ module ActiveRecord end end + def type_caster(results, name) + caster = results.column_types.fetch(name, results.identity_type) + lambda { |value| caster.type_cast value } + end + def build_scope super.joins(join).select(join_select) end diff --git a/activerecord/lib/active_record/associations/preloader/through_association.rb b/activerecord/lib/active_record/associations/preloader/through_association.rb index de06931845..2c625cec04 100644 --- a/activerecord/lib/active_record/associations/preloader/through_association.rb +++ b/activerecord/lib/active_record/associations/preloader/through_association.rb @@ -27,17 +27,16 @@ module ActiveRecord def through_records_by_owner Preloader.new(owners, through_reflection.name, through_scope).run - Hash[owners.map do |owner| - through_records = Array.wrap(owner.send(through_reflection.name)) + should_reset = (through_scope != through_reflection.klass.unscoped) || + (reflection.options[:source_type] && through_reflection.collection?) - # Dont cache the association - we would only be caching a subset - if (through_scope != through_reflection.klass.unscoped) || - (reflection.options[:source_type] && through_reflection.collection?) - owner.association(through_reflection.name).reset - end + owners.each_with_object({}) do |owner, h| + association = owner.association through_reflection.name + h[owner] = Array(association.reader) - [owner, through_records] - end] + # Dont cache the association - we would only be caching a subset + association.reset if should_reset + end end def through_scope 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 41b5a6e926..f168282ea3 100644 --- a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb +++ b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb @@ -51,7 +51,7 @@ module ActiveRecord def create_time_zone_conversion_attribute?(name, column) time_zone_aware_attributes && !self.skip_time_zone_conversion_for_attributes.include?(name.to_sym) && - [:datetime, :timestamp].include?(column.type) + (:datetime == column.type || :timestamp == column.type) end end end diff --git a/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb b/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb index c8fa4ef9af..552a22d28a 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb @@ -51,7 +51,6 @@ module ActiveRecord return value unless column case column.type - when :binary then value when :integer then value.to_i when :float then value.to_f else diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb b/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb index 751655e61c..527d13b9b0 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb @@ -139,7 +139,8 @@ module ActiveRecord exec_cache(sql, binds) types = {} - result.fields.each_with_index do |fname, i| + fields = result.fields + fields.each_with_index do |fname, i| ftype = result.ftype i fmod = result.fmod i types[fname] = OID::TYPE_MAP.fetch(ftype, fmod) { |oid, mod| @@ -148,7 +149,7 @@ module ActiveRecord } end - ret = ActiveRecord::Result.new(result.fields, result.values, types) + ret = ActiveRecord::Result.new(fields, result.values, types) result.clear return ret end diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb index a7a40ca72b..40263b2a70 100644 --- a/activerecord/lib/active_record/fixtures.rb +++ b/activerecord/lib/active_record/fixtures.rb @@ -379,16 +379,16 @@ module ActiveRecord @@all_cached_fixtures = Hash.new { |h,k| h[k] = {} } - def self.default_fixture_model_name(fixture_set_name) # :nodoc: - ActiveRecord::Base.pluralize_table_names ? + def self.default_fixture_model_name(fixture_set_name, config = ActiveRecord::Base) # :nodoc: + config.pluralize_table_names ? fixture_set_name.singularize.camelize : fixture_set_name.camelize end - def self.default_fixture_table_name(fixture_set_name) # :nodoc: - "#{ ActiveRecord::Base.table_name_prefix }"\ + def self.default_fixture_table_name(fixture_set_name, config = ActiveRecord::Base) # :nodoc: + "#{ config.table_name_prefix }"\ "#{ fixture_set_name.tr('/', '_') }"\ - "#{ ActiveRecord::Base.table_name_suffix }".to_sym + "#{ config.table_name_suffix }".to_sym end def self.reset_cache @@ -436,7 +436,7 @@ module ActiveRecord cattr_accessor :all_loaded_fixtures self.all_loaded_fixtures = {} - def self.create_fixtures(fixtures_directory, fixture_set_names, class_names = {}) + def self.create_fixtures(fixtures_directory, fixture_set_names, class_names = {}, config = ActiveRecord::Base) fixture_set_names = Array(fixture_set_names).map(&:to_s) class_names = class_names.stringify_keys @@ -455,7 +455,7 @@ module ActiveRecord fixtures_map[fs_name] = new( # ActiveRecord::FixtureSet.new connection, fs_name, - class_names[fs_name] || (default_fixture_model_name(fs_name).safe_constantize), + class_names[fs_name] || (default_fixture_model_name(fs_name, config).safe_constantize), ::File.join(fixtures_directory, fs_name)) end @@ -497,12 +497,13 @@ module ActiveRecord Zlib.crc32(label.to_s) % MAX_ID end - attr_reader :table_name, :name, :fixtures, :model_class + attr_reader :table_name, :name, :fixtures, :model_class, :config - def initialize(connection, name, class_name, path) + def initialize(connection, name, class_name, path, config = ActiveRecord::Base) @fixtures = {} # Ordered hash @name = name @path = path + @config = config if class_name.is_a?(String) ActiveSupport::Deprecation.warn("The ability to pass in strings as a class name will be removed in Rails 4.2, consider using the class itself instead.") @@ -519,7 +520,7 @@ module ActiveRecord @table_name = ( model_class.respond_to?(:table_name) ? model_class.table_name : - self.class.default_fixture_table_name(name) ) + self.class.default_fixture_table_name(name, config) ) read_fixture_files end @@ -543,7 +544,7 @@ module ActiveRecord # Return a hash of rows to be inserted. The key is the table, the value is # a list of rows to insert to that table. def table_rows - now = ActiveRecord::Base.default_timezone == :utc ? Time.now.utc : Time.now + now = config.default_timezone == :utc ? Time.now.utc : Time.now now = now.to_s(:db) # allow a standard key to be used for doing defaults in YAML @@ -727,14 +728,16 @@ module ActiveRecord class_attribute :use_transactional_fixtures class_attribute :use_instantiated_fixtures # true, false, or :no_instances class_attribute :pre_loaded_fixtures + class_attribute :config self.fixture_table_names = [] self.use_transactional_fixtures = true self.use_instantiated_fixtures = false self.pre_loaded_fixtures = false + self.config = ActiveRecord::Base self.fixture_class_names = Hash.new do |h, fixture_set_name| - h[fixture_set_name] = ActiveRecord::FixtureSet.default_fixture_model_name(fixture_set_name) + h[fixture_set_name] = ActiveRecord::FixtureSet.default_fixture_model_name(fixture_set_name, self.config) end end @@ -760,7 +763,7 @@ module ActiveRecord end self.fixture_table_names |= fixture_set_names - require_fixture_classes(fixture_set_names) + require_fixture_classes(fixture_set_names, self.config) setup_fixture_accessors(fixture_set_names) end @@ -775,7 +778,7 @@ module ActiveRecord end end - def require_fixture_classes(fixture_set_names = nil) + def require_fixture_classes(fixture_set_names = nil, config = ActiveRecord::Base) if fixture_set_names fixture_set_names = fixture_set_names.map { |n| n.to_s } else @@ -783,7 +786,7 @@ module ActiveRecord end fixture_set_names.each do |file_name| - file_name = file_name.singularize if ActiveRecord::Base.pluralize_table_names + file_name = file_name.singularize if config.pluralize_table_names try_to_load_dependency(file_name) end end @@ -835,7 +838,7 @@ module ActiveRecord !self.class.uses_transaction?(method_name) end - def setup_fixtures + def setup_fixtures(config = ActiveRecord::Base) if pre_loaded_fixtures && !use_transactional_fixtures raise RuntimeError, 'pre_loaded_fixtures requires use_transactional_fixtures' end @@ -849,7 +852,7 @@ module ActiveRecord if @@already_loaded_fixtures[self.class] @loaded_fixtures = @@already_loaded_fixtures[self.class] else - @loaded_fixtures = load_fixtures + @loaded_fixtures = load_fixtures(config) @@already_loaded_fixtures[self.class] = @loaded_fixtures end @fixture_connections = enlist_fixture_connections @@ -860,11 +863,11 @@ module ActiveRecord else ActiveRecord::FixtureSet.reset_cache @@already_loaded_fixtures[self.class] = nil - @loaded_fixtures = load_fixtures + @loaded_fixtures = load_fixtures(config) end # Instantiate fixtures for every test if requested. - instantiate_fixtures if use_instantiated_fixtures + instantiate_fixtures(config) if use_instantiated_fixtures end def teardown_fixtures @@ -886,19 +889,19 @@ module ActiveRecord end private - def load_fixtures - fixtures = ActiveRecord::FixtureSet.create_fixtures(fixture_path, fixture_table_names, fixture_class_names) + def load_fixtures(config) + fixtures = ActiveRecord::FixtureSet.create_fixtures(fixture_path, fixture_table_names, fixture_class_names, config) Hash[fixtures.map { |f| [f.name, f] }] end # for pre_loaded_fixtures, only require the classes once. huge speed improvement @@required_fixture_classes = false - def instantiate_fixtures + def instantiate_fixtures(config) if pre_loaded_fixtures raise RuntimeError, 'Load fixtures before instantiating them.' if ActiveRecord::FixtureSet.all_loaded_fixtures.empty? unless @@required_fixture_classes - self.class.require_fixture_classes ActiveRecord::FixtureSet.all_loaded_fixtures.keys + self.class.require_fixture_classes ActiveRecord::FixtureSet.all_loaded_fixtures.keys, config @@required_fixture_classes = true end ActiveRecord::FixtureSet.instantiate_all_loaded_fixtures(self, load_instances?) diff --git a/activerecord/lib/active_record/model_schema.rb b/activerecord/lib/active_record/model_schema.rb index 23541d1d27..75c0c1bda8 100644 --- a/activerecord/lib/active_record/model_schema.rb +++ b/activerecord/lib/active_record/model_schema.rb @@ -224,13 +224,20 @@ module ActiveRecord def decorate_columns(columns_hash) # :nodoc: return if columns_hash.empty? - columns_hash.each do |name, col| - if serialized_attributes.key?(name) - columns_hash[name] = AttributeMethods::Serialization::Type.new(col) - end - if create_time_zone_conversion_attribute?(name, col) - columns_hash[name] = AttributeMethods::TimeZoneConversion::Type.new(col) - end + @serialized_column_names ||= self.columns_hash.keys.find_all do |name| + serialized_attributes.key?(name) + end + + @serialized_column_names.each do |name| + columns_hash[name] = AttributeMethods::Serialization::Type.new(columns_hash[name]) + end + + @time_zone_column_names ||= self.columns_hash.find_all do |name, col| + create_time_zone_conversion_attribute?(name, col) + end.map!(&:first) + + @time_zone_column_names.each do |name| + columns_hash[name] = AttributeMethods::TimeZoneConversion::Type.new(columns_hash[name]) end columns_hash @@ -284,16 +291,19 @@ module ActiveRecord undefine_attribute_methods connection.schema_cache.clear_table_cache!(table_name) if table_exists? - @arel_engine = nil - @column_defaults = nil - @column_names = nil - @columns = nil - @columns_hash = nil - @column_types = nil - @content_columns = nil - @dynamic_methods_hash = nil - @inheritance_column = nil unless defined?(@explicit_inheritance_column) && @explicit_inheritance_column - @relation = nil + @arel_engine = nil + @column_defaults = nil + @column_names = nil + @columns = nil + @columns_hash = nil + @column_types = nil + @content_columns = nil + @dynamic_methods_hash = nil + @inheritance_column = nil unless defined?(@explicit_inheritance_column) && @explicit_inheritance_column + @relation = nil + @serialized_column_names = nil + @time_zone_column_names = nil + @cached_time_zone = nil end # This is a hook for use by modules that need to do extra stuff to diff --git a/activerecord/lib/active_record/relation/predicate_builder.rb b/activerecord/lib/active_record/relation/predicate_builder.rb index 8948f2bba5..c60cd27a83 100644 --- a/activerecord/lib/active_record/relation/predicate_builder.rb +++ b/activerecord/lib/active_record/relation/predicate_builder.rb @@ -55,7 +55,7 @@ module ActiveRecord # # For polymorphic relationships, find the foreign key and type: # PriceEstimate.where(estimate_of: treasure) - if klass && value.class < Base && reflection = klass.reflect_on_association(column.to_sym) + if klass && value.is_a?(Base) && reflection = klass.reflect_on_association(column.to_sym) if reflection.polymorphic? queries << build(table[reflection.foreign_type], value.class.base_class) end diff --git a/activerecord/test/cases/adapters/postgresql/quoting_test.rb b/activerecord/test/cases/adapters/postgresql/quoting_test.rb index a534f0e56a..1122f8b9a1 100644 --- a/activerecord/test/cases/adapters/postgresql/quoting_test.rb +++ b/activerecord/test/cases/adapters/postgresql/quoting_test.rb @@ -52,6 +52,11 @@ module ActiveRecord c = Column.new(nil, nil, 'text') assert_equal "'666'", @conn.quote(fixnum, c) end + + def test_quote_time_usec + assert_equal "'1970-01-01 00:00:00.000000'", @conn.quote(Time.at(0)) + assert_equal "'1970-01-01 00:00:00.000000'", @conn.quote(Time.at(0).to_datetime) + end end end end diff --git a/activerecord/test/cases/associations/cascaded_eager_loading_test.rb b/activerecord/test/cases/associations/cascaded_eager_loading_test.rb index e693d34f99..811d91f849 100644 --- a/activerecord/test/cases/associations/cascaded_eager_loading_test.rb +++ b/activerecord/test/cases/associations/cascaded_eager_loading_test.rb @@ -52,12 +52,10 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase def test_cascaded_eager_association_loading_with_join_for_count categories = Category.joins(:categorizations).includes([{:posts=>:comments}, :authors]) - assert_nothing_raised do - assert_equal 4, categories.count - assert_equal 4, categories.to_a.count - assert_equal 3, categories.distinct.count - assert_equal 3, categories.to_a.uniq.size # Must uniq since instantiating with inner joins will get dupes - end + assert_equal 4, categories.count + assert_equal 4, categories.to_a.count + assert_equal 3, categories.distinct.count + assert_equal 3, categories.to_a.uniq.size # Must uniq since instantiating with inner joins will get dupes end def test_cascaded_eager_association_loading_with_duplicated_includes diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb index afbe65062d..4e877aed2e 100644 --- a/activerecord/test/cases/fixtures_test.rb +++ b/activerecord/test/cases/fixtures_test.rb @@ -574,7 +574,7 @@ class FixturesBrokenRollbackTest < ActiveRecord::TestCase end private - def load_fixtures + def load_fixtures(config) raise 'argh' end end diff --git a/activerecord/test/cases/relation/where_test.rb b/activerecord/test/cases/relation/where_test.rb index d333be3560..3e460fa3d6 100644 --- a/activerecord/test/cases/relation/where_test.rb +++ b/activerecord/test/cases/relation/where_test.rb @@ -81,6 +81,31 @@ module ActiveRecord assert_equal expected.to_sql, actual.to_sql end + def test_decorated_polymorphic_where + treasure_decorator = Struct.new(:model) do + def self.method_missing(method, *args, &block) + Treasure.send(method, *args, &block) + end + + def is_a?(klass) + model.is_a?(klass) + end + + def method_missing(method, *args, &block) + model.send(method, *args, &block) + end + end + + treasure = Treasure.new + treasure.id = 1 + decorated_treasure = treasure_decorator.new(treasure) + + expected = PriceEstimate.where(estimate_of_type: 'Treasure', estimate_of_id: 1) + actual = PriceEstimate.where(estimate_of: decorated_treasure) + + assert_equal expected.to_sql, actual.to_sql + end + def test_aliased_attribute expected = Topic.where(heading: 'The First Topic') actual = Topic.where(title: 'The First Topic') diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md index 81c6246c5c..f15297f279 100644 --- a/activesupport/CHANGELOG.md +++ b/activesupport/CHANGELOG.md @@ -1,3 +1,8 @@ +* Ensure that autoloaded constants in all-caps nestings are marked as + autoloaded. + + *Simon Coffey* + * Add String#remove(pattern) as a short-hand for the common pattern of String#gsub(pattern, '') *DHH* diff --git a/activesupport/lib/active_support/cache/memory_store.rb b/activesupport/lib/active_support/cache/memory_store.rb index b979521c99..34ac91334a 100644 --- a/activesupport/lib/active_support/cache/memory_store.rb +++ b/activesupport/lib/active_support/cache/memory_store.rb @@ -124,7 +124,6 @@ module ActiveSupport protected - # See https://gist.github.com/ssimeonov/6047200 PER_ENTRY_OVERHEAD = 240 def cached_size(key, entry) diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb index 73559bfe0e..db9f5d4baa 100644 --- a/activesupport/lib/active_support/dependencies.rb +++ b/activesupport/lib/active_support/dependencies.rb @@ -459,7 +459,7 @@ module ActiveSupport #:nodoc: if loaded.include?(expanded) raise "Circular dependency detected while autoloading constant #{qualified_name}" else - require_or_load(expanded) + require_or_load(expanded, qualified_name) raise LoadError, "Unable to autoload constant #{qualified_name}, expected #{file_path} to define it" unless from_mod.const_defined?(const_name, false) return from_mod.const_get(const_name) end diff --git a/activesupport/test/autoloading_fixtures/html/some_class.rb b/activesupport/test/autoloading_fixtures/html/some_class.rb new file mode 100644 index 0000000000..b43d15d891 --- /dev/null +++ b/activesupport/test/autoloading_fixtures/html/some_class.rb @@ -0,0 +1,4 @@ +module HTML + class SomeClass + end +end diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb index 68b6cc6e8c..9b84e75902 100644 --- a/activesupport/test/dependencies_test.rb +++ b/activesupport/test/dependencies_test.rb @@ -647,6 +647,14 @@ class DependenciesTest < ActiveSupport::TestCase Object.class_eval { remove_const :E } end + def test_constants_in_capitalized_nesting_marked_as_autoloaded + with_autoloading_fixtures do + ActiveSupport::Dependencies.load_missing_constant(HTML, "SomeClass") + + assert ActiveSupport::Dependencies.autoloaded?("HTML::SomeClass") + end + end + def test_unloadable with_autoloading_fixtures do Object.const_set :M, Module.new diff --git a/guides/assets/images/akshaysurve.jpg b/guides/assets/images/akshaysurve.jpg Binary files differnew file mode 100644 index 0000000000..cfc3333958 --- /dev/null +++ b/guides/assets/images/akshaysurve.jpg diff --git a/guides/source/asset_pipeline.md b/guides/source/asset_pipeline.md index 0b553ca75f..8fa86cb516 100644 --- a/guides/source/asset_pipeline.md +++ b/guides/source/asset_pipeline.md @@ -235,6 +235,11 @@ scope of the application or those libraries which are shared across applications * `vendor/assets` is for assets that are owned by outside entities, such as code for JavaScript plugins and CSS frameworks. +WARNING: If you are upgrading from Rails 3, please take into account that assets +under `lib/assets` or `vendor/assets` are available for inclusion via the +application manifests but no longer part of the precompile array. See +[Precompiling Assets](#precompiling-assets) for guidance. + #### Search Paths When a file is referenced from a manifest or a helper, Sprockets searches the diff --git a/guides/source/command_line.md b/guides/source/command_line.md index 639476eeeb..f11e08a0c1 100644 --- a/guides/source/command_line.md +++ b/guides/source/command_line.md @@ -471,7 +471,7 @@ spec/models/user_spec.rb: INFO: A good description of unit testing in Rails is given in [A Guide to Testing Rails Applications](testing.html) -Rails comes with a test suite called `Test::Unit`. Rails owes its stability to the use of tests. The tasks available in the `test:` namespace helps in running the different tests you will hopefully write. +Rails comes with a test suite called Minitest. Rails owes its stability to the use of tests. The tasks available in the `test:` namespace helps in running the different tests you will hopefully write. ### `tmp` diff --git a/guides/source/configuring.md b/guides/source/configuring.md index ce18091ff9..3cf5cdd71f 100644 --- a/guides/source/configuring.md +++ b/guides/source/configuring.md @@ -131,8 +131,6 @@ numbers. New applications filter out passwords by adding the following `config.f * `config.beginning_of_week` sets the default beginning of week for the application. Accepts a valid week day symbol (e.g. `:monday`). -* `config.whiny_nils` enables or disables warnings when a certain set of methods are invoked on `nil` and it does not respond to them. Defaults to true in development and test environments. - ### Configuring Assets * `config.assets.enabled` a flag that controls whether the asset @@ -632,11 +630,11 @@ WARNING: Some parts of your application, notably routing, are not yet set up at ### `Rails::Railtie#initializer` -Rails has several initializers that run on startup that are all defined by using the `initializer` method from `Rails::Railtie`. Here's an example of the `initialize_whiny_nils` initializer from Active Support: +Rails has several initializers that run on startup that are all defined by using the `initializer` method from `Rails::Railtie`. Here's an example of the `set_helpers_path` initializer from Action Controller: ```ruby -initializer "active_support.initialize_whiny_nils" do |app| - require 'active_support/whiny_nil' if app.config.whiny_nils +initializer "action_controller.set_helpers_path" do |app| + ActionController::Helpers.helpers_path = app.helpers_paths end ``` @@ -670,20 +668,6 @@ Below is a comprehensive list of all the initializers found in Rails in the orde * `i18n.callbacks` In the development environment, sets up a `to_prepare` callback which will call `I18n.reload!` if any of the locales have changed since the last request. In production mode this callback will only run on the first request. -* `active_support.initialize_whiny_nils` Requires `active_support/whiny_nil` if `config.whiny_nils` is true. This file will output errors such as: - - ``` - Called id for nil, which would mistakenly be 4 - if you really wanted the id of nil, use object_id - ``` - - And: - - ``` - You have a nil object when you didn't expect it! - You might have expected an instance of Array. - The error occurred while evaluating nil.each - ``` - * `active_support.deprecation_behavior` Sets up deprecation reporting for environments, defaulting to `:log` for development, `:notify` for production and `:stderr` for test. If a value isn't set for `config.active_support.deprecation` then this initializer will prompt the user to configure this line in the current environment's `config/environments` file. Can be set to an array of values. * `active_support.initialize_time_zone` Sets the default time zone for the application based on the `config.time_zone` setting, which defaults to "UTC". diff --git a/guides/source/contributing_to_ruby_on_rails.md b/guides/source/contributing_to_ruby_on_rails.md index fa3a5958f6..fc6b2f992a 100644 --- a/guides/source/contributing_to_ruby_on_rails.md +++ b/guides/source/contributing_to_ruby_on_rails.md @@ -46,9 +46,28 @@ WARNING: Please do not report security vulnerabilities with public GitHub issue ### What about Feature Requests? -Please don't put "feature request" items into GitHub Issues. If there's a new feature that you want to see added to Ruby on Rails, you'll need to write the code yourself - or convince someone else to partner with you to write the code. Later in this guide you'll find detailed instructions for proposing a patch to Ruby on Rails. If you enter a wishlist item in GitHub Issues with no code, you can expect it to be marked "invalid" as soon as it's reviewed. - -If you'd like feedback on an idea for a feature before doing the work for make a patch, please send an email to the [rails-core mailing list](https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core). You might get no response, which means that everyone is indifferent. You might find someone who's also interested in building that feature. You might get a "This won't be accepted." But it's the proper place to discuss new ideas. GitHub Issues are not a particularly good venue for the sometimes long and involved discussions new features require. +Please don't put "feature request" items into GitHub Issues. If there's a new +feature that you want to see added to Ruby on Rails, you'll need to write the +code yourself - or convince someone else to partner with you to write the code. +Later in this guide you'll find detailed instructions for proposing a patch to +Ruby on Rails. If you enter a wishlist item in GitHub Issues with no code, you +can expect it to be marked "invalid" as soon as it's reviewed. + +Sometimes, the line between 'bug' and 'feature' is a hard one to draw. +Generally, a feature is anything that adds new behavior, while a bug is +anything that fixes already existing behavior that is mis-behaving. Sometimes, +the core team will have to make a judgement call. That said, the distinction +generally just affects which release your patch will get in to; we love feature +submissions! They just won't get backported to maintenance branches. + +If you'd like feedback on an idea for a feature before doing the work for make +a patch, please send an email to the [rails-core mailing +list](https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core). You +might get no response, which means that everyone is indifferent. You might find +someone who's also interested in building that feature. You might get a "This +won't be accepted." But it's the proper place to discuss new ideas. GitHub +Issues are not a particularly good venue for the sometimes long and involved +discussions new features require. Setting Up a Development Environment ------------------------------------ @@ -291,7 +310,13 @@ Your name can be added directly after the last word if you don't provide any cod ### Sanity Check -You should not be the only person who looks at the code before you submit it. You know at least one other Rails developer, right? Show them what you're doing and ask for feedback. Doing this in private before you push a patch out publicly is the "smoke test" for a patch: if you can't convince one other developer of the beauty of your code, you're unlikely to convince the core team either. +You should not be the only person who looks at the code before you submit it. +If you know someone else who uses Rails, try asking them if they'll check out +your work. If you don't know anyone else using Rails, try hopping into the IRC +room or posting about your idea to the rails-core mailing list. Doing this in +private before you push a patch out publicly is the “smoke test” for a patch: +if you can’t convince one other developer of the beauty of your code, you’re +unlikely to convince the core team either. ### Commit Your Changes @@ -415,7 +440,24 @@ Fill in some details about your potential patch including a meaningful title. Wh ### Get some Feedback -Now you need to get other people to look at your patch, just as you've looked at other people's patches. You can use the [rubyonrails-core mailing list](http://groups.google.com/group/rubyonrails-core/) or the #rails-contrib channel on IRC freenode for this. You might also try just talking to Rails developers that you know. +Most pull requests will go through a few iterations before they get merged. +Different contributors will sometimes have different opinions, and often +patches will need revised before they can get merged. + +Some contributors to Rails have email notifications from GitHub turned on, but +others do not. Furthermore, (almost) everyone who works on Rails is a +volunteer, and so it may take a few days for you to get your first feedback on +a pull request. Don't despair! Sometimes it's quick, sometimes it's slow. Such +is the open source life. + +If it's been over a week, and you haven't heard anything, you might want to try +and nudge things along. You can use the [rubyonrails-core mailing +list](http://groups.google.com/group/rubyonrails-core/) for this. You can also +leave another comment on the pull request. + +While you're waiting for feedback on your pull request, open up a few other +pull requests and give someone else some! I'm sure they'll appreciate it in +the same way that you appreciate feedback on your patches. ### Iterate as Necessary diff --git a/guides/source/credits.html.erb b/guides/source/credits.html.erb index 10dd8178fb..5beae9c29b 100644 --- a/guides/source/credits.html.erb +++ b/guides/source/credits.html.erb @@ -74,3 +74,7 @@ Oscar Del Ben is a software engineer at <a href="http://www.wildfireapp.com/">Wi <%= author('Heiko Webers', 'hawe') do %> Heiko Webers is the founder of <a href="http://www.bauland42.de">bauland42</a>, a German web application security consulting and development company focused on Ruby on Rails. He blogs at the <a href="http://www.rorsecurity.info">Ruby on Rails Security Project</a>. After 10 years of desktop application development, Heiko has rarely looked back. <% end %> + +<%= author('Akshay Surve', 'startupjockey', 'akshaysurve.jpg') do %> + Akshay Surve is the Founder at <a href="http://www.deltax.com">DeltaX</a>, hackathon specialist, a midnight code junkie and ocassionally writes prose. You can connect with him on <a href="https://twitter.com/akshaysurve">Twitter</a>, <a href="http://www.linkedin.com/in/akshaysurve">Linkedin</a>, <a href="http://www.akshaysurve.com/">Personal Blog</a> or <a href="http://www.quora.com/Akshay-Surve">Quora</a>. +<% end %> diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md index 5b1758a771..81e57aee34 100644 --- a/guides/source/getting_started.md +++ b/guides/source/getting_started.md @@ -573,6 +573,41 @@ Finally, we redirect the user to the `show` action, which we'll define later. TIP: As we'll see later, `@post.save` returns a boolean indicating whether the model was saved or not. +If you now go to +<http://localhost:3000/posts/new> you'll *almost* be able to create a post. Try +it! You should get an error that looks like this: + +![Forbidden attributes for new post](images/getting_started/forbidden_attributes_for_new_post.png) + +Rails has several security features that help you write secure applications, +and you're running into one of them now. This one is called +`strong_parameters`, which requires us to tell Rails exactly which parameters +we want to accept in our controllers. In this case, we want to allow the +`title` and `text` parameters, so change your `create` controller action to +look like this: + +```ruby +def create + @post = Post.new(post_params) + + @post.save + redirect_to @post +end + +private + def post_params + params.require(:post).permit(:title, :text) + end +``` + +See the `permit`? It allows us to accept both `title` and `text` in this +action. + +TIP: Note that `def post_params` is private. This new approach prevents an attacker from +setting the model's attributes by manipulating the hash passed to the model. +For more information, refer to +[this blog post about Strong Parameters](http://weblog.rubyonrails.org/2012/3/21/strong-parameters/). + ### Showing Posts If you submit the form again now, Rails will complain about not finding @@ -618,44 +653,11 @@ content: </p> ``` -If you now go to -<http://localhost:3000/posts/new> you'll *almost* be able to create a post. Try -it! You should get an error that looks like this: - -![Forbidden attributes for new post](images/getting_started/forbidden_attributes_for_new_post.png) - -Rails has several security features that help you write secure applications, -and you're running into one of them now. This one is called -`strong_parameters`, which requires us to tell Rails exactly which parameters -we want to accept in our controllers. In this case, we want to allow the -`title` and `text` parameters, so change your `create` controller action to -look like this: - -``` -def create - @post = Post.new(post_params) - - @post.save - redirect_to @post -end - -private - def post_params - params.require(:post).permit(:title, :text) - end -``` - -See the `permit`? It allows us to accept both `title` and `text` in this -action. With this change, you should finally be able to create new posts. +With this change, you should finally be able to create new posts. Visit <http://localhost:3000/posts/new> and give it a try! ![Show action for posts](images/getting_started/show_action_for_posts.png) -TIP: Note that `def post_params` is private. This new approach prevents an attacker from -setting the model's attributes by manipulating the hash passed to the model. -For more information, refer to -[this blog post about Strong Parameters](http://weblog.rubyonrails.org/2012/3/21/strong-parameters/). - ### Listing all posts We still need a way to list all our posts, so let's do that. diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md index 391551938a..357918a73c 100644 --- a/guides/source/upgrading_ruby_on_rails.md +++ b/guides/source/upgrading_ruby_on_rails.md @@ -172,6 +172,24 @@ this gem such as `whitelist_attributes` or `mass_assignment_sanitizer` options. * Rails 4.0 has deprecated `ActiveRecord::Fixtures` in favor of `ActiveRecord::FixtureSet`. * Rails 4.0 has deprecated `ActiveRecord::TestCase` in favor of `ActiveSupport::TestCase`. +* Rails 4.0 has deprecated the old-style hash based finder API. This means that + methods which previously accepted "finder options" no longer do. + +* All dynamic methods except for `find_by_...` and `find_by_...!` are deprecated. + Here's how you can handle the changes: + + * `find_all_by_...` becomes `where(...)`. + * `find_last_by_...` becomes `where(...).last`. + * `scoped_by_...` becomes `where(...)`. + * `find_or_initialize_by_...` becomes `find_or_initialize_by(...)`. + * `find_or_create_by_...` becomes `find_or_create_by(...)`. + +* Note that `where(...)` returns a relation, not an array like the old finders. If you require an `Array`, use `where(...).to_a`. + +* These equivalent methods may not execute the same SQL as the previous implementation. + +* To re-enable the old finders, you can use the [activerecord-deprecated_finders gem](https://github.com/rails/activerecord-deprecated_finders). + ### Active Resource Rails 4.0 extracted Active Resource to its own gem. If you still need the feature you can add the [Active Resource gem](https://github.com/rails/activeresource) in your Gemfile. diff --git a/railties/lib/rails/generators/base.rb b/railties/lib/rails/generators/base.rb index 7e938fab47..8aec8bc8f9 100644 --- a/railties/lib/rails/generators/base.rb +++ b/railties/lib/rails/generators/base.rb @@ -168,15 +168,15 @@ module Rails as_hook = options.delete(:as) || generator_name names.each do |name| - defaults = if options[:type] == :boolean - { } - elsif [true, false].include?(default_value_for_option(name, options)) - { banner: "" } - else - { desc: "#{name.to_s.humanize} to be invoked", banner: "NAME" } - end - unless class_options.key?(name) + defaults = if options[:type] == :boolean + { } + elsif [true, false].include?(default_value_for_option(name, options)) + { banner: "" } + else + { desc: "#{name.to_s.humanize} to be invoked", banner: "NAME" } + end + class_option(name, defaults.merge!(options)) end @@ -255,12 +255,7 @@ module Rails # Split the class from its module nesting nesting = class_name.split('::') last_name = nesting.pop - - # Extract the last Module in the nesting - last = nesting.inject(Object) do |last_module, nest| - break unless last_module.const_defined?(nest, false) - last_module.const_get(nest) - end + last = extract_last_module(nesting) if last && last.const_defined?(last_name.camelize, false) raise Error, "The name '#{class_name}' is either already used in your application " << @@ -270,6 +265,14 @@ module Rails end end + # Takes in an array of nested modules and extracts the last module + def extract_last_module(nesting) + nesting.inject(Object) do |last_module, nest| + break unless last_module.const_defined?(nest, false) + last_module.const_get(nest) + end + end + # Use Rails default banner. def self.banner "rails generate #{namespace.sub(/^rails:/,'')} #{self.arguments.map{ |a| a.usage }.join(' ')} [options]".gsub(/\s+/, ' ') diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb index 9fb8ea6955..041bfcb733 100644 --- a/railties/lib/rails/generators/rails/app/app_generator.rb +++ b/railties/lib/rails/generators/rails/app/app_generator.rb @@ -68,7 +68,7 @@ module Rails directory "bin" do |content| "#{shebang}\n" + content end - chmod "bin", 0755, verbose: false + chmod "bin", 0755 & ~File.umask, verbose: false end def config |