diff options
51 files changed, 274 insertions, 139 deletions
@@ -8,9 +8,13 @@ else gem "arel", '~> 2.1.3' end +gem "jquery-rails" gem "coffee-script" gem "sass" -gem "uglifier", ">= 1.0.0" + +# This needs to be with require false to avoid +# it being automatically loaded by sprockets +gem "uglifier", ">= 1.0.0", :require => false gem "rake", ">= 0.8.7" gem "mocha", ">= 0.9.8" diff --git a/actionpack/lib/action_controller/metal/streaming.rb b/actionpack/lib/action_controller/metal/streaming.rb index 0bb436a476..5fe5334458 100644 --- a/actionpack/lib/action_controller/metal/streaming.rb +++ b/actionpack/lib/action_controller/metal/streaming.rb @@ -24,20 +24,8 @@ module ActionController #:nodoc: # # == Examples # - # Streaming can be added to a controller easily, all you need to do is - # call +stream+ in the controller class: - # - # class PostsController - # stream - # end - # - # The +stream+ method accepts the same options as +before_filter+ and friends: - # - # class PostsController - # stream :only => :index - # end - # - # You can also selectively turn on streaming for specific actions: + # Streaming can be added to a given template easily, all you need to do is + # to pass the :stream option. # # class PostsController # def index @@ -72,6 +60,9 @@ module ActionController #:nodoc: # render :stream => true # end # + # Notice that :stream only works with templates. Rendering :json + # or :xml with :stream won't work. + # # == Communication between layout and template # # When streaming, rendering happens top-down instead of inside-out. @@ -209,33 +200,9 @@ module ActionController #:nodoc: extend ActiveSupport::Concern include AbstractController::Rendering - attr_internal :stream - - module ClassMethods - # Render streaming templates. It accepts :only, :except, :if and :unless as options - # to specify when to stream, as in ActionController filters. - def stream(options={}) - if defined?(Fiber) - before_filter :_stream_filter, options - else - raise "You cannot use streaming if Fiber is not available." - end - end - end protected - # Mark following render calls as streaming. - def _stream_filter #:nodoc: - self.stream = true - end - - # Consider the stream option when normalazing options. - def _normalize_options(options) #:nodoc: - super - options[:stream] = self.stream unless options.key?(:stream) - end - # Set proper cache control and transfer encoding when streaming def _process_options(options) #:nodoc: super diff --git a/actionpack/lib/action_view/asset_paths.rb b/actionpack/lib/action_view/asset_paths.rb index 4dd02755d3..96d8fd0dfe 100644 --- a/actionpack/lib/action_view/asset_paths.rb +++ b/actionpack/lib/action_view/asset_paths.rb @@ -1,3 +1,4 @@ +require 'zlib' require 'active_support/core_ext/file' module ActionView @@ -111,7 +112,7 @@ module ActionView args << current_request if (arity > 1 || arity < 0) && has_request? host.call(*args) else - (host =~ /%d/) ? host % (source.hash % 4) : host + (host =~ /%d/) ? host % (Zlib.crc32(source) % 4) : host end end end diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb index fd2970b8e2..36a0a20066 100644 --- a/actionpack/lib/action_view/base.rb +++ b/actionpack/lib/action_view/base.rb @@ -194,7 +194,7 @@ module ActionView #:nodoc: end def initialize(context = nil, assigns = {}, controller = nil, formats = nil) #:nodoc: - @_config = {} + @_config = ActiveSupport::InheritableOptions.new # Handle all these for backwards compatibility. # TODO Provide a new API for AV::Base and deprecate this one. diff --git a/actionpack/lib/sprockets/compressors.rb b/actionpack/lib/sprockets/compressors.rb new file mode 100644 index 0000000000..6544953df4 --- /dev/null +++ b/actionpack/lib/sprockets/compressors.rb @@ -0,0 +1,21 @@ +module Sprockets + class NullCompressor + def compress(content) + content + end + end + + class LazyCompressor + def initialize(&block) + @block = block + end + + def compressor + @compressor ||= @block.call || NullCompressor.new + end + + def compress(content) + compressor.compress(content) + end + end +end
\ No newline at end of file diff --git a/actionpack/lib/sprockets/helpers/rails_helper.rb b/actionpack/lib/sprockets/helpers/rails_helper.rb index 7d709de9e2..a95e7c0649 100644 --- a/actionpack/lib/sprockets/helpers/rails_helper.rb +++ b/actionpack/lib/sprockets/helpers/rails_helper.rb @@ -9,13 +9,8 @@ module Sprockets def asset_paths @asset_paths ||= begin config = self.config if respond_to?(:config) + config ||= Rails.application.config controller = self.controller if respond_to?(:controller) - config ||= Rails.application.config - if config.action_controller.present? - config.action_controller.default_asset_host_protocol ||= :relative - else - config.default_asset_host_protocol ||= :relative - end paths = RailsHelper::AssetPaths.new(config, controller) paths.asset_environment = asset_environment paths.asset_prefix = asset_prefix diff --git a/actionpack/lib/sprockets/railtie.rb b/actionpack/lib/sprockets/railtie.rb index d1e97c594e..c28bdc3061 100644 --- a/actionpack/lib/sprockets/railtie.rb +++ b/actionpack/lib/sprockets/railtie.rb @@ -1,8 +1,12 @@ module Sprockets autoload :Helpers, "sprockets/helpers" + autoload :LazyCompressor, "sprockets/compressors" + autoload :NullCompressor, "sprockets/compressors" # TODO: Get rid of config.assets.enabled class Railtie < ::Rails::Railtie + config.default_asset_host_protocol = :relative + rake_tasks do load "sprockets/assets.rake" end @@ -60,14 +64,14 @@ module Sprockets env.logger = Rails.logger if env.respond_to?(:cache) - env.cache = Rails.cache + env.cache = assets.cache_store || Rails.cache end if assets.compress # temporarily hardcode default JS compressor to uglify. Soon, it will work # the same as SCSS, where a default plugin sets the default. - env.js_compressor = expand_js_compressor(assets.js_compressor || :uglifier) - env.css_compressor = expand_css_compressor(assets.css_compressor) + env.js_compressor = LazyCompressor.new { expand_js_compressor(assets.js_compressor || :uglifier) } + env.css_compressor = LazyCompressor.new { expand_css_compressor(assets.css_compressor) } end env diff --git a/actionpack/test/controller/new_base/render_streaming_test.rb b/actionpack/test/controller/new_base/render_streaming_test.rb index 48cf0ab9cb..1a17e24914 100644 --- a/actionpack/test/controller/new_base/render_streaming_test.rb +++ b/actionpack/test/controller/new_base/render_streaming_test.rb @@ -10,9 +10,9 @@ module RenderStreaming )] layout "application" - stream :only => [:hello_world, :skip] def hello_world + render :stream => true end def layout_exception diff --git a/actionpack/test/template/asset_tag_helper_test.rb b/actionpack/test/template/asset_tag_helper_test.rb index df61901b44..d5bd7256f7 100644 --- a/actionpack/test/template/asset_tag_helper_test.rb +++ b/actionpack/test/template/asset_tag_helper_test.rb @@ -1,3 +1,4 @@ +require 'zlib' require 'abstract_unit' require 'active_support/ordered_options' @@ -689,9 +690,9 @@ class AssetTagHelperTest < ActionView::TestCase @controller.config.asset_host = 'http://a%d.example.com' config.perform_caching = true - hash = '/javascripts/cache/money.js'.hash % 4 + number = Zlib.crc32('/javascripts/cache/money.js') % 4 assert_dom_equal( - %(<script src="http://a#{hash}.example.com/javascripts/cache/money.js" type="text/javascript"></script>), + %(<script src="http://a#{number}.example.com/javascripts/cache/money.js" type="text/javascript"></script>), javascript_include_tag(:all, :cache => "cache/money") ) diff --git a/actionpack/test/template/test_case_test.rb b/actionpack/test/template/test_case_test.rb index f463675a2e..a75f1bc981 100644 --- a/actionpack/test/template/test_case_test.rb +++ b/actionpack/test/template/test_case_test.rb @@ -45,6 +45,10 @@ module ActionView assert_same _view, view end + test "retrieve non existing config values" do + assert_equal nil, ActionView::Base.new.config.something_odd + end + test "works without testing a helper module" do assert_equal 'Eloy', render('developers/developer', :developer => stub(:name => 'Eloy')) end diff --git a/activerecord/lib/active_record/associations/association.rb b/activerecord/lib/active_record/associations/association.rb index daadc8aa81..bb519c5703 100644 --- a/activerecord/lib/active_record/associations/association.rb +++ b/activerecord/lib/active_record/associations/association.rb @@ -30,7 +30,7 @@ module ActiveRecord @updated = false reset - construct_scope + reset_scope end # Returns the name of the table of the related class: @@ -51,7 +51,7 @@ module ActiveRecord # Reloads the \target and returns +self+ on success. def reload reset - construct_scope + reset_scope load_target self unless target.nil? end @@ -84,21 +84,25 @@ module ActiveRecord end def scoped - target_scope.merge(@association_scope) + target_scope.merge(association_scope) end - # Construct the scope for this association. + # The scope for this association. # # Note that the association_scope is merged into the target_scope only when the # scoped method is called. This is because at that point the call may be surrounded # by scope.scoping { ... } or with_scope { ... } etc, which affects the scope which # actually gets built. - def construct_scope + def association_scope if klass - @association_scope = AssociationScope.new(self).scope + @association_scope ||= AssociationScope.new(self).scope end end + def reset_scope + @association_scope = nil + end + # Set the inverse association, if possible def set_inverse_instance(record) if record && invertible_for?(record) diff --git a/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb b/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb index d7632b2ea9..30fc44b4c2 100644 --- a/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb +++ b/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb @@ -7,24 +7,22 @@ module ActiveRecord::Associations::Builder def build reflection = super check_validity(reflection) - define_after_destroy_method + define_destroy_hook reflection end private - def define_after_destroy_method + def define_destroy_hook name = self.name - model.send(:class_eval, <<-eoruby, __FILE__, __LINE__ + 1) - def #{after_destroy_method_name} - association(#{name.to_sym.inspect}).delete_all - end - eoruby - model.after_destroy after_destroy_method_name - end - - def after_destroy_method_name - "has_and_belongs_to_many_after_destroy_for_#{name}" + model.send(:include, Module.new { + class_eval <<-RUBY, __FILE__, __LINE__ + 1 + def destroy_associations + association(#{name.to_sym.inspect}).delete_all + super + end + RUBY + }) end # TODO: These checks should probably be moved into the Reflection, and we should not be diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb index 224e0095d9..3e68f973e7 100644 --- a/activerecord/lib/active_record/associations/collection_association.rb +++ b/activerecord/lib/active_record/associations/collection_association.rb @@ -50,7 +50,7 @@ module ActiveRecord else column = "#{reflection.quoted_table_name}.#{reflection.association_primary_key}" - scoped.select(column).except(:includes).map! do |record| + scoped.select(column).map! do |record| record.send(reflection.association_primary_key) end end @@ -78,10 +78,14 @@ module ActiveRecord end def find(*args) - if options[:finder_sql] - find_by_scan(*args) + if block_given? + load_target.find(*args) { |*block_args| yield(*block_args) } else - scoped.find(*args) + if options[:finder_sql] + find_by_scan(*args) + else + scoped.find(*args) + end end end diff --git a/activerecord/lib/active_record/associations/singular_association.rb b/activerecord/lib/active_record/associations/singular_association.rb index 6b010064d5..a1a921bcb4 100644 --- a/activerecord/lib/active_record/associations/singular_association.rb +++ b/activerecord/lib/active_record/associations/singular_association.rb @@ -18,11 +18,11 @@ module ActiveRecord end def create(attributes = {}, options = {}, &block) - build(attributes, options, &block).tap { |record| record.save } + create_record(attributes, options, &block) end def create!(attributes = {}, options = {}, &block) - build(attributes, options, &block).tap { |record| record.save! } + create_record(attributes, options, true, &block) end def build(attributes = {}, options = {}) @@ -50,6 +50,15 @@ module ActiveRecord def set_new_record(record) replace(record) end + + def create_record(attributes, options, raise_error = false) + record = build_record(attributes, options) + yield(record) if block_given? + saved = record.save + set_new_record(record) + raise RecordInvalid.new(record) if !saved && raise_error + record + end end end end diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb index 036d514a03..085fdba639 100644 --- a/activerecord/lib/active_record/autosave_association.rb +++ b/activerecord/lib/active_record/autosave_association.rb @@ -347,7 +347,7 @@ module ActiveRecord end # reconstruct the scope now that we know the owner's id - association.send(:construct_scope) if association.respond_to?(:construct_scope) + association.send(:reset_scope) if association.respond_to?(:reset_scope) end end diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index 3b8df4f2f1..eb4a16ecf5 100644 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -1058,7 +1058,7 @@ module ActiveRecord #:nodoc: if match.finder? options = arguments.extract_options! relation = options.any? ? scoped(options) : scoped - relation.send :find_by_attributes, match, attribute_names, *arguments + relation.send :find_by_attributes, match, attribute_names, *arguments, &block elsif match.instantiator? scoped.send :find_or_instantiator_by_attributes, match, attribute_names, *arguments, &block end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb index 29dd0a9ea3..a84f73c73f 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb @@ -670,7 +670,7 @@ module ActiveRecord # If the schema is not specified as part of +name+ then it will only find tables within # the current schema search path (regardless of permissions to access tables in other schemas) def table_exists?(name) - schema, table = extract_schema_and_table(name.to_s) + schema, table = Utils.extract_schema_and_table(name.to_s) return false unless table binds = [[nil, table]] @@ -947,6 +947,23 @@ module ActiveRecord "DISTINCT #{columns}, #{order_columns * ', '}" end + module Utils + # Returns an array of <tt>[schema_name, table_name]</tt> extracted from +name+. + # +schema_name+ is nil if not specified in +name+. + # +schema_name+ and +table_name+ exclude surrounding quotes (regardless of whether provided in +name+) + # +name+ supports the range of schema/table references understood by PostgreSQL, for example: + # + # * <tt>table_name</tt> + # * <tt>"table.name"</tt> + # * <tt>schema_name.table_name</tt> + # * <tt>schema_name."table.name"</tt> + # * <tt>"schema.name"."table name"</tt> + def self.extract_schema_and_table(name) + table, schema = name.scan(/[^".\s]+|"[^"]*"/)[0..1].collect{|m| m.gsub(/(^"|"$)/,'') }.reverse + [schema, table] + end + end + protected # Returns the version of the connected PostgreSQL server. def postgresql_version @@ -1085,21 +1102,6 @@ module ActiveRecord end end - # Returns an array of <tt>[schema_name, table_name]</tt> extracted from +name+. - # +schema_name+ is nil if not specified in +name+. - # +schema_name+ and +table_name+ exclude surrounding quotes (regardless of whether provided in +name+) - # +name+ supports the range of schema/table references understood by PostgreSQL, for example: - # - # * <tt>table_name</tt> - # * <tt>"table.name"</tt> - # * <tt>schema_name.table_name</tt> - # * <tt>schema_name."table.name"</tt> - # * <tt>"schema.name"."table name"</tt> - def extract_schema_and_table(name) - table, schema = name.scan(/[^".\s]+|"[^"]*"/)[0..1].collect{|m| m.gsub(/(^"|"$)/,'') }.reverse - [schema, table] - end - def extract_table_ref_from_insert_sql(sql) sql[/into\s+([^\(]*).*values\s*\(/i] $1.strip if $1 diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb index f425118f59..d9cd7987b0 100644 --- a/activerecord/lib/active_record/persistence.rb +++ b/activerecord/lib/active_record/persistence.rb @@ -79,6 +79,8 @@ module ActiveRecord # Deletes the record in the database and freezes this instance to reflect # that no changes should be made (since they can't be persisted). def destroy + destroy_associations + if persisted? IdentityMap.remove(self) if IdentityMap.enabled? pk = self.class.primary_key @@ -284,6 +286,11 @@ module ActiveRecord end private + + # A hook to be overriden by association modules. + def destroy_associations + end + def create_or_update raise ReadOnlyRecord if readonly? result = new_record? ? create : update diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake index 399f3c5d03..44e5520230 100644 --- a/activerecord/lib/active_record/railties/databases.rake +++ b/activerecord/lib/active_record/railties/databases.rake @@ -44,6 +44,12 @@ db_namespace = namespace :db do create_database(ActiveRecord::Base.configurations[Rails.env]) end + def mysql_creation_options(config) + @charset = ENV['CHARSET'] || 'utf8' + @collation = ENV['COLLATION'] || 'utf8_unicode_ci' + {:charset => (config['charset'] || @charset), :collation => (config['collation'] || @collation)} + end + def create_database(config) begin if config['adapter'] =~ /sqlite/ @@ -67,9 +73,6 @@ db_namespace = namespace :db do rescue case config['adapter'] when /mysql/ - @charset = ENV['CHARSET'] || 'utf8' - @collation = ENV['COLLATION'] || 'utf8_unicode_ci' - creation_options = {:charset => (config['charset'] || @charset), :collation => (config['collation'] || @collation)} if config['adapter'] =~ /jdbc/ #FIXME After Jdbcmysql gives this class require 'active_record/railties/jdbcmysql_error' @@ -80,7 +83,7 @@ db_namespace = namespace :db do access_denied_error = 1045 begin ActiveRecord::Base.establish_connection(config.merge('database' => nil)) - ActiveRecord::Base.connection.create_database(config['database'], creation_options) + ActiveRecord::Base.connection.create_database(config['database'], mysql_creation_options(config)) ActiveRecord::Base.establish_connection(config) rescue error_class => sqlerr if sqlerr.errno == access_denied_error @@ -443,7 +446,7 @@ db_namespace = namespace :db do case abcs['test']['adapter'] when /mysql/ ActiveRecord::Base.establish_connection(:test) - ActiveRecord::Base.connection.recreate_database(abcs['test']['database'], abcs['test']) + ActiveRecord::Base.connection.recreate_database(abcs['test']['database'], mysql_creation_options(abcs['test'])) when /postgresql/ ActiveRecord::Base.clear_active_connections! drop_database(abcs['test']) diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index 9cd146b857..6258a16d0f 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -1,4 +1,5 @@ require 'active_support/core_ext/object/blank' +require 'active_support/core_ext/module/delegation' module ActiveRecord # = Active Record Relation @@ -249,8 +250,7 @@ module ActiveRecord # Person.update(people.keys, people.values) def update(id, attributes) if id.is_a?(Array) - idx = -1 - id.collect { |one_id| idx += 1; update(one_id, attributes[idx]) } + id.each.with_index.map {|one_id, idx| update(one_id, attributes[idx])} else object = find(id) object.update_attributes(attributes) diff --git a/activerecord/lib/active_record/relation/batches.rb b/activerecord/lib/active_record/relation/batches.rb index d52b84179f..46ab67d1cf 100644 --- a/activerecord/lib/active_record/relation/batches.rb +++ b/activerecord/lib/active_record/relation/batches.rb @@ -20,8 +20,6 @@ module ActiveRecord find_in_batches(options) do |records| records.each { |record| yield record } end - - self end # Yields each batch of records that was found by the find +options+ as diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb index 9c5f603c01..0ac821b2d7 100644 --- a/activerecord/lib/active_record/relation/calculations.rb +++ b/activerecord/lib/active_record/relation/calculations.rb @@ -89,8 +89,12 @@ module ActiveRecord # +calculate+ for examples with options. # # Person.sum('age') # => 4562 - def sum(column_name, options = {}) - calculate(:sum, column_name, options) + def sum(*args) + if block_given? + self.to_a.sum(*args) {|*block_args| yield(*block_args)} + else + calculate(:sum, *args) + end end # This calculates aggregate values in the given column. Methods for count, sum, average, diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index c6e8762b4a..422d89060b 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -259,6 +259,7 @@ module ActiveRecord if match.bang? && result.blank? raise RecordNotFound, "Couldn't find #{@klass.name} with #{conditions.to_a.collect {|p| p.join(' = ')}.join(', ')}" else + yield(result) if block_given? result end end diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index ec2e4d4dcd..d17861f407 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -307,7 +307,7 @@ module ActiveRecord order_query.map do |o| case o - when Arel::Nodes::Ascending, Arel::Nodes::Descending + when Arel::Nodes::Ordering o.reverse when String, Symbol o.to_s.split(',').collect do |s| diff --git a/activerecord/test/cases/adapters/postgresql/schema_test.rb b/activerecord/test/cases/adapters/postgresql/schema_test.rb index 27e7b1a1c3..3a7f1badf0 100644 --- a/activerecord/test/cases/adapters/postgresql/schema_test.rb +++ b/activerecord/test/cases/adapters/postgresql/schema_test.rb @@ -229,8 +229,8 @@ class SchemaTest < ActiveRecord::TestCase %("schema"."table_name") => %w{schema table_name}, %("even spaces".table) => ['even spaces','table'], %(schema."table.name") => ['schema', 'table.name'] - }.each do |given,expect| - assert_equal expect, @connection.send(:extract_schema_and_table, given) + }.each do |given, expect| + assert_equal expect, ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::Utils.extract_schema_and_table(given) end end diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index 7338513b41..4190f6d76d 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -667,4 +667,18 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase firm = client.create_firm!{ |f| f.name = 'Agency Company' } assert_equal 'Agency Company', firm.name end + + def test_should_set_foreign_key_on_create_association + client = Client.create! :name => "fuu" + + firm = client.create_firm :name => "baa" + assert_equal firm.id, client.client_of + end + + def test_should_set_foreign_key_on_create_association! + client = Client.create! :name => "fuu" + + firm = client.create_firm! :name => "baa" + assert_equal firm.id, client.client_of + end end diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 7e331658a3..a2764f3e3b 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -226,6 +226,10 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_equal 2, Firm.find(:first, :order => "id").clients.length end + def test_finding_array_compatibility + assert_equal 2, Firm.order(:id).find{|f| f.id > 0}.clients.length + end + def test_find_with_blank_conditions [[], {}, nil, ""].each do |blank| assert_equal 2, Firm.find(:first, :order => "id").clients.find(:all, :conditions => blank).size diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index 877148bd5e..0b1ba31ac2 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -714,6 +714,11 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase assert_equal [categories(:general).id], authors(:mary).categories_like_general_ids end + def test_get_collection_singular_ids_on_has_many_through_with_conditions_and_include + person = Person.first + assert_equal person.posts_with_no_comment_ids, person.posts_with_no_comments.map(&:id) + end + def test_count_has_many_through_with_named_scope assert_equal 2, authors(:mary).categories.count assert_equal 1, authors(:mary).categories.general.count diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 5fef3faab9..9feb7b010f 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -53,6 +53,16 @@ class Weird < ActiveRecord::Base; end class Boolean < ActiveRecord::Base; end +class LintTest < ActiveRecord::TestCase + include ActiveModel::Lint::Tests + + class LintModel < ActiveRecord::Base; end + + def setup + @model = LintModel.new + end +end + class BasicsTest < ActiveRecord::TestCase fixtures :topics, :companies, :developers, :projects, :computers, :accounts, :minimalistics, 'warehouse-things', :authors, :categorizations, :categories, :posts diff --git a/activerecord/test/cases/batches_test.rb b/activerecord/test/cases/batches_test.rb index 6620464d6a..50ddf6c757 100644 --- a/activerecord/test/cases/batches_test.rb +++ b/activerecord/test/cases/batches_test.rb @@ -18,6 +18,13 @@ class EachTest < ActiveRecord::TestCase end end + def test_each_should_not_return_query_chain_and_execcute_only_one_query + assert_queries(1) do + result = Post.find_each(:batch_size => 100000){ } + assert_nil result + end + end + def test_each_should_raise_if_select_is_set_without_id assert_raise(RuntimeError) do Post.find_each(:select => :title, :batch_size => 1) { |post| post } diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index 56f6d795b6..224b3f3d1f 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -397,6 +397,10 @@ class CalculationsTest < ActiveRecord::TestCase Account.sum(:credit_limit, :from => 'accounts', :conditions => "credit_limit > 50") end + def test_sum_array_compatibility + assert_equal Account.sum(:credit_limit), Account.sum(&:credit_limit) + end + def test_average_with_from_option assert_equal Account.average(:credit_limit), Account.average(:credit_limit, :from => 'accounts') assert_equal Account.average(:credit_limit, :conditions => "credit_limit > 50"), diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb index 306b437fb3..842e8a0049 100644 --- a/activerecord/test/cases/fixtures_test.rb +++ b/activerecord/test/cases/fixtures_test.rb @@ -178,11 +178,9 @@ class FixturesTest < ActiveRecord::TestCase assert_nothing_raised do fixtures = ActiveRecord::Fixtures.new(Account.connection, 'categories', 'Category', FIXTURES_ROOT + "/categories_ordered") - i = 0 - fixtures.each do |name, fixture| + fixtures.each.with_index do |(name, fixture), i| assert_equal "fixture_no_#{i}", name assert_equal "Category #{i}", fixture['name'] - i += 1 end end end @@ -589,8 +587,8 @@ class FoxyFixturesTest < ActiveRecord::TestCase end def test_preserves_existing_fixture_data - assert_equal(2.weeks.ago.to_date, pirates(:redbeard).created_on.to_date) - assert_equal(2.weeks.ago.to_date, pirates(:redbeard).updated_on.to_date) + assert_equal(2.weeks.ago.utc.to_date, pirates(:redbeard).created_on.utc.to_date) + assert_equal(2.weeks.ago.utc.to_date, pirates(:redbeard).updated_on.utc.to_date) end def test_generates_unique_ids diff --git a/activerecord/test/cases/habtm_destroy_order_test.rb b/activerecord/test/cases/habtm_destroy_order_test.rb index f2b91d977e..2ce0de360e 100644 --- a/activerecord/test/cases/habtm_destroy_order_test.rb +++ b/activerecord/test/cases/habtm_destroy_order_test.rb @@ -16,6 +16,16 @@ class HabtmDestroyOrderTest < ActiveRecord::TestCase assert !sicp.destroyed? end + test 'should not raise error if have foreign key in the join table' do + student = Student.new(:name => "Ben Bitdiddle") + lesson = Lesson.new(:name => "SICP") + lesson.students << student + lesson.save! + assert_nothing_raised do + student.destroy + end + end + test "not destroying a student with lessons leaves student<=>lesson association intact" do # test a normal before_destroy doesn't destroy the habtm joins begin diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index 5a95e68eb4..0aaa0342b1 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -391,6 +391,15 @@ class RelationTest < ActiveRecord::TestCase assert_equal Post.find(1).last_comment, post.last_comment end + def test_dynamic_find_by_attributes_should_yield_found_object + david = authors(:david) + yielded_value = nil + Author.find_by_name(david.name) do |author| + yielded_value = author + end + assert_equal david, yielded_value + end + def test_dynamic_find_by_attributes david = authors(:david) author = Author.preload(:taggings).find_by_id(david.id) diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index 4fe311b441..e6cd274586 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -305,6 +305,8 @@ ActiveRecord::Schema.define do t.references :student end + create_table :lint_models, :force => true + create_table :line_items, :force => true do |t| t.integer :invoice_id t.integer :amount @@ -719,6 +721,8 @@ ActiveRecord::Schema.define do end execute "ALTER TABLE fk_test_has_fk ADD CONSTRAINT fk_name FOREIGN KEY (#{quote_column_name 'fk_id'}) REFERENCES #{quote_table_name 'fk_test_has_pk'} (#{quote_column_name 'id'})" + + execute "ALTER TABLE lessons_students ADD CONSTRAINT student_id_fk FOREIGN KEY (#{quote_column_name 'student_id'}) REFERENCES #{quote_table_name 'students'} (#{quote_column_name 'id'})" end end diff --git a/activesupport/lib/active_support/cache.rb b/activesupport/lib/active_support/cache.rb index 85692428e3..ac88c82709 100644 --- a/activesupport/lib/active_support/cache.rb +++ b/activesupport/lib/active_support/cache.rb @@ -557,7 +557,7 @@ module ActiveSupport @expires_in = options[:expires_in] @expires_in = @expires_in.to_f if @expires_in @created_at = Time.now.to_f - if value + if defined?(value) if should_compress?(value, options) @value = Zlib::Deflate.deflate(Marshal.dump(value)) @compressed = true @@ -576,7 +576,7 @@ module ActiveSupport # Get the value stored in the cache. def value - if @value + if defined?(@value) val = compressed? ? Marshal.load(Zlib::Inflate.inflate(@value)) : @value unless val.frozen? val.freeze rescue nil diff --git a/activesupport/lib/active_support/core_ext/string/conversions.rb b/activesupport/lib/active_support/core_ext/string/conversions.rb index 5b2cb6e331..664537eea4 100644 --- a/activesupport/lib/active_support/core_ext/string/conversions.rb +++ b/activesupport/lib/active_support/core_ext/string/conversions.rb @@ -34,9 +34,9 @@ class String # Form can be either :utc (default) or :local. def to_time(form = :utc) return nil if self.blank? - d = ::Date._parse(self, false).values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction).map { |arg| arg || 0 } + d = ::Date._parse(self, false).values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction, :offset).map { |arg| arg || 0 } d[6] *= 1000000 - ::Time.send("#{form}_time", *d) + ::Time.send("#{form}_time", *d[0..6]) - d[7] end def to_date diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb index ed5ccb44de..498127e5bc 100644 --- a/activesupport/test/caching_test.rb +++ b/activesupport/test/caching_test.rb @@ -188,6 +188,11 @@ module CacheStoreBehavior assert_equal nil, @cache.read('foo') end + def test_should_read_and_write_false + assert_equal true, @cache.write('foo', false) + assert_equal false, @cache.read('foo') + end + def test_read_multi @cache.write('foo', 'bar') @cache.write('fu', 'baz') diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb index 0360cf2901..4000cc913a 100644 --- a/activesupport/test/core_ext/string_ext_test.rb +++ b/activesupport/test/core_ext/string_ext_test.rb @@ -158,6 +158,7 @@ class StringInflectionsTest < Test::Unit::TestCase assert_equal Time.local(2005, 2, 27, 23, 50, 19, 275038), "2005-02-27T23:50:19.275038".to_time(:local) assert_equal DateTime.civil(2039, 2, 27, 23, 50), "2039-02-27 23:50".to_time assert_equal Time.local_time(2039, 2, 27, 23, 50), "2039-02-27 23:50".to_time(:local) + assert_equal Time.utc(2039, 2, 27, 23, 50), "2039-02-27 22:50 -0100".to_time assert_nil "".to_time end diff --git a/activesupport/test/whiny_nil_test.rb b/activesupport/test/whiny_nil_test.rb index ec3ca99ee6..1acaf7228f 100644 --- a/activesupport/test/whiny_nil_test.rb +++ b/activesupport/test/whiny_nil_test.rb @@ -33,11 +33,10 @@ class WhinyNilTest < Test::Unit::TestCase end def test_id - nil.stubs(:object_id).returns(999) nil.id rescue RuntimeError => nme assert_no_match(/nil:NilClass/, nme.message) - assert_match(/999/, nme.message) + assert_match(Regexp.new(nil.object_id.to_s), nme.message) end def test_no_to_ary_coercion diff --git a/railties/guides/source/command_line.textile b/railties/guides/source/command_line.textile index b0edc1017d..9e3b25d794 100644 --- a/railties/guides/source/command_line.textile +++ b/railties/guides/source/command_line.textile @@ -507,7 +507,7 @@ We had to create the *gitapp* directory and initialize an empty git repository b <shell> $ cat config/database.yml -# PostgreSQL. Versions 7.4 and 8.x are supported. +# PostgreSQL. Versions 8.2 and up are supported. # # Install the ruby-postgres driver: # gem install ruby-postgres diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb index 3b74de690a..1a29483a73 100644 --- a/railties/lib/rails/application/configuration.rb +++ b/railties/lib/rails/application/configuration.rb @@ -34,7 +34,7 @@ module Rails @assets = ActiveSupport::OrderedOptions.new @assets.enabled = false @assets.paths = [] - @assets.precompile = [ /\w+\.(?!js|css).+/, "application.js", "application.css" ] + @assets.precompile = [ /\w+\.(?!js|css).+/, /application.(css|js)$/ ] @assets.prefix = "/assets" @assets.js_compressor = nil diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcpostgresql.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcpostgresql.yml index 996ff4baa3..fe9466b366 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcpostgresql.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcpostgresql.yml @@ -1,4 +1,4 @@ -# PostgreSQL. Versions 7.4 and 8.x are supported. +# PostgreSQL. Versions 8.2 and up are supported. # # Configure Using Gemfile # gem 'activerecord-jdbcpostgresql-adapter' diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml index 467dfc3956..f08f86aac3 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml @@ -1,4 +1,4 @@ -# PostgreSQL. Versions 7.4 and 8.x are supported. +# PostgreSQL. Versions 8.2 and up are supported. # # Install the pg driver: # gem install pg diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt index ffd9058238..3e0c29a587 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt +++ b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt @@ -22,6 +22,11 @@ # Only use best-standards-support built into browsers config.action_dispatch.best_standards_support = :builtin + <%- unless options.skip_active_record? -%> + # Raise exception on mass assignment protection for ActiveRecord models + config.active_record.mass_assignment_sanitizer = :strict + <%- end -%> + # Do not compress assets config.assets.compress = false end diff --git a/railties/lib/rails/source_annotation_extractor.rb b/railties/lib/rails/source_annotation_extractor.rb index 6d6e7f8b59..1eed763aa3 100644 --- a/railties/lib/rails/source_annotation_extractor.rb +++ b/railties/lib/rails/source_annotation_extractor.rb @@ -28,9 +28,9 @@ class SourceAnnotationExtractor end end - # Prints all annotations with tag +tag+ under the root directories +app+, +lib+, - # and +test+ (recursively). Only filenames with extension +.builder+, +.rb+, - # +.rxml+, +.rhtml+, or +.erb+ are taken into account. The +options+ + # Prints all annotations with tag +tag+ under the root directories +app+, +config+, +lib+, + # +script+, and +test+ (recursively). Only filenames with extension + # +.builder+, +.rb+, +.rxml+, +.rhtml+, or +.erb+ are taken into account. The +options+ # hash is passed to each annotation's +to_s+. # # This class method is the single entry point for the rake tasks. @@ -49,7 +49,7 @@ class SourceAnnotationExtractor # with their annotations. Only files with annotations are included, and only # those with extension +.builder+, +.rb+, +.rxml+, +.rhtml+, and +.erb+ # are taken into account. - def find(dirs=%w(app lib test)) + def find(dirs=%w(app config lib script test)) dirs.inject({}) { |h, dir| h.update(find_in(dir)) } end diff --git a/railties/lib/rails/tasks/engine.rake b/railties/lib/rails/tasks/engine.rake index 2f0e7be896..2152e811f5 100644 --- a/railties/lib/rails/tasks/engine.rake +++ b/railties/lib/rails/tasks/engine.rake @@ -67,3 +67,5 @@ def find_engine_path(path) find_engine_path(File.expand_path('..', path)) end end + +Rake.application.invoke_task(:load_app) diff --git a/railties/test/application/assets_test.rb b/railties/test/application/assets_test.rb index b76dae8e18..e1eee71a9e 100644 --- a/railties/test/application/assets_test.rb +++ b/railties/test/application/assets_test.rb @@ -35,16 +35,30 @@ module ApplicationTests assert_match "alert()", last_response.body end + test "assets do not require compressors until it is used" do + app_file "app/assets/javascripts/demo.js.erb", "<%= :alert %>();" + ENV["RAILS_ENV"] = "production" + require "#{app_path}/config/environment" + + assert !defined?(Uglifier) + get "/assets/demo.js" + assert_match "alert()", last_response.body + assert defined?(Uglifier) + end + test "assets are compiled properly" do app_file "app/assets/javascripts/application.js", "alert();" + app_file "app/assets/javascripts/foo/application.js", "alert();" capture(:stdout) do Dir.chdir(app_path){ `bundle exec rake assets:precompile` } end - - file = Dir["#{app_path}/public/assets/application-*.js"][0] - assert_not_nil file, "Expected application.js asset to be generated, but none found" - assert_equal "alert();\n", File.read(file) + files = Dir["#{app_path}/public/assets/application-*.js"] + files << Dir["#{app_path}/public/assets/foo/application-*.js"].first + files.each do |file| + assert_not_nil file, "Expected application.js asset to be generated, but none found" + assert_equal "alert();\n", File.read(file) + end end test "assets are cleaned up properly" do diff --git a/railties/test/application/rake_test.rb b/railties/test/application/rake_test.rb index b61e2851bf..7671c129e9 100644 --- a/railties/test/application/rake_test.rb +++ b/railties/test/application/rake_test.rb @@ -61,22 +61,22 @@ module ApplicationTests def test_rake_test_error_output Dir.chdir(app_path){ `rake db:migrate` } - + app_file "config/database.yml", <<-RUBY development: RUBY - + app_file "test/unit/one_unit_test.rb", <<-RUBY RUBY - + app_file "test/functional/one_functional_test.rb", <<-RUBY raise RuntimeError RUBY - + app_file "test/integration/one_integration_test.rb", <<-RUBY raise RuntimeError RUBY - + silence_stderr do output = Dir.chdir(app_path){ `rake test` } assert_match /Errors running test:units! #<ActiveRecord::AdapterNotSpecified/, output @@ -151,5 +151,14 @@ module ApplicationTests assert_equal 2, ::AppTemplate::Application::Product.count assert_equal 0, ::AppTemplate::Application::User.count end + + def test_scaffold_tests_pass_by_default + content = Dir.chdir(app_path) do + `rails generate scaffold user username:string password:string` + `bundle exec rake db:migrate db:test:clone test` + end + + assert_match(/7 tests, 10 assertions, 0 failures, 0 errors/, content) + end end -end +end
\ No newline at end of file diff --git a/railties/test/generators/plugin_new_generator_test.rb b/railties/test/generators/plugin_new_generator_test.rb index be72391e58..4bd77ff7e3 100644 --- a/railties/test/generators/plugin_new_generator_test.rb +++ b/railties/test/generators/plugin_new_generator_test.rb @@ -159,6 +159,14 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase assert_match(/1 tests, 1 assertions, 0 failures, 0 errors/, `bundle exec rake test`) end + def test_ensure_that_migration_tasks_work_with_mountable_option + run_generator [destination_root, "--mountable"] + FileUtils.cd destination_root + quietly { system 'bundle install' } + `bundle exec rake db:migrate` + assert_equal 0, $?.exitstatus + end + def test_creating_engine_in_full_mode run_generator [destination_root, "--full"] assert_file "app/assets/javascripts/bukkits" diff --git a/railties/test/railties/generators_test.rb b/railties/test/railties/generators_test.rb index 08dd1ebbc2..1d4ba0e5b6 100644 --- a/railties/test/railties/generators_test.rb +++ b/railties/test/railties/generators_test.rb @@ -32,8 +32,8 @@ module RailtiesTests end def build_engine(is_mountable=false) + FileUtils.rm_rf(engine_path) FileUtils.mkdir_p(engine_path) - FileUtils.rm_r(engine_path) mountable = is_mountable ? "--mountable" : "" |