From cf04e621270bb2e5e9e7971d2c59e73d6797482d Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Thu, 17 Apr 2008 23:30:01 -0500 Subject: [PATCH 01/48] Tidy up ActiveSupport::Callbacks::CallbackChain instance API. --- .../lib/action_controller/dispatcher.rb | 2 +- actionpack/lib/action_controller/filters.rb | 6 ++-- activemodel/lib/active_model/validations.rb | 3 +- activerecord/lib/active_record/validations.rb | 3 +- activesupport/lib/active_support/callbacks.rb | 25 ++++++++++----- activesupport/test/callbacks_test.rb | 31 +++++++++++++++++++ 6 files changed, 54 insertions(+), 16 deletions(-) diff --git a/actionpack/lib/action_controller/dispatcher.rb b/actionpack/lib/action_controller/dispatcher.rb index 30db7d9f73d1a..99e1f74c0affd 100644 --- a/actionpack/lib/action_controller/dispatcher.rb +++ b/actionpack/lib/action_controller/dispatcher.rb @@ -22,7 +22,7 @@ def dispatch(cgi = nil, session_options = CgiRequest::DEFAULT_SESSION_OPTIONS, o def to_prepare(identifier = nil, &block) @prepare_dispatch_callbacks ||= ActiveSupport::Callbacks::CallbackChain.new callback = ActiveSupport::Callbacks::Callback.new(:prepare_dispatch, block, :identifier => identifier) - @prepare_dispatch_callbacks.replace_or_append_callback(callback) + @prepare_dispatch_callbacks | callback end # If the block raises, send status code as a last-ditch response. diff --git a/actionpack/lib/action_controller/filters.rb b/actionpack/lib/action_controller/filters.rb index 73721cd1ec26a..8c977877413d5 100644 --- a/actionpack/lib/action_controller/filters.rb +++ b/actionpack/lib/action_controller/filters.rb @@ -265,7 +265,7 @@ def create_filters(filters, filter_type, &block) def skip_filter_in_chain(*filters, &test) filters, conditions = extract_options(filters) filters.each do |filter| - if callback = find_callback(filter) then delete(callback) end + if callback = find(filter) then delete(callback) end end if conditions.empty? update_filter_in_chain(filters, :skip => conditions, &test) end @@ -302,7 +302,7 @@ def find_filter_prepend_position(filters, filter_type) def find_or_create_filter(filter, filter_type, options = {}) update_filter_in_chain([filter], options) - if found_filter = find_callback(filter) { |f| f.type == filter_type } + if found_filter = find(filter) { |f| f.type == filter_type } found_filter else filter_kind = case @@ -326,7 +326,7 @@ def find_or_create_filter(filter, filter_type, options = {}) end def update_filter_in_chain(filters, options, &test) - filters.map! { |f| block_given? ? find_callback(f, &test) : find_callback(f) } + filters.map! { |f| block_given? ? find(f, &test) : find(f) } filters.compact! map! do |filter| diff --git a/activemodel/lib/active_model/validations.rb b/activemodel/lib/active_model/validations.rb index 503fb10795e20..3b7b9050bed9e 100644 --- a/activemodel/lib/active_model/validations.rb +++ b/activemodel/lib/active_model/validations.rb @@ -7,8 +7,7 @@ def self.included(base) # :nodoc: %w( validate validate_on_create validate_on_update ).each do |validation_method| base.class_eval <<-"end_eval" def self.#{validation_method}(*methods, &block) - methods = CallbackChain.build(:#{validation_method}, *methods, &block) - self.#{validation_method}_callback_chain.replace(#{validation_method}_callback_chain | methods) + self.#{validation_method}_callback_chain | CallbackChain.build(:#{validation_method}, *methods, &block) end def self.#{validation_method}_callback_chain diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb index 86cda9aa66237..7b70f78405af9 100755 --- a/activerecord/lib/active_record/validations.rb +++ b/activerecord/lib/active_record/validations.rb @@ -285,8 +285,7 @@ def self.included(base) # :nodoc: VALIDATIONS.each do |validation_method| base.class_eval <<-"end_eval" def self.#{validation_method}(*methods, &block) - methods = CallbackChain.build(:#{validation_method}, *methods, &block) - self.#{validation_method}_callback_chain.replace(#{validation_method}_callback_chain | methods) + self.#{validation_method}_callback_chain | CallbackChain.build(:#{validation_method}, *methods, &block) end def self.#{validation_method}_callback_chain diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb index 329cc2fdc72f6..282b6cbcbc3ed 100644 --- a/activesupport/lib/active_support/callbacks.rb +++ b/activesupport/lib/active_support/callbacks.rb @@ -96,17 +96,26 @@ def run(object, options = {}, &terminator) end end - def find_callback(callback, &block) + def |(chain) + if chain.is_a?(Callback) + if found_callback = find(chain) + index = index(found_callback) + self[index] = chain + else + self << chain + end + else + chain.each { |callback| self | callback } + end + self + end + + def find(callback, &block) select { |c| c == callback && (!block_given? || yield(c)) }.first end - def replace_or_append_callback(callback) - if found_callback = find_callback(callback) - index = index(found_callback) - self[index] = callback - else - self << callback - end + def delete(callback) + super(find(callback)) end private diff --git a/activesupport/test/callbacks_test.rb b/activesupport/test/callbacks_test.rb index 3f8cb7f01a974..7f71ca226267a 100644 --- a/activesupport/test/callbacks_test.rb +++ b/activesupport/test/callbacks_test.rb @@ -96,6 +96,8 @@ def test_save_conditional_person end class CallbackTest < Test::Unit::TestCase + include ActiveSupport::Callbacks + def test_eql callback = Callback.new(:before, :save, :identifier => :lifesaver) assert callback.eql?(Callback.new(:before, :save, :identifier => :lifesaver)) @@ -115,3 +117,32 @@ def test_dup assert_equal({}, a.options) end end + +class CallbackChainTest < Test::Unit::TestCase + include ActiveSupport::Callbacks + + def setup + @chain = CallbackChain.build(:make, :bacon, :lettuce, :tomato) + end + + def test_build + assert_equal 3, @chain.size + assert_equal [:bacon, :lettuce, :tomato], @chain.map(&:method) + end + + def test_find + assert_equal :bacon, @chain.find(:bacon).method + end + + def test_union + assert_equal [:bacon, :lettuce, :tomato], (@chain | Callback.new(:make, :bacon)).map(&:method) + assert_equal [:bacon, :lettuce, :tomato, :turkey], (@chain | CallbackChain.build(:make, :bacon, :lettuce, :tomato, :turkey)).map(&:method) + assert_equal [:bacon, :lettuce, :tomato, :turkey, :mayo], (@chain | Callback.new(:make, :mayo)).map(&:method) + end + + def test_delete + assert_equal [:bacon, :lettuce, :tomato], @chain.map(&:method) + @chain.delete(:bacon) + assert_equal [:lettuce, :tomato], @chain.map(&:method) + end +end From 986aec5dbbdfb578945e706cbe6a54c4f06640e5 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Thu, 17 Apr 2008 23:49:03 +0100 Subject: [PATCH 02/48] Refactor Dispatcher callbacks to remove unnecessary Dependencies checks in production environment. --- .../lib/action_controller/dispatcher.rb | 73 +++++++++---------- actionpack/test/controller/dispatcher_test.rb | 55 +++++--------- railties/lib/console_app.rb | 4 +- railties/lib/initializer.rb | 9 +++ railties/test/console_app_test.rb | 21 +++--- 5 files changed, 73 insertions(+), 89 deletions(-) diff --git a/actionpack/lib/action_controller/dispatcher.rb b/actionpack/lib/action_controller/dispatcher.rb index 99e1f74c0affd..6e1e7a261fcdb 100644 --- a/actionpack/lib/action_controller/dispatcher.rb +++ b/actionpack/lib/action_controller/dispatcher.rb @@ -5,6 +5,30 @@ class Dispatcher @@guard = Mutex.new class << self + def define_dispatcher_callbacks(cache_classes) + unless cache_classes + # Development mode callbacks + before_dispatch :reload_application + after_dispatch :cleanup_application + end + + # Common callbacks + to_prepare :load_application_controller do + begin + require_dependency 'application' unless defined?(::ApplicationController) + rescue LoadError => error + raise unless error.message =~ /application\.rb/ + end + end + + if defined?(ActiveRecord) + before_dispatch { ActiveRecord::Base.verify_active_connections! } + to_prepare(:activerecord_instantiate_observers) { ActiveRecord::Base.instantiate_observers } + end + + after_dispatch :flush_logger if defined?(RAILS_DEFAULT_LOGGER) && RAILS_DEFAULT_LOGGER.respond_to?(:flush) + end + # Backward-compatible class method takes CGI-specific args. Deprecated # in favor of Dispatcher.new(output, request, response).dispatch. def dispatch(cgi = nil, session_options = CgiRequest::DEFAULT_SESSION_OPTIONS, output = $stdout) @@ -69,23 +93,9 @@ def failsafe_logger cattr_accessor :error_file_path self.error_file_path = Rails.public_path if defined?(Rails.public_path) - cattr_accessor :unprepared - self.unprepared = true - include ActiveSupport::Callbacks define_callbacks :prepare_dispatch, :before_dispatch, :after_dispatch - before_dispatch :reload_application - before_dispatch :prepare_application - after_dispatch :flush_logger - after_dispatch :cleanup_application - - if defined? ActiveRecord - to_prepare :activerecord_instantiate_observers do - ActiveRecord::Base.instantiate_observers - end - end - def initialize(output, request = nil, response = nil) @output, @request, @response = output, request, response end @@ -114,40 +124,23 @@ def dispatch_cgi(cgi, session_options) end def reload_application - if Dependencies.load? - Routing::Routes.reload - self.unprepared = true - end - end + # Run prepare callbacks before every request in development mode + run_callbacks :prepare_dispatch - def prepare_application(force = false) - begin - require_dependency 'application' unless defined?(::ApplicationController) - rescue LoadError => error - raise unless error.message =~ /application\.rb/ - end - - ActiveRecord::Base.verify_active_connections! if defined?(ActiveRecord) - - if unprepared || force - run_callbacks :prepare_dispatch - ActionView::TemplateFinder.reload! unless ActionView::Base.cache_template_loading - self.unprepared = false - end + Routing::Routes.reload + ActionView::TemplateFinder.reload! unless ActionView::Base.cache_template_loading end # Cleanup the application by clearing out loaded classes so they can # be reloaded on the next request without restarting the server. - def cleanup_application(force = false) - if Dependencies.load? || force - ActiveRecord::Base.reset_subclasses if defined?(ActiveRecord) - Dependencies.clear - ActiveRecord::Base.clear_reloadable_connections! if defined?(ActiveRecord) - end + def cleanup_application + ActiveRecord::Base.reset_subclasses if defined?(ActiveRecord) + Dependencies.clear + ActiveRecord::Base.clear_reloadable_connections! if defined?(ActiveRecord) end def flush_logger - RAILS_DEFAULT_LOGGER.flush if defined?(RAILS_DEFAULT_LOGGER) && RAILS_DEFAULT_LOGGER.respond_to?(:flush) + RAILS_DEFAULT_LOGGER.flush end protected diff --git a/actionpack/test/controller/dispatcher_test.rb b/actionpack/test/controller/dispatcher_test.rb index c4f49f1e168e0..eea0813ed5818 100644 --- a/actionpack/test/controller/dispatcher_test.rb +++ b/actionpack/test/controller/dispatcher_test.rb @@ -11,7 +11,13 @@ def setup @output = StringIO.new ENV['REQUEST_METHOD'] = 'GET' + # Clear callbacks as they are redefined by Dispatcher#define_dispatcher_callbacks Dispatcher.instance_variable_set("@prepare_dispatch_callbacks", ActiveSupport::Callbacks::CallbackChain.new) + Dispatcher.instance_variable_set("@before_dispatch_callbacks", ActiveSupport::Callbacks::CallbackChain.new) + Dispatcher.instance_variable_set("@after_dispatch_callbacks", ActiveSupport::Callbacks::CallbackChain.new) + + Dispatcher.stubs(:require_dependency) + @dispatcher = Dispatcher.new(@output) end @@ -20,17 +26,13 @@ def teardown end def test_clears_dependencies_after_dispatch_if_in_loading_mode - Dependencies.stubs(:load?).returns(true) - ActionController::Routing::Routes.expects(:reload).once Dependencies.expects(:clear).once - dispatch + dispatch(@output, false) end def test_leaves_dependencies_after_dispatch_if_not_in_loading_mode - Dependencies.stubs(:load?).returns(false) - ActionController::Routing::Routes.expects(:reload).never Dependencies.expects(:clear).never @@ -51,40 +53,25 @@ def test_failsafe_response assert_equal "Status: 400 Bad Request\r\nContent-Type: text/html\r\n\r\n

400 Bad Request

", @output.string end - def test_reload_application_sets_unprepared_if_loading_dependencies - Dependencies.stubs(:load?).returns(false) - ActionController::Routing::Routes.expects(:reload).never - @dispatcher.unprepared = false - @dispatcher.send!(:reload_application) - assert !@dispatcher.unprepared - - Dependencies.stubs(:load?).returns(true) - ActionController::Routing::Routes.expects(:reload).once - @dispatcher.send!(:reload_application) - assert @dispatcher.unprepared - end - - def test_prepare_application_runs_callbacks_if_unprepared + def test_prepare_callbacks a = b = c = nil Dispatcher.to_prepare { |*args| a = b = c = 1 } Dispatcher.to_prepare { |*args| b = c = 2 } Dispatcher.to_prepare { |*args| c = 3 } - # Skip the callbacks when already prepared. - @dispatcher.unprepared = false - @dispatcher.send! :prepare_application + # Ensure to_prepare callbacks are not run when defined assert_nil a || b || c - # Perform the callbacks when unprepared. - @dispatcher.unprepared = true - @dispatcher.send! :prepare_application + # Run callbacks + @dispatcher.send :run_callbacks, :prepare_dispatch + assert_equal 1, a assert_equal 2, b assert_equal 3, c - # But when not :load, make sure they are only run once + # Make sure they are only run once a = b = c = nil - @dispatcher.send! :prepare_application + @dispatcher.send :dispatch assert_nil a || b || c end @@ -93,28 +80,20 @@ def test_to_prepare_with_identifier_replaces Dispatcher.to_prepare(:unique_id) { |*args| a = b = 1 } Dispatcher.to_prepare(:unique_id) { |*args| a = 2 } - @dispatcher.unprepared = true - @dispatcher.send! :prepare_application + @dispatcher.send :run_callbacks, :prepare_dispatch assert_equal 2, a assert_equal nil, b end - def test_to_prepare_only_runs_once_if_not_loading_dependencies - Dependencies.stubs(:load?).returns(false) - called = 0 - Dispatcher.to_prepare(:unprepared_test) { |*args| called += 1 } - 2.times { dispatch } - assert_equal 1, called - end - private - def dispatch(output = @output) + def dispatch(output = @output, cache_classes = true) controller = mock controller.stubs(:process).returns(controller) controller.stubs(:out).with(output).returns('response') ActionController::Routing::Routes.stubs(:recognize).returns(controller) + Dispatcher.define_dispatcher_callbacks(cache_classes) Dispatcher.dispatch(nil, {}, output) end diff --git a/railties/lib/console_app.rb b/railties/lib/console_app.rb index c7673642ec029..88e7962b433b0 100644 --- a/railties/lib/console_app.rb +++ b/railties/lib/console_app.rb @@ -24,7 +24,7 @@ def new_session def reload! puts "Reloading..." dispatcher = ActionController::Dispatcher.new($stdout) - dispatcher.cleanup_application(true) - dispatcher.prepare_application(true) + dispatcher.cleanup_application + dispatcher.reload_application true end diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb index 18af73fc8941d..b5bf9266f5175 100644 --- a/railties/lib/initializer.rb +++ b/railties/lib/initializer.rb @@ -135,6 +135,9 @@ def process load_application_initializers + # Prepare dispatcher callbacks and run 'prepare' callbacks + prepare_dispatcher + # the framework is now fully initialized after_initialize @@ -442,6 +445,12 @@ def load_application_initializers end end + def prepare_dispatcher + require 'dispatcher' unless defined?(::Dispatcher) + Dispatcher.define_dispatcher_callbacks(configuration.cache_classes) + Dispatcher.new(RAILS_DEFAULT_LOGGER).send :run_callbacks, :prepare_dispatch + end + end # The Configuration class holds all the parameters for the Initializer and diff --git a/railties/test/console_app_test.rb b/railties/test/console_app_test.rb index 7615d95498dac..6cfc907b80319 100644 --- a/railties/test/console_app_test.rb +++ b/railties/test/console_app_test.rb @@ -13,17 +13,20 @@ class ApplicationController < ActionController::Base; end Test::Unit.run = false class ConsoleAppTest < Test::Unit::TestCase - def test_reload_should_fire_preparation_callbacks - a = b = c = nil + uses_mocha 'console reload test' do + def test_reload_should_fire_preparation_callbacks + a = b = c = nil - Dispatcher.to_prepare { a = b = c = 1 } - Dispatcher.to_prepare { b = c = 2 } - Dispatcher.to_prepare { c = 3 } + Dispatcher.to_prepare { a = b = c = 1 } + Dispatcher.to_prepare { b = c = 2 } + Dispatcher.to_prepare { c = 3 } + ActionController::Routing::Routes.expects(:reload) - reload! + reload! - assert_equal 1, a - assert_equal 2, b - assert_equal 3, c + assert_equal 1, a + assert_equal 2, b + assert_equal 3, c + end end end From a4c15303cbc96fffd66c68abdeebe73d8883e5ab Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Fri, 18 Apr 2008 14:44:55 -0500 Subject: [PATCH 03/48] Slight optimization to CallbackChain#union and delete. --- activesupport/lib/active_support/callbacks.rb | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb index 282b6cbcbc3ed..5c512370493db 100644 --- a/activesupport/lib/active_support/callbacks.rb +++ b/activesupport/lib/active_support/callbacks.rb @@ -97,15 +97,14 @@ def run(object, options = {}, &terminator) end def |(chain) - if chain.is_a?(Callback) - if found_callback = find(chain) - index = index(found_callback) + if chain.is_a?(CallbackChain) + chain.each { |callback| self | callback } + elsif chain.is_a?(Callback) + if index = index(chain) self[index] = chain else self << chain end - else - chain.each { |callback| self | callback } end self end @@ -115,7 +114,7 @@ def find(callback, &block) end def delete(callback) - super(find(callback)) + super(callback.is_a?(Callback) ? callback : find(callback)) end private From db11ef9546b1ad16cf539395b75450c1c8e9714c Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Fri, 18 Apr 2008 14:50:10 -0700 Subject: [PATCH 04/48] Override Ruby 1.8.7's incompatible Symbol#to_proc. --- activesupport/lib/active_support/core_ext/symbol.rb | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/activesupport/lib/active_support/core_ext/symbol.rb b/activesupport/lib/active_support/core_ext/symbol.rb index 54f541ad9ac7f..d41d47e70e6e1 100644 --- a/activesupport/lib/active_support/core_ext/symbol.rb +++ b/activesupport/lib/active_support/core_ext/symbol.rb @@ -1,4 +1,11 @@ -unless :test.respond_to?(:to_proc) +# Remove 1.8.7's incompatible method. +if :to_proc.respond_to?(:to_proc) && [1] != ([[1, 2]].map(&:first) rescue false) + class Symbol + remove_method :to_proc + end +end + +unless :to_proc.respond_to?(:to_proc) class Symbol # Turns the symbol into a simple proc, which is especially useful for enumerations. Examples: # From dfdb9f738e9842752c340634622624544efe18c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 18 Apr 2008 17:10:58 -0500 Subject: [PATCH 05/48] Cleanup generator tests by extracting repeated code into generator_test_helper. Add test for mailer generator. Signed-off-by: Joshua Peek --- .../components/mailer/mailer_generator.rb | 8 +- .../test/generators/generator_test_helper.rb | 159 +++++++++--- .../generators/rails_mailer_generator_test.rb | 26 ++ .../generators/rails_model_generator_test.rb | 80 +----- .../rails_resource_generator_test.rb | 78 +----- .../rails_scaffold_generator_test.rb | 240 ++++++------------ 6 files changed, 227 insertions(+), 364 deletions(-) create mode 100644 railties/test/generators/rails_mailer_generator_test.rb diff --git a/railties/lib/rails_generator/generators/components/mailer/mailer_generator.rb b/railties/lib/rails_generator/generators/components/mailer/mailer_generator.rb index 3ff4f039729c5..dc1202d7c8cab 100644 --- a/railties/lib/rails_generator/generators/components/mailer/mailer_generator.rb +++ b/railties/lib/rails_generator/generators/components/mailer/mailer_generator.rb @@ -11,12 +11,8 @@ def manifest m.directory File.join('test/fixtures', file_path) # Mailer class and unit test. - m.template "mailer.rb", File.join('app/models', - class_path, - "#{file_name}.rb") - m.template "unit_test.rb", File.join('test/unit', - class_path, - "#{file_name}_test.rb") + m.template "mailer.rb", File.join('app/models', class_path, "#{file_name}.rb") + m.template "unit_test.rb", File.join('test/unit', class_path, "#{file_name}_test.rb") # View template and fixture for each action. actions.each do |action| diff --git a/railties/test/generators/generator_test_helper.rb b/railties/test/generators/generator_test_helper.rb index 4007cf16ca4a6..190bc91d52991 100644 --- a/railties/test/generators/generator_test_helper.rb +++ b/railties/test/generators/generator_test_helper.rb @@ -1,3 +1,51 @@ +require 'test/unit' +require 'fileutils' + +# Mock out what we need from AR::Base +module ActiveRecord + class Base + class << self + attr_accessor :pluralize_table_names + end + self.pluralize_table_names = true + end + + module ConnectionAdapters + class Column + attr_reader :name, :default, :type, :limit, :null, :sql_type, :precision, :scale + + def initialize(name, default, sql_type = nil) + @name = name + @default = default + @type = @sql_type = sql_type + end + + def human_name + @name.humanize + end + end + end +end + +# Mock up necessities from ActionView +module ActionView + module Helpers + module ActionRecordHelper; end + class InstanceTag; end + end +end + +# Set RAILS_ROOT appropriately fixture generation +tmp_dir = "#{File.dirname(__FILE__)}/../fixtures/tmp" + +if defined? RAILS_ROOT + RAILS_ROOT.replace tmp_dir +else + RAILS_ROOT = tmp_dir +end +FileUtils.mkdir_p RAILS_ROOT + +$LOAD_PATH.unshift "#{File.dirname(__FILE__)}/../../lib" require 'initializer' # Mocks out the configuration @@ -9,35 +57,62 @@ def self.configuration require 'rails_generator' +class GeneratorTestCase < Test::Unit::TestCase + include FileUtils + + def setup + ActiveRecord::Base.pluralize_table_names = true + + mkdir_p "#{RAILS_ROOT}/app/views/layouts" + mkdir_p "#{RAILS_ROOT}/config" + mkdir_p "#{RAILS_ROOT}/db" + mkdir_p "#{RAILS_ROOT}/test/fixtures" + mkdir_p "#{RAILS_ROOT}/public/stylesheets" + + File.open("#{RAILS_ROOT}/config/routes.rb", 'w') do |f| + f << "ActionController::Routing::Routes.draw do |map|\n\nend" + end + end -module GeneratorTestHelper + def teardown + rm_rf "#{RAILS_ROOT}/app" + rm_rf "#{RAILS_ROOT}/test" + rm_rf "#{RAILS_ROOT}/config" + rm_rf "#{RAILS_ROOT}/db" + rm_rf "#{RAILS_ROOT}/public" + end + + def test_truth + # don't complain, test/unit + end + # Instantiates the Generator - def build_generator(name,params) - Rails::Generator::Base.instance(name,params) + def build_generator(name, params) + Rails::Generator::Base.instance(name, params) end # Runs the create command (like the command line does) - def run_generator(name,params) + def run_generator(name, params) silence_generator do - build_generator(name,params).command(:create).invoke! + build_generator(name, params).command(:create).invoke! end end # Silences the logger temporarily and returns the output as a String def silence_generator - logger_original=Rails::Generator::Base.logger - myout=StringIO.new - Rails::Generator::Base.logger=Rails::Generator::SimpleLogger.new(myout) + logger_original = Rails::Generator::Base.logger + myout = StringIO.new + Rails::Generator::Base.logger = Rails::Generator::SimpleLogger.new(myout) yield if block_given? - Rails::Generator::Base.logger=logger_original + Rails::Generator::Base.logger = logger_original myout.string end # asserts that the given controller was generated. # It takes a name or symbol without the _controller part and an optional super class. # The contents of the class source file is passed to a block. - def assert_generated_controller_for(name,parent="ApplicationController") - assert_generated_class "app/controllers/#{name.to_s.underscore}_controller",parent do |body| + def assert_generated_controller_for(name, parent = "ApplicationController") + assert_generated_class "app/controllers/#{name.to_s.underscore}_controller", parent do |body| yield body if block_given? end end @@ -45,8 +120,8 @@ def assert_generated_controller_for(name,parent="ApplicationController") # asserts that the given model was generated. # It takes a name or symbol and an optional super class. # the contents of the class source file is passed to a block. - def assert_generated_model_for(name,parent="ActiveRecord::Base") - assert_generated_class "app/models/#{name.to_s.underscore}",parent do |body| + def assert_generated_model_for(name, parent = "ActiveRecord::Base") + assert_generated_class "app/models/#{name.to_s.underscore}", parent do |body| yield body if block_given? end end @@ -63,7 +138,7 @@ def assert_generated_helper_for(name) # asserts that the given functional test was generated. # It takes a name or symbol without the _controller_test part and an optional super class. # the contents of the class source file is passed to a block. - def assert_generated_functional_test_for(name,parent="ActionController::TestCase") + def assert_generated_functional_test_for(name, parent = "ActionController::TestCase") assert_generated_class "test/functional/#{name.to_s.underscore}_controller_test",parent do |body| yield body if block_given? end @@ -72,8 +147,8 @@ def assert_generated_functional_test_for(name,parent="ActionController::TestCase # asserts that the given unit test was generated. # It takes a name or symbol without the _test part and an optional super class. # the contents of the class source file is passed to a block. - def assert_generated_unit_test_for(name,parent="ActiveSupport::TestCase") - assert_generated_class "test/unit/#{name.to_s.underscore}_test",parent do |body| + def assert_generated_unit_test_for(name, parent = "ActiveSupport::TestCase") + assert_generated_class "test/unit/#{name.to_s.underscore}_test", parent do |body| yield body if block_given? end end @@ -89,17 +164,18 @@ def assert_generated_file(path) # asserts that the given file exists def assert_file_exists(path) - assert File.exist?("#{RAILS_ROOT}/#{path}"),"The file '#{RAILS_ROOT}/#{path}' should exist" + assert File.exist?("#{RAILS_ROOT}/#{path}"), + "The file '#{RAILS_ROOT}/#{path}' should exist" end # asserts that the given class source file was generated. # It takes a path without the .rb part and an optional super class. # the contents of the class source file is passed to a block. - def assert_generated_class(path,parent=nil) - path=~/\/?(\d+_)?(\w+)$/ - class_name=$2.camelize + def assert_generated_class(path, parent=nil) + path =~ /\/?(\d+_)?(\w+)$/ + class_name = $2.camelize assert_generated_file("#{path}.rb") do |body| - assert body=~/class #{class_name}#{parent.nil? ? '':" < #{parent}"}/,"the file '#{path}.rb' should be a class" + assert_match /class #{class_name}#{parent.nil? ? '':" < #{parent}"}/, body, "the file '#{path}.rb' should be a class" yield body if block_given? end end @@ -108,10 +184,10 @@ def assert_generated_class(path,parent=nil) # It takes a path without the .rb part. # the contents of the class source file is passed to a block. def assert_generated_module(path) - path=~/\/?(\w+)$/ - module_name=$1.camelize + path =~ /\/?(\w+)$/ + module_name = $1.camelize assert_generated_file("#{path}.rb") do |body| - assert body=~/module #{module_name}/,"the file '#{path}.rb' should be a module" + assert_match /module #{module_name}/, body, "the file '#{path}.rb' should be a module" yield body if block_given? end end @@ -130,7 +206,8 @@ def assert_generated_stylesheet(path) # the parsed yaml tree is passed to a block. def assert_generated_yaml(path) assert_generated_file("#{path}.yml") do |body| - assert yaml=YAML.load(body) + yaml = YAML.load(body) + assert yaml, 'YAML data missing' yield yaml if block_given? end end @@ -147,23 +224,22 @@ def assert_generated_fixtures_for(name) # asserts that the given views were generated. # It takes a controller name and a list of views (including extensions). # The body of each view is passed to a block - def assert_generated_views_for(name,*actions) + def assert_generated_views_for(name, *actions) actions.each do |action| - assert_generated_file("app/views/#{name.to_s.underscore}/#{action.to_s}") do |body| + assert_generated_file("app/views/#{name.to_s.underscore}/#{action}") do |body| yield body if block_given? end end end - def assert_generated_migration(name,parent="ActiveRecord::Migration") - file = - Dir.glob("#{RAILS_ROOT}/db/migrate/*_#{name.to_s.underscore}.rb").first - file = file.match(/db\/migrate\/[0-9]+_#{name.to_s.underscore}/).to_s - assert_generated_class file,parent do |body| - assert body=~/timestamps/, "should have timestamps defined" - yield body if block_given? - end + def assert_generated_migration(name, parent = "ActiveRecord::Migration") + file = Dir.glob("#{RAILS_ROOT}/db/migrate/*_#{name.to_s.underscore}.rb").first + file = file.match(/db\/migrate\/[0-9]+_\w+/).to_s + assert_generated_class file, parent do |body| + assert_match /timestamps/, body, "should have timestamps defined" + yield body if block_given? end + end # Asserts that the given migration file was not generated. # It takes the name of the migration as a parameter. @@ -175,22 +251,23 @@ def assert_skipped_migration(name) # asserts that the given resource was added to the routes. def assert_added_route_for(name) assert_generated_file("config/routes.rb") do |body| - assert body=~/map.resources :#{name.to_s.underscore}/,"should add route for :#{name.to_s.underscore}" + assert_match /map.resources :#{name.to_s.underscore}/, body, + "should add route for :#{name.to_s.underscore}" end end # asserts that the given methods are defined in the body. # This does assume standard rails code conventions with regards to the source code. # The body of each individual method is passed to a block. - def assert_has_method(body,*methods) + def assert_has_method(body, *methods) methods.each do |name| - assert body=~/^ def #{name.to_s}\n((\n| .*\n)*) end/,"should have method #{name.to_s}" - yield( name, $1 ) if block_given? + assert body =~ /^ def #{name}(\(.+\))?\n((\n| .*\n)*) end/, "should have method #{name}" + yield(name, $2) if block_given? end end # asserts that the given column is defined in the migration - def assert_generated_column(body,name,type) - assert body=~/t\.#{type.to_s} :#{name.to_s}/, "should have column #{name.to_s} defined" + def assert_generated_column(body, name, type) + assert_match /t\.#{type.to_s} :#{name.to_s}/, body, "should have column #{name.to_s} defined" end end diff --git a/railties/test/generators/rails_mailer_generator_test.rb b/railties/test/generators/rails_mailer_generator_test.rb new file mode 100644 index 0000000000000..9b5debbdb1a18 --- /dev/null +++ b/railties/test/generators/rails_mailer_generator_test.rb @@ -0,0 +1,26 @@ +require 'generators/generator_test_helper' + +class RailsMailerGeneratorTest < GeneratorTestCase + + def test_generates_mailer + run_generator('mailer', %w(Notifier reset_password)) + + assert_generated_model_for :notifier, 'ActionMailer::Base' do |model| + assert_has_method model, :reset_password do |name, body| + assert_equal [ + "@subject = 'Notifier#reset_password'", + "@body = {}", + "@recipients = ''", + "@from = ''", + "@sent_on = sent_at", + "@headers = {}" + ], + body.split("\n").map{|line| line.sub(' '*4, '') } + end + end + + assert_generated_views_for :notifier, 'reset_password.erb' + assert_generated_unit_test_for :notifier, 'ActionMailer::TestCase' + assert_generated_file "test/fixtures/notifier/reset_password" + end +end diff --git a/railties/test/generators/rails_model_generator_test.rb b/railties/test/generators/rails_model_generator_test.rb index 86ad9c4dc8ef4..0bfc338566d5e 100644 --- a/railties/test/generators/rails_model_generator_test.rb +++ b/railties/test/generators/rails_model_generator_test.rb @@ -1,84 +1,6 @@ -require 'test/unit' - -# Optionally load RubyGems -begin - require 'rubygems' -rescue LoadError -end - -# Mock out what we need from AR::Base -module ActiveRecord - class Base - class << self - attr_accessor :pluralize_table_names - end - self.pluralize_table_names = true - end - - module ConnectionAdapters - class Column - attr_reader :name, :default, :type, :limit, :null, :sql_type, :precision, :scale - def initialize(name, default, sql_type=nil) - @namename - @default=default - @type=@sql_type=sql_type - end - - def human_name - @name.humanize - end - end - end -end - -# Mock up necessities from ActionView -module ActionView - module Helpers - module ActionRecordHelper; end - class InstanceTag; end - end -end - -# Set RAILS_ROOT appropriately fixture generation -tmp_dir="#{File.dirname(__FILE__)}/../fixtures/tmp" -if defined?(RAILS_ROOT) - RAILS_ROOT.replace(tmp_dir) -else - RAILS_ROOT=tmp_dir -end -Dir.mkdir(RAILS_ROOT) unless File.exist?(RAILS_ROOT) - - -$LOAD_PATH.unshift "#{File.dirname(__FILE__)}/../../lib" - require 'generators/generator_test_helper' -class RailsModelGeneratorTest < Test::Unit::TestCase - include GeneratorTestHelper - - def setup - ActiveRecord::Base.pluralize_table_names = true - Dir.mkdir("#{RAILS_ROOT}/app") unless File.exist?("#{RAILS_ROOT}/app") - Dir.mkdir("#{RAILS_ROOT}/app/views") unless File.exist?("#{RAILS_ROOT}/app/views") - Dir.mkdir("#{RAILS_ROOT}/app/views/layouts") unless File.exist?("#{RAILS_ROOT}/app/views/layouts") - Dir.mkdir("#{RAILS_ROOT}/config") unless File.exist?("#{RAILS_ROOT}/config") - Dir.mkdir("#{RAILS_ROOT}/db") unless File.exist?("#{RAILS_ROOT}/db") - Dir.mkdir("#{RAILS_ROOT}/test") unless File.exist?("#{RAILS_ROOT}/test") - Dir.mkdir("#{RAILS_ROOT}/test/fixtures") unless File.exist?("#{RAILS_ROOT}/test/fixtures") - Dir.mkdir("#{RAILS_ROOT}/public") unless File.exist?("#{RAILS_ROOT}/public") - Dir.mkdir("#{RAILS_ROOT}/public/stylesheets") unless File.exist?("#{RAILS_ROOT}/public/stylesheets") - File.open("#{RAILS_ROOT}/config/routes.rb", 'w') do |f| - f<<"ActionController::Routing::Routes.draw do |map|\n\nend\n" - end - end - - def teardown - FileUtils.rm_rf "#{RAILS_ROOT}/app" - FileUtils.rm_rf "#{RAILS_ROOT}/test" - FileUtils.rm_rf "#{RAILS_ROOT}/config" - FileUtils.rm_rf "#{RAILS_ROOT}/db" - FileUtils.rm_rf "#{RAILS_ROOT}/public" - end +class RailsModelGeneratorTest < GeneratorTestCase def test_model_generates_resources run_generator('model', %w(Product name:string)) diff --git a/railties/test/generators/rails_resource_generator_test.rb b/railties/test/generators/rails_resource_generator_test.rb index 511f1059c22ed..45e4850ef5c02 100644 --- a/railties/test/generators/rails_resource_generator_test.rb +++ b/railties/test/generators/rails_resource_generator_test.rb @@ -1,82 +1,6 @@ -require 'test/unit' - -# Optionally load RubyGems -begin - require 'rubygems' -rescue LoadError -end - -# Mock out what we need from AR::Base -module ActiveRecord - class Base - class << self - attr_accessor :pluralize_table_names - end - self.pluralize_table_names = true - end - - module ConnectionAdapters - class Column - attr_reader :name, :default, :type, :limit, :null, :sql_type, :precision, :scale - def initialize(name, default, sql_type=nil) - @namename - @default=default - @type=@sql_type=sql_type - end - - def human_name - @name.humanize - end - end - end -end - -# Mock up necessities from ActionView -module ActionView - module Helpers - module ActionRecordHelper; end - class InstanceTag; end - end -end - -# Set RAILS_ROOT appropriately fixture generation -tmp_dir="#{File.dirname(__FILE__)}/../fixtures/tmp" -if defined?(RAILS_ROOT) - RAILS_ROOT.replace(tmp_dir) -else - RAILS_ROOT=tmp_dir -end -Dir.mkdir(RAILS_ROOT) unless File.exist?(RAILS_ROOT) - -$LOAD_PATH.unshift "#{File.dirname(__FILE__)}/../../lib" require 'generators/generator_test_helper' -class RailsResourceGeneratorTest < Test::Unit::TestCase - include GeneratorTestHelper - - def setup - ActiveRecord::Base.pluralize_table_names = true - Dir.mkdir("#{RAILS_ROOT}/app") unless File.exist?("#{RAILS_ROOT}/app") - Dir.mkdir("#{RAILS_ROOT}/app/views") unless File.exist?("#{RAILS_ROOT}/app/views") - Dir.mkdir("#{RAILS_ROOT}/app/views/layouts") unless File.exist?("#{RAILS_ROOT}/app/views/layouts") - Dir.mkdir("#{RAILS_ROOT}/config") unless File.exist?("#{RAILS_ROOT}/config") - Dir.mkdir("#{RAILS_ROOT}/db") unless File.exist?("#{RAILS_ROOT}/db") - Dir.mkdir("#{RAILS_ROOT}/test") unless File.exist?("#{RAILS_ROOT}/test") - Dir.mkdir("#{RAILS_ROOT}/test/fixtures") unless File.exist?("#{RAILS_ROOT}/test/fixtures") - Dir.mkdir("#{RAILS_ROOT}/public") unless File.exist?("#{RAILS_ROOT}/public") - Dir.mkdir("#{RAILS_ROOT}/public/stylesheets") unless File.exist?("#{RAILS_ROOT}/public/stylesheets") - File.open("#{RAILS_ROOT}/config/routes.rb", 'w') do |f| - f<<"ActionController::Routing::Routes.draw do |map|\n\nend\n" - end - end - - def teardown - FileUtils.rm_rf "#{RAILS_ROOT}/app" - FileUtils.rm_rf "#{RAILS_ROOT}/test" - FileUtils.rm_rf "#{RAILS_ROOT}/config" - FileUtils.rm_rf "#{RAILS_ROOT}/db" - FileUtils.rm_rf "#{RAILS_ROOT}/public" - end +class RailsResourceGeneratorTest < GeneratorTestCase def test_resource_generates_resources run_generator('resource', %w(Product name:string)) diff --git a/railties/test/generators/rails_scaffold_generator_test.rb b/railties/test/generators/rails_scaffold_generator_test.rb index 34a1ad2fe570b..220f9e372e530 100644 --- a/railties/test/generators/rails_scaffold_generator_test.rb +++ b/railties/test/generators/rails_scaffold_generator_test.rb @@ -1,189 +1,107 @@ -require 'abstract_unit' - -# Optionally load RubyGems. -begin - require 'rubygems' -rescue LoadError -end - -# Mock out what we need from AR::Base. -module ActiveRecord - class Base - class << self - attr_accessor :pluralize_table_names - end - self.pluralize_table_names = true - end - - module ConnectionAdapters - class Column - attr_reader :name, :default, :type, :limit, :null, :sql_type, :precision, :scale - - def initialize(name, default, sql_type = nil) - @name=name - @default=default - @type=@sql_type=sql_type - end - - def human_name - @name.humanize - end - end - end -end +require 'generators/generator_test_helper' -# And what we need from ActionView -module ActionView - module Helpers - module ActiveRecordHelper; end - class InstanceTag; end +class RailsScaffoldGeneratorTest < GeneratorTestCase + + def test_scaffolded_names + g = Rails::Generator::Base.instance('scaffold', %w(ProductLine)) + assert_equal "ProductLines", g.controller_name + assert_equal "ProductLines", g.controller_class_name + assert_equal "ProductLine", g.controller_singular_name + assert_equal "product_lines", g.controller_plural_name + assert_equal "product_lines", g.controller_file_name + assert_equal "product_lines", g.controller_table_name end -end + def test_scaffold_generates_resources -# Must set before requiring generator libs. -tmp_dir="#{File.dirname(__FILE__)}/../fixtures/tmp" -if defined?(RAILS_ROOT) - RAILS_ROOT.replace(tmp_dir) -else - RAILS_ROOT=tmp_dir -end -Dir.mkdir(RAILS_ROOT) unless File.exist?(RAILS_ROOT) - -$LOAD_PATH.unshift "#{File.dirname(__FILE__)}/../../lib" + run_generator('scaffold', %w(Product name:string)) -require 'generators/generator_test_helper' + assert_generated_controller_for :products do |f| -uses_mocha "Scaffold Generator Tests" do - class RailsScaffoldGeneratorTest < Test::Unit::TestCase - - include GeneratorTestHelper - - def setup - ActiveRecord::Base.pluralize_table_names = true - Dir.mkdir("#{RAILS_ROOT}/app") unless File.exist?("#{RAILS_ROOT}/app") - Dir.mkdir("#{RAILS_ROOT}/app/views") unless File.exist?("#{RAILS_ROOT}/app/views") - Dir.mkdir("#{RAILS_ROOT}/app/views/layouts") unless File.exist?("#{RAILS_ROOT}/app/views/layouts") - Dir.mkdir("#{RAILS_ROOT}/config") unless File.exist?("#{RAILS_ROOT}/config") - Dir.mkdir("#{RAILS_ROOT}/db") unless File.exist?("#{RAILS_ROOT}/db") - Dir.mkdir("#{RAILS_ROOT}/test") unless File.exist?("#{RAILS_ROOT}/test") - Dir.mkdir("#{RAILS_ROOT}/test/fixtures") unless File.exist?("#{RAILS_ROOT}/test/fixtures") - Dir.mkdir("#{RAILS_ROOT}/public") unless File.exist?("#{RAILS_ROOT}/public") - Dir.mkdir("#{RAILS_ROOT}/public/stylesheets") unless File.exist?("#{RAILS_ROOT}/public/stylesheets") - File.open("#{RAILS_ROOT}/config/routes.rb", 'w') do |f| - f<<"ActionController::Routing::Routes.draw do |map|\n\nend\n" + assert_has_method f, :index do |name, m| + assert_match /@products = Product\.find\(:all\)/, m, "#{name} should query products table" end - end - - def teardown - FileUtils.rm_rf "#{RAILS_ROOT}/app" - FileUtils.rm_rf "#{RAILS_ROOT}/test" - FileUtils.rm_rf "#{RAILS_ROOT}/config" - FileUtils.rm_rf "#{RAILS_ROOT}/db" - FileUtils.rm_rf "#{RAILS_ROOT}/public" - end - - def test_scaffolded_names - g = Rails::Generator::Base.instance('scaffold', %w(ProductLine)) - assert_equal "ProductLines", g.controller_name - assert_equal "ProductLines", g.controller_class_name - assert_equal "ProductLine", g.controller_singular_name - assert_equal "product_lines", g.controller_plural_name - assert_equal "product_lines", g.controller_file_name - assert_equal "product_lines", g.controller_table_name - end - - def test_scaffold_generates_resources - - run_generator('scaffold', %w(Product name:string)) - assert_generated_controller_for :products do |f| - - assert_has_method f, :index do |name, m| - assert_match /@products = Product\.find\(:all\)/, m, "#{name} should query products table" - end - - assert_has_method f, :show, :edit, :update, :destroy do |name, m| - assert_match /@product = Product\.find\(params\[:id\]\)/, m, "#{name.to_s} should query products table" - end - - assert_has_method f, :new do |name, m| - assert_match /@product = Product\.new/, m, "#{name.to_s} should instantiate a product" - end - - assert_has_method f, :create do |name, m| - assert_match /@product = Product\.new\(params\[:product\]\)/, m, "#{name.to_s} should instantiate a product" - assert_match /format.xml \{ render :xml => @product.errors, :status => :unprocessable_entity \}/, m, "#{name.to_s} should set status to :unprocessable_entity code for xml" - end + assert_has_method f, :show, :edit, :update, :destroy do |name, m| + assert_match /@product = Product\.find\(params\[:id\]\)/, m, "#{name.to_s} should query products table" + end + assert_has_method f, :new do |name, m| + assert_match /@product = Product\.new/, m, "#{name.to_s} should instantiate a product" end - assert_generated_model_for :product - assert_generated_functional_test_for :products - assert_generated_unit_test_for :product - assert_generated_fixtures_for :products - assert_generated_helper_for :products - assert_generated_stylesheet :scaffold - assert_generated_views_for :products, "index.html.erb", "new.html.erb", "edit.html.erb", "show.html.erb" + assert_has_method f, :create do |name, m| + assert_match /@product = Product\.new\(params\[:product\]\)/, m, "#{name.to_s} should instantiate a product" + assert_match /format.xml \{ render :xml => @product.errors, :status => :unprocessable_entity \}/, m, "#{name.to_s} should set status to :unprocessable_entity code for xml" + end - assert_generated_migration :create_products - assert_added_route_for :products end - def test_scaffold_skip_migration_skips_migration - run_generator('scaffold', %w(Product name:string --skip-migration)) - - assert_generated_model_for :product - assert_generated_functional_test_for :products - assert_generated_unit_test_for :product - assert_generated_fixtures_for :products - assert_generated_helper_for :products - assert_generated_stylesheet :scaffold - assert_generated_views_for :products, "index.html.erb","new.html.erb","edit.html.erb","show.html.erb" - assert_skipped_migration :create_products - assert_added_route_for :products - end + assert_generated_model_for :product + assert_generated_functional_test_for :products + assert_generated_unit_test_for :product + assert_generated_fixtures_for :products + assert_generated_helper_for :products + assert_generated_stylesheet :scaffold + assert_generated_views_for :products, "index.html.erb", "new.html.erb", "edit.html.erb", "show.html.erb" - def test_scaffold_generates_resources_with_attributes - run_generator('scaffold', %w(Product name:string supplier_id:integer created_at:timestamp)) + assert_generated_migration :create_products + assert_added_route_for :products + end - assert_generated_controller_for :products do |f| + def test_scaffold_skip_migration_skips_migration + run_generator('scaffold', %w(Product name:string --skip-migration)) + + assert_generated_model_for :product + assert_generated_functional_test_for :products + assert_generated_unit_test_for :product + assert_generated_fixtures_for :products + assert_generated_helper_for :products + assert_generated_stylesheet :scaffold + assert_generated_views_for :products, "index.html.erb","new.html.erb","edit.html.erb","show.html.erb" + assert_skipped_migration :create_products + assert_added_route_for :products + end - assert_has_method f, :index do |name, m| - assert_match /@products = Product\.find\(:all\)/, m, "#{name} should query products table" - end + def test_scaffold_generates_resources_with_attributes + run_generator('scaffold', %w(Product name:string supplier_id:integer created_at:timestamp)) - assert_has_method f, :show, :edit, :update, :destroy do |name, m| - assert_match /@product = Product\.find\(params\[:id\]\)/, m, "#{name.to_s} should query products table" - end + assert_generated_controller_for :products do |f| - assert_has_method f, :new do |name, m| - assert_match /@product = Product\.new/, m, "#{name.to_s} should instantiate a product" - end + assert_has_method f, :index do |name, m| + assert_match /@products = Product\.find\(:all\)/, m, "#{name} should query products table" + end - assert_has_method f, :create do |name, m| - assert_match /@product = Product\.new\(params\[:product\]\)/, m, "#{name.to_s} should instantiate a product" - assert_match /format.xml \{ render :xml => @product.errors, :status => :unprocessable_entity \}/, m, "#{name.to_s} should set status to :unprocessable_entity code for xml" - end + assert_has_method f, :show, :edit, :update, :destroy do |name, m| + assert_match /@product = Product\.find\(params\[:id\]\)/, m, "#{name.to_s} should query products table" + end + assert_has_method f, :new do |name, m| + assert_match /@product = Product\.new/, m, "#{name.to_s} should instantiate a product" end - assert_generated_model_for :product - assert_generated_functional_test_for :products - assert_generated_unit_test_for :product - assert_generated_fixtures_for :products - assert_generated_helper_for :products - assert_generated_stylesheet :scaffold - assert_generated_views_for :products, "index.html.erb", "new.html.erb", "edit.html.erb", "show.html.erb" - - assert_generated_migration :create_products do |t| - assert_generated_column t, :name, :string - assert_generated_column t, :supplier_id, :integer - assert_generated_column t, :created_at, :timestamp + assert_has_method f, :create do |name, m| + assert_match /@product = Product\.new\(params\[:product\]\)/, m, "#{name.to_s} should instantiate a product" + assert_match /format.xml \{ render :xml => @product.errors, :status => :unprocessable_entity \}/, m, "#{name.to_s} should set status to :unprocessable_entity code for xml" end - assert_added_route_for :products end + assert_generated_model_for :product + assert_generated_functional_test_for :products + assert_generated_unit_test_for :product + assert_generated_fixtures_for :products + assert_generated_helper_for :products + assert_generated_stylesheet :scaffold + assert_generated_views_for :products, "index.html.erb", "new.html.erb", "edit.html.erb", "show.html.erb" + + assert_generated_migration :create_products do |t| + assert_generated_column t, :name, :string + assert_generated_column t, :supplier_id, :integer + assert_generated_column t, :created_at, :timestamp + end + + assert_added_route_for :products end -end \ No newline at end of file + +end From 36eecda8d0b5ebd3341692868b8faeec8fbce9d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 18 Apr 2008 17:13:15 -0500 Subject: [PATCH 06/48] Changed mailer generator to not use instance variables. Signed-off-by: Joshua Peek --- .../generators/components/mailer/templates/mailer.rb | 12 ++++++------ .../test/generators/rails_mailer_generator_test.rb | 12 ++++++------ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/railties/lib/rails_generator/generators/components/mailer/templates/mailer.rb b/railties/lib/rails_generator/generators/components/mailer/templates/mailer.rb index 127495fcbbe02..3a1724a62eead 100644 --- a/railties/lib/rails_generator/generators/components/mailer/templates/mailer.rb +++ b/railties/lib/rails_generator/generators/components/mailer/templates/mailer.rb @@ -2,12 +2,12 @@ class <%= class_name %> < ActionMailer::Base <% for action in actions -%> def <%= action %>(sent_at = Time.now) - @subject = '<%= class_name %>#<%= action %>' - @body = {} - @recipients = '' - @from = '' - @sent_on = sent_at - @headers = {} + subject '<%= class_name %>#<%= action %>' + recipients '' + from '' + sent_on sent_at + + body :action => '<%= action %>' end <% end -%> end diff --git a/railties/test/generators/rails_mailer_generator_test.rb b/railties/test/generators/rails_mailer_generator_test.rb index 9b5debbdb1a18..3cf8cda442873 100644 --- a/railties/test/generators/rails_mailer_generator_test.rb +++ b/railties/test/generators/rails_mailer_generator_test.rb @@ -8,12 +8,12 @@ def test_generates_mailer assert_generated_model_for :notifier, 'ActionMailer::Base' do |model| assert_has_method model, :reset_password do |name, body| assert_equal [ - "@subject = 'Notifier#reset_password'", - "@body = {}", - "@recipients = ''", - "@from = ''", - "@sent_on = sent_at", - "@headers = {}" + "subject 'Notifier#reset_password'", + "recipients ''", + "from ''", + "sent_on sent_at", + "", + "body :action => 'reset_password'" ], body.split("\n").map{|line| line.sub(' '*4, '') } end From 69a5c1df8293fc8de2cec0fc9fa18181cb9ad469 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 18 Apr 2008 17:19:28 -0500 Subject: [PATCH 07/48] Add example for default_url_options[:host] to generated mailers. Signed-off-by: Joshua Peek --- .../generators/components/mailer/templates/mailer.rb | 6 +++++- railties/test/generators/rails_mailer_generator_test.rb | 5 ++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/railties/lib/rails_generator/generators/components/mailer/templates/mailer.rb b/railties/lib/rails_generator/generators/components/mailer/templates/mailer.rb index 3a1724a62eead..0c7e6bebafd06 100644 --- a/railties/lib/rails_generator/generators/components/mailer/templates/mailer.rb +++ b/railties/lib/rails_generator/generators/components/mailer/templates/mailer.rb @@ -1,4 +1,7 @@ class <%= class_name %> < ActionMailer::Base + + # change to your domain name + default_url_options[:host] = 'example.com' <% for action in actions -%> def <%= action %>(sent_at = Time.now) @@ -7,7 +10,8 @@ def <%= action %>(sent_at = Time.now) from '' sent_on sent_at - body :action => '<%= action %>' + body :greeting => 'Hi,' end <% end -%> + end diff --git a/railties/test/generators/rails_mailer_generator_test.rb b/railties/test/generators/rails_mailer_generator_test.rb index 3cf8cda442873..03170c3b618f8 100644 --- a/railties/test/generators/rails_mailer_generator_test.rb +++ b/railties/test/generators/rails_mailer_generator_test.rb @@ -13,10 +13,13 @@ def test_generates_mailer "from ''", "sent_on sent_at", "", - "body :action => 'reset_password'" + "body :greeting => 'Hi,'" ], body.split("\n").map{|line| line.sub(' '*4, '') } end + + assert_match /^ default_url_options\[:host\] = 'example.com'$/m, model, + 'model should include default_url_options :host declaration' end assert_generated_views_for :notifier, 'reset_password.erb' From 534c6b2444970d59aea654aa3c6aeb41c206d14d Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Sat, 19 Apr 2008 16:16:32 +0100 Subject: [PATCH 08/48] Introduce ActionView::InlineTemplate class --- actionpack/CHANGELOG | 2 ++ actionpack/lib/action_controller/base.rb | 2 +- actionpack/lib/action_view.rb | 1 + actionpack/lib/action_view/base.rb | 2 +- actionpack/lib/action_view/inline_template.rb | 20 +++++++++++++++++ actionpack/lib/action_view/template.rb | 22 ++++++++----------- .../test/controller/custom_handler_test.rb | 6 ++--- 7 files changed, 37 insertions(+), 18 deletions(-) create mode 100644 actionpack/lib/action_view/inline_template.rb diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG index 1e53a3966719c..e8cef9eb71b4a 100644 --- a/actionpack/CHANGELOG +++ b/actionpack/CHANGELOG @@ -1,5 +1,7 @@ *SVN* +* Introduce ActionView::InlineTemplate class. [Pratik] + * Automatically parse posted JSON content for Mime::JSON requests. [rick] POST /posts diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb index 63ad4d042a2fa..f620c442fdb76 100755 --- a/actionpack/lib/action_controller/base.rb +++ b/actionpack/lib/action_controller/base.rb @@ -870,7 +870,7 @@ def render(options = nil, extra_options = {}, &block) #:doc: elsif inline = options[:inline] add_variables_to_assigns - tmpl = ActionView::Template.new(@template, options[:inline], false, options[:locals], true, options[:type]) + tmpl = ActionView::InlineTemplate.new(@template, options[:inline], options[:locals], options[:type]) render_for_text(@template.render_template(tmpl), options[:status]) elsif action_name = options[:action] diff --git a/actionpack/lib/action_view.rb b/actionpack/lib/action_view.rb index e20812d308a7f..f9de5c1307fcd 100644 --- a/actionpack/lib/action_view.rb +++ b/actionpack/lib/action_view.rb @@ -30,6 +30,7 @@ require 'action_view/template_finder' require 'action_view/template' require 'action_view/partial_template' +require 'action_view/inline_template' require 'action_view/base' require 'action_view/partials' diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb index e83c8b6bd34b0..f001b81ecae98 100644 --- a/actionpack/lib/action_view/base.rb +++ b/actionpack/lib/action_view/base.rb @@ -279,7 +279,7 @@ def render(options = {}, local_assigns = {}, &block) #:nodoc: elsif options[:partial] render_partial(options[:partial], ActionView::Base::ObjectWrapper.new(options[:object]), options[:locals]) elsif options[:inline] - template = Template.new(self, options[:inline], false, options[:locals], true, options[:type]) + template = InlineTemplate.new(self, options[:inline], options[:locals], options[:type]) render_template(template) end end diff --git a/actionpack/lib/action_view/inline_template.rb b/actionpack/lib/action_view/inline_template.rb new file mode 100644 index 0000000000000..87c012d18168c --- /dev/null +++ b/actionpack/lib/action_view/inline_template.rb @@ -0,0 +1,20 @@ +module ActionView #:nodoc: + class InlineTemplate < Template #:nodoc: + + def initialize(view, source, locals = {}, type = nil) + @view = view + @finder = @view.finder + + @source = source + @extension = type + @locals = locals || {} + + @handler = self.class.handler_class_for_extension(@extension).new(@view) + end + + def method_key + @source + end + + end +end diff --git a/actionpack/lib/action_view/template.rb b/actionpack/lib/action_view/template.rb index 0cd6784fd8cba..985aa090e5440 100644 --- a/actionpack/lib/action_view/template.rb +++ b/actionpack/lib/action_view/template.rb @@ -2,22 +2,18 @@ module ActionView #:nodoc: class Template #:nodoc: attr_accessor :locals - attr_reader :handler, :path, :source, :extension, :filename, :path_without_extension, :method + attr_reader :handler, :path, :extension, :filename, :path_without_extension, :method - def initialize(view, path_or_source, use_full_path, locals = {}, inline = false, inline_type = nil) + def initialize(view, path, use_full_path, locals = {}) @view = view @finder = @view.finder - unless inline - # Clear the forward slash at the beginning if exists - @path = use_full_path ? path_or_source.sub(/^\//, '') : path_or_source - @view.first_render ||= @path - @source = nil # Don't read the source until we know that it is required - set_extension_and_file_name(use_full_path) - else - @source = path_or_source - @extension = inline_type - end + # Clear the forward slash at the beginning if exists + @path = use_full_path ? path.sub(/^\//, '') : path + @view.first_render ||= @path + @source = nil # Don't read the source until we know that it is required + set_extension_and_file_name(use_full_path) + @locals = locals || {} @handler = self.class.handler_class_for_extension(@extension).new(@view) end @@ -32,7 +28,7 @@ def source end def method_key - @method_key ||= (@filename || @source) + @filename end def base_path_for_exception diff --git a/actionpack/test/controller/custom_handler_test.rb b/actionpack/test/controller/custom_handler_test.rb index cf1e2361bdb9f..ac484ae17eee8 100644 --- a/actionpack/test/controller/custom_handler_test.rb +++ b/actionpack/test/controller/custom_handler_test.rb @@ -20,7 +20,7 @@ def setup end def test_custom_render - template = ActionView::Template.new(@view, "hello <%= one %>", false, { :one => "two" }, true, "foo") + template = ActionView::InlineTemplate.new(@view, "hello <%= one %>", { :one => "two" }, "foo") result = @view.render_template(template) assert_equal( @@ -29,7 +29,7 @@ def test_custom_render end def test_custom_render2 - template = ActionView::Template.new(@view, "hello <%= one %>", false, { :one => "two" }, true, "foo2") + template = ActionView::InlineTemplate.new(@view, "hello <%= one %>", { :one => "two" }, "foo2") result = @view.render_template(template) assert_equal( [ "hello <%= one %>", { :one => "two" }, @view ], @@ -38,7 +38,7 @@ def test_custom_render2 def test_unhandled_extension # uses the ERb handler by default if the extension isn't recognized - template = ActionView::Template.new(@view, "hello <%= one %>", false, { :one => "two" }, true, "bar") + template = ActionView::InlineTemplate.new(@view, "hello <%= one %>", { :one => "two" }, "bar") result = @view.render_template(template) assert_equal "hello two", result end From ef4c65088fb907fc819e6b5d83d284c38cdaabfc Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Sat, 19 Apr 2008 18:52:14 +0100 Subject: [PATCH 09/48] Move missing template logic to ActionView --- actionpack/CHANGELOG | 2 ++ actionpack/lib/action_controller/base.rb | 13 ------------- actionpack/lib/action_controller/layout.rb | 4 +--- actionpack/lib/action_controller/rescue.rb | 2 +- actionpack/lib/action_view/base.rb | 3 +++ actionpack/lib/action_view/template.rb | 16 ++++++++++------ actionpack/test/controller/cookie_test.rb | 2 +- actionpack/test/controller/flash_test.rb | 2 +- actionpack/test/controller/layout_test.rb | 2 +- actionpack/test/controller/mime_responds_test.rb | 2 +- actionpack/test/controller/new_render_test.rb | 4 ++-- actionpack/test/controller/rescue_test.rb | 2 +- actionpack/test/template/template_object_test.rb | 2 +- 13 files changed, 25 insertions(+), 31 deletions(-) diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG index e8cef9eb71b4a..4694c0e996f8c 100644 --- a/actionpack/CHANGELOG +++ b/actionpack/CHANGELOG @@ -1,5 +1,7 @@ *SVN* +* Move missing template logic to ActionView. [Pratik] + * Introduce ActionView::InlineTemplate class. [Pratik] * Automatically parse posted JSON content for Mime::JSON requests. [rick] diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb index f620c442fdb76..32df035871bbf 100755 --- a/actionpack/lib/action_controller/base.rb +++ b/actionpack/lib/action_controller/base.rb @@ -16,9 +16,6 @@ class ActionControllerError < StandardError #:nodoc: class SessionRestoreError < ActionControllerError #:nodoc: end - class MissingTemplate < ActionControllerError #:nodoc: - end - class RenderError < ActionControllerError #:nodoc: end @@ -1105,7 +1102,6 @@ def reset_session #:doc: private def render_for_file(template_path, status = nil, use_full_path = false, locals = {}) #:nodoc: add_variables_to_assigns - assert_existence_of_template_file(template_path) if use_full_path logger.info("Rendering #{template_path}" + (status ? " (#{status})" : '')) if logger render_for_text(@template.render_file(template_path, use_full_path, locals), status) end @@ -1267,15 +1263,6 @@ def template_exempt_from_layout?(template_name = default_template_name) @@exempt_from_layout.any? { |ext| name_with_extension =~ ext } end - def assert_existence_of_template_file(template_name) - unless template_exists?(template_name) || ignore_missing_templates - full_template_path = template_name.include?('.') ? template_name : "#{template_name}.#{@template.template_format}.erb" - display_paths = view_paths.join(':') - template_type = (template_name =~ /layouts/i) ? 'layout' : 'template' - raise(MissingTemplate, "Missing #{template_type} #{full_template_path} in view path #{display_paths}") - end - end - def default_template_name(action_name = self.action_name) if action_name action_name = action_name.to_s diff --git a/actionpack/lib/action_controller/layout.rb b/actionpack/lib/action_controller/layout.rb index 5484add3b5056..b5b59f2d7c2c6 100644 --- a/actionpack/lib/action_controller/layout.rb +++ b/actionpack/lib/action_controller/layout.rb @@ -244,9 +244,7 @@ def active_layout(passed_layout = nil) def render_with_a_layout(options = nil, extra_options = {}, &block) #:nodoc: template_with_options = options.is_a?(Hash) - if apply_layout?(template_with_options, options) && (layout = pick_layout(template_with_options, options)) - assert_existence_of_template_file(layout) - + if (layout = pick_layout(template_with_options, options)) && apply_layout?(template_with_options, options) options = options.merge :layout => false if template_with_options logger.info("Rendering template within #{layout}") if logger diff --git a/actionpack/lib/action_controller/rescue.rb b/actionpack/lib/action_controller/rescue.rb index f5ad04532bd93..d4d561bdb7e2c 100644 --- a/actionpack/lib/action_controller/rescue.rb +++ b/actionpack/lib/action_controller/rescue.rb @@ -26,7 +26,7 @@ module Rescue DEFAULT_RESCUE_TEMPLATE = 'diagnostics' DEFAULT_RESCUE_TEMPLATES = { - 'ActionController::MissingTemplate' => 'missing_template', + 'ActionView::MissingTemplate' => 'missing_template', 'ActionController::RoutingError' => 'routing_error', 'ActionController::UnknownAction' => 'unknown_action', 'ActionView::TemplateError' => 'template_error' diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb index f001b81ecae98..e57c447682191 100644 --- a/actionpack/lib/action_view/base.rb +++ b/actionpack/lib/action_view/base.rb @@ -1,6 +1,9 @@ module ActionView #:nodoc: class ActionViewError < StandardError #:nodoc: end + + class MissingTemplate < ActionViewError #:nodoc: + end # Action View templates can be written in three ways. If the template file has a +.erb+ (or +.rhtml+) extension then it uses a mixture of ERb # (included in Ruby) and HTML. If the template file has a +.builder+ (or +.rxml+) extension then Jim Weirich's Builder::XmlMarkup library is used. diff --git a/actionpack/lib/action_view/template.rb b/actionpack/lib/action_view/template.rb index 985aa090e5440..bc3d8d5e522a6 100644 --- a/actionpack/lib/action_view/template.rb +++ b/actionpack/lib/action_view/template.rb @@ -54,9 +54,8 @@ def set_extension_and_file_name(use_full_path) @filename = @finder.pick_template(@path_without_extension, @extension) else @extension = @finder.pick_template_extension(@path).to_s - unless @extension - raise ActionViewError, "No template found for #{@path} in #{@finder.view_paths.inspect}" - end + raise_missing_template_exception unless @extension + @filename = @finder.pick_template(@path, @extension) @extension = @extension.gsub(/^.+\./, '') # strip off any formats end @@ -64,9 +63,14 @@ def set_extension_and_file_name(use_full_path) @filename = @path end - if @filename.blank? - raise ActionViewError, "Couldn't find template file for #{@path} in #{@finder.view_paths.inspect}" - end + raise_missing_template_exception if @filename.blank? + end + + def raise_missing_template_exception + full_template_path = @path.include?('.') ? @path : "#{@path}.#{@view.template_format}.erb" + display_paths = @finder.view_paths.join(':') + template_type = (@path =~ /layouts/i) ? 'layout' : 'template' + raise(MissingTemplate, "Missing #{template_type} #{full_template_path} in view path #{display_paths}") end # Template Handlers diff --git a/actionpack/test/controller/cookie_test.rb b/actionpack/test/controller/cookie_test.rb index 0483fe918a43d..42f3bd26a48b9 100644 --- a/actionpack/test/controller/cookie_test.rb +++ b/actionpack/test/controller/cookie_test.rb @@ -37,7 +37,7 @@ def authenticate_with_http_only end def rescue_action(e) - raise unless ActionController::MissingTemplate # No templates here, and we don't care about the output + raise unless ActionView::MissingTemplate # No templates here, and we don't care about the output end end diff --git a/actionpack/test/controller/flash_test.rb b/actionpack/test/controller/flash_test.rb index f672f2f427b49..e562531bf37ae 100644 --- a/actionpack/test/controller/flash_test.rb +++ b/actionpack/test/controller/flash_test.rb @@ -52,7 +52,7 @@ def use_flash_after_reset_session end def rescue_action(e) - raise unless ActionController::MissingTemplate === e + raise unless ActionView::MissingTemplate === e end # methods for test_sweep_after_halted_filter_chain diff --git a/actionpack/test/controller/layout_test.rb b/actionpack/test/controller/layout_test.rb index 145543a35743c..3dc311b78add8 100644 --- a/actionpack/test/controller/layout_test.rb +++ b/actionpack/test/controller/layout_test.rb @@ -216,7 +216,7 @@ def test_exception_raised_when_layout_file_not_found @controller = SetsNonExistentLayoutFile.new get :hello @response.template.class.module_eval { attr_accessor :exception } - assert_equal ActionController::MissingTemplate, @response.template.exception.class + assert_equal ActionView::MissingTemplate, @response.template.exception.class end end diff --git a/actionpack/test/controller/mime_responds_test.rb b/actionpack/test/controller/mime_responds_test.rb index c34643ddd5455..c617cb2e847ba 100644 --- a/actionpack/test/controller/mime_responds_test.rb +++ b/actionpack/test/controller/mime_responds_test.rb @@ -468,7 +468,7 @@ def test_format_with_custom_response_type_and_request_headers_with_only_one_layo assert_equal '
Hello future from Firefox!
', @response.body @request.env["HTTP_ACCEPT"] = "text/iphone" - assert_raises(ActionController::MissingTemplate) { get :iphone_with_html_response_type_without_layout } + assert_raises(ActionView::MissingTemplate) { get :iphone_with_html_response_type_without_layout } end end diff --git a/actionpack/test/controller/new_render_test.rb b/actionpack/test/controller/new_render_test.rb index 342e2e7f87d2e..80cf09e5f39e9 100644 --- a/actionpack/test/controller/new_render_test.rb +++ b/actionpack/test/controller/new_render_test.rb @@ -652,7 +652,7 @@ def test_render_to_string_partial end def test_bad_render_to_string_still_throws_exception - assert_raises(ActionController::MissingTemplate) { get :render_to_string_with_exception } + assert_raises(ActionView::MissingTemplate) { get :render_to_string_with_exception } end def test_render_to_string_that_throws_caught_exception_doesnt_break_assigns @@ -787,7 +787,7 @@ def test_partial_with_implicit_local_assignment end def test_render_missing_partial_template - assert_raises(ActionView::ActionViewError) do + assert_raises(ActionView::MissingTemplate) do get :missing_partial end end diff --git a/actionpack/test/controller/rescue_test.rb b/actionpack/test/controller/rescue_test.rb index 011992474f0f7..27fcc5e04cfbf 100644 --- a/actionpack/test/controller/rescue_test.rb +++ b/actionpack/test/controller/rescue_test.rb @@ -279,7 +279,7 @@ def test_rescue_templates assert_equal ActionController::Rescue::DEFAULT_RESCUE_TEMPLATE, templates.default assert_equal ActionController::Rescue::DEFAULT_RESCUE_TEMPLATE, templates[Exception.new] - assert_equal 'missing_template', templates[ActionController::MissingTemplate.name] + assert_equal 'missing_template', templates[ActionView::MissingTemplate.name] assert_equal 'routing_error', templates[ActionController::RoutingError.name] assert_equal 'unknown_action', templates[ActionController::UnknownAction.name] assert_equal 'template_error', templates[ActionView::TemplateError.name] diff --git a/actionpack/test/template/template_object_test.rb b/actionpack/test/template/template_object_test.rb index b3a33938cf52e..7adcde421f521 100644 --- a/actionpack/test/template/template_object_test.rb +++ b/actionpack/test/template/template_object_test.rb @@ -82,7 +82,7 @@ def test_js def test_xml @view.template_format = :xml - assert_raise ActionView::ActionViewError do + assert_raise ActionView::MissingTemplate do ActionView::PartialTemplate.new(@view, @path, nil) end end From 17d4164a16e5fe7b252375211424a2999a331291 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Sat, 19 Apr 2008 13:06:57 -0500 Subject: [PATCH 10/48] Introduce ActionView::TestCase for testing view helpers. --- actionpack/lib/action_view.rb | 6 +- actionpack/lib/action_view/base.rb | 10 +-- actionpack/lib/action_view/test_case.rb | 64 +++++++++++++++++++ actionpack/test/abstract_unit.rb | 1 + .../template/active_record_helper_test.rb | 9 +-- .../test/template/asset_tag_helper_test.rb | 12 ++-- .../test/template/benchmark_helper_test.rb | 4 +- actionpack/test/template/date_helper_test.rb | 5 +- actionpack/test/template/form_helper_test.rb | 11 +--- .../test/template/form_options_helper_test.rb | 5 +- .../test/template/form_tag_helper_test.rb | 8 +-- .../test/template/javascript_helper_test.rb | 10 +-- .../test/template/number_helper_test.rb | 4 +- .../test/template/prototype_helper_test.rb | 56 ++++++---------- .../test/template/record_tag_helper_test.rb | 11 +--- .../test/template/sanitize_helper_test.rb | 5 +- .../template/scriptaculous_helper_test.rb | 14 +--- actionpack/test/template/tag_helper_test.rb | 7 +- actionpack/test/template/test_test.rb | 56 ++++++++++++++++ actionpack/test/template/text_helper_test.rb | 5 +- actionpack/test/template/url_helper_test.rb | 18 +++--- 21 files changed, 190 insertions(+), 131 deletions(-) create mode 100644 actionpack/lib/action_view/test_case.rb create mode 100644 actionpack/test/template/test_test.rb diff --git a/actionpack/lib/action_view.rb b/actionpack/lib/action_view.rb index f9de5c1307fcd..609334d52d1f4 100644 --- a/actionpack/lib/action_view.rb +++ b/actionpack/lib/action_view.rb @@ -38,6 +38,8 @@ ActionView::Base.class_eval do include ActionView::Partials -end -ActionView::Base.load_helpers + ActionView::Base.helper_modules.each do |helper_module| + include helper_module + end +end diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb index e57c447682191..12dd7d2bc91a9 100644 --- a/actionpack/lib/action_view/base.rb +++ b/actionpack/lib/action_view/base.rb @@ -205,15 +205,17 @@ module CompiledTemplates #:nodoc: class ObjectWrapper < Struct.new(:value) #:nodoc: end - def self.load_helpers #:nodoc: - Dir.entries("#{File.dirname(__FILE__)}/helpers").sort.each do |file| + def self.helper_modules #:nodoc: + helpers = [] + Dir.entries(File.expand_path("#{File.dirname(__FILE__)}/helpers")).sort.each do |file| next unless file =~ /^([a-z][a-z_]*_helper).rb$/ require "action_view/helpers/#{$1}" helper_module_name = $1.camelize if Helpers.const_defined?(helper_module_name) - include Helpers.const_get(helper_module_name) + helpers << Helpers.const_get(helper_module_name) end end + return helpers end def initialize(view_paths = [], assigns_for_first_render = {}, controller = nil)#:nodoc: @@ -323,7 +325,7 @@ def template_format end end - private + private def wrap_content_for_layout(content) original_content_for_layout = @content_for_layout @content_for_layout = content diff --git a/actionpack/lib/action_view/test_case.rb b/actionpack/lib/action_view/test_case.rb new file mode 100644 index 0000000000000..b2e6589d81e38 --- /dev/null +++ b/actionpack/lib/action_view/test_case.rb @@ -0,0 +1,64 @@ +require 'active_support/test_case' + +module ActionView + class NonInferrableHelperError < ActionViewError + def initialize(name) + super "Unable to determine the helper to test from #{name}. " + + "You'll need to specify it using tests YourHelper in your " + + "test case definition" + end + end + + class TestCase < ActiveSupport::TestCase + class_inheritable_accessor :helper_class + @@helper_class = nil + + class << self + def tests(helper_class) + self.helper_class = helper_class + end + + def helper_class + if current_helper_class = read_inheritable_attribute(:helper_class) + current_helper_class + else + self.helper_class = determine_default_helper_class(name) + end + end + + def determine_default_helper_class(name) + name.sub(/Test$/, '').constantize + rescue NameError + raise NonInferrableHelperError.new(name) + end + end + + ActionView::Base.helper_modules.each do |helper_module| + include helper_module + end + include ActionController::PolymorphicRoutes + include ActionController::RecordIdentifier + + setup :setup_with_helper_class + + def setup_with_helper_class + self.class.send(:include, helper_class) + end + + class TestController < ActionController::Base + attr_accessor :request, :response + + def initialize + @request = ActionController::TestRequest.new + @response = ActionController::TestResponse.new + end + end + + private + def method_missing(selector, *args) + controller = TestController.new + return controller.send!(selector, *args) if ActionController::Routing::Routes.named_routes.helpers.include?(selector) + super + end + end +end diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb index 700bc1f5e3623..d90f299b8ae5a 100644 --- a/actionpack/test/abstract_unit.rb +++ b/actionpack/test/abstract_unit.rb @@ -8,6 +8,7 @@ require 'action_controller' require 'action_controller/cgi_ext' require 'action_controller/test_process' +require 'action_view/test_case' begin require 'ruby-debug' diff --git a/actionpack/test/template/active_record_helper_test.rb b/actionpack/test/template/active_record_helper_test.rb index 31fe7bbc29023..dfc30e651a523 100644 --- a/actionpack/test/template/active_record_helper_test.rb +++ b/actionpack/test/template/active_record_helper_test.rb @@ -1,12 +1,7 @@ require 'abstract_unit' -class ActiveRecordHelperTest < Test::Unit::TestCase - include ActionView::Helpers::FormHelper - include ActionView::Helpers::ActiveRecordHelper - include ActionView::Helpers::TextHelper - include ActionView::Helpers::TagHelper - include ActionView::Helpers::UrlHelper - include ActionView::Helpers::FormTagHelper +class ActiveRecordHelperTest < ActionView::TestCase + tests ActionView::Helpers::ActiveRecordHelper silence_warnings do Post = Struct.new("Post", :title, :author_name, :body, :secret, :written_on) diff --git a/actionpack/test/template/asset_tag_helper_test.rb b/actionpack/test/template/asset_tag_helper_test.rb index ffb8856a5947c..4a8117a88a79e 100644 --- a/actionpack/test/template/asset_tag_helper_test.rb +++ b/actionpack/test/template/asset_tag_helper_test.rb @@ -1,9 +1,7 @@ require 'abstract_unit' -class AssetTagHelperTest < Test::Unit::TestCase - include ActionView::Helpers::TagHelper - include ActionView::Helpers::UrlHelper - include ActionView::Helpers::AssetTagHelper +class AssetTagHelperTest < ActionView::TestCase + tests ActionView::Helpers::AssetTagHelper def setup silence_warnings do @@ -445,10 +443,8 @@ def test_caching_stylesheet_include_tag_when_caching_off end end -class AssetTagHelperNonVhostTest < Test::Unit::TestCase - include ActionView::Helpers::TagHelper - include ActionView::Helpers::UrlHelper - include ActionView::Helpers::AssetTagHelper +class AssetTagHelperNonVhostTest < ActionView::TestCase + tests ActionView::Helpers::AssetTagHelper def setup @controller = Class.new do diff --git a/actionpack/test/template/benchmark_helper_test.rb b/actionpack/test/template/benchmark_helper_test.rb index 76c0780482f45..d95a3dee2655f 100644 --- a/actionpack/test/template/benchmark_helper_test.rb +++ b/actionpack/test/template/benchmark_helper_test.rb @@ -1,8 +1,8 @@ require 'abstract_unit' require 'action_view/helpers/benchmark_helper' -class BenchmarkHelperTest < Test::Unit::TestCase - include ActionView::Helpers::BenchmarkHelper +class BenchmarkHelperTest < ActionView::TestCase + tests ActionView::Helpers::BenchmarkHelper class MockLogger attr_reader :logged diff --git a/actionpack/test/template/date_helper_test.rb b/actionpack/test/template/date_helper_test.rb index 25b1f9f002848..9bd433e76b79d 100755 --- a/actionpack/test/template/date_helper_test.rb +++ b/actionpack/test/template/date_helper_test.rb @@ -1,8 +1,7 @@ require 'abstract_unit' -class DateHelperTest < Test::Unit::TestCase - include ActionView::Helpers::DateHelper - include ActionView::Helpers::FormHelper +class DateHelperTest < ActionView::TestCase + tests ActionView::Helpers::DateHelper silence_warnings do Post = Struct.new("Post", :id, :written_on, :updated_at) diff --git a/actionpack/test/template/form_helper_test.rb b/actionpack/test/template/form_helper_test.rb index 766e88375b014..c48d5dfd2d12a 100644 --- a/actionpack/test/template/form_helper_test.rb +++ b/actionpack/test/template/form_helper_test.rb @@ -30,15 +30,8 @@ def name class Comment::Nested < Comment; end -class FormHelperTest < Test::Unit::TestCase - include ActionView::Helpers::FormHelper - include ActionView::Helpers::FormTagHelper - include ActionView::Helpers::UrlHelper - include ActionView::Helpers::TagHelper - include ActionView::Helpers::TextHelper - include ActionView::Helpers::ActiveRecordHelper - include ActionView::Helpers::RecordIdentificationHelper - include ActionController::PolymorphicRoutes +class FormHelperTest < ActionView::TestCase + tests ActionView::Helpers::FormHelper def setup @post = Post.new diff --git a/actionpack/test/template/form_options_helper_test.rb b/actionpack/test/template/form_options_helper_test.rb index f3ecc18233313..48a26deea91e1 100644 --- a/actionpack/test/template/form_options_helper_test.rb +++ b/actionpack/test/template/form_options_helper_test.rb @@ -22,9 +22,8 @@ def to_s ActionView::Helpers::FormOptionsHelper::TimeZone = MockTimeZone -class FormOptionsHelperTest < Test::Unit::TestCase - include ActionView::Helpers::FormHelper - include ActionView::Helpers::FormOptionsHelper +class FormOptionsHelperTest < ActionView::TestCase + tests ActionView::Helpers::FormOptionsHelper silence_warnings do Post = Struct.new('Post', :title, :author_name, :body, :secret, :written_on, :category, :origin) diff --git a/actionpack/test/template/form_tag_helper_test.rb b/actionpack/test/template/form_tag_helper_test.rb index 7caa85802a7f8..73a8bd4d87d69 100644 --- a/actionpack/test/template/form_tag_helper_test.rb +++ b/actionpack/test/template/form_tag_helper_test.rb @@ -1,11 +1,7 @@ require 'abstract_unit' -class FormTagHelperTest < Test::Unit::TestCase - include ActionView::Helpers::UrlHelper - include ActionView::Helpers::TagHelper - include ActionView::Helpers::FormTagHelper - include ActionView::Helpers::TextHelper - include ActionView::Helpers::CaptureHelper +class FormTagHelperTest < ActionView::TestCase + tests ActionView::Helpers::FormTagHelper def setup @controller = Class.new do diff --git a/actionpack/test/template/javascript_helper_test.rb b/actionpack/test/template/javascript_helper_test.rb index 581ca58f897d7..f18adb990c92e 100644 --- a/actionpack/test/template/javascript_helper_test.rb +++ b/actionpack/test/template/javascript_helper_test.rb @@ -1,13 +1,7 @@ require 'abstract_unit' -class JavaScriptHelperTest < Test::Unit::TestCase - include ActionView::Helpers::JavaScriptHelper - - include ActionView::Helpers::UrlHelper - include ActionView::Helpers::TagHelper - include ActionView::Helpers::TextHelper - include ActionView::Helpers::FormHelper - include ActionView::Helpers::CaptureHelper +class JavaScriptHelperTest < ActionView::TestCase + tests ActionView::Helpers::JavaScriptHelper def test_define_javascript_functions # check if prototype.js is included first diff --git a/actionpack/test/template/number_helper_test.rb b/actionpack/test/template/number_helper_test.rb index 7065ca7a8410f..4a8d09b544e1c 100644 --- a/actionpack/test/template/number_helper_test.rb +++ b/actionpack/test/template/number_helper_test.rb @@ -1,7 +1,7 @@ require 'abstract_unit' -class NumberHelperTest < Test::Unit::TestCase - include ActionView::Helpers::NumberHelper +class NumberHelperTest < ActionView::TestCase + tests ActionView::Helpers::NumberHelper def test_number_to_phone assert_equal("800-555-1212", number_to_phone(8005551212)) diff --git a/actionpack/test/template/prototype_helper_test.rb b/actionpack/test/template/prototype_helper_test.rb index 28e58b0a08537..a84d4e72af082 100644 --- a/actionpack/test/template/prototype_helper_test.rb +++ b/actionpack/test/template/prototype_helper_test.rb @@ -24,24 +24,11 @@ def name class Author::Nested < Author; end -module BaseTest - def self.included(base) - base.send :attr_accessor, :template_format - end +class PrototypeHelperBaseTest < ActionView::TestCase + tests ActionView::Helpers::PrototypeHelper + + attr_accessor :template_format - include ActionView::Helpers::JavaScriptHelper - include ActionView::Helpers::PrototypeHelper - include ActionView::Helpers::ScriptaculousHelper - - include ActionView::Helpers::UrlHelper - include ActionView::Helpers::TagHelper - include ActionView::Helpers::TextHelper - include ActionView::Helpers::FormTagHelper - include ActionView::Helpers::FormHelper - include ActionView::Helpers::CaptureHelper - include ActionView::Helpers::RecordIdentificationHelper - include ActionController::PolymorphicRoutes - def setup @template = nil @controller = Class.new do @@ -59,25 +46,22 @@ def url_for(options) end.new end -protected - - def request_forgery_protection_token - nil - end - - def protect_against_forgery? - false - end - - def create_generator - block = Proc.new { |*args| yield *args if block_given? } - JavaScriptGenerator.new self, &block - end + protected + def request_forgery_protection_token + nil + end + + def protect_against_forgery? + false + end + + def create_generator + block = Proc.new { |*args| yield *args if block_given? } + JavaScriptGenerator.new self, &block + end end -class PrototypeHelperTest < Test::Unit::TestCase - include BaseTest - +class PrototypeHelperTest < PrototypeHelperBaseTest def setup @record = @author = Author.new @article = Article.new @@ -294,9 +278,7 @@ def author_article_path(author, article) end end -class JavaScriptGeneratorTest < Test::Unit::TestCase - include BaseTest - +class JavaScriptGeneratorTest < PrototypeHelperBaseTest def setup super @generator = create_generator diff --git a/actionpack/test/template/record_tag_helper_test.rb b/actionpack/test/template/record_tag_helper_test.rb index bb5440be20912..0afbb54f57a30 100644 --- a/actionpack/test/template/record_tag_helper_test.rb +++ b/actionpack/test/template/record_tag_helper_test.rb @@ -9,14 +9,9 @@ def body end end -class RecordTagHelperTest < Test::Unit::TestCase - include ActionView::Helpers::RecordTagHelper - include ActionView::Helpers::CaptureHelper - include ActionView::Helpers::RecordIdentificationHelper - include ActionView::Helpers::TagHelper - include ActionView::Helpers::TextHelper - include ActionView::Helpers::UrlHelper - +class RecordTagHelperTest < ActionView::TestCase + tests ActionView::Helpers::RecordTagHelper + def setup @post = Post.new end diff --git a/actionpack/test/template/sanitize_helper_test.rb b/actionpack/test/template/sanitize_helper_test.rb index a840c8b4cbfef..e5427d9dc1cc2 100644 --- a/actionpack/test/template/sanitize_helper_test.rb +++ b/actionpack/test/template/sanitize_helper_test.rb @@ -3,9 +3,8 @@ # The exhaustive tests are in test/controller/html/sanitizer_test.rb. # This tests the that the helpers hook up correctly to the sanitizer classes. -class SanitizeHelperTest < Test::Unit::TestCase - include ActionView::Helpers::SanitizeHelper - include ActionView::Helpers::TagHelper +class SanitizeHelperTest < ActionView::TestCase + tests ActionView::Helpers::SanitizeHelper include TestingSandbox def test_strip_links diff --git a/actionpack/test/template/scriptaculous_helper_test.rb b/actionpack/test/template/scriptaculous_helper_test.rb index 91856ff980508..690a7751b50fa 100644 --- a/actionpack/test/template/scriptaculous_helper_test.rb +++ b/actionpack/test/template/scriptaculous_helper_test.rb @@ -1,16 +1,8 @@ require 'abstract_unit' -class ScriptaculousHelperTest < Test::Unit::TestCase - include ActionView::Helpers::JavaScriptHelper - include ActionView::Helpers::PrototypeHelper - include ActionView::Helpers::ScriptaculousHelper - - include ActionView::Helpers::UrlHelper - include ActionView::Helpers::TagHelper - include ActionView::Helpers::TextHelper - include ActionView::Helpers::FormHelper - include ActionView::Helpers::CaptureHelper - +class ScriptaculousHelperTest < ActionView::TestCase + tests ActionView::Helpers::ScriptaculousHelper + def setup @controller = Class.new do def url_for(options) diff --git a/actionpack/test/template/tag_helper_test.rb b/actionpack/test/template/tag_helper_test.rb index 4b73289060cec..4da6116095324 100644 --- a/actionpack/test/template/tag_helper_test.rb +++ b/actionpack/test/template/tag_helper_test.rb @@ -1,10 +1,7 @@ require 'abstract_unit' -class TagHelperTest < Test::Unit::TestCase - include ActionView::Helpers::TagHelper - include ActionView::Helpers::UrlHelper - include ActionView::Helpers::TextHelper - include ActionView::Helpers::CaptureHelper +class TagHelperTest < ActionView::TestCase + tests ActionView::Helpers::TagHelper def test_tag assert_equal "
", tag("br") diff --git a/actionpack/test/template/test_test.rb b/actionpack/test/template/test_test.rb new file mode 100644 index 0000000000000..660f51b3be2fb --- /dev/null +++ b/actionpack/test/template/test_test.rb @@ -0,0 +1,56 @@ +require 'abstract_unit' + +module PeopleHelper + def title(text) + content_tag(:h1, text) + end + + def homepage_path + people_path + end + + def homepage_url + people_url + end + + def link_to_person(person) + link_to person.name, person + end +end + +class PeopleHelperTest < ActionView::TestCase + def setup + ActionController::Routing::Routes.draw do |map| + map.people 'people', :controller => 'people', :action => 'index' + map.connect ':controller/:action/:id' + end + end + + def test_title + assert_equal "

Ruby on Rails

", title("Ruby on Rails") + end + + def test_homepage_path + assert_equal "/people", homepage_path + end + + def test_homepage_url + assert_equal "http://test.host/people", homepage_url + end + + uses_mocha "link_to_person" do + def test_link_to_person + person = mock(:name => "David") + expects(:mocha_mock_path).with(person).returns("/people/1") + assert_equal 'David', link_to_person(person) + end + end +end + +class CrazyHelperTest < ActionView::TestCase + tests PeopleHelper + + def test_helper_class_can_be_set_manually_not_just_inferred + assert_equal PeopleHelper, self.class.helper_class + end +end diff --git a/actionpack/test/template/text_helper_test.rb b/actionpack/test/template/text_helper_test.rb index 7d92bce4bd27f..25ecda687fae5 100644 --- a/actionpack/test/template/text_helper_test.rb +++ b/actionpack/test/template/text_helper_test.rb @@ -1,9 +1,8 @@ require 'abstract_unit' require 'testing_sandbox' -class TextHelperTest < Test::Unit::TestCase - include ActionView::Helpers::TextHelper - include ActionView::Helpers::TagHelper +class TextHelperTest < ActionView::TestCase + tests ActionView::Helpers::TextHelper include TestingSandbox def setup diff --git a/actionpack/test/template/url_helper_test.rb b/actionpack/test/template/url_helper_test.rb index 9cd3b6e2f9b03..d45ea08a6fc75 100644 --- a/actionpack/test/template/url_helper_test.rb +++ b/actionpack/test/template/url_helper_test.rb @@ -2,10 +2,8 @@ RequestMock = Struct.new("Request", :request_uri, :protocol, :host_with_port, :env) -class UrlHelperTest < Test::Unit::TestCase - include ActionView::Helpers::AssetTagHelper - include ActionView::Helpers::UrlHelper - include ActionView::Helpers::TagHelper +class UrlHelperTest < ActionView::TestCase + tests ActionView::Helpers::UrlHelper def setup @controller = Class.new do @@ -293,7 +291,7 @@ def protect_against_forgery? end end -class UrlHelperWithControllerTest < Test::Unit::TestCase +class UrlHelperWithControllerTest < ActionView::TestCase class UrlHelperController < ActionController::Base self.view_paths = [ "#{File.dirname(__FILE__)}/../fixtures/" ] @@ -310,7 +308,7 @@ def show_named_route def rescue_action(e) raise e end end - include ActionView::Helpers::UrlHelper + tests ActionView::Helpers::UrlHelper def setup @request = ActionController::TestRequest.new @@ -348,7 +346,7 @@ def with_url_helper_routing end end -class LinkToUnlessCurrentWithControllerTest < Test::Unit::TestCase +class LinkToUnlessCurrentWithControllerTest < ActionView::TestCase class TasksController < ActionController::Base self.view_paths = ["#{File.dirname(__FILE__)}/../fixtures/"] @@ -372,7 +370,7 @@ def render_default end end - include ActionView::Helpers::UrlHelper + tests ActionView::Helpers::UrlHelper def setup @request = ActionController::TestRequest.new @@ -440,7 +438,7 @@ def to_s end end -class PolymorphicControllerTest < Test::Unit::TestCase +class PolymorphicControllerTest < ActionView::TestCase class WorkshopsController < ActionController::Base self.view_paths = ["#{File.dirname(__FILE__)}/../fixtures/"] @@ -479,7 +477,7 @@ def show def rescue_action(e) raise e end end - include ActionView::Helpers::UrlHelper + tests ActionView::Helpers::UrlHelper def setup @request = ActionController::TestRequest.new From 3f8d3cd04ff0bd7cbf70c11d49a3dc009dfa98a0 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Sat, 19 Apr 2008 19:26:56 +0100 Subject: [PATCH 11/48] Remove unused ignore_missing_templates option --- actionpack/lib/action_controller/base.rb | 5 +---- actionpack/test/abstract_unit.rb | 1 - 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb index 32df035871bbf..c0f3122fbf7b8 100755 --- a/actionpack/lib/action_controller/base.rb +++ b/actionpack/lib/action_controller/base.rb @@ -327,9 +327,6 @@ class Base # Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers. cattr_accessor :logger - # Turn on +ignore_missing_templates+ if you want to unit test actions without making the associated templates. - cattr_accessor :ignore_missing_templates - # Controls the resource action separator @@resource_action_separator = "/" cattr_accessor :resource_action_separator @@ -1219,7 +1216,7 @@ def add_instance_variables_to_assigns end def add_class_variables_to_assigns - %w(view_paths logger ignore_missing_templates).each do |cvar| + %w(view_paths logger).each do |cvar| @assigns[cvar] = self.send(cvar) end end diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb index d90f299b8ae5a..fa1c3293b42fe 100644 --- a/actionpack/test/abstract_unit.rb +++ b/actionpack/test/abstract_unit.rb @@ -20,7 +20,6 @@ ActiveSupport::Deprecation.debug = true ActionController::Base.logger = nil -ActionController::Base.ignore_missing_templates = false ActionController::Routing::Routes.reload rescue nil From 14a40804a29a57ad05ca6bffbe1e5334089593a9 Mon Sep 17 00:00:00 2001 From: Paul Horsfall Date: Sat, 19 Apr 2008 16:19:47 -0500 Subject: [PATCH 12/48] Add conditional options to caches_page method [#25 state:resolved] Signed-off-by: Joshua Peek --- actionpack/CHANGELOG | 2 ++ actionpack/lib/action_controller/caching/pages.rb | 12 ++++++++++-- actionpack/test/controller/caching_test.rb | 9 ++++++++- 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG index 4694c0e996f8c..9c72fd945ac9e 100644 --- a/actionpack/CHANGELOG +++ b/actionpack/CHANGELOG @@ -1,5 +1,7 @@ *SVN* +* Add conditional options to caches_page method. [Paul Horsfall] + * Move missing template logic to ActionView. [Pratik] * Introduce ActionView::InlineTemplate class. [Pratik] diff --git a/actionpack/lib/action_controller/caching/pages.rb b/actionpack/lib/action_controller/caching/pages.rb index 755f1e4e0a4dc..7aa6ce154b929 100644 --- a/actionpack/lib/action_controller/caching/pages.rb +++ b/actionpack/lib/action_controller/caching/pages.rb @@ -78,10 +78,18 @@ def cache_page(content, path) # Caches the +actions+ using the page-caching approach that'll store the cache in a path within the page_cache_directory that # matches the triggering url. + # + # Usage: + # + # # cache the index action + # caches_page :index + # + # # cache the index action except for JSON requests + # caches_page :index, :if => Proc.new { |c| !c.request.format.json? } def caches_page(*actions) return unless perform_caching - actions = actions.map(&:to_s) - after_filter { |c| c.cache_page if actions.include?(c.action_name) } + options = actions.extract_options! + after_filter({:only => actions}.merge(options)) { |c| c.cache_page } end private diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb index 7bd64e2870984..ddc1c6838363e 100644 --- a/actionpack/test/controller/caching_test.rb +++ b/actionpack/test/controller/caching_test.rb @@ -8,7 +8,8 @@ ActionController::Base.cache_store = :file_store, FILE_STORE_PATH class PageCachingTestController < ActionController::Base - caches_page :ok, :no_content, :found, :not_found + caches_page :ok, :no_content, :if => Proc.new { |c| !c.request.format.json? } + caches_page :found, :not_found def ok head :ok @@ -127,6 +128,12 @@ def test_should_cache_ok_at_custom_path end end end + + def test_page_caching_conditional_options + @request.env['HTTP_ACCEPT'] = 'application/json' + get :ok + assert_page_not_cached :ok + end private def assert_page_cached(action, message = "#{action} should have been cached") From 715db1a7973dfc02466207a913bacc4702187dad Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sat, 19 Apr 2008 16:06:30 -0700 Subject: [PATCH 13/48] Feature check :force_encoding instead of RUBY_VERSION --- activesupport/lib/active_support/core_ext/string/access.rb | 2 +- activesupport/lib/active_support/core_ext/string/unicode.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/activesupport/lib/active_support/core_ext/string/access.rb b/activesupport/lib/active_support/core_ext/string/access.rb index 89999ff13696d..1a949c0b77960 100644 --- a/activesupport/lib/active_support/core_ext/string/access.rb +++ b/activesupport/lib/active_support/core_ext/string/access.rb @@ -1,7 +1,7 @@ module ActiveSupport #:nodoc: module CoreExtensions #:nodoc: module String #:nodoc: - if RUBY_VERSION < '1.9' + unless '1.9'.respond_to?(:force_encoding) # Makes it easier to access parts of a string, such as specific characters and substrings. module Access # Returns the character at the +position+ treating the string as an array (where 0 is the first character). diff --git a/activesupport/lib/active_support/core_ext/string/unicode.rb b/activesupport/lib/active_support/core_ext/string/unicode.rb index 0e9770af2599e..963920d4a6950 100644 --- a/activesupport/lib/active_support/core_ext/string/unicode.rb +++ b/activesupport/lib/active_support/core_ext/string/unicode.rb @@ -1,7 +1,7 @@ module ActiveSupport #:nodoc: module CoreExtensions #:nodoc: module String #:nodoc: - if RUBY_VERSION < '1.9' + unless '1.9'.respond_to?(:force_encoding) # Define methods for handling unicode data. module Unicode # +chars+ is a Unicode safe proxy for string methods. It creates and returns an instance of the From f67b070facef6574df3c4386e3975242273fe456 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sat, 19 Apr 2008 17:16:19 -0700 Subject: [PATCH 14/48] Override incompatible 1.8.7p1 String#chars --- activesupport/lib/active_support/core_ext/string/unicode.rb | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/activesupport/lib/active_support/core_ext/string/unicode.rb b/activesupport/lib/active_support/core_ext/string/unicode.rb index 963920d4a6950..1f5077350511c 100644 --- a/activesupport/lib/active_support/core_ext/string/unicode.rb +++ b/activesupport/lib/active_support/core_ext/string/unicode.rb @@ -4,6 +4,12 @@ module String #:nodoc: unless '1.9'.respond_to?(:force_encoding) # Define methods for handling unicode data. module Unicode + def self.included(base) + if '1.8.7'.respond_to?(:chars) + base.class_eval { remove_method :chars } + end + end + # +chars+ is a Unicode safe proxy for string methods. It creates and returns an instance of the # ActiveSupport::Multibyte::Chars class which encapsulates the original string. A Unicode safe version of all # the String methods are defined on this proxy class. Undefined methods are forwarded to String, so all of the From daab53d8c0bca1114c1485d0dcc52858a264ab9e Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 20 Apr 2008 03:52:13 -0700 Subject: [PATCH 15/48] Incompatible Symbol#to_proc was reverted upstream --- activesupport/lib/active_support/core_ext/symbol.rb | 7 ------- 1 file changed, 7 deletions(-) diff --git a/activesupport/lib/active_support/core_ext/symbol.rb b/activesupport/lib/active_support/core_ext/symbol.rb index d41d47e70e6e1..e4ac4438099f7 100644 --- a/activesupport/lib/active_support/core_ext/symbol.rb +++ b/activesupport/lib/active_support/core_ext/symbol.rb @@ -1,10 +1,3 @@ -# Remove 1.8.7's incompatible method. -if :to_proc.respond_to?(:to_proc) && [1] != ([[1, 2]].map(&:first) rescue false) - class Symbol - remove_method :to_proc - end -end - unless :to_proc.respond_to?(:to_proc) class Symbol # Turns the symbol into a simple proc, which is especially useful for enumerations. Examples: From 46ab7422d9ebac0d529f71a3a7c2feaf0b9d5dbd Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Sun, 20 Apr 2008 11:45:44 -0500 Subject: [PATCH 16/48] Use define_callbacks helper for ActiveRecord validations. --- activemodel/lib/active_model/validations.rb | 18 +------------ activerecord/lib/active_record/validations.rb | 26 ++++--------------- activerecord/test/cases/validations_test.rb | 18 ++++++------- activesupport/lib/active_support/callbacks.rb | 20 +++++++------- 4 files changed, 25 insertions(+), 57 deletions(-) diff --git a/activemodel/lib/active_model/validations.rb b/activemodel/lib/active_model/validations.rb index 3b7b9050bed9e..b15bdb06cadc8 100644 --- a/activemodel/lib/active_model/validations.rb +++ b/activemodel/lib/active_model/validations.rb @@ -3,23 +3,7 @@ module Validations def self.included(base) # :nodoc: base.extend(ClassMethods) base.send!(:include, ActiveSupport::Callbacks) - - %w( validate validate_on_create validate_on_update ).each do |validation_method| - base.class_eval <<-"end_eval" - def self.#{validation_method}(*methods, &block) - self.#{validation_method}_callback_chain | CallbackChain.build(:#{validation_method}, *methods, &block) - end - - def self.#{validation_method}_callback_chain - if chain = read_inheritable_attribute(:#{validation_method}) - return chain - else - write_inheritable_attribute(:#{validation_method}, CallbackChain.new) - return #{validation_method}_callback_chain - end - end - end_eval - end + base.define_callbacks :validate, :validate_on_create, :validate_on_update end module ClassMethods diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb index 7b70f78405af9..1d12ea8ad7eb7 100755 --- a/activerecord/lib/active_record/validations.rb +++ b/activerecord/lib/active_record/validations.rb @@ -281,23 +281,7 @@ def self.included(base) # :nodoc: end base.send :include, ActiveSupport::Callbacks - - VALIDATIONS.each do |validation_method| - base.class_eval <<-"end_eval" - def self.#{validation_method}(*methods, &block) - self.#{validation_method}_callback_chain | CallbackChain.build(:#{validation_method}, *methods, &block) - end - - def self.#{validation_method}_callback_chain - if chain = read_inheritable_attribute(:#{validation_method}) - return chain - else - write_inheritable_attribute(:#{validation_method}, CallbackChain.new) - return #{validation_method}_callback_chain - end - end - end_eval - end + base.define_callbacks *VALIDATIONS end # All of the following validations are defined in the class scope of the model that you're interested in validating. @@ -403,7 +387,7 @@ def validates_each(*attrs) # method, proc or string should return or evaluate to a true or false value. # * unless - Specifies a method, proc or string to call to determine if the validation should # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The - # method, proc or string should return or evaluate to a true or false value. + # method, proc or string should return or evaluate to a true or false value. def validates_confirmation_of(*attr_names) configuration = { :message => ActiveRecord::Errors.default_error_messages[:confirmation], :on => :save } configuration.update(attr_names.extract_options!) @@ -437,7 +421,7 @@ def validates_confirmation_of(*attr_names) # method, proc or string should return or evaluate to a true or false value. # * unless - Specifies a method, proc or string to call to determine if the validation should # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The - # method, proc or string should return or evaluate to a true or false value. + # method, proc or string should return or evaluate to a true or false value. def validates_acceptance_of(*attr_names) configuration = { :message => ActiveRecord::Errors.default_error_messages[:accepted], :on => :save, :allow_nil => true, :accept => "1" } configuration.update(attr_names.extract_options!) @@ -519,7 +503,7 @@ def validates_presence_of(*attr_names) # method, proc or string should return or evaluate to a true or false value. # * unless - Specifies a method, proc or string to call to determine if the validation should # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The - # method, proc or string should return or evaluate to a true or false value. + # method, proc or string should return or evaluate to a true or false value. def validates_length_of(*attrs) # Merge given options with defaults. options = { @@ -596,7 +580,7 @@ def validates_length_of(*attrs) # attribute (that maps to a column). When the record is updated, the same check is made but disregarding the record itself. # # Because this check is performed outside the database there is still a chance that duplicate values - # will be inserted in two parallel transactions. To guarantee against this you should create a + # will be inserted in two parallel transactions. To guarantee against this you should create a # unique index on the field. See +add_index+ for more information. # # Configuration options: diff --git a/activerecord/test/cases/validations_test.rb b/activerecord/test/cases/validations_test.rb index 97ac22eaf343e..ca36ad3581b5b 100755 --- a/activerecord/test/cases/validations_test.rb +++ b/activerecord/test/cases/validations_test.rb @@ -58,9 +58,9 @@ class ValidationsTest < ActiveRecord::TestCase fixtures :topics, :developers, 'warehouse-things' def setup - Topic.write_inheritable_attribute(:validate, nil) - Topic.write_inheritable_attribute(:validate_on_create, nil) - Topic.write_inheritable_attribute(:validate_on_update, nil) + Topic.instance_variable_set("@validate_callbacks", ActiveSupport::Callbacks::CallbackChain.new) + Topic.instance_variable_set("@validate_on_create_callbacks", ActiveSupport::Callbacks::CallbackChain.new) + Topic.instance_variable_set("@validate_on_update_callbacks", ActiveSupport::Callbacks::CallbackChain.new) end def test_single_field_validation @@ -839,16 +839,16 @@ def test_validates_size_of_association reply = t.replies.build('title' => 'areply', 'content' => 'whateveragain') assert t.valid? end - + def test_validates_size_of_association_using_within assert_nothing_raised { Topic.validates_size_of :replies, :within => 1..2 } t = Topic.new('title' => 'noreplies', 'content' => 'whatever') assert !t.save assert t.errors.on(:replies) - + reply = t.replies.build('title' => 'areply', 'content' => 'whateveragain') assert t.valid? - + 2.times { t.replies.build('title' => 'areply', 'content' => 'whateveragain') } assert !t.save assert t.errors.on(:replies) @@ -1351,9 +1351,9 @@ class ValidatesNumericalityTest < ActiveRecord::TestCase JUNK = ["not a number", "42 not a number", "0xdeadbeef", "00-1", "--3", "+-3", "+3-1", "-+019.0", "12.12.13.12", "123\nnot a number"] def setup - Topic.write_inheritable_attribute(:validate, nil) - Topic.write_inheritable_attribute(:validate_on_create, nil) - Topic.write_inheritable_attribute(:validate_on_update, nil) + Topic.instance_variable_set("@validate_callbacks", ActiveSupport::Callbacks::CallbackChain.new) + Topic.instance_variable_set("@validate_on_create_callbacks", ActiveSupport::Callbacks::CallbackChain.new) + Topic.instance_variable_set("@validate_on_update_callbacks", ActiveSupport::Callbacks::CallbackChain.new) end def test_default_validates_numericality_of diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb index 5c512370493db..9c59b7ac76ce9 100644 --- a/activesupport/lib/active_support/callbacks.rb +++ b/activesupport/lib/active_support/callbacks.rb @@ -99,8 +99,8 @@ def run(object, options = {}, &terminator) def |(chain) if chain.is_a?(CallbackChain) chain.each { |callback| self | callback } - elsif chain.is_a?(Callback) - if index = index(chain) + else + if (found_callback = find(chain)) && (index = index(chain)) self[index] = chain else self << chain @@ -224,8 +224,8 @@ def self.#{callback}_callback_chain end end - # Runs all the callbacks defined for the given options. - # + # Runs all the callbacks defined for the given options. + # # If a block is given it will be called after each callback receiving as arguments: # # * the result from the callback @@ -236,31 +236,31 @@ def self.#{callback}_callback_chain # Example: # class Storage # include ActiveSupport::Callbacks - # + # # define_callbacks :before_save, :after_save # end - # + # # class ConfigStorage < Storage # before_save :pass # before_save :pass # before_save :stop # before_save :pass - # + # # def pass # puts "pass" # end - # + # # def stop # puts "stop" # return false # end - # + # # def save # result = run_callbacks(:before_save) { |result, object| result == false } # puts "- save" if result # end # end - # + # # config = ConfigStorage.new # config.save # From a2028a7d7bf4336d01656d947df77ee504927db0 Mon Sep 17 00:00:00 2001 From: Frederick Cheung Date: Mon, 21 Apr 2008 11:45:48 +1200 Subject: [PATCH 17/48] Fix sqlite adapter to work with the quoted table names returned by later versions of sqlite3. --- .../lib/active_record/connection_adapters/sqlite_adapter.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb index 92d11e56e1d60..59a51c02792f8 100644 --- a/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb @@ -257,7 +257,7 @@ def select(sql, name = nil) #:nodoc: record = {} row.each_key do |key| if key.is_a?(String) - record[key.sub(/^\w+\./, '')] = row[key] + record[key.sub(/^"?\w+"?\./, '')] = row[key] end end record From 55622e0bde999193ae4a848d28cf2ce7e9247d83 Mon Sep 17 00:00:00 2001 From: Frederick Cheung Date: Mon, 21 Apr 2008 11:47:15 +1200 Subject: [PATCH 18/48] Avoid adding two DISTINCT statements to queries in sqlite 2. --- activerecord/lib/active_record/calculations.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/calculations.rb b/activerecord/lib/active_record/calculations.rb index 64527ec3f0746..b5bf82ee11274 100644 --- a/activerecord/lib/active_record/calculations.rb +++ b/activerecord/lib/active_record/calculations.rb @@ -178,7 +178,7 @@ def construct_calculation_sql(operation, column_name, options) #:nodoc: sql = "SELECT COUNT(*) AS #{aggregate_alias}" if use_workaround sql << ", #{options[:group_field]} AS #{options[:group_alias]}" if options[:group] - sql << " FROM (SELECT DISTINCT #{column_name}" if use_workaround + sql << " FROM (SELECT #{distinct}#{column_name}" if use_workaround sql << " FROM #{connection.quote_table_name(table_name)} " if merged_includes.any? join_dependency = ActiveRecord::Associations::ClassMethods::JoinDependency.new(self, merged_includes, options[:joins]) From 59f5d4fc79b72a2bf0f7ffada4a1a73eb303d943 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 20 Apr 2008 16:49:58 -0700 Subject: [PATCH 19/48] Use append_features instead of included to get the inclusion order right --- activesupport/lib/active_support/core_ext/string/unicode.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/activesupport/lib/active_support/core_ext/string/unicode.rb b/activesupport/lib/active_support/core_ext/string/unicode.rb index 1f5077350511c..ba16d4d86670e 100644 --- a/activesupport/lib/active_support/core_ext/string/unicode.rb +++ b/activesupport/lib/active_support/core_ext/string/unicode.rb @@ -4,10 +4,11 @@ module String #:nodoc: unless '1.9'.respond_to?(:force_encoding) # Define methods for handling unicode data. module Unicode - def self.included(base) + def self.append_features(base) if '1.8.7'.respond_to?(:chars) base.class_eval { remove_method :chars } end + super end # +chars+ is a Unicode safe proxy for string methods. It creates and returns an instance of the From caa03a5c870c6a03a35f6dcfaf040a6d689eaee2 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Mon, 21 Apr 2008 02:43:48 +0100 Subject: [PATCH 20/48] Remove ActionController::Base#add_class_variables_to_assigns --- actionpack/lib/action_controller/base.rb | 7 ------- 1 file changed, 7 deletions(-) diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb index c0f3122fbf7b8..93007e2d1c259 100755 --- a/actionpack/lib/action_controller/base.rb +++ b/actionpack/lib/action_controller/base.rb @@ -1194,7 +1194,6 @@ def self.action_methods def add_variables_to_assigns unless @variables_added add_instance_variables_to_assigns - add_class_variables_to_assigns if view_controller_internals @variables_added = true end end @@ -1215,12 +1214,6 @@ def add_instance_variables_to_assigns end end - def add_class_variables_to_assigns - %w(view_paths logger).each do |cvar| - @assigns[cvar] = self.send(cvar) - end - end - def protected_instance_variables if view_controller_internals %w(@assigns @performed_redirect @performed_render) From 2b69840e5efba885c8ec6281d5b8a56fcabff283 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Mon, 21 Apr 2008 03:38:16 +0100 Subject: [PATCH 21/48] Remove ActionController::Base#view_controller_internals Get rid of ActionController::Base#view_controller_internals flag and use @@protected_view_variables for storing the list of controller specific instance variables which should be inaccessible inside views. --- actionpack/CHANGELOG | 2 ++ actionpack/lib/action_controller/base.rb | 30 ++++--------------- .../lib/action_controller/caching/actions.rb | 5 ---- actionpack/test/controller/new_render_test.rb | 16 ---------- 4 files changed, 8 insertions(+), 45 deletions(-) diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG index 9c72fd945ac9e..6555560bdd8f9 100644 --- a/actionpack/CHANGELOG +++ b/actionpack/CHANGELOG @@ -1,5 +1,7 @@ *SVN* +* Remove ActionController::Base#view_controller_internals flag. [Pratik] + * Add conditional options to caches_page method. [Paul Horsfall] * Move missing template logic to ActionView. [Pratik] diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb index 93007e2d1c259..1aa027f9d7a71 100755 --- a/actionpack/lib/action_controller/base.rb +++ b/actionpack/lib/action_controller/base.rb @@ -253,16 +253,11 @@ class Base DEFAULT_RENDER_STATUS_CODE = "200 OK" include StatusCodes - - # Determines whether the view has access to controller internals @request, @response, @session, and @template. - # By default, it does. - @@view_controller_internals = true - cattr_accessor :view_controller_internals - - # Protected instance variable cache - @@protected_variables_cache = nil - cattr_accessor :protected_variables_cache - + + # Controller specific instance variables which will not be accessible inside views. + @@protected_view_variables = %w(@assigns @performed_redirect @performed_render @variables_added @request_origin @url @parent_controller + @action_name @before_filter_chain_aborted @action_cache_path) + # Prepends all the URL-generating helpers from AssetHelper. This makes it possible to easily move javascripts, stylesheets, # and images to a dedicated asset server away from the main web server. Example: # ActionController::Base.asset_host = "http://assets.example.com" @@ -1207,24 +1202,11 @@ def reset_variables_added_to_assigns end def add_instance_variables_to_assigns - @@protected_variables_cache ||= Set.new(protected_instance_variables) - instance_variable_names.each do |var| - next if @@protected_variables_cache.include?(var) + (instance_variable_names - @@protected_view_variables).each do |var| @assigns[var[1..-1]] = instance_variable_get(var) end end - def protected_instance_variables - if view_controller_internals - %w(@assigns @performed_redirect @performed_render) - else - %w(@assigns @performed_redirect @performed_render - @_request @request @_response @response @_params @params - @_session @session @_cookies @cookies - @template @request_origin @parent_controller) - end - end - def request_origin # this *needs* to be cached! # otherwise you'd get different results if calling it more than once diff --git a/actionpack/lib/action_controller/caching/actions.rb b/actionpack/lib/action_controller/caching/actions.rb index 4410e47eb347c..7b0551c66449c 100644 --- a/actionpack/lib/action_controller/caching/actions.rb +++ b/actionpack/lib/action_controller/caching/actions.rb @@ -41,7 +41,6 @@ def self.included(base) #:nodoc: base.extend(ClassMethods) base.class_eval do attr_accessor :rendered_action_cache, :action_cache_path - alias_method_chain :protected_instance_variables, :action_caching end end @@ -55,10 +54,6 @@ def caches_action(*actions) end protected - def protected_instance_variables_with_action_caching - protected_instance_variables_without_action_caching + %w(@action_cache_path) - end - def expire_action(options = {}) return unless cache_configured? diff --git a/actionpack/test/controller/new_render_test.rb b/actionpack/test/controller/new_render_test.rb index 80cf09e5f39e9..9f9d861d3209b 100644 --- a/actionpack/test/controller/new_render_test.rb +++ b/actionpack/test/controller/new_render_test.rb @@ -529,26 +529,10 @@ def test_private_methods end def test_access_to_request_in_view - view_internals_old_value = ActionController::Base.view_controller_internals - - ActionController::Base.view_controller_internals = false - ActionController::Base.protected_variables_cache = nil - - get :hello_world - assert !assigns.include?('_request'), '_request should not be in assigns' - assert !assigns.include?('request'), 'request should not be in assigns' - - ActionController::Base.view_controller_internals = true - ActionController::Base.protected_variables_cache = nil - get :hello_world assert !assigns.include?('request'), 'request should not be in assigns' assert_kind_of ActionController::AbstractRequest, assigns['_request'] assert_kind_of ActionController::AbstractRequest, @response.template.request - - ensure - ActionController::Base.view_controller_internals = view_internals_old_value - ActionController::Base.protected_variables_cache = nil end def test_render_xml From 549c81db4a9ca941ea65ae2edafb0f34784f12f2 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 20 Apr 2008 17:52:21 -0700 Subject: [PATCH 22/48] Ruby 1.8.7 compat: String#start_with? and #end_with? --- .../lib/active_support/core_ext/string.rb | 13 +++---------- .../active_support/core_ext/string/iterators.rb | 4 ++++ .../core_ext/string/starts_ends_with.rb | 16 ++++++++++++---- 3 files changed, 19 insertions(+), 14 deletions(-) diff --git a/activesupport/lib/active_support/core_ext/string.rb b/activesupport/lib/active_support/core_ext/string.rb index a83474f278f93..25386af70a39f 100644 --- a/activesupport/lib/active_support/core_ext/string.rb +++ b/activesupport/lib/active_support/core_ext/string.rb @@ -2,7 +2,7 @@ require 'active_support/core_ext/string/conversions' require 'active_support/core_ext/string/access' require 'active_support/core_ext/string/starts_ends_with' -require 'active_support/core_ext/string/iterators' unless 'test'.respond_to?(:each_char) +require 'active_support/core_ext/string/iterators' require 'active_support/core_ext/string/unicode' require 'active_support/core_ext/string/xchar' require 'active_support/core_ext/string/filters' @@ -12,14 +12,7 @@ class String #:nodoc: include ActiveSupport::CoreExtensions::String::Conversions include ActiveSupport::CoreExtensions::String::Filters include ActiveSupport::CoreExtensions::String::Inflections - if RUBY_VERSION < '1.9' - include ActiveSupport::CoreExtensions::String::StartsEndsWith - else - alias starts_with? start_with? - alias ends_with? end_with? - end - if defined? ActiveSupport::CoreExtensions::String::Iterators - include ActiveSupport::CoreExtensions::String::Iterators - end + include ActiveSupport::CoreExtensions::String::StartsEndsWith + include ActiveSupport::CoreExtensions::String::Iterators include ActiveSupport::CoreExtensions::String::Unicode end diff --git a/activesupport/lib/active_support/core_ext/string/iterators.rb b/activesupport/lib/active_support/core_ext/string/iterators.rb index 73114d9d5fefe..66a08a5cd0231 100644 --- a/activesupport/lib/active_support/core_ext/string/iterators.rb +++ b/activesupport/lib/active_support/core_ext/string/iterators.rb @@ -5,6 +5,10 @@ module CoreExtensions #:nodoc: module String #:nodoc: # Custom string iterators module Iterators + def self.append_features(base) + super unless '1.9'.respond_to?(:each_char) + end + # Yields a single-character string for each character in the string. # When $KCODE = 'UTF8', multi-byte characters are yielded appropriately. def each_char diff --git a/activesupport/lib/active_support/core_ext/string/starts_ends_with.rb b/activesupport/lib/active_support/core_ext/string/starts_ends_with.rb index 39606697982c6..09f9a188b51ed 100644 --- a/activesupport/lib/active_support/core_ext/string/starts_ends_with.rb +++ b/activesupport/lib/active_support/core_ext/string/starts_ends_with.rb @@ -3,10 +3,18 @@ module CoreExtensions #:nodoc: module String #:nodoc: # Additional string tests. module StartsEndsWith - def self.included(base) - base.class_eval do - alias_method :start_with?, :starts_with? - alias_method :end_with?, :ends_with? + def self.append_features(base) + if '1.8.7 and up'.respond_to?(:start_with?) + base.class_eval do + alias_method :starts_with?, :start_with? + alias_method :ends_with?, :end_with? + end + else + super + base.class_eval do + alias_method :start_with?, :starts_with? + alias_method :end_with?, :ends_with? + end end end From 0b21ac5118c293b43e5370d7a3da980514f089a2 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 20 Apr 2008 19:16:48 -0700 Subject: [PATCH 23/48] Ruby 1.8.7 compat: override unordered Enumerable#group_by --- activesupport/lib/active_support/core_ext/enumerable.rb | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/activesupport/lib/active_support/core_ext/enumerable.rb b/activesupport/lib/active_support/core_ext/enumerable.rb index 1b96eb166a2ec..8f111e29fc106 100644 --- a/activesupport/lib/active_support/core_ext/enumerable.rb +++ b/activesupport/lib/active_support/core_ext/enumerable.rb @@ -1,4 +1,7 @@ module Enumerable + # Ruby 1.8.7 introduces group_by, but the result isn't ordered. Override it. + remove_method(:group_by) if [].respond_to?(:group_by) && RUBY_VERSION < '1.9' + # Collect an enumerable into sets, grouped by the result of a block. Useful, # for example, for grouping records by date. # @@ -19,7 +22,7 @@ def group_by (grouped[yield(element)] ||= []) << element grouped end - end if RUBY_VERSION < '1.9' + end unless [].respond_to?(:group_by) # Calculates a sum from the elements. Examples: # From 1d18651ea36e2ba274b6c2e0fd4edd425e028589 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 20 Apr 2008 19:26:46 -0700 Subject: [PATCH 24/48] Ruby 1.8.7 compat: detect and alias non-superclass DateTime#to_s --- .../core_ext/date_time/conversions.rb | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/activesupport/lib/active_support/core_ext/date_time/conversions.rb b/activesupport/lib/active_support/core_ext/date_time/conversions.rb index aa9caf17744e8..c0175a5f28084 100644 --- a/activesupport/lib/active_support/core_ext/date_time/conversions.rb +++ b/activesupport/lib/active_support/core_ext/date_time/conversions.rb @@ -3,17 +3,22 @@ module CoreExtensions #:nodoc: module DateTime #:nodoc: # Converting datetimes to formatted strings, dates, and times. module Conversions - def self.included(base) #:nodoc: + def self.append_features(base) #:nodoc: base.class_eval do - alias_method :to_default_s, :to_s if instance_methods.include?(:to_s) - alias_method :to_s, :to_formatted_s alias_method :default_inspect, :inspect - alias_method :inspect, :readable_inspect + alias_method :to_default_s, :to_s unless (instance_methods(false) & [:to_s, 'to_s']).empty? # Ruby 1.9 has DateTime#to_time which internally relies on Time. We define our own #to_time which allows # DateTimes outside the range of what can be created with Time. remove_method :to_time if instance_methods.include?(:to_time) end + + super + + base.class_eval do + alias_method :to_s, :to_formatted_s + alias_method :inspect, :readable_inspect + end end # Convert to a formatted string. See Time::DATE_FORMATS for predefined formats. From 32b82e4c6f5523cdf5ee78c3022c50b46e018351 Mon Sep 17 00:00:00 2001 From: gbuesing Date: Sun, 20 Apr 2008 21:57:04 -0500 Subject: [PATCH 25/48] Duration #since and #ago with no argument (e.g., 5.days.ago) return TimeWithZone when config.time_zone is set. Introducing Time.current, which returns Time.zone.now if config.time_zone is set, otherwise just returns Time.now --- activesupport/CHANGELOG | 2 + .../lib/active_support/core_ext/time/zones.rb | 5 +++ activesupport/lib/active_support/duration.rb | 6 +-- activesupport/test/core_ext/duration_test.rb | 42 +++++++++++++++++++ .../test/core_ext/time_with_zone_test.rb | 24 +++++++++++ 5 files changed, 76 insertions(+), 3 deletions(-) diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG index cfdefed91e060..a911361d3b07e 100644 --- a/activesupport/CHANGELOG +++ b/activesupport/CHANGELOG @@ -1,5 +1,7 @@ *SVN* +* Duration #since and #ago with no argument (e.g., 5.days.ago) return TimeWithZone when config.time_zone is set. Introducing Time.current, which returns Time.zone.now if config.time_zone is set, otherwise just returns Time.now [Geoff Buesing] + * Time#since behaves correctly when passed a Duration. Closes #11527 [kemiller] * Add #getutc alias for DateTime#utc [Geoff Buesing] diff --git a/activesupport/lib/active_support/core_ext/time/zones.rb b/activesupport/lib/active_support/core_ext/time/zones.rb index d2b95698e5e89..3ffc71407cc05 100644 --- a/activesupport/lib/active_support/core_ext/time/zones.rb +++ b/activesupport/lib/active_support/core_ext/time/zones.rb @@ -35,6 +35,11 @@ def use_zone(time_zone) ::Time.zone = old_zone end + # Returns Time.zone.now when config.time_zone is set, otherwise just returns Time.now. + def current + ::Time.zone_default ? ::Time.zone.now : ::Time.now + end + private def get_zone(time_zone) return time_zone if time_zone.nil? || time_zone.is_a?(TimeZone) diff --git a/activesupport/lib/active_support/duration.rb b/activesupport/lib/active_support/duration.rb index ff51b49dcf491..8eae85d38e9d1 100644 --- a/activesupport/lib/active_support/duration.rb +++ b/activesupport/lib/active_support/duration.rb @@ -51,14 +51,14 @@ def self.===(other) #:nodoc: # Calculates a new Time or Date that is as far in the future # as this Duration represents. - def since(time = ::Time.now) + def since(time = ::Time.current) sum(1, time) end alias :from_now :since # Calculates a new Time or Date that is as far in the past # as this Duration represents. - def ago(time = ::Time.now) + def ago(time = ::Time.current) sum(-1, time) end alias :until :ago @@ -73,7 +73,7 @@ def inspect #:nodoc: protected - def sum(sign, time = ::Time.now) #:nodoc: + def sum(sign, time = ::Time.current) #:nodoc: parts.inject(time) do |t,(type,number)| if t.acts_like?(:time) || t.acts_like?(:date) if type == :seconds diff --git a/activesupport/test/core_ext/duration_test.rb b/activesupport/test/core_ext/duration_test.rb index df878f917b846..7b17fe71db903 100644 --- a/activesupport/test/core_ext/duration_test.rb +++ b/activesupport/test/core_ext/duration_test.rb @@ -29,4 +29,46 @@ def test_argument_error flunk("ArgumentError should be raised, but we got #{$!.class} instead") end end + + uses_mocha 'TestDurationSinceAndAgoWithCurrentTime' do + def test_since_and_ago_anchored_to_time_now_when_time_zone_default_not_set + Time.zone_default = nil + with_env_tz 'US/Eastern' do + Time.stubs(:now).returns Time.local(2000) + # since + assert_equal false, 5.seconds.since.is_a?(ActiveSupport::TimeWithZone) + assert_equal Time.local(2000,1,1,0,0,5), 5.seconds.since + # ago + assert_equal false, 5.seconds.ago.is_a?(ActiveSupport::TimeWithZone) + assert_equal Time.local(1999,12,31,23,59,55), 5.seconds.ago + end + end + + def test_since_and_ago_anchored_to_time_zone_now_when_time_zone_default_set + silence_warnings do # silence warnings raised by tzinfo gem + Time.zone_default = TimeZone['Eastern Time (US & Canada)'] + with_env_tz 'US/Eastern' do + Time.stubs(:now).returns Time.local(2000) + # since + assert_equal true, 5.seconds.since.is_a?(ActiveSupport::TimeWithZone) + assert_equal Time.utc(2000,1,1,0,0,5), 5.seconds.since.time + assert_equal 'Eastern Time (US & Canada)', 5.seconds.since.time_zone.name + # ago + assert_equal true, 5.seconds.ago.is_a?(ActiveSupport::TimeWithZone) + assert_equal Time.utc(1999,12,31,23,59,55), 5.seconds.ago.time + assert_equal 'Eastern Time (US & Canada)', 5.seconds.ago.time_zone.name + end + end + ensure + Time.zone_default = nil + end + end + + protected + def with_env_tz(new_tz = 'US/Eastern') + old_tz, ENV['TZ'] = ENV['TZ'], new_tz + yield + ensure + old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ') + end end diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb index efab8a24c8f7c..df70e82c1de44 100644 --- a/activesupport/test/core_ext/time_with_zone_test.rb +++ b/activesupport/test/core_ext/time_with_zone_test.rb @@ -627,6 +627,30 @@ def test_time_zone_setter_with_non_identifying_argument_returns_nil assert_equal nil, Time.zone end + uses_mocha 'TestTimeCurrent' do + def test_current_returns_time_now_when_zone_default_not_set + with_env_tz 'US/Eastern' do + Time.stubs(:now).returns Time.local(2000) + assert_equal false, Time.current.is_a?(ActiveSupport::TimeWithZone) + assert_equal Time.local(2000), Time.current + end + end + + def test_current_returns_time_zone_now_when_zone_default_set + silence_warnings do # silence warnings raised by tzinfo gem + Time.zone_default = TimeZone['Eastern Time (US & Canada)'] + with_env_tz 'US/Eastern' do + Time.stubs(:now).returns Time.local(2000) + assert_equal true, Time.current.is_a?(ActiveSupport::TimeWithZone) + assert_equal 'Eastern Time (US & Canada)', Time.current.time_zone.name + assert_equal Time.utc(2000), Time.current.time + end + end + ensure + Time.zone_default = nil + end + end + protected def with_env_tz(new_tz = 'US/Eastern') old_tz, ENV['TZ'] = ENV['TZ'], new_tz From f386676661068573d2b58f6bd7a7245b4ff5ce5d Mon Sep 17 00:00:00 2001 From: Steven Soroka Date: Mon, 21 Apr 2008 16:40:16 +1200 Subject: [PATCH 26/48] Use the rails user when creating and dropping the database rather than falling back to the currently logged in user who may or may not have CREATE / DROP privileges and no password. Closes #11564 (trac) --- activerecord/Rakefile | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/activerecord/Rakefile b/activerecord/Rakefile index b475b27037560..50c120107bf63 100755 --- a/activerecord/Rakefile +++ b/activerecord/Rakefile @@ -19,6 +19,8 @@ RELEASE_NAME = "REL #{PKG_VERSION}" RUBY_FORGE_PROJECT = "activerecord" RUBY_FORGE_USER = "webster132" +MYSQL_DB_USER = 'rails' + PKG_FILES = FileList[ "lib/**/*", "test/**/*", "examples/**/*", "doc/**/*", "[A-Z]*", "install.rb", "Rakefile" ].exclude(/\bCVS\b|~$/) @@ -46,16 +48,14 @@ end namespace :mysql do desc 'Build the MySQL test databases' task :build_databases do - %x( mysqladmin create activerecord_unittest ) - %x( mysqladmin create activerecord_unittest2 ) - %x( mysql -e "grant all on activerecord_unittest.* to rails@localhost" ) - %x( mysql -e "grant all on activerecord_unittest2.* to rails@localhost" ) + %x( mysqladmin --user=#{MYSQL_DB_USER} create activerecord_unittest ) + %x( mysqladmin --user=#{MYSQL_DB_USER} create activerecord_unittest2 ) end desc 'Drop the MySQL test databases' task :drop_databases do - %x( mysqladmin -f drop activerecord_unittest ) - %x( mysqladmin -f drop activerecord_unittest2 ) + %x( mysqladmin --user=#{MYSQL_DB_USER} -f drop activerecord_unittest ) + %x( mysqladmin --user=#{MYSQL_DB_USER} -f drop activerecord_unittest2 ) end desc 'Rebuild the MySQL test databases' From c2c779044ffb1c435f4722f62fcbd400883f3225 Mon Sep 17 00:00:00 2001 From: gbuesing Date: Mon, 21 Apr 2008 00:08:45 -0500 Subject: [PATCH 27/48] datetime_select defaults to Time.zone.now when config.time_zone is set --- actionpack/CHANGELOG | 2 ++ .../lib/action_view/helpers/date_helper.rb | 2 +- actionpack/test/template/date_helper_test.rb | 36 +++++++++++++++++++ 3 files changed, 39 insertions(+), 1 deletion(-) diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG index 6555560bdd8f9..46251534ecd3d 100644 --- a/actionpack/CHANGELOG +++ b/actionpack/CHANGELOG @@ -1,5 +1,7 @@ *SVN* +* datetime_select defaults to Time.zone.now when config.time_zone is set [Geoff Buesing] + * Remove ActionController::Base#view_controller_internals flag. [Pratik] * Add conditional options to caches_page method. [Paul Horsfall] diff --git a/actionpack/lib/action_view/helpers/date_helper.rb b/actionpack/lib/action_view/helpers/date_helper.rb index c71d59f3732b9..23b7f3ba7c9c4 100755 --- a/actionpack/lib/action_view/helpers/date_helper.rb +++ b/actionpack/lib/action_view/helpers/date_helper.rb @@ -675,7 +675,7 @@ def options_with_prefix(position, options) def default_time_from_options(default) case default when nil - Time.now + Time.current when Date, Time default else diff --git a/actionpack/test/template/date_helper_test.rb b/actionpack/test/template/date_helper_test.rb index 9bd433e76b79d..fab41d801d1ea 100755 --- a/actionpack/test/template/date_helper_test.rb +++ b/actionpack/test/template/date_helper_test.rb @@ -1219,6 +1219,42 @@ def test_datetime_select assert_dom_equal expected, datetime_select("post", "updated_at") end + + uses_mocha 'TestDatetimeSelectDefaultsToTimeZoneNowWhenConfigTimeZoneIsSet' do + def test_datetime_select_defaults_to_time_zone_now_when_config_time_zone_is_set + time = stub(:year => 2004, :month => 6, :day => 15, :hour => 16, :min => 35, :sec => 0) + time_zone = mock() + time_zone.expects(:now).returns time + Time.zone_default = time_zone + @post = Post.new + + expected = %{\n" + + expected << %{\n" + + expected << %{\n" + + expected << " — " + + expected << %{\n" + expected << " : " + expected << %{\n" + + assert_dom_equal expected, datetime_select("post", "updated_at") + ensure + Time.zone_default = nil + end + end def test_datetime_select_within_fields_for @post = Post.new From f757f5838818ce35f7927a10a8cda6f9583869c5 Mon Sep 17 00:00:00 2001 From: gbuesing Date: Mon, 21 Apr 2008 00:40:04 -0500 Subject: [PATCH 28/48] select_datetime and select_time default to Time.zone.now when config.time_zone is set --- actionpack/CHANGELOG | 2 ++ .../lib/action_view/helpers/date_helper.rb | 4 ++-- actionpack/test/template/date_helper_test.rb | 18 ++++++++++++++++++ 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG index 46251534ecd3d..a3b425287d11f 100644 --- a/actionpack/CHANGELOG +++ b/actionpack/CHANGELOG @@ -1,5 +1,7 @@ *SVN* +* select_datetime and select_time default to Time.zone.now when config.time_zone is set [Geoff Buesing] + * datetime_select defaults to Time.zone.now when config.time_zone is set [Geoff Buesing] * Remove ActionController::Base#view_controller_internals flag. [Pratik] diff --git a/actionpack/lib/action_view/helpers/date_helper.rb b/actionpack/lib/action_view/helpers/date_helper.rb index 23b7f3ba7c9c4..9f7790d0f9cb1 100755 --- a/actionpack/lib/action_view/helpers/date_helper.rb +++ b/actionpack/lib/action_view/helpers/date_helper.rb @@ -250,7 +250,7 @@ def datetime_select(object_name, method, options = {}, html_options = {}) # # prefixed with 'payday' rather than 'date' # select_datetime(my_date_time, :prefix => 'payday') # - def select_datetime(datetime = Time.now, options = {}, html_options = {}) + def select_datetime(datetime = Time.current, options = {}, html_options = {}) separator = options[:datetime_separator] || '' select_date(datetime, options, html_options) + separator + select_time(datetime, options, html_options) end @@ -321,7 +321,7 @@ def select_date(date = Date.today, options = {}, html_options = {}) # # separated by ':' and includes an input for seconds # select_time(my_time, :time_separator => ':', :include_seconds => true) # - def select_time(datetime = Time.now, options = {}, html_options = {}) + def select_time(datetime = Time.current, options = {}, html_options = {}) separator = options[:time_separator] || '' select_hour(datetime, options, html_options) + separator + select_minute(datetime, options, html_options) + (options[:include_seconds] ? separator + select_second(datetime, options, html_options) : '') end diff --git a/actionpack/test/template/date_helper_test.rb b/actionpack/test/template/date_helper_test.rb index fab41d801d1ea..2373600bfeb8e 100755 --- a/actionpack/test/template/date_helper_test.rb +++ b/actionpack/test/template/date_helper_test.rb @@ -933,6 +933,24 @@ def test_select_time_with_html_options assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), {}, :class => 'selector') assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), {:include_seconds => false}, :class => 'selector') end + + uses_mocha 'TestDatetimeAndTimeSelectUseTimeCurrentAsDefault' do + def test_select_datetime_uses_time_current_as_default + time = stub(:year => 2004, :month => 6, :day => 15, :hour => 16, :min => 35, :sec => 0) + Time.expects(:current).returns time + expects(:select_date).with(time, anything, anything).returns('') + expects(:select_time).with(time, anything, anything).returns('') + select_datetime + end + + def test_select_time_uses_time_current_as_default + time = stub(:year => 2004, :month => 6, :day => 15, :hour => 16, :min => 35, :sec => 0) + Time.expects(:current).returns time + expects(:select_hour).with(time, anything, anything).returns('') + expects(:select_minute).with(time, anything, anything).returns('') + select_time + end + end def test_date_select @post = Post.new From a04f0228776e7616c372f867a1212b5798cde80a Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Mon, 21 Apr 2008 11:39:46 +0100 Subject: [PATCH 29/48] Delegate ivars to controller instead of copying Reduce number of instance variables being copied from controller to view. Instead, delegate them to controller instance. --- actionpack/CHANGELOG | 2 ++ actionpack/lib/action_controller/base.rb | 3 ++- actionpack/lib/action_view/base.rb | 9 ++++----- actionpack/test/controller/new_render_test.rb | 19 +++++++++++++++---- 4 files changed, 23 insertions(+), 10 deletions(-) diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG index a3b425287d11f..5a2122b64b534 100644 --- a/actionpack/CHANGELOG +++ b/actionpack/CHANGELOG @@ -1,5 +1,7 @@ *SVN* +* Reduce number of instance variables being copied from controller to view. [Pratik] + * select_datetime and select_time default to Time.zone.now when config.time_zone is set [Geoff Buesing] * datetime_select defaults to Time.zone.now when config.time_zone is set [Geoff Buesing] diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb index 1aa027f9d7a71..0c0d0ec4ac86c 100755 --- a/actionpack/lib/action_controller/base.rb +++ b/actionpack/lib/action_controller/base.rb @@ -256,7 +256,8 @@ class Base # Controller specific instance variables which will not be accessible inside views. @@protected_view_variables = %w(@assigns @performed_redirect @performed_render @variables_added @request_origin @url @parent_controller - @action_name @before_filter_chain_aborted @action_cache_path) + @action_name @before_filter_chain_aborted @action_cache_path @_session @_cookies @_headers @_params + @_flash @_response) # Prepends all the URL-generating helpers from AssetHelper. This makes it possible to easily move javascripts, stylesheets, # and images to a dedicated asset server away from the main web server. Example: diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb index 12dd7d2bc91a9..4ed20fec89fa1 100644 --- a/actionpack/lib/action_view/base.rb +++ b/actionpack/lib/action_view/base.rb @@ -156,9 +156,6 @@ class Base attr_reader :finder attr_accessor :base_path, :assigns, :template_extension, :first_render attr_accessor :controller - - attr_reader :logger, :response, :headers - attr_internal :cookies, :flash, :headers, :params, :request, :response, :session attr_writer :template_format attr_accessor :current_render_extension @@ -185,7 +182,10 @@ class Base @@erb_variable = '_erbout' cattr_accessor :erb_variable - delegate :request_forgery_protection_token, :to => :controller + attr_internal :request + + delegate :request_forgery_protection_token, :template, :params, :session, :cookies, :response, :headers, + :flash, :logger, :to => :controller module CompiledTemplates #:nodoc: # holds compiled template code @@ -222,7 +222,6 @@ def initialize(view_paths = [], assigns_for_first_render = {}, controller = nil) @assigns = assigns_for_first_render @assigns_added = nil @controller = controller - @logger = controller && controller.logger @finder = TemplateFinder.new(self, view_paths) end diff --git a/actionpack/test/controller/new_render_test.rb b/actionpack/test/controller/new_render_test.rb index 9f9d861d3209b..8e39057f55154 100644 --- a/actionpack/test/controller/new_render_test.rb +++ b/actionpack/test/controller/new_render_test.rb @@ -239,6 +239,14 @@ def accessing_params_in_template render :inline => "Hello: <%= params[:name] %>" end + def accessing_request_in_template + render :inline => "Hello: <%= request.host %>" + end + + def accessing_logger_in_template + render :inline => "<%= logger.class %>" + end + def accessing_params_in_template_with_layout render :layout => nil, :inline => "Hello: <%= params[:name] %>" end @@ -529,10 +537,13 @@ def test_private_methods end def test_access_to_request_in_view - get :hello_world - assert !assigns.include?('request'), 'request should not be in assigns' - assert_kind_of ActionController::AbstractRequest, assigns['_request'] - assert_kind_of ActionController::AbstractRequest, @response.template.request + get :accessing_request_in_template + assert_equal "Hello: www.nextangle.com", @response.body + end + + def test_access_to_logger_in_view + get :accessing_logger_in_template + assert_equal "Logger", @response.body end def test_render_xml From 6dbe90dd9b287ca383de9bae371614352a8646e7 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Mon, 21 Apr 2008 12:03:01 +0100 Subject: [PATCH 30/48] Alias Object#instance_variable_names to Object#instance_variables for Ruby 1.8.x --- .../active_support/core_ext/object/instance_variables.rb | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/activesupport/lib/active_support/core_ext/object/instance_variables.rb b/activesupport/lib/active_support/core_ext/object/instance_variables.rb index ee1010b250cb4..9f1d4ed2aa1f8 100644 --- a/activesupport/lib/active_support/core_ext/object/instance_variables.rb +++ b/activesupport/lib/active_support/core_ext/object/instance_variables.rb @@ -33,8 +33,12 @@ def instance_values #:nodoc: # end # # C.new(0, 1).instance_variable_names # => ["@y", "@x"] - def instance_variable_names - instance_variables.map(&:to_s) + if RUBY_VERSION >= '1.9' + def instance_variable_names + instance_variables.map(&:to_s) + end + else + alias_method :instance_variable_names, :instance_variables end # Copies the instance variables of +object+ into +self+. From 1a29a6717887ac1422bcce9067536987ee64f94d Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 21 Apr 2008 11:54:23 -0500 Subject: [PATCH 31/48] Mock RailsFCGIHandler and Dispatcher to stop mocha deprecation warnings. --- railties/test/fcgi_dispatcher_test.rb | 30 +++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/railties/test/fcgi_dispatcher_test.rb b/railties/test/fcgi_dispatcher_test.rb index 61342110226f8..64d054d45c087 100644 --- a/railties/test/fcgi_dispatcher_test.rb +++ b/railties/test/fcgi_dispatcher_test.rb @@ -124,6 +124,24 @@ def test_uninterrupted_processing class RailsFCGIHandlerSignalsTest < Test::Unit::TestCase + class ::RailsFCGIHandler + attr_accessor :signal + alias_method :old_gc_countdown, :gc_countdown + def gc_countdown + signal ? Process.kill(signal, $$) : old_gc_countdown + end + end + + class ::Dispatcher + class << self + attr_accessor :signal + alias_method :old_dispatch, :dispatch + def dispatch(cgi) + signal ? Process.kill(signal, $$) : old_dispatch + end + end + end + def setup @log = StringIO.new @handler = RailsFCGIHandler.new(@log) @@ -132,7 +150,7 @@ def setup def test_interrupted_via_HUP_when_not_in_request cgi = mock FCGI.expects(:each_cgi).once.yields(cgi) - @handler.expects(:gc_countdown).returns(lambda { Process.kill 'HUP', $$ } ) + @handler.expects(:signal).times(2).returns('HUP') @handler.expects(:reload!).once @handler.expects(:close_connection).never @@ -145,7 +163,7 @@ def test_interrupted_via_HUP_when_not_in_request def test_interrupted_via_HUP_when_in_request cgi = mock FCGI.expects(:each_cgi).once.yields(cgi) - Dispatcher.expects(:dispatch).with(cgi).returns( lambda { Process.kill 'HUP', $$ } ) + Dispatcher.expects(:signal).times(2).returns('HUP') @handler.expects(:reload!).once @handler.expects(:close_connection).never @@ -158,7 +176,7 @@ def test_interrupted_via_HUP_when_in_request def test_interrupted_via_USR1_when_not_in_request cgi = mock FCGI.expects(:each_cgi).once.yields(cgi) - @handler.expects(:gc_countdown).returns( lambda { Process.kill 'USR1', $$ } ) + @handler.expects(:signal).times(2).returns('USR1') @handler.expects(:exit_handler).never @handler.expects(:reload!).never @@ -172,7 +190,7 @@ def test_interrupted_via_USR1_when_not_in_request def test_interrupted_via_USR1_when_in_request cgi = mock FCGI.expects(:each_cgi).once.yields(cgi) - Dispatcher.expects(:dispatch).with(cgi).returns( lambda { Process.kill 'USR1', $$ } ) + Dispatcher.expects(:signal).times(2).returns('USR1') @handler.expects(:reload!).never @handler.expects(:close_connection).with(cgi).once @@ -185,7 +203,7 @@ def test_interrupted_via_USR1_when_in_request def test_restart_via_USR2_when_in_request cgi = mock FCGI.expects(:each_cgi).once.yields(cgi) - @handler.expects(:gc_countdown).returns( lambda { Process.kill 'USR2', $$ } ) + @handler.expects(:signal).times(2).returns('USR2') @handler.expects(:exit_handler).never @handler.expects(:reload!).never @@ -200,7 +218,7 @@ def test_restart_via_USR2_when_in_request def test_interrupted_via_TERM cgi = mock FCGI.expects(:each_cgi).once.yields(cgi) - Dispatcher.expects(:dispatch).with(cgi).returns(lambda { Process.kill 'TERM', $$ }) + Dispatcher.expects(:signal).times(2).returns('TERM') @handler.expects(:reload!).never @handler.expects(:close_connection).never From 1642b2362ecd627c5bdd9965ff3d527a95e2b244 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 21 Apr 2008 12:23:15 -0500 Subject: [PATCH 32/48] Gem dependencies don't require a version. Also fixed up failing gem dependency tests. --- railties/lib/rails/gem_dependency.rb | 4 +--- railties/test/gem_dependency_test.rb | 4 ++++ 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/railties/lib/rails/gem_dependency.rb b/railties/lib/rails/gem_dependency.rb index 3985443ceb391..2034841cd2dac 100644 --- a/railties/lib/rails/gem_dependency.rb +++ b/railties/lib/rails/gem_dependency.rb @@ -13,11 +13,9 @@ def initialize(name, options = {}) @requirement = options[:requirement] elsif options[:version] @requirement = Gem::Requirement.create(options[:version]) - else - raise ArgumentError.new('Must pass either :version or :requirement') end - @version = @requirement.instance_variable_get("@requirements").first.last if @requirement + @version = @requirement.instance_variable_get("@requirements").first.last if @requirement @name = name.to_s @lib = options[:lib] @source = options[:source] diff --git a/railties/test/gem_dependency_test.rb b/railties/test/gem_dependency_test.rb index 887ad535893fb..3ae01893277e6 100644 --- a/railties/test/gem_dependency_test.rb +++ b/railties/test/gem_dependency_test.rb @@ -1,5 +1,9 @@ require 'plugin_test_helper' +class Rails::GemDependency + public :install_command, :unpack_command +end + uses_mocha "Plugin Tests" do class GemDependencyTest < Test::Unit::TestCase def setup From eef9002968609a0d8d4a8006aebcd6f18f993f4a Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 21 Apr 2008 13:24:38 -0500 Subject: [PATCH 33/48] Update plugin loading tests to reflect changes in plugin fixtures. --- railties/test/initializer_test.rb | 49 ++++++++------- railties/test/plugin_loader_test.rb | 89 ++++++++++++++-------------- railties/test/plugin_locator_test.rb | 27 ++++----- 3 files changed, 79 insertions(+), 86 deletions(-) diff --git a/railties/test/initializer_test.rb b/railties/test/initializer_test.rb index 0df0164ca673a..31b3255610b24 100644 --- a/railties/test/initializer_test.rb +++ b/railties/test/initializer_test.rb @@ -38,27 +38,27 @@ def setup end config.after_initialize do $test_after_initialize_block2 = "congratulations" - end + end assert_nil $test_after_initialize_block1 - assert_nil $test_after_initialize_block2 + assert_nil $test_after_initialize_block2 Rails::Initializer.run(:after_initialize, config) end - + def teardown $test_after_initialize_block1 = nil - $test_after_initialize_block2 = nil + $test_after_initialize_block2 = nil end def test_should_have_called_the_first_after_initialize_block assert_equal "success", $test_after_initialize_block1 end - + def test_should_have_called_the_second_after_initialize_block assert_equal "congratulations", $test_after_initialize_block2 end end - + class Initializer_after_initialize_with_no_block_environment_Test < Test::Unit::TestCase def setup @@ -69,7 +69,7 @@ def setup config.after_initialize # don't pass a block, this is what we're testing! config.after_initialize do $test_after_initialize_block2 = "congratulations" - end + end assert_nil $test_after_initialize_block1 Rails::Initializer.run(:after_initialize, config) @@ -77,7 +77,7 @@ def setup def teardown $test_after_initialize_block1 = nil - $test_after_initialize_block2 = nil + $test_after_initialize_block2 = nil end def test_should_have_called_the_first_after_initialize_block @@ -95,7 +95,7 @@ class ConfigurationFrameworkPathsTests < Test::Unit::TestCase def setup @config = Rails::Configuration.new @config.frameworks.clear - + File.stubs(:directory?).returns(true) @config.stubs(:framework_root_path).returns('') end @@ -112,7 +112,7 @@ def test_minimal def test_actioncontroller_or_actionview_add_actionpack @config.frameworks << :action_controller assert_framework_path '/actionpack/lib' - + @config.frameworks = [:action_view] assert_framework_path '/actionpack/lib' end @@ -162,7 +162,7 @@ def test_no_plugins_are_loaded_if_the_configuration_has_an_empty_plugin_list end def test_only_the_specified_plugins_are_located_in_the_order_listed - plugin_names = [:plugin_with_no_lib_dir, :acts_as_chunky_bacon] + plugin_names = [:plugin_with_no_lib_dir] only_load_the_following_plugins! plugin_names load_plugins! assert_plugins plugin_names, @initializer.loaded_plugins @@ -171,27 +171,27 @@ def test_only_the_specified_plugins_are_located_in_the_order_listed def test_all_plugins_are_loaded_when_registered_plugin_list_is_untouched failure_tip = "It's likely someone has added a new plugin fixture without updating this list" load_plugins! - assert_plugins [:a, :acts_as_chunky_bacon, :plugin_with_no_lib_dir, :stubby], @initializer.loaded_plugins, failure_tip + assert_plugins [:plugin_with_no_lib_dir, :stubby], @initializer.loaded_plugins, failure_tip end def test_all_plugins_loaded_when_all_is_used - plugin_names = [:stubby, :acts_as_chunky_bacon, :all] + plugin_names = [:stubby, :all] only_load_the_following_plugins! plugin_names load_plugins! failure_tip = "It's likely someone has added a new plugin fixture without updating this list" - assert_plugins [:stubby, :acts_as_chunky_bacon, :a, :plugin_with_no_lib_dir], @initializer.loaded_plugins, failure_tip + assert_plugins [:stubby, :plugin_with_no_lib_dir], @initializer.loaded_plugins, failure_tip end def test_all_plugins_loaded_after_all - plugin_names = [:stubby, :all, :acts_as_chunky_bacon] + plugin_names = [:all, :stubby] only_load_the_following_plugins! plugin_names load_plugins! failure_tip = "It's likely someone has added a new plugin fixture without updating this list" - assert_plugins [:stubby, :a, :plugin_with_no_lib_dir, :acts_as_chunky_bacon], @initializer.loaded_plugins, failure_tip + assert_plugins [:plugin_with_no_lib_dir, :stubby], @initializer.loaded_plugins, failure_tip end def test_plugin_names_may_be_strings - plugin_names = ['stubby', 'acts_as_chunky_bacon', :a, :plugin_with_no_lib_dir] + plugin_names = ['stubby', :plugin_with_no_lib_dir] only_load_the_following_plugins! plugin_names load_plugins! failure_tip = "It's likely someone has added a new plugin fixture without updating this list" @@ -204,22 +204,21 @@ def test_registering_a_plugin_name_that_does_not_exist_raises_a_load_error load_plugins! end end - + def test_should_ensure_all_loaded_plugins_load_paths_are_added_to_the_load_path - only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon] + only_load_the_following_plugins! [:stubby] @initializer.add_plugin_load_paths - + assert $LOAD_PATH.include?(File.join(plugin_fixture_path('default/stubby'), 'lib')) - assert $LOAD_PATH.include?(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib')) end - + private - + def load_plugins! @initializer.add_plugin_load_paths @initializer.load_plugins end end - -end + +end diff --git a/railties/test/plugin_loader_test.rb b/railties/test/plugin_loader_test.rb index 30fcacbaa1971..09d15a577ade3 100644 --- a/railties/test/plugin_loader_test.rb +++ b/railties/test/plugin_loader_test.rb @@ -11,18 +11,18 @@ def self.configuration class TestPluginLoader < Test::Unit::TestCase ORIGINAL_LOAD_PATH = $LOAD_PATH.dup - + def setup reset_load_path! - + @configuration = Rails::Configuration.new @configuration.plugin_paths << plugin_fixture_root_path @initializer = Rails::Initializer.new(@configuration) @valid_plugin_path = plugin_fixture_path('default/stubby') @empty_plugin_path = plugin_fixture_path('default/empty') - + @failure_tip = "It's likely someone has added a new plugin fixture without updating this list" - + @loader = Rails::Plugin::Loader.new(@initializer) end @@ -34,109 +34,106 @@ def test_should_locate_plugins_by_asking_each_locator_specifed_in_configuration_ @configuration.plugin_locators = [locator_class_1, locator_class_2] assert_equal [:a, :b, :c, :d, :e, :f], @loader.send(:locate_plugins) end - + def test_should_memoize_the_result_of_locate_plugins_as_all_plugins plugin_list = [:a, :b, :c] @loader.expects(:locate_plugins).once.returns(plugin_list) assert_equal plugin_list, @loader.all_plugins assert_equal plugin_list, @loader.all_plugins # ensuring that locate_plugins isn't called again end - + def test_should_return_empty_array_if_configuration_plugins_is_empty @configuration.plugins = [] assert_equal [], @loader.plugins end - + def test_should_find_all_availble_plugins_and_return_as_all_plugins - assert_plugins [:a, :acts_as_chunky_bacon, :plugin_with_no_lib_dir, :stubby], @loader.all_plugins.reverse, @failure_tip + assert_plugins [:stubby, :plugin_with_no_lib_dir], @loader.all_plugins.reverse, @failure_tip end def test_should_return_all_plugins_as_plugins_when_registered_plugin_list_is_untouched - assert_plugins [:a, :acts_as_chunky_bacon, :plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip + assert_plugins [:plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip end - + def test_should_return_all_plugins_as_plugins_when_registered_plugin_list_is_nil @configuration.plugins = nil - assert_plugins [:a, :acts_as_chunky_bacon, :plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip + assert_plugins [:plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip end def test_should_return_specific_plugins_named_in_config_plugins_array_if_set - plugin_names = [:acts_as_chunky_bacon, :stubby] + plugin_names = [:stubby] only_load_the_following_plugins! plugin_names assert_plugins plugin_names, @loader.plugins end - + def test_should_respect_the_order_of_plugins_given_in_configuration - plugin_names = [:stubby, :acts_as_chunky_bacon] + plugin_names = [:stubby] only_load_the_following_plugins! plugin_names - assert_plugins plugin_names, @loader.plugins + assert_plugins plugin_names, @loader.plugins end - + def test_should_load_all_plugins_in_natural_order_when_all_is_used only_load_the_following_plugins! [:all] - assert_plugins [:a, :acts_as_chunky_bacon, :plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip + assert_plugins [:plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip end - + def test_should_load_specified_plugins_in_order_and_then_all_remaining_plugins_when_all_is_used - only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon, :all] - assert_plugins [:stubby, :acts_as_chunky_bacon, :a, :plugin_with_no_lib_dir], @loader.plugins, @failure_tip + only_load_the_following_plugins! [:stubby, :all] + assert_plugins [:stubby, :plugin_with_no_lib_dir], @loader.plugins, @failure_tip end - + def test_should_be_able_to_specify_loading_of_plugins_loaded_after_all - only_load_the_following_plugins! [:stubby, :all, :acts_as_chunky_bacon] - assert_plugins [:stubby, :a, :plugin_with_no_lib_dir, :acts_as_chunky_bacon], @loader.plugins, @failure_tip + only_load_the_following_plugins! [:stubby, :all] + assert_plugins [:stubby, :plugin_with_no_lib_dir], @loader.plugins, @failure_tip end def test_should_accept_plugin_names_given_as_strings - only_load_the_following_plugins! ['stubby', 'acts_as_chunky_bacon', :a, :plugin_with_no_lib_dir] - assert_plugins [:stubby, :acts_as_chunky_bacon, :a, :plugin_with_no_lib_dir], @loader.plugins, @failure_tip + only_load_the_following_plugins! ['stubby', :plugin_with_no_lib_dir] + assert_plugins [:stubby, :plugin_with_no_lib_dir], @loader.plugins, @failure_tip end - + def test_should_add_plugin_load_paths_to_global_LOAD_PATH_array - only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon] + only_load_the_following_plugins! [:stubby] stubbed_application_lib_index_in_LOAD_PATHS = 5 @loader.stubs(:application_lib_index).returns(stubbed_application_lib_index_in_LOAD_PATHS) - + @loader.add_plugin_load_paths - + assert $LOAD_PATH.index(File.join(plugin_fixture_path('default/stubby'), 'lib')) >= stubbed_application_lib_index_in_LOAD_PATHS - assert $LOAD_PATH.index(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib')) >= stubbed_application_lib_index_in_LOAD_PATHS - end - + end + def test_should_add_plugin_load_paths_to_Dependencies_load_paths - only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon] + only_load_the_following_plugins! [:stubby] @loader.add_plugin_load_paths - + assert Dependencies.load_paths.include?(File.join(plugin_fixture_path('default/stubby'), 'lib')) - assert Dependencies.load_paths.include?(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib')) end - + def test_should_add_plugin_load_paths_to_Dependencies_load_once_paths - only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon] + only_load_the_following_plugins! [:stubby] @loader.add_plugin_load_paths - + assert Dependencies.load_once_paths.include?(File.join(plugin_fixture_path('default/stubby'), 'lib')) - assert Dependencies.load_once_paths.include?(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib')) end - + def test_should_add_all_load_paths_from_a_plugin_to_LOAD_PATH_array plugin_load_paths = ["a", "b"] plugin = stub(:load_paths => plugin_load_paths) @loader.stubs(:plugins).returns([plugin]) - + @loader.add_plugin_load_paths - + plugin_load_paths.each { |path| assert $LOAD_PATH.include?(path) } end - + private - + def reset_load_path! $LOAD_PATH.clear - ORIGINAL_LOAD_PATH.each { |path| $LOAD_PATH << path } + ORIGINAL_LOAD_PATH.each { |path| $LOAD_PATH << path } end end - + end diff --git a/railties/test/plugin_locator_test.rb b/railties/test/plugin_locator_test.rb index 5f1dd991eabe9..a7a76e1cd0176 100644 --- a/railties/test/plugin_locator_test.rb +++ b/railties/test/plugin_locator_test.rb @@ -3,13 +3,13 @@ uses_mocha "Plugin Locator Tests" do class PluginLocatorTest < Test::Unit::TestCase - + def test_should_require_subclasses_to_implement_the_plugins_method assert_raises(RuntimeError) do Rails::Plugin::Locator.new(nil).plugins end end - + def test_should_iterator_over_plugins_returned_by_plugins_when_calling_each locator = Rails::Plugin::Locator.new(nil) locator.stubs(:plugins).returns([:a, :b, :c]) @@ -17,12 +17,12 @@ def test_should_iterator_over_plugins_returned_by_plugins_when_calling_each plugin_consumer.expects(:consume).with(:a) plugin_consumer.expects(:consume).with(:b) plugin_consumer.expects(:consume).with(:c) - + locator.each do |plugin| plugin_consumer.consume(plugin) end end - + end @@ -39,25 +39,22 @@ def setup end def test_should_return_rails_plugin_instances_when_calling_create_plugin_with_a_valid_plugin_directory - assert_kind_of Rails::Plugin, @locator.send(:create_plugin, @valid_plugin_path) + assert_kind_of Rails::Plugin, @locator.send(:create_plugin, @valid_plugin_path) end - + def test_should_return_nil_when_calling_create_plugin_with_an_invalid_plugin_directory - assert_nil @locator.send(:create_plugin, @empty_plugin_path) + assert_nil @locator.send(:create_plugin, @empty_plugin_path) end - + def test_should_return_all_plugins_found_under_the_set_plugin_paths - assert_equal ["a", "acts_as_chunky_bacon", "plugin_with_no_lib_dir", "stubby"].sort, @locator.plugins.map(&:name).sort + assert_equal ["plugin_with_no_lib_dir", "stubby"].sort, @locator.plugins.map(&:name).sort end - + def test_should_find_plugins_only_under_the_plugin_paths_set_in_configuration @configuration.plugin_paths = [File.join(plugin_fixture_root_path, "default")] - assert_equal ["acts_as_chunky_bacon", "plugin_with_no_lib_dir", "stubby"].sort, @locator.plugins.map(&:name).sort - - @configuration.plugin_paths = [File.join(plugin_fixture_root_path, "alternate")] - assert_equal ["a"], @locator.plugins.map(&:name) + assert_equal ["plugin_with_no_lib_dir", "stubby"].sort, @locator.plugins.map(&:name).sort end - + def test_should_not_raise_any_error_and_return_no_plugins_if_the_plugin_path_value_does_not_exist @configuration.plugin_paths = ["some_missing_directory"] assert_nothing_raised do From 1d09ccd949eb113601ee84c10a508d36c63c62b7 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 21 Apr 2008 13:27:19 -0500 Subject: [PATCH 34/48] Revert "Update plugin loading tests to reflect changes in plugin fixtures." This reverts commit eef9002968609a0d8d4a8006aebcd6f18f993f4a. --- railties/test/initializer_test.rb | 49 +++++++-------- railties/test/plugin_loader_test.rb | 89 ++++++++++++++-------------- railties/test/plugin_locator_test.rb | 27 +++++---- 3 files changed, 86 insertions(+), 79 deletions(-) diff --git a/railties/test/initializer_test.rb b/railties/test/initializer_test.rb index 31b3255610b24..0df0164ca673a 100644 --- a/railties/test/initializer_test.rb +++ b/railties/test/initializer_test.rb @@ -38,27 +38,27 @@ def setup end config.after_initialize do $test_after_initialize_block2 = "congratulations" - end + end assert_nil $test_after_initialize_block1 - assert_nil $test_after_initialize_block2 + assert_nil $test_after_initialize_block2 Rails::Initializer.run(:after_initialize, config) end - + def teardown $test_after_initialize_block1 = nil - $test_after_initialize_block2 = nil + $test_after_initialize_block2 = nil end def test_should_have_called_the_first_after_initialize_block assert_equal "success", $test_after_initialize_block1 end - + def test_should_have_called_the_second_after_initialize_block assert_equal "congratulations", $test_after_initialize_block2 end end - + class Initializer_after_initialize_with_no_block_environment_Test < Test::Unit::TestCase def setup @@ -69,7 +69,7 @@ def setup config.after_initialize # don't pass a block, this is what we're testing! config.after_initialize do $test_after_initialize_block2 = "congratulations" - end + end assert_nil $test_after_initialize_block1 Rails::Initializer.run(:after_initialize, config) @@ -77,7 +77,7 @@ def setup def teardown $test_after_initialize_block1 = nil - $test_after_initialize_block2 = nil + $test_after_initialize_block2 = nil end def test_should_have_called_the_first_after_initialize_block @@ -95,7 +95,7 @@ class ConfigurationFrameworkPathsTests < Test::Unit::TestCase def setup @config = Rails::Configuration.new @config.frameworks.clear - + File.stubs(:directory?).returns(true) @config.stubs(:framework_root_path).returns('') end @@ -112,7 +112,7 @@ def test_minimal def test_actioncontroller_or_actionview_add_actionpack @config.frameworks << :action_controller assert_framework_path '/actionpack/lib' - + @config.frameworks = [:action_view] assert_framework_path '/actionpack/lib' end @@ -162,7 +162,7 @@ def test_no_plugins_are_loaded_if_the_configuration_has_an_empty_plugin_list end def test_only_the_specified_plugins_are_located_in_the_order_listed - plugin_names = [:plugin_with_no_lib_dir] + plugin_names = [:plugin_with_no_lib_dir, :acts_as_chunky_bacon] only_load_the_following_plugins! plugin_names load_plugins! assert_plugins plugin_names, @initializer.loaded_plugins @@ -171,27 +171,27 @@ def test_only_the_specified_plugins_are_located_in_the_order_listed def test_all_plugins_are_loaded_when_registered_plugin_list_is_untouched failure_tip = "It's likely someone has added a new plugin fixture without updating this list" load_plugins! - assert_plugins [:plugin_with_no_lib_dir, :stubby], @initializer.loaded_plugins, failure_tip + assert_plugins [:a, :acts_as_chunky_bacon, :plugin_with_no_lib_dir, :stubby], @initializer.loaded_plugins, failure_tip end def test_all_plugins_loaded_when_all_is_used - plugin_names = [:stubby, :all] + plugin_names = [:stubby, :acts_as_chunky_bacon, :all] only_load_the_following_plugins! plugin_names load_plugins! failure_tip = "It's likely someone has added a new plugin fixture without updating this list" - assert_plugins [:stubby, :plugin_with_no_lib_dir], @initializer.loaded_plugins, failure_tip + assert_plugins [:stubby, :acts_as_chunky_bacon, :a, :plugin_with_no_lib_dir], @initializer.loaded_plugins, failure_tip end def test_all_plugins_loaded_after_all - plugin_names = [:all, :stubby] + plugin_names = [:stubby, :all, :acts_as_chunky_bacon] only_load_the_following_plugins! plugin_names load_plugins! failure_tip = "It's likely someone has added a new plugin fixture without updating this list" - assert_plugins [:plugin_with_no_lib_dir, :stubby], @initializer.loaded_plugins, failure_tip + assert_plugins [:stubby, :a, :plugin_with_no_lib_dir, :acts_as_chunky_bacon], @initializer.loaded_plugins, failure_tip end def test_plugin_names_may_be_strings - plugin_names = ['stubby', :plugin_with_no_lib_dir] + plugin_names = ['stubby', 'acts_as_chunky_bacon', :a, :plugin_with_no_lib_dir] only_load_the_following_plugins! plugin_names load_plugins! failure_tip = "It's likely someone has added a new plugin fixture without updating this list" @@ -204,21 +204,22 @@ def test_registering_a_plugin_name_that_does_not_exist_raises_a_load_error load_plugins! end end - + def test_should_ensure_all_loaded_plugins_load_paths_are_added_to_the_load_path - only_load_the_following_plugins! [:stubby] + only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon] @initializer.add_plugin_load_paths - + assert $LOAD_PATH.include?(File.join(plugin_fixture_path('default/stubby'), 'lib')) + assert $LOAD_PATH.include?(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib')) end - + private - + def load_plugins! @initializer.add_plugin_load_paths @initializer.load_plugins end end - -end + +end diff --git a/railties/test/plugin_loader_test.rb b/railties/test/plugin_loader_test.rb index 09d15a577ade3..30fcacbaa1971 100644 --- a/railties/test/plugin_loader_test.rb +++ b/railties/test/plugin_loader_test.rb @@ -11,18 +11,18 @@ def self.configuration class TestPluginLoader < Test::Unit::TestCase ORIGINAL_LOAD_PATH = $LOAD_PATH.dup - + def setup reset_load_path! - + @configuration = Rails::Configuration.new @configuration.plugin_paths << plugin_fixture_root_path @initializer = Rails::Initializer.new(@configuration) @valid_plugin_path = plugin_fixture_path('default/stubby') @empty_plugin_path = plugin_fixture_path('default/empty') - + @failure_tip = "It's likely someone has added a new plugin fixture without updating this list" - + @loader = Rails::Plugin::Loader.new(@initializer) end @@ -34,106 +34,109 @@ def test_should_locate_plugins_by_asking_each_locator_specifed_in_configuration_ @configuration.plugin_locators = [locator_class_1, locator_class_2] assert_equal [:a, :b, :c, :d, :e, :f], @loader.send(:locate_plugins) end - + def test_should_memoize_the_result_of_locate_plugins_as_all_plugins plugin_list = [:a, :b, :c] @loader.expects(:locate_plugins).once.returns(plugin_list) assert_equal plugin_list, @loader.all_plugins assert_equal plugin_list, @loader.all_plugins # ensuring that locate_plugins isn't called again end - + def test_should_return_empty_array_if_configuration_plugins_is_empty @configuration.plugins = [] assert_equal [], @loader.plugins end - + def test_should_find_all_availble_plugins_and_return_as_all_plugins - assert_plugins [:stubby, :plugin_with_no_lib_dir], @loader.all_plugins.reverse, @failure_tip + assert_plugins [:a, :acts_as_chunky_bacon, :plugin_with_no_lib_dir, :stubby], @loader.all_plugins.reverse, @failure_tip end def test_should_return_all_plugins_as_plugins_when_registered_plugin_list_is_untouched - assert_plugins [:plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip + assert_plugins [:a, :acts_as_chunky_bacon, :plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip end - + def test_should_return_all_plugins_as_plugins_when_registered_plugin_list_is_nil @configuration.plugins = nil - assert_plugins [:plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip + assert_plugins [:a, :acts_as_chunky_bacon, :plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip end def test_should_return_specific_plugins_named_in_config_plugins_array_if_set - plugin_names = [:stubby] + plugin_names = [:acts_as_chunky_bacon, :stubby] only_load_the_following_plugins! plugin_names assert_plugins plugin_names, @loader.plugins end - + def test_should_respect_the_order_of_plugins_given_in_configuration - plugin_names = [:stubby] + plugin_names = [:stubby, :acts_as_chunky_bacon] only_load_the_following_plugins! plugin_names - assert_plugins plugin_names, @loader.plugins + assert_plugins plugin_names, @loader.plugins end - + def test_should_load_all_plugins_in_natural_order_when_all_is_used only_load_the_following_plugins! [:all] - assert_plugins [:plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip + assert_plugins [:a, :acts_as_chunky_bacon, :plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip end - + def test_should_load_specified_plugins_in_order_and_then_all_remaining_plugins_when_all_is_used - only_load_the_following_plugins! [:stubby, :all] - assert_plugins [:stubby, :plugin_with_no_lib_dir], @loader.plugins, @failure_tip + only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon, :all] + assert_plugins [:stubby, :acts_as_chunky_bacon, :a, :plugin_with_no_lib_dir], @loader.plugins, @failure_tip end - + def test_should_be_able_to_specify_loading_of_plugins_loaded_after_all - only_load_the_following_plugins! [:stubby, :all] - assert_plugins [:stubby, :plugin_with_no_lib_dir], @loader.plugins, @failure_tip + only_load_the_following_plugins! [:stubby, :all, :acts_as_chunky_bacon] + assert_plugins [:stubby, :a, :plugin_with_no_lib_dir, :acts_as_chunky_bacon], @loader.plugins, @failure_tip end def test_should_accept_plugin_names_given_as_strings - only_load_the_following_plugins! ['stubby', :plugin_with_no_lib_dir] - assert_plugins [:stubby, :plugin_with_no_lib_dir], @loader.plugins, @failure_tip + only_load_the_following_plugins! ['stubby', 'acts_as_chunky_bacon', :a, :plugin_with_no_lib_dir] + assert_plugins [:stubby, :acts_as_chunky_bacon, :a, :plugin_with_no_lib_dir], @loader.plugins, @failure_tip end - + def test_should_add_plugin_load_paths_to_global_LOAD_PATH_array - only_load_the_following_plugins! [:stubby] + only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon] stubbed_application_lib_index_in_LOAD_PATHS = 5 @loader.stubs(:application_lib_index).returns(stubbed_application_lib_index_in_LOAD_PATHS) - + @loader.add_plugin_load_paths - + assert $LOAD_PATH.index(File.join(plugin_fixture_path('default/stubby'), 'lib')) >= stubbed_application_lib_index_in_LOAD_PATHS - end - + assert $LOAD_PATH.index(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib')) >= stubbed_application_lib_index_in_LOAD_PATHS + end + def test_should_add_plugin_load_paths_to_Dependencies_load_paths - only_load_the_following_plugins! [:stubby] + only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon] @loader.add_plugin_load_paths - + assert Dependencies.load_paths.include?(File.join(plugin_fixture_path('default/stubby'), 'lib')) + assert Dependencies.load_paths.include?(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib')) end - + def test_should_add_plugin_load_paths_to_Dependencies_load_once_paths - only_load_the_following_plugins! [:stubby] + only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon] @loader.add_plugin_load_paths - + assert Dependencies.load_once_paths.include?(File.join(plugin_fixture_path('default/stubby'), 'lib')) + assert Dependencies.load_once_paths.include?(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib')) end - + def test_should_add_all_load_paths_from_a_plugin_to_LOAD_PATH_array plugin_load_paths = ["a", "b"] plugin = stub(:load_paths => plugin_load_paths) @loader.stubs(:plugins).returns([plugin]) - + @loader.add_plugin_load_paths - + plugin_load_paths.each { |path| assert $LOAD_PATH.include?(path) } end - + private - + def reset_load_path! $LOAD_PATH.clear - ORIGINAL_LOAD_PATH.each { |path| $LOAD_PATH << path } + ORIGINAL_LOAD_PATH.each { |path| $LOAD_PATH << path } end end - + end diff --git a/railties/test/plugin_locator_test.rb b/railties/test/plugin_locator_test.rb index a7a76e1cd0176..5f1dd991eabe9 100644 --- a/railties/test/plugin_locator_test.rb +++ b/railties/test/plugin_locator_test.rb @@ -3,13 +3,13 @@ uses_mocha "Plugin Locator Tests" do class PluginLocatorTest < Test::Unit::TestCase - + def test_should_require_subclasses_to_implement_the_plugins_method assert_raises(RuntimeError) do Rails::Plugin::Locator.new(nil).plugins end end - + def test_should_iterator_over_plugins_returned_by_plugins_when_calling_each locator = Rails::Plugin::Locator.new(nil) locator.stubs(:plugins).returns([:a, :b, :c]) @@ -17,12 +17,12 @@ def test_should_iterator_over_plugins_returned_by_plugins_when_calling_each plugin_consumer.expects(:consume).with(:a) plugin_consumer.expects(:consume).with(:b) plugin_consumer.expects(:consume).with(:c) - + locator.each do |plugin| plugin_consumer.consume(plugin) end end - + end @@ -39,22 +39,25 @@ def setup end def test_should_return_rails_plugin_instances_when_calling_create_plugin_with_a_valid_plugin_directory - assert_kind_of Rails::Plugin, @locator.send(:create_plugin, @valid_plugin_path) + assert_kind_of Rails::Plugin, @locator.send(:create_plugin, @valid_plugin_path) end - + def test_should_return_nil_when_calling_create_plugin_with_an_invalid_plugin_directory - assert_nil @locator.send(:create_plugin, @empty_plugin_path) + assert_nil @locator.send(:create_plugin, @empty_plugin_path) end - + def test_should_return_all_plugins_found_under_the_set_plugin_paths - assert_equal ["plugin_with_no_lib_dir", "stubby"].sort, @locator.plugins.map(&:name).sort + assert_equal ["a", "acts_as_chunky_bacon", "plugin_with_no_lib_dir", "stubby"].sort, @locator.plugins.map(&:name).sort end - + def test_should_find_plugins_only_under_the_plugin_paths_set_in_configuration @configuration.plugin_paths = [File.join(plugin_fixture_root_path, "default")] - assert_equal ["plugin_with_no_lib_dir", "stubby"].sort, @locator.plugins.map(&:name).sort + assert_equal ["acts_as_chunky_bacon", "plugin_with_no_lib_dir", "stubby"].sort, @locator.plugins.map(&:name).sort + + @configuration.plugin_paths = [File.join(plugin_fixture_root_path, "alternate")] + assert_equal ["a"], @locator.plugins.map(&:name) end - + def test_should_not_raise_any_error_and_return_no_plugins_if_the_plugin_path_value_does_not_exist @configuration.plugin_paths = ["some_missing_directory"] assert_nothing_raised do From 4ac33de4d61efe27454bbced7aece88604508bf1 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 21 Apr 2008 13:48:44 -0500 Subject: [PATCH 35/48] Add back empty plugin folders that were lost when we moved to git. --- .../fixtures/plugins/alternate/a/lib/a.rb | 0 .../lib/acts_as_chunky_bacon.rb | 0 .../fixtures/plugins/default/empty/README | 0 railties/test/plugin_loader_test.rb | 64 +++++++++---------- 4 files changed, 32 insertions(+), 32 deletions(-) create mode 100644 railties/test/fixtures/plugins/alternate/a/lib/a.rb create mode 100644 railties/test/fixtures/plugins/default/acts/acts_as_chunky_bacon/lib/acts_as_chunky_bacon.rb create mode 100644 railties/test/fixtures/plugins/default/empty/README diff --git a/railties/test/fixtures/plugins/alternate/a/lib/a.rb b/railties/test/fixtures/plugins/alternate/a/lib/a.rb new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/railties/test/fixtures/plugins/default/acts/acts_as_chunky_bacon/lib/acts_as_chunky_bacon.rb b/railties/test/fixtures/plugins/default/acts/acts_as_chunky_bacon/lib/acts_as_chunky_bacon.rb new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/railties/test/fixtures/plugins/default/empty/README b/railties/test/fixtures/plugins/default/empty/README new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/railties/test/plugin_loader_test.rb b/railties/test/plugin_loader_test.rb index 30fcacbaa1971..41bd6ec7eabae 100644 --- a/railties/test/plugin_loader_test.rb +++ b/railties/test/plugin_loader_test.rb @@ -11,18 +11,18 @@ def self.configuration class TestPluginLoader < Test::Unit::TestCase ORIGINAL_LOAD_PATH = $LOAD_PATH.dup - + def setup reset_load_path! - + @configuration = Rails::Configuration.new @configuration.plugin_paths << plugin_fixture_root_path @initializer = Rails::Initializer.new(@configuration) @valid_plugin_path = plugin_fixture_path('default/stubby') @empty_plugin_path = plugin_fixture_path('default/empty') - + @failure_tip = "It's likely someone has added a new plugin fixture without updating this list" - + @loader = Rails::Plugin::Loader.new(@initializer) end @@ -34,27 +34,27 @@ def test_should_locate_plugins_by_asking_each_locator_specifed_in_configuration_ @configuration.plugin_locators = [locator_class_1, locator_class_2] assert_equal [:a, :b, :c, :d, :e, :f], @loader.send(:locate_plugins) end - + def test_should_memoize_the_result_of_locate_plugins_as_all_plugins plugin_list = [:a, :b, :c] @loader.expects(:locate_plugins).once.returns(plugin_list) assert_equal plugin_list, @loader.all_plugins assert_equal plugin_list, @loader.all_plugins # ensuring that locate_plugins isn't called again end - + def test_should_return_empty_array_if_configuration_plugins_is_empty @configuration.plugins = [] assert_equal [], @loader.plugins end - + def test_should_find_all_availble_plugins_and_return_as_all_plugins - assert_plugins [:a, :acts_as_chunky_bacon, :plugin_with_no_lib_dir, :stubby], @loader.all_plugins.reverse, @failure_tip + assert_plugins [:stubby, :plugin_with_no_lib_dir, :acts_as_chunky_bacon, :a], @loader.all_plugins.reverse, @failure_tip end def test_should_return_all_plugins_as_plugins_when_registered_plugin_list_is_untouched assert_plugins [:a, :acts_as_chunky_bacon, :plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip end - + def test_should_return_all_plugins_as_plugins_when_registered_plugin_list_is_nil @configuration.plugins = nil assert_plugins [:a, :acts_as_chunky_bacon, :plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip @@ -65,23 +65,23 @@ def test_should_return_specific_plugins_named_in_config_plugins_array_if_set only_load_the_following_plugins! plugin_names assert_plugins plugin_names, @loader.plugins end - + def test_should_respect_the_order_of_plugins_given_in_configuration plugin_names = [:stubby, :acts_as_chunky_bacon] only_load_the_following_plugins! plugin_names - assert_plugins plugin_names, @loader.plugins + assert_plugins plugin_names, @loader.plugins end - + def test_should_load_all_plugins_in_natural_order_when_all_is_used only_load_the_following_plugins! [:all] assert_plugins [:a, :acts_as_chunky_bacon, :plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip end - + def test_should_load_specified_plugins_in_order_and_then_all_remaining_plugins_when_all_is_used only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon, :all] assert_plugins [:stubby, :acts_as_chunky_bacon, :a, :plugin_with_no_lib_dir], @loader.plugins, @failure_tip end - + def test_should_be_able_to_specify_loading_of_plugins_loaded_after_all only_load_the_following_plugins! [:stubby, :all, :acts_as_chunky_bacon] assert_plugins [:stubby, :a, :plugin_with_no_lib_dir, :acts_as_chunky_bacon], @loader.plugins, @failure_tip @@ -91,52 +91,52 @@ def test_should_accept_plugin_names_given_as_strings only_load_the_following_plugins! ['stubby', 'acts_as_chunky_bacon', :a, :plugin_with_no_lib_dir] assert_plugins [:stubby, :acts_as_chunky_bacon, :a, :plugin_with_no_lib_dir], @loader.plugins, @failure_tip end - + def test_should_add_plugin_load_paths_to_global_LOAD_PATH_array only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon] stubbed_application_lib_index_in_LOAD_PATHS = 5 @loader.stubs(:application_lib_index).returns(stubbed_application_lib_index_in_LOAD_PATHS) - + @loader.add_plugin_load_paths - + assert $LOAD_PATH.index(File.join(plugin_fixture_path('default/stubby'), 'lib')) >= stubbed_application_lib_index_in_LOAD_PATHS - assert $LOAD_PATH.index(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib')) >= stubbed_application_lib_index_in_LOAD_PATHS - end - + assert $LOAD_PATH.index(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib')) >= stubbed_application_lib_index_in_LOAD_PATHS + end + def test_should_add_plugin_load_paths_to_Dependencies_load_paths only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon] @loader.add_plugin_load_paths - + assert Dependencies.load_paths.include?(File.join(plugin_fixture_path('default/stubby'), 'lib')) - assert Dependencies.load_paths.include?(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib')) + assert Dependencies.load_paths.include?(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib')) end - + def test_should_add_plugin_load_paths_to_Dependencies_load_once_paths only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon] @loader.add_plugin_load_paths - + assert Dependencies.load_once_paths.include?(File.join(plugin_fixture_path('default/stubby'), 'lib')) - assert Dependencies.load_once_paths.include?(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib')) + assert Dependencies.load_once_paths.include?(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib')) end - + def test_should_add_all_load_paths_from_a_plugin_to_LOAD_PATH_array plugin_load_paths = ["a", "b"] plugin = stub(:load_paths => plugin_load_paths) @loader.stubs(:plugins).returns([plugin]) - + @loader.add_plugin_load_paths - + plugin_load_paths.each { |path| assert $LOAD_PATH.include?(path) } end - + private - + def reset_load_path! $LOAD_PATH.clear - ORIGINAL_LOAD_PATH.each { |path| $LOAD_PATH << path } + ORIGINAL_LOAD_PATH.each { |path| $LOAD_PATH << path } end end - + end From 4809dcc1b50330a04ec61dd1fef6cdba9892ac3d Mon Sep 17 00:00:00 2001 From: Cody Fauser Date: Mon, 21 Apr 2008 14:31:54 -0500 Subject: [PATCH 36/48] * Remove default_url_options from mailer generator * Improve mailer documentation regarding generating URLs * Add no_match to mailer generator to warn contributors about default_url_options Signed-off-by: Joshua Peek --- actionmailer/lib/action_mailer/base.rb | 39 +++++++++++++------ .../components/mailer/templates/mailer.rb | 2 - .../generators/rails_mailer_generator_test.rb | 6 +-- 3 files changed, 30 insertions(+), 17 deletions(-) diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb index 8a4f34447c2e6..3dfe828b062ff 100644 --- a/actionmailer/lib/action_mailer/base.rb +++ b/actionmailer/lib/action_mailer/base.rb @@ -73,21 +73,36 @@ module ActionMailer #:nodoc: # <%= truncate(note.body, 25) %> # # - # = Generating URLs for mailer views + # = Generating URLs + # + # URLs can be generated in mailer views using url_for or named routes. + # Unlike controllers from Action Pack, the mailer instance doesn't have any context about the incoming request, + # so you'll need to provide all of the details needed to generate a URL. # - # If your view includes URLs from the application, you need to use url_for in the mailing method instead of the view. - # Unlike controllers from Action Pack, the mailer instance doesn't have any context about the incoming request. That's - # why you need to jump this little hoop and supply all the details needed for the URL. Example: + # When using url_for you'll need to provide the :host, :controller, and :action: + # + # <%= url_for(:host => "example.com", :controller => "welcome", :action => "greeting") %> # - # def signup_notification(recipient) - # recipients recipient.email_address_with_name - # from "system@example.com" - # subject "New account information" - # body :account => recipient, - # :home_page => url_for(:host => "example.com", :controller => "welcome", :action => "greeting") - # end + # When using named routes you only need to supply the :host: + # + # <%= users_url(:host => "example.com") %> + # + # You will want to avoid using the name_of_route_path form of named routes because it doesn't make sense to + # generate relative URLs in email messages. + # + # It is also possible to set a default host that will be used in all mailers by setting the :host option in + # the ActionMailer::Base.default_url_options hash as follows: + # + # ActionMailer::Base.default_url_options[:host] = "example.com" + # + # This can also be set as a configuration option in environment.rb: + # + # config.action_mailer.default_url_options = { :host => "example.com" } # - # You can now access @home_page in the template and get http://example.com/welcome/greeting. + # If you do decide to set a default :host for your mailers you will want to use the + # :only_path => false option when using url_for. This will ensure that absolute URLs are generated because + # the url_for view helper will, by default, generate relative URLs when a :host option isn't + # explicitly provided. # # = Sending mail # diff --git a/railties/lib/rails_generator/generators/components/mailer/templates/mailer.rb b/railties/lib/rails_generator/generators/components/mailer/templates/mailer.rb index 0c7e6bebafd06..ce15ae9de9063 100644 --- a/railties/lib/rails_generator/generators/components/mailer/templates/mailer.rb +++ b/railties/lib/rails_generator/generators/components/mailer/templates/mailer.rb @@ -1,7 +1,5 @@ class <%= class_name %> < ActionMailer::Base - # change to your domain name - default_url_options[:host] = 'example.com' <% for action in actions -%> def <%= action %>(sent_at = Time.now) diff --git a/railties/test/generators/rails_mailer_generator_test.rb b/railties/test/generators/rails_mailer_generator_test.rb index 03170c3b618f8..de61e6736d8b2 100644 --- a/railties/test/generators/rails_mailer_generator_test.rb +++ b/railties/test/generators/rails_mailer_generator_test.rb @@ -17,9 +17,9 @@ def test_generates_mailer ], body.split("\n").map{|line| line.sub(' '*4, '') } end - - assert_match /^ default_url_options\[:host\] = 'example.com'$/m, model, - 'model should include default_url_options :host declaration' + + assert_no_match /(self.default_url_options =|default_url_options\[.*\] =)/, model, + 'individual mailer models should not set default_url_options because the options are shared by all mailers' end assert_generated_views_for :notifier, 'reset_password.erb' From 105910429d5873dce677ef32eef5f705e0625d86 Mon Sep 17 00:00:00 2001 From: Cheah Chu Yeow Date: Sun, 13 Apr 2008 14:40:30 +0800 Subject: [PATCH 37/48] Introduce ActiveResource::Base.timeout. This allows a timeout to be set on the internal Net::HTTP instance ARes uses (default is 60 seconds). Setting a low timeout allows ARes clients to fail-fast in the event of a unresponsive/crashed server, rather than cause cascading failures in your application. Signed-off-by: Michael Koziarski --- activeresource/lib/active_resource/base.rb | 38 ++++++++++- .../lib/active_resource/connection.rb | 12 +++- activeresource/test/base_test.rb | 66 +++++++++++++++++++ activeresource/test/connection_test.rb | 5 ++ 4 files changed, 117 insertions(+), 4 deletions(-) diff --git a/activeresource/lib/active_resource/base.rb b/activeresource/lib/active_resource/base.rb index cd53c5d77157c..4072b9494dffc 100644 --- a/activeresource/lib/active_resource/base.rb +++ b/activeresource/lib/active_resource/base.rb @@ -166,6 +166,26 @@ module ActiveResource # # Learn more about Active Resource's validation features in the ActiveResource::Validations documentation. # + # === Timeouts + # + # Active Resource relies on HTTP to access RESTful APIs and as such is inherently susceptible to slow or + # unresponsive servers. In such cases, your Active Resource method calls could timeout. You can control the + # amount of time before Active Resource times out with the +timeout+ variable. + # + # class Person < ActiveResource::Base + # self.site = "http://api.people.com:3000/" + # self.timeout = 5 + # end + # + # This sets the +timeout+ to 5 seconds. You can adjust the timeout to a value suitable for the RESTful API + # you are accessing. It is recommended to set this to a reasonably low value to allow your Active Resource + # clients (especially if you are using Active Resource in a Rails application) to fail-fast (see + # http://en.wikipedia.org/wiki/Fail-fast) rather than cause cascading failures that could incapacitate your + # server. + # + # Internally, Active Resource relies on Ruby's Net::HTTP library to make HTTP requests. Setting +timeout+ + # sets the read_timeout of the internal Net::HTTP instance to the same value. The default + # read_timeout is 60 seconds on most Ruby implementations. class Base # The logger for diagnosing and tracing Active Resource calls. cattr_accessor :logger @@ -257,12 +277,27 @@ def format=(mime_type_reference_or_format) write_inheritable_attribute("format", format) connection.format = format if site end - + # Returns the current format, default is ActiveResource::Formats::XmlFormat def format # :nodoc: read_inheritable_attribute("format") || ActiveResource::Formats[:xml] end + # Sets the number of seconds after which requests to the REST API should time out. + def timeout=(timeout) + @connection = nil + @timeout = timeout + end + + # Gets tthe number of seconds after which requests to the REST API should time out. + def timeout + if defined?(@timeout) + @timeout + elsif superclass != Object && superclass.timeout + superclass.timeout + end + end + # An instance of ActiveResource::Connection that is the base connection to the remote service. # The +refresh+ parameter toggles whether or not the connection is refreshed at every request # or not (defaults to false). @@ -271,6 +306,7 @@ def connection(refresh = false) @connection = Connection.new(site, format) if refresh || @connection.nil? @connection.user = user if user @connection.password = password if password + @connection.timeout = timeout if timeout @connection else superclass.connection diff --git a/activeresource/lib/active_resource/connection.rb b/activeresource/lib/active_resource/connection.rb index c8cee7aaa3bd6..3b61009f430f1 100644 --- a/activeresource/lib/active_resource/connection.rb +++ b/activeresource/lib/active_resource/connection.rb @@ -55,7 +55,7 @@ def allowed_methods # This class is used by ActiveResource::Base to interface with REST # services. class Connection - attr_reader :site, :user, :password + attr_reader :site, :user, :password, :timeout attr_accessor :format class << self @@ -90,6 +90,11 @@ def password=(password) @password = password end + # Set the number of seconds after which HTTP requests to the remote service should time out. + def timeout=(timeout) + @timeout = timeout + end + # Execute a GET request. # Used to get (find) resources. def get(path, headers = {}) @@ -167,18 +172,19 @@ def http http = Net::HTTP.new(@site.host, @site.port) http.use_ssl = @site.is_a?(URI::HTTPS) http.verify_mode = OpenSSL::SSL::VERIFY_NONE if http.use_ssl + http.read_timeout = @timeout if @timeout # If timeout is not set, the default Net::HTTP timeout (60s) is used. http end def default_header @default_header ||= { 'Content-Type' => format.mime_type } end - + # Builds headers for request to remote service. def build_request_headers(headers) authorization_header.update(default_header).update(headers) end - + # Sets authorization header def authorization_header (@user || @password ? { 'Authorization' => 'Basic ' + ["#{@user}:#{ @password}"].pack('m').delete("\r\n") } : {}) diff --git a/activeresource/test/base_test.rb b/activeresource/test/base_test.rb index 9caca803b7494..9e2f6c1831f5d 100644 --- a/activeresource/test/base_test.rb +++ b/activeresource/test/base_test.rb @@ -88,6 +88,12 @@ def test_should_accept_setting_password assert_equal('test123', Forum.connection.password) end + def test_should_accept_setting_timeout + Forum.timeout = 5 + assert_equal(5, Forum.timeout) + assert_equal(5, Forum.connection.timeout) + end + def test_user_variable_can_be_reset actor = Class.new(ActiveResource::Base) actor.site = 'http://cinema' @@ -108,6 +114,16 @@ def test_password_variable_can_be_reset assert_nil actor.connection.password end + def test_timeout_variable_can_be_reset + actor = Class.new(ActiveResource::Base) + actor.site = 'http://cinema' + assert_nil actor.timeout + actor.timeout = 5 + actor.timeout = nil + assert_nil actor.timeout + assert_nil actor.connection.timeout + end + def test_credentials_from_site_are_decoded actor = Class.new(ActiveResource::Base) actor.site = 'http://my%40email.com:%31%32%33@cinema' @@ -232,6 +248,40 @@ def test_password_reader_uses_superclass_password_until_written assert_equal fruit.password, apple.password, 'subclass did not adopt changes from parent class' end + def test_timeout_reader_uses_superclass_timeout_until_written + # Superclass is Object so returns nil. + assert_nil ActiveResource::Base.timeout + assert_nil Class.new(ActiveResource::Base).timeout + Person.timeout = 5 + + # Subclass uses superclass timeout. + actor = Class.new(Person) + assert_equal Person.timeout, actor.timeout + + # Changing subclass timeout doesn't change superclass timeout. + actor.timeout = 10 + assert_not_equal Person.timeout, actor.timeout + + # Changing superclass timeout doesn't overwrite subclass timeout. + Person.timeout = 15 + assert_not_equal Person.timeout, actor.timeout + + # Changing superclass timeout after subclassing changes subclass timeout. + jester = Class.new(actor) + actor.timeout = 20 + assert_equal actor.timeout, jester.timeout + + # Subclasses are always equal to superclass timeout when not overridden. + fruit = Class.new(ActiveResource::Base) + apple = Class.new(fruit) + + fruit.timeout = 25 + assert_equal fruit.timeout, apple.timeout, 'subclass did not adopt changes from parent class' + + fruit.timeout = 30 + assert_equal fruit.timeout, apple.timeout, 'subclass did not adopt changes from parent class' + end + def test_updating_baseclass_site_object_wipes_descendent_cached_connection_objects # Subclasses are always equal to superclass site when not overridden fruit = Class.new(ActiveResource::Base) @@ -279,6 +329,22 @@ def test_updating_baseclass_password_wipes_descendent_cached_connection_objects assert_not_equal(first_connection, second_connection, 'Connection should be re-created') end + def test_updating_baseclass_timeout_wipes_descendent_cached_connection_objects + # Subclasses are always equal to superclass timeout when not overridden + fruit = Class.new(ActiveResource::Base) + apple = Class.new(fruit) + fruit.site = 'http://market' + + fruit.timeout = 5 + assert_equal fruit.connection.timeout, apple.connection.timeout + first_connection = apple.connection.object_id + + fruit.timeout = 10 + assert_equal fruit.connection.timeout, apple.connection.timeout + second_connection = apple.connection.object_id + assert_not_equal(first_connection, second_connection, 'Connection should be re-created') + end + def test_collection_name assert_equal "people", Person.collection_name end diff --git a/activeresource/test/connection_test.rb b/activeresource/test/connection_test.rb index 38fdbd3b2f9e5..6c907614e786e 100644 --- a/activeresource/test/connection_test.rb +++ b/activeresource/test/connection_test.rb @@ -101,6 +101,11 @@ def test_site_accessor_accepts_uri_or_string_argument assert_equal site, @conn.site end + def test_timeout_accessor + @conn.timeout = 5 + assert_equal 5, @conn.timeout + end + def test_get matz = @conn.get("/people/1.xml") assert_equal "Matz", matz["name"] From cf32baf915442ffe153ec0e4d8148f147776c30a Mon Sep 17 00:00:00 2001 From: Cheah Chu Yeow Date: Wed, 16 Apr 2008 18:39:19 +0800 Subject: [PATCH 38/48] Rescue from Timeout::Error in ActiveResource::Connection. Signed-off-by: Michael Koziarski --- activeresource/lib/active_resource/connection.rb | 10 ++++++++++ activeresource/test/abstract_unit.rb | 14 +++++++++++++- activeresource/test/connection_test.rb | 9 +++++++++ 3 files changed, 32 insertions(+), 1 deletion(-) diff --git a/activeresource/lib/active_resource/connection.rb b/activeresource/lib/active_resource/connection.rb index 3b61009f430f1..98b3f87167e60 100644 --- a/activeresource/lib/active_resource/connection.rb +++ b/activeresource/lib/active_resource/connection.rb @@ -18,6 +18,14 @@ def to_s end end + # Raised when a Timeout::Error occurs. + class TimeoutError < ConnectionError + def initialize(message) + @message = message + end + def to_s; @message ;end + end + # 3xx Redirection class Redirection < ConnectionError # :nodoc: def to_s; response['Location'] ? "#{super} => #{response['Location']}" : super; end @@ -134,6 +142,8 @@ def request(method, path, *arguments) time = Benchmark.realtime { result = http.send(method, path, *arguments) } logger.info "--> #{result.code} #{result.message} (#{result.body ? result.body : 0}b %.2fs)" % time if logger handle_response(result) + rescue Timeout::Error => e + raise TimeoutError.new(e.message) end # Handles response and error codes from remote service. diff --git a/activeresource/test/abstract_unit.rb b/activeresource/test/abstract_unit.rb index db1e0b9535655..615a6d922251b 100644 --- a/activeresource/test/abstract_unit.rb +++ b/activeresource/test/abstract_unit.rb @@ -7,4 +7,16 @@ $:.unshift "#{File.dirname(__FILE__)}/../test" require 'setter_trap' -ActiveResource::Base.logger = Logger.new("#{File.dirname(__FILE__)}/debug.log") \ No newline at end of file +ActiveResource::Base.logger = Logger.new("#{File.dirname(__FILE__)}/debug.log") + +# Wrap tests that use Mocha and skip if unavailable. +def uses_mocha(test_name) + unless Object.const_defined?(:Mocha) + require 'mocha' + require 'stubba' + end + yield +rescue LoadError => load_error + raise unless load_error.message =~ /mocha/i + $stderr.puts "Skipping #{test_name} tests. `gem install mocha` and try again." +end \ No newline at end of file diff --git a/activeresource/test/connection_test.rb b/activeresource/test/connection_test.rb index 6c907614e786e..8e43e451ff9f6 100644 --- a/activeresource/test/connection_test.rb +++ b/activeresource/test/connection_test.rb @@ -168,6 +168,15 @@ def test_delete_with_header assert_equal 200, response.code end + uses_mocha('test_timeout') do + def test_timeout + @http = mock('new Net::HTTP') + @conn.expects(:http).returns(@http) + @http.expects(:get).raises(Timeout::Error, 'execution expired') + assert_raises(ActiveResource::TimeoutError) { @conn.get('/people_timeout.xml') } + end + end + protected def assert_response_raises(klass, code) assert_raise(klass, "Expected response code #{code} to raise #{klass}") do From 6ccfc0ebdedb53794c4981521c4299d842caf896 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 21 Apr 2008 19:09:46 -0500 Subject: [PATCH 39/48] Add .empty files to empty directories so git preserves them. --- .../a/lib/a.rb => lib/generators/missing_class/templates/.empty} | 0 .../generators/missing_generator/templates/.empty} | 0 .../empty/README => lib/generators/missing_templates/.empty} | 0 railties/test/fixtures/plugins/alternate/a/lib/.empty | 0 .../fixtures/plugins/default/acts/acts_as_chunky_bacon/lib/.empty | 0 railties/test/fixtures/plugins/default/empty/.empty | 0 6 files changed, 0 insertions(+), 0 deletions(-) rename railties/test/fixtures/{plugins/alternate/a/lib/a.rb => lib/generators/missing_class/templates/.empty} (100%) rename railties/test/fixtures/{plugins/default/acts/acts_as_chunky_bacon/lib/acts_as_chunky_bacon.rb => lib/generators/missing_generator/templates/.empty} (100%) rename railties/test/fixtures/{plugins/default/empty/README => lib/generators/missing_templates/.empty} (100%) create mode 100644 railties/test/fixtures/plugins/alternate/a/lib/.empty create mode 100644 railties/test/fixtures/plugins/default/acts/acts_as_chunky_bacon/lib/.empty create mode 100644 railties/test/fixtures/plugins/default/empty/.empty diff --git a/railties/test/fixtures/plugins/alternate/a/lib/a.rb b/railties/test/fixtures/lib/generators/missing_class/templates/.empty similarity index 100% rename from railties/test/fixtures/plugins/alternate/a/lib/a.rb rename to railties/test/fixtures/lib/generators/missing_class/templates/.empty diff --git a/railties/test/fixtures/plugins/default/acts/acts_as_chunky_bacon/lib/acts_as_chunky_bacon.rb b/railties/test/fixtures/lib/generators/missing_generator/templates/.empty similarity index 100% rename from railties/test/fixtures/plugins/default/acts/acts_as_chunky_bacon/lib/acts_as_chunky_bacon.rb rename to railties/test/fixtures/lib/generators/missing_generator/templates/.empty diff --git a/railties/test/fixtures/plugins/default/empty/README b/railties/test/fixtures/lib/generators/missing_templates/.empty similarity index 100% rename from railties/test/fixtures/plugins/default/empty/README rename to railties/test/fixtures/lib/generators/missing_templates/.empty diff --git a/railties/test/fixtures/plugins/alternate/a/lib/.empty b/railties/test/fixtures/plugins/alternate/a/lib/.empty new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/railties/test/fixtures/plugins/default/acts/acts_as_chunky_bacon/lib/.empty b/railties/test/fixtures/plugins/default/acts/acts_as_chunky_bacon/lib/.empty new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/railties/test/fixtures/plugins/default/empty/.empty b/railties/test/fixtures/plugins/default/empty/.empty new file mode 100644 index 0000000000000..e69de29bb2d1d From de8b0087c61af6c8b1cab7c1760f2e326b996702 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 21 Apr 2008 19:14:37 -0500 Subject: [PATCH 40/48] Don't require generator_test_helper in RailsGeneratorTest. --- railties/test/rails_generator_test.rb | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/railties/test/rails_generator_test.rb b/railties/test/rails_generator_test.rb index e1445e0a20304..b2fc2f585de43 100644 --- a/railties/test/rails_generator_test.rb +++ b/railties/test/rails_generator_test.rb @@ -33,7 +33,16 @@ class InstanceTag; end end $LOAD_PATH.unshift "#{File.dirname(__FILE__)}/../lib" -require 'generators/generator_test_helper' +require 'initializer' + +# Mocks out the configuration +module Rails + def self.configuration + Rails::Configuration.new + end +end + +require 'rails_generator' class RailsGeneratorTest < Test::Unit::TestCase BUILTINS = %w(controller integration_test mailer migration model observer plugin resource scaffold session_migration) @@ -44,9 +53,9 @@ def setup end def test_sources - expected = [:lib, :vendor, + expected = [:lib, :vendor, "plugins (vendor/plugins)".to_sym, # /generators and /rails_generators - :user, + :user, :RubyGems, :RubyGems, # gems named _generator, gems containing /rails_generator/ folder :builtin] expected.delete(:RubyGems) unless Object.const_defined?(:Gem) From 0a94f16b9532894aeb7aed2aec5082dd3b521414 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 21 Apr 2008 19:49:16 -0500 Subject: [PATCH 41/48] Fallback to Ruby's pseudo random number generator if the system does not have SHA512 installed. --- railties/lib/rails_generator/secret_key_generator.rb | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/railties/lib/rails_generator/secret_key_generator.rb b/railties/lib/rails_generator/secret_key_generator.rb index 801b33c761dc3..64fbbb90f81f8 100644 --- a/railties/lib/rails_generator/secret_key_generator.rb +++ b/railties/lib/rails_generator/secret_key_generator.rb @@ -76,7 +76,12 @@ def generate_secret_with_openssl OpenSSL::Random.seed(rand(0).to_s + Time.now.usec.to_s) end data = OpenSSL::BN.rand(2048, -1, false).to_s - return OpenSSL::Digest::SHA512.new(data).hexdigest + + if OpenSSL::OPENSSL_VERSION_NUMBER > 0x00908000 + OpenSSL::Digest::SHA512.new(data).hexdigest + else + generate_secret_with_prng + end end # Generate a random secret key with /dev/urandom. From a4fc93c3a9f59dcd7cf56c6ae1cb1fb749f6678b Mon Sep 17 00:00:00 2001 From: Frederick Cheung Date: Mon, 21 Apr 2008 11:00:01 +0100 Subject: [PATCH 42/48] Use schema.rb for all databases Move adapter specific schema into their own files Signed-off-by: Michael Koziarski --- .../connection_adapters/postgresql_adapter.rb | 2 +- .../test/cases/aaa_create_tables_test.rb | 58 +- .../has_many_through_associations_test.rb | 2 +- activerecord/test/cases/associations_test.rb | 2 +- activerecord/test/cases/base_test.rb | 2 +- activerecord/test/schema/db2.drop.sql | 33 - activerecord/test/schema/db2.sql | 235 ------- activerecord/test/schema/db22.drop.sql | 1 - activerecord/test/schema/db22.sql | 4 - activerecord/test/schema/firebird.drop.sql | 65 -- activerecord/test/schema/firebird.sql | 310 ---------- activerecord/test/schema/firebird2.drop.sql | 2 - activerecord/test/schema/firebird2.sql | 6 - activerecord/test/schema/frontbase.drop.sql | 33 - activerecord/test/schema/frontbase.sql | 273 --------- activerecord/test/schema/frontbase2.drop.sql | 1 - activerecord/test/schema/frontbase2.sql | 4 - .../test/schema/mysql_specific_schema.rb | 12 + activerecord/test/schema/openbase.drop.sql | 2 - activerecord/test/schema/openbase.sql | 318 ---------- activerecord/test/schema/openbase2.drop.sql | 2 - activerecord/test/schema/openbase2.sql | 7 - activerecord/test/schema/oracle.drop.sql | 67 -- activerecord/test/schema/oracle.sql | 330 ---------- activerecord/test/schema/oracle2.drop.sql | 2 - activerecord/test/schema/oracle2.sql | 6 - activerecord/test/schema/postgresql.drop.sql | 44 -- activerecord/test/schema/postgresql.sql | 294 --------- activerecord/test/schema/postgresql2.drop.sql | 1 - activerecord/test/schema/postgresql2.sql | 4 - .../test/schema/postgresql_specific_schema.rb | 103 ++++ activerecord/test/schema/schema.rb | 575 +++++++++--------- activerecord/test/schema/schema2.rb | 9 +- activerecord/test/schema/sqlite.drop.sql | 33 - activerecord/test/schema/sqlite.sql | 219 ------- activerecord/test/schema/sqlite2.drop.sql | 1 - activerecord/test/schema/sqlite2.sql | 4 - .../test/schema/sqlite_specific_schema.rb | 25 + .../test/schema/sqlserver_specific_schema.rb | 5 + activerecord/test/schema/sybase.drop.sql | 35 -- activerecord/test/schema/sybase.sql | 222 ------- activerecord/test/schema/sybase2.drop.sql | 2 - activerecord/test/schema/sybase2.sql | 5 - 43 files changed, 432 insertions(+), 2928 deletions(-) delete mode 100644 activerecord/test/schema/db2.drop.sql delete mode 100644 activerecord/test/schema/db2.sql delete mode 100644 activerecord/test/schema/db22.drop.sql delete mode 100644 activerecord/test/schema/db22.sql delete mode 100644 activerecord/test/schema/firebird.drop.sql delete mode 100644 activerecord/test/schema/firebird.sql delete mode 100644 activerecord/test/schema/firebird2.drop.sql delete mode 100644 activerecord/test/schema/firebird2.sql delete mode 100644 activerecord/test/schema/frontbase.drop.sql delete mode 100644 activerecord/test/schema/frontbase.sql delete mode 100644 activerecord/test/schema/frontbase2.drop.sql delete mode 100644 activerecord/test/schema/frontbase2.sql create mode 100644 activerecord/test/schema/mysql_specific_schema.rb delete mode 100644 activerecord/test/schema/openbase.drop.sql delete mode 100644 activerecord/test/schema/openbase.sql delete mode 100644 activerecord/test/schema/openbase2.drop.sql delete mode 100644 activerecord/test/schema/openbase2.sql delete mode 100644 activerecord/test/schema/oracle.drop.sql delete mode 100644 activerecord/test/schema/oracle.sql delete mode 100644 activerecord/test/schema/oracle2.drop.sql delete mode 100644 activerecord/test/schema/oracle2.sql delete mode 100644 activerecord/test/schema/postgresql.drop.sql delete mode 100644 activerecord/test/schema/postgresql.sql delete mode 100644 activerecord/test/schema/postgresql2.drop.sql delete mode 100644 activerecord/test/schema/postgresql2.sql create mode 100644 activerecord/test/schema/postgresql_specific_schema.rb delete mode 100644 activerecord/test/schema/sqlite.drop.sql delete mode 100644 activerecord/test/schema/sqlite.sql delete mode 100644 activerecord/test/schema/sqlite2.drop.sql delete mode 100644 activerecord/test/schema/sqlite2.sql create mode 100644 activerecord/test/schema/sqlite_specific_schema.rb create mode 100644 activerecord/test/schema/sqlserver_specific_schema.rb delete mode 100644 activerecord/test/schema/sybase.drop.sql delete mode 100644 activerecord/test/schema/sybase.sql delete mode 100644 activerecord/test/schema/sybase2.drop.sql delete mode 100644 activerecord/test/schema/sybase2.sql diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb index 674e92ee29f20..54b50fabd88a4 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb @@ -617,7 +617,7 @@ def reset_pk_sequence!(table, pk = nil, sequence = nil) #:nodoc: quoted_sequence = quote_column_name(sequence) select_value <<-end_sql, 'Reset sequence' - SELECT setval('#{sequence}', (SELECT COALESCE(MAX(#{pk})+(SELECT increment_by FROM #{quoted_sequence}), (SELECT min_value FROM #{quoted_sequence})) FROM #{quote_table_name(table)}), false) + SELECT setval('#{quoted_sequence}', (SELECT COALESCE(MAX(#{quote_column_name pk})+(SELECT increment_by FROM #{quoted_sequence}), (SELECT min_value FROM #{quoted_sequence})) FROM #{quote_table_name(table)}), false) end_sql else @logger.warn "#{table} has primary key #{pk} with no default sequence" if @logger diff --git a/activerecord/test/cases/aaa_create_tables_test.rb b/activerecord/test/cases/aaa_create_tables_test.rb index 32e0d2936ea28..3911afac4940a 100644 --- a/activerecord/test/cases/aaa_create_tables_test.rb +++ b/activerecord/test/cases/aaa_create_tables_test.rb @@ -4,65 +4,21 @@ class AAACreateTablesTest < ActiveRecord::TestCase self.use_transactional_fixtures = false - def test_drop_and_create_main_tables - recreate ActiveRecord::Base unless use_migrations? - assert true - end - def test_load_schema - if ActiveRecord::Base.connection.supports_migrations? - eval(File.read(SCHEMA_ROOT + "/schema.rb")) - else - recreate ActiveRecord::Base, '3' + eval(File.read(SCHEMA_ROOT + "/schema.rb")) + if File.exists?(adapter_specific_schema_file) + eval(File.read(adapter_specific_schema_file)) end assert true end def test_drop_and_create_courses_table - if Course.connection.supports_migrations? - eval(File.read(SCHEMA_ROOT + "/schema2.rb")) - end - recreate Course, '2' unless use_migrations_for_courses? + eval(File.read(SCHEMA_ROOT + "/schema2.rb")) assert true end private - def use_migrations? - unittest_sql_filename = ActiveRecord::Base.connection.adapter_name.downcase + ".sql" - not File.exist? SCHEMA_ROOT + "/#{unittest_sql_filename}" - end - - def use_migrations_for_courses? - unittest2_sql_filename = ActiveRecord::Base.connection.adapter_name.downcase + "2.sql" - not File.exist? SCHEMA_ROOT + "/#{unittest2_sql_filename}" - end - - def recreate(base, suffix = nil) - connection = base.connection - adapter_name = connection.adapter_name.downcase + suffix.to_s - execute_sql_file SCHEMA_ROOT + "/#{adapter_name}.drop.sql", connection - execute_sql_file SCHEMA_ROOT + "/#{adapter_name}.sql", connection - end - - def execute_sql_file(path, connection) - # OpenBase has a different format for sql files - if current_adapter?(:OpenBaseAdapter) then - File.read(path).split("go").each_with_index do |sql, i| - begin - # OpenBase does not support comments embedded in sql - connection.execute(sql,"SQL statement ##{i}") unless sql.blank? - rescue ActiveRecord::StatementInvalid - #$stderr.puts "warning: #{$!}" - end - end - else - File.read(path).split(';').each_with_index do |sql, i| - begin - connection.execute("\n\n-- statement ##{i}\n#{sql}\n") unless sql.blank? - rescue ActiveRecord::StatementInvalid - #$stderr.puts "warning: #{$!}" - end - end - end - end + def adapter_specific_schema_file + SCHEMA_ROOT + '/' + ActiveRecord::Base.connection.adapter_name.downcase + '_specific_schema.rb' + end end diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index 00bcb05e2d9f6..a9899102d7367 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -25,7 +25,7 @@ def test_associating_new new_person = nil # so block binding catches it assert_queries(0) do - new_person = Person.new + new_person = Person.new :first_name => 'bob' end # Associating new records always saves them diff --git a/activerecord/test/cases/associations_test.rb b/activerecord/test/cases/associations_test.rb index bfb95eca1a037..ed2fab6d22693 100755 --- a/activerecord/test/cases/associations_test.rb +++ b/activerecord/test/cases/associations_test.rb @@ -41,7 +41,7 @@ def test_bad_collection_keys end def test_should_construct_new_finder_sql_after_create - person = Person.new + person = Person.new :first_name => 'clark' assert_equal [], person.readers.find(:all) person.save! reader = Reader.create! :person => person, :post => Post.new(:title => "foo", :body => "bar") diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index e5bba1b63d8ef..45d47837a491c 100755 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -1704,7 +1704,7 @@ def test_find_on_abstract_base_class_doesnt_use_type_condition old_class = LooseDescendant Object.send :remove_const, :LooseDescendant - descendant = old_class.create! + descendant = old_class.create! :first_name => 'bob' assert_not_nil LoosePerson.find(descendant.id), "Should have found instance of LooseDescendant when finding abstract LoosePerson: #{descendant.inspect}" ensure unless Object.const_defined?(:LooseDescendant) diff --git a/activerecord/test/schema/db2.drop.sql b/activerecord/test/schema/db2.drop.sql deleted file mode 100644 index 286066ea20042..0000000000000 --- a/activerecord/test/schema/db2.drop.sql +++ /dev/null @@ -1,33 +0,0 @@ -DROP TABLE accounts; -DROP TABLE funny_jokes; -DROP TABLE companies; -DROP TABLE topics; -DROP TABLE developers; -DROP TABLE projects; -DROP TABLE developers_projects; -DROP TABLE orders; -DROP TABLE customers; -DROP TABLE movies; -DROP TABLE subscribers; -DROP TABLE booleantests; -DROP TABLE auto_id_tests; -DROP TABLE entrants; -DROP TABLE colnametests; -DROP TABLE mixins; -DROP TABLE people; -DROP TABLE readers; -DROP TABLE binaries; -DROP TABLE computers; -DROP TABLE posts; -DROP TABLE comments; -DROP TABLE authors; -DROP TABLE tasks; -DROP TABLE categories; -DROP TABLE categories_posts; -DROP TABLE fk_test_has_pk; -DROP TABLE fk_test_has_fk; -DROP TABLE keyboards; -DROP TABLE legacy_things; -DROP TABLE numeric_data; -DROP TABLE mixed_case_monkeys; -DROP TABLE minimalistics; diff --git a/activerecord/test/schema/db2.sql b/activerecord/test/schema/db2.sql deleted file mode 100644 index 6e088bd8eded5..0000000000000 --- a/activerecord/test/schema/db2.sql +++ /dev/null @@ -1,235 +0,0 @@ -CREATE TABLE accounts ( - id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000), - firm_id INT DEFAULT NULL, - credit_limit INT DEFAULT NULL, - PRIMARY KEY (id) -); - -CREATE TABLE funny_jokes ( - id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000), - name VARCHAR(50) DEFAULT NULL, - PRIMARY KEY (id) -); - -CREATE TABLE companies ( - id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000), - type VARCHAR(50) DEFAULT NULL, - ruby_type VARCHAR(50) DEFAULT NULL, - firm_id INT DEFAULT NULL, - name VARCHAR(50) DEFAULT NULL, - client_of INT DEFAULT NULL, - rating INT DEFAULT 1, - PRIMARY KEY (id) -); - -CREATE TABLE topics ( - id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000), - title VARCHAR(255) DEFAULT NULL, - author_name VARCHAR(255) DEFAULT NULL, - author_email_address VARCHAR(255) DEFAULT NULL, - written_on TIMESTAMP DEFAULT NULL, - bonus_time TIME DEFAULT NULL, - last_read DATE DEFAULT NULL, - content VARCHAR(3000), - approved SMALLINT DEFAULT 1, - replies_count INT DEFAULT 0, - parent_id INT DEFAULT NULL, - type VARCHAR(50) DEFAULT NULL, - PRIMARY KEY (id) -); - -CREATE TABLE developers ( - id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000), - name VARCHAR(100) DEFAULT NULL, - salary INT DEFAULT 70000, - created_at TIMESTAMP DEFAULT NULL, - updated_at TIMESTAMP DEFAULT NULL, - PRIMARY KEY (id) -); - -CREATE TABLE projects ( - id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000), - name VARCHAR(100) DEFAULT NULL, - type VARCHAR(255) DEFAULT NULL, - PRIMARY KEY (id) -); - -CREATE TABLE developers_projects ( - developer_id INT NOT NULL, - project_id INT NOT NULL, - joined_on DATE DEFAULT NULL, - access_level SMALLINT DEFAULT 1 -); - -CREATE TABLE orders ( - id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000), - name VARCHAR(100) DEFAULT NULL, - billing_customer_id INT DEFAULT NULL, - shipping_customer_id INT DEFAULT NULL, - PRIMARY KEY (id) -); - -CREATE TABLE customers ( - id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000), - name VARCHAR(100) DEFAULT NULL, - balance INT DEFAULT 0, - address_street VARCHAR(100) DEFAULT NULL, - address_city VARCHAR(100) DEFAULT NULL, - address_country VARCHAR(100) DEFAULT NULL, - gps_location VARCHAR(100) DEFAULT NULL, - PRIMARY KEY (id) -); - -CREATE TABLE movies ( - movieid INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000), - name VARCHAR(100) DEFAULT NULL, - PRIMARY KEY (movieid) -); - -CREATE TABLE subscribers ( - nick VARCHAR(100) NOT NULL, - name VARCHAR(100) DEFAULT NULL, - PRIMARY KEY (nick) -); - -CREATE TABLE booleantests ( - id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000), - value INT DEFAULT NULL, - PRIMARY KEY (id) -); - -CREATE TABLE auto_id_tests ( - auto_id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000), - value INT DEFAULT NULL, - PRIMARY KEY (auto_id) -); - -CREATE TABLE entrants ( - id INT NOT NULL PRIMARY KEY, - name VARCHAR(255) NOT NULL, - course_id INT NOT NULL -); - -CREATE TABLE colnametests ( - id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000), - references INT NOT NULL, - PRIMARY KEY (id) -); - -CREATE TABLE mixins ( - id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000), - parent_id INT DEFAULT NULL, - pos INT DEFAULT NULL, - created_at TIMESTAMP DEFAULT NULL, - updated_at TIMESTAMP DEFAULT NULL, - lft INT DEFAULT NULL, - rgt INT DEFAULT NULL, - root_id INT DEFAULT NULL, - type VARCHAR(40) DEFAULT NULL, - PRIMARY KEY (id) -); - -CREATE TABLE people ( - id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000), - first_name VARCHAR(40) NOT NULL, - lock_version INT DEFAULT 0, - PRIMARY KEY (id) -); - -CREATE TABLE readers ( - id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000), - post_id INT NOT NULL, - person_id INT NOT NULL, - PRIMARY KEY (id) -); - -CREATE TABLE binaries ( - id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000), - data BLOB(50000), - PRIMARY KEY (id) -); - -CREATE TABLE computers ( - id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000), - developer INT NOT NULL, - extendedWarranty INT NOT NULL -); - -CREATE TABLE posts ( - id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000), - author_id INT DEFAULT NULL, - title VARCHAR(255) DEFAULT NULL, - type VARCHAR(255) DEFAULT NULL, - body VARCHAR(3000) DEFAULT NULL -); - -CREATE TABLE comments ( - id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000), - post_id INT DEFAULT NULL, - type VARCHAR(255) DEFAULT NULL, - body VARCHAR(3000) DEFAULT NULL -); - -CREATE TABLE authors ( - id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000), - name VARCHAR(255) DEFAULT NULL -); - -CREATE TABLE tasks ( - id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000), - starting TIMESTAMP DEFAULT NULL, - ending TIMESTAMP DEFAULT NULL -); - -CREATE TABLE categories ( - id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000), - name VARCHAR(255) NOT NULL, - type VARCHAR(40) DEFAULT NULL -); - -CREATE TABLE categories_posts ( - category_id INT NOT NULL, - post_id INT NOT NULL -); - -CREATE TABLE keyboards ( - key_number INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000), - name VARCHAR(255) -); - -CREATE TABLE fk_test_has_pk ( - id INT NOT NULL PRIMARY KEY -); - -CREATE TABLE fk_test_has_fk ( - id INT NOT NULL PRIMARY KEY, - fk_id INT NOT NULL, - - FOREIGN KEY (fk_id) REFERENCES fk_test_has_pk(id) -); - ---This table has an altered lock_version column name -CREATE TABLE legacy_things ( - id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000), - tps_report_number INT DEFAULT NULL, - version INT DEFAULT 0, - PRIMARY KEY (id) -); - -CREATE TABLE numeric_data ( - id INT NOT NULL PRIMARY KEY, - bank_balance DECIMAL(10,2), - big_bank_balance DECIMAL(15,2), - world_population DECIMAL(10), - my_house_population DECIMAL(2), - decimal_number_with_default DECIMAL(3,2) DEFAULT 2.78 -); - -CREATE TABLE mixed_case_monkeys ( - monkeyID INT NOT NULL PRIMARY KEY, - fleaCount INT -); - -CREATE TABLE minimalistics ( - id INT NOT NULL PRIMARY KEY -); diff --git a/activerecord/test/schema/db22.drop.sql b/activerecord/test/schema/db22.drop.sql deleted file mode 100644 index 09681bf4460fd..0000000000000 --- a/activerecord/test/schema/db22.drop.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE courses; diff --git a/activerecord/test/schema/db22.sql b/activerecord/test/schema/db22.sql deleted file mode 100644 index 246ca0f6c45d9..0000000000000 --- a/activerecord/test/schema/db22.sql +++ /dev/null @@ -1,4 +0,0 @@ -CREATE TABLE courses ( - id INT NOT NULL PRIMARY KEY, - name VARCHAR(255) NOT NULL -); diff --git a/activerecord/test/schema/firebird.drop.sql b/activerecord/test/schema/firebird.drop.sql deleted file mode 100644 index 378843bf9b59a..0000000000000 --- a/activerecord/test/schema/firebird.drop.sql +++ /dev/null @@ -1,65 +0,0 @@ -DROP TABLE accounts; -DROP TABLE funny_jokes; -DROP TABLE companies; -DROP TABLE topics; -DROP TABLE developers; -DROP TABLE projects; -DROP TABLE developers_projects; -DROP TABLE orders; -DROP TABLE customers; -DROP TABLE movies; -DROP TABLE subscribers; -DROP TABLE booleantests; -DROP TABLE auto_id_tests; -DROP TABLE entrants; -DROP TABLE colnametests; -DROP TABLE mixins; -DROP TABLE people; -DROP TABLE readers; -DROP TABLE binaries; -DROP TABLE computers; -DROP TABLE posts; -DROP TABLE comments; -DROP TABLE authors; -DROP TABLE tasks; -DROP TABLE categories; -DROP TABLE categories_posts; -DROP TABLE fk_test_has_fk; -DROP TABLE fk_test_has_pk; -DROP TABLE keyboards; -DROP TABLE defaults; -DROP TABLE legacy_things; -DROP TABLE numeric_data; -DROP TABLE mixed_case_monkeys; -DROP TABLE minimalistics; - -DROP DOMAIN D_BOOLEAN; - -DROP GENERATOR accounts_seq; -DROP GENERATOR funny_jokes_seq; -DROP GENERATOR companies_nonstd_seq; -DROP GENERATOR topics_seq; -DROP GENERATOR developers_seq; -DROP GENERATOR projects_seq; -DROP GENERATOR orders_seq; -DROP GENERATOR customers_seq; -DROP GENERATOR movies_seq; -DROP GENERATOR booleantests_seq; -DROP GENERATOR auto_id_tests_seq; -DROP GENERATOR entrants_seq; -DROP GENERATOR colnametests_seq; -DROP GENERATOR mixins_seq; -DROP GENERATOR people_seq; -DROP GENERATOR binaries_seq; -DROP GENERATOR computers_seq; -DROP GENERATOR posts_seq; -DROP GENERATOR comments_seq; -DROP GENERATOR authors_seq; -DROP GENERATOR tasks_seq; -DROP GENERATOR categories_seq; -DROP GENERATOR keyboards_seq; -DROP GENERATOR defaults_seq; -DROP GENERATOR legacy_things_seq; -DROP GENERATOR numeric_data_seq; -DROP GENERATOR mixed_case_monkeys_seq; -DROP GENERATOR minimalistics_seq; diff --git a/activerecord/test/schema/firebird.sql b/activerecord/test/schema/firebird.sql deleted file mode 100644 index 9ed6453ff7f21..0000000000000 --- a/activerecord/test/schema/firebird.sql +++ /dev/null @@ -1,310 +0,0 @@ -CREATE DOMAIN D_BOOLEAN AS SMALLINT CHECK (VALUE IN (0, 1) OR VALUE IS NULL); - -CREATE TABLE accounts ( - id BIGINT NOT NULL, - firm_id BIGINT, - credit_limit INTEGER, - PRIMARY KEY (id) -); -CREATE GENERATOR accounts_seq; -SET GENERATOR accounts_seq TO 10000; - -CREATE TABLE funny_jokes ( - id BIGINT NOT NULL, - name VARCHAR(50), - PRIMARY KEY (id) -); -CREATE GENERATOR funny_jokes_seq; -SET GENERATOR funny_jokes_seq TO 10000; - -CREATE TABLE companies ( - id BIGINT NOT NULL, - "TYPE" VARCHAR(50), - ruby_type VARCHAR(50), - firm_id BIGINT, - name VARCHAR(50), - client_of INTEGER, - rating INTEGER DEFAULT 1, - PRIMARY KEY (id) -); -CREATE GENERATOR companies_nonstd_seq; -SET GENERATOR companies_nonstd_seq TO 10000; - -CREATE TABLE topics ( - id BIGINT NOT NULL, - title VARCHAR(255), - author_name VARCHAR(255), - author_email_address VARCHAR(255), - written_on TIMESTAMP, - bonus_time TIME, - last_read DATE, - content VARCHAR(4000), - approved D_BOOLEAN DEFAULT 1, - replies_count INTEGER DEFAULT 0, - parent_id BIGINT, - "TYPE" VARCHAR(50), - PRIMARY KEY (id) -); -CREATE GENERATOR topics_seq; -SET GENERATOR topics_seq TO 10000; - -CREATE TABLE developers ( - id BIGINT NOT NULL, - name VARCHAR(100), - salary INTEGER DEFAULT 70000, - created_at TIMESTAMP, - updated_at TIMESTAMP, - PRIMARY KEY (id) -); -CREATE GENERATOR developers_seq; -SET GENERATOR developers_seq TO 10000; - -CREATE TABLE projects ( - id BIGINT NOT NULL, - name VARCHAR(100), - "TYPE" VARCHAR(255), - PRIMARY KEY (id) -); -CREATE GENERATOR projects_seq; -SET GENERATOR projects_seq TO 10000; - -CREATE TABLE developers_projects ( - developer_id BIGINT NOT NULL, - project_id BIGINT NOT NULL, - joined_on DATE, - access_level SMALLINT DEFAULT 1 -); - -CREATE TABLE orders ( - id BIGINT NOT NULL, - name VARCHAR(100), - billing_customer_id BIGINT, - shipping_customer_id BIGINT, - PRIMARY KEY (id) -); -CREATE GENERATOR orders_seq; -SET GENERATOR orders_seq TO 10000; - -CREATE TABLE customers ( - id BIGINT NOT NULL, - name VARCHAR(100), - balance INTEGER DEFAULT 0, - address_street VARCHAR(100), - address_city VARCHAR(100), - address_country VARCHAR(100), - gps_location VARCHAR(100), - PRIMARY KEY (id) -); -CREATE GENERATOR customers_seq; -SET GENERATOR customers_seq TO 10000; - -CREATE TABLE movies ( - movieid BIGINT NOT NULL, - name varchar(100), - PRIMARY KEY (movieid) -); -CREATE GENERATOR movies_seq; -SET GENERATOR movies_seq TO 10000; - -CREATE TABLE subscribers ( - nick VARCHAR(100) NOT NULL, - name VARCHAR(100), - PRIMARY KEY (nick) -); - -CREATE TABLE booleantests ( - id BIGINT NOT NULL, - "VALUE" D_BOOLEAN, - PRIMARY KEY (id) -); -CREATE GENERATOR booleantests_seq; -SET GENERATOR booleantests_seq TO 10000; - -CREATE TABLE auto_id_tests ( - auto_id BIGINT NOT NULL, - "VALUE" INTEGER, - PRIMARY KEY (auto_id) -); -CREATE GENERATOR auto_id_tests_seq; -SET GENERATOR auto_id_tests_seq TO 10000; - -CREATE TABLE entrants ( - id BIGINT NOT NULL, - name VARCHAR(255) NOT NULL, - course_id INTEGER NOT NULL, - PRIMARY KEY (id) -); -CREATE GENERATOR entrants_seq; -SET GENERATOR entrants_seq TO 10000; - -CREATE TABLE colnametests ( - id BIGINT NOT NULL, - "REFERENCES" INTEGER NOT NULL, - PRIMARY KEY (id) -); -CREATE GENERATOR colnametests_seq; -SET GENERATOR colnametests_seq TO 10000; - -CREATE TABLE mixins ( - id BIGINT NOT NULL, - parent_id BIGINT, - pos INTEGER, - created_at TIMESTAMP, - updated_at TIMESTAMP, - lft INTEGER, - rgt INTEGER, - root_id BIGINT, - "TYPE" VARCHAR(40), - PRIMARY KEY (id) -); -CREATE GENERATOR mixins_seq; -SET GENERATOR mixins_seq TO 10000; - -CREATE TABLE people ( - id BIGINT NOT NULL, - first_name VARCHAR(40), - lock_version INTEGER DEFAULT 0 NOT NULL, - PRIMARY KEY (id) -); -CREATE GENERATOR people_seq; -SET GENERATOR people_seq TO 10000; - -CREATE TABLE readers ( - id BIGINT NOT NULL, - post_id BIGINT NOT NULL, - person_id BIGINT NOT NULL, - PRIMARY KEY (id) -); -CREATE GENERATOR readers_seq; -SET GENERATOR readers_seq TO 10000; - -CREATE TABLE binaries ( - id BIGINT NOT NULL, - data BLOB, - PRIMARY KEY (id) -); -CREATE GENERATOR binaries_seq; -SET GENERATOR binaries_seq TO 10000; - -CREATE TABLE computers ( - id BIGINT NOT NULL, - developer INTEGER NOT NULL, - "extendedWarranty" INTEGER NOT NULL, - PRIMARY KEY (id) -); -CREATE GENERATOR computers_seq; -SET GENERATOR computers_seq TO 10000; - -CREATE TABLE posts ( - id BIGINT NOT NULL, - author_id BIGINT, - title VARCHAR(255) NOT NULL, - "TYPE" VARCHAR(255) NOT NULL, - body VARCHAR(3000) NOT NULL, - PRIMARY KEY (id) -); -CREATE GENERATOR posts_seq; -SET GENERATOR posts_seq TO 10000; - -CREATE TABLE comments ( - id BIGINT NOT NULL, - post_id BIGINT NOT NULL, - "TYPE" VARCHAR(255) NOT NULL, - body VARCHAR(3000) NOT NULL, - PRIMARY KEY (id) -); -CREATE GENERATOR comments_seq; -SET GENERATOR comments_seq TO 10000; - -CREATE TABLE authors ( - id BIGINT NOT NULL, - name VARCHAR(255) NOT NULL, - PRIMARY KEY (id) -); -CREATE GENERATOR authors_seq; -SET GENERATOR authors_seq TO 10000; - -CREATE TABLE tasks ( - id BIGINT NOT NULL, - "STARTING" TIMESTAMP, - ending TIMESTAMP, - PRIMARY KEY (id) -); -CREATE GENERATOR tasks_seq; -SET GENERATOR tasks_seq TO 10000; - -CREATE TABLE categories ( - id BIGINT NOT NULL, - name VARCHAR(255) NOT NULL, - "TYPE" VARCHAR(255) NOT NULL, - PRIMARY KEY (id) -); -CREATE GENERATOR categories_seq; -SET GENERATOR categories_seq TO 10000; - -CREATE TABLE categories_posts ( - category_id BIGINT NOT NULL, - post_id BIGINT NOT NULL, - PRIMARY KEY (category_id, post_id) -); - -CREATE TABLE fk_test_has_pk ( - id BIGINT NOT NULL, - PRIMARY KEY (id) -); - -CREATE TABLE fk_test_has_fk ( - id BIGINT NOT NULL, - fk_id BIGINT NOT NULL, - PRIMARY KEY (id), - FOREIGN KEY (fk_id) REFERENCES fk_test_has_pk(id) -); - -CREATE TABLE keyboards ( - key_number BIGINT NOT NULL, - name VARCHAR(50), - PRIMARY KEY (key_number) -); -CREATE GENERATOR keyboards_seq; -SET GENERATOR keyboards_seq TO 10000; - -CREATE TABLE defaults ( - id BIGINT NOT NULL, - default_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP -); -CREATE GENERATOR defaults_seq; -SET GENERATOR defaults_seq TO 10000; - -CREATE TABLE legacy_things ( - id BIGINT NOT NULL, - tps_report_number INTEGER, - version INTEGER DEFAULT 0 NOT NULL, - PRIMARY KEY (id) -); -CREATE GENERATOR legacy_things_seq; -SET GENERATOR legacy_things_seq TO 10000; - -CREATE TABLE numeric_data ( - id BIGINT NOT NULL, - bank_balance DECIMAL(10,2), - big_bank_balance DECIMAL(15,2), - world_population DECIMAL(10), - my_house_population DECIMAL(2), - decimal_number_with_default DECIMAL(3,2) DEFAULT 2.78, - PRIMARY KEY (id) -); -CREATE GENERATOR numeric_data_seq; -SET GENERATOR numeric_data_seq TO 10000; - -CREATE TABLE mixed_case_monkeys ( - "monkeyID" BIGINT NOT NULL, - "fleaCount" INTEGER -); -CREATE GENERATOR mixed_case_monkeys_seq; -SET GENERATOR mixed_case_monkeys_seq TO 10000; - -CREATE TABLE minimalistics ( - id BIGINT NOT NULL -); -CREATE GENERATOR minimalistics_seq; -SET GENERATOR minimalistics_seq TO 10000; diff --git a/activerecord/test/schema/firebird2.drop.sql b/activerecord/test/schema/firebird2.drop.sql deleted file mode 100644 index c59fb1f2ff96d..0000000000000 --- a/activerecord/test/schema/firebird2.drop.sql +++ /dev/null @@ -1,2 +0,0 @@ -DROP TABLE courses; -DROP GENERATOR courses_seq; diff --git a/activerecord/test/schema/firebird2.sql b/activerecord/test/schema/firebird2.sql deleted file mode 100644 index c1bc251fbcfd4..0000000000000 --- a/activerecord/test/schema/firebird2.sql +++ /dev/null @@ -1,6 +0,0 @@ -CREATE TABLE courses ( - id BIGINT NOT NULL PRIMARY KEY, - name VARCHAR(255) NOT NULL -); -CREATE GENERATOR courses_seq; -SET GENERATOR courses_seq TO 10000; diff --git a/activerecord/test/schema/frontbase.drop.sql b/activerecord/test/schema/frontbase.drop.sql deleted file mode 100644 index 58ec56bd4fead..0000000000000 --- a/activerecord/test/schema/frontbase.drop.sql +++ /dev/null @@ -1,33 +0,0 @@ -DROP TABLE accounts CASCADE; -DROP TABLE funny_jokes CASCADE; -DROP TABLE companies CASCADE; -DROP TABLE topics CASCADE; -DROP TABLE developers CASCADE; -DROP TABLE projects CASCADE; -DROP TABLE developers_projects CASCADE; -DROP TABLE orders CASCADE; -DROP TABLE customers CASCADE; -DROP TABLE movies CASCADE; -DROP TABLE subscribers CASCADE; -DROP TABLE booleantests CASCADE; -DROP TABLE auto_id_tests CASCADE; -DROP TABLE entrants CASCADE; -DROP TABLE colnametests CASCADE; -DROP TABLE mixins CASCADE; -DROP TABLE people CASCADE; -DROP TABLE readers CASCADE; -DROP TABLE binaries CASCADE; -DROP TABLE computers CASCADE; -DROP TABLE posts CASCADE; -DROP TABLE comments CASCADE; -DROP TABLE authors CASCADE; -DROP TABLE tasks CASCADE; -DROP TABLE categories CASCADE; -DROP TABLE categories_posts CASCADE; -DROP TABLE fk_test_has_fk CASCADE; -DROP TABLE fk_test_has_pk CASCADE; -DROP TABLE keyboards CASCADE; -DROP TABLE legacy_things CASCADE; -DROP TABLE numeric_data CASCADE; -DROP TABLE mixed_case_monkeys CASCADE; -DROP TABLE minimalistics CASCADE; diff --git a/activerecord/test/schema/frontbase.sql b/activerecord/test/schema/frontbase.sql deleted file mode 100644 index 6945a385c6d45..0000000000000 --- a/activerecord/test/schema/frontbase.sql +++ /dev/null @@ -1,273 +0,0 @@ -CREATE TABLE accounts ( - id integer DEFAULT unique, - firm_id integer, - credit_limit integer, - PRIMARY KEY (id) -); -SET UNIQUE FOR accounts(id); - -CREATE TABLE funny_jokes ( - id integer DEFAULT unique, - firm_id integer default NULL, - name character varying(50), - PRIMARY KEY (id) -); -SET UNIQUE FOR funny_jokes(id); - -CREATE TABLE companies ( - id integer DEFAULT unique, - "type" character varying(50), - "ruby_type" character varying(50), - firm_id integer, - name character varying(50), - client_of integer, - rating integer default 1, - PRIMARY KEY (id) -); -SET UNIQUE FOR companies(id); - -CREATE TABLE topics ( - id integer DEFAULT unique, - title character varying(255), - author_name character varying(255), - author_email_address character varying(255), - written_on timestamp, - bonus_time time, - last_read date, - content varchar(65536), - approved boolean default true, - replies_count integer default 0, - parent_id integer, - "type" character varying(50), - PRIMARY KEY (id) -); -SET UNIQUE FOR topics(id); - -CREATE TABLE developers ( - id integer DEFAULT unique, - name character varying(100), - salary integer DEFAULT 70000, - created_at timestamp, - updated_at timestamp, - PRIMARY KEY (id) -); -SET UNIQUE FOR developers(id); - -CREATE TABLE projects ( - id integer DEFAULT unique, - name character varying(100), - type varchar(255), - PRIMARY KEY (id) -); -SET UNIQUE FOR projects(id); - -CREATE TABLE developers_projects ( - developer_id integer NOT NULL, - project_id integer NOT NULL, - joined_on date, - access_level integer default 1 -); - -CREATE TABLE orders ( - id integer DEFAULT unique, - name character varying(100), - billing_customer_id integer, - shipping_customer_id integer, - PRIMARY KEY (id) -); -SET UNIQUE FOR orders(id); - -CREATE TABLE customers ( - id integer DEFAULT unique, - name character varying(100), - balance integer default 0, - address_street character varying(100), - address_city character varying(100), - address_country character varying(100), - gps_location character varying(100), - PRIMARY KEY (id) -); -SET UNIQUE FOR customers(id); - -CREATE TABLE movies ( - movieid integer DEFAULT unique, - name varchar(65536), - PRIMARY KEY (movieid) -); -SET UNIQUE FOR movies(movieid); - -CREATE TABLE subscribers ( - nick varchar(65536) NOT NULL, - name varchar(65536), - PRIMARY KEY (nick) -); - -CREATE TABLE booleantests ( - id integer DEFAULT unique, - value boolean, - PRIMARY KEY (id) -); -SET UNIQUE FOR booleantests(id); - -CREATE TABLE auto_id_tests ( - auto_id integer DEFAULT unique, - value integer, - PRIMARY KEY (auto_id) -); -SET UNIQUE FOR auto_id_tests(auto_id); - -CREATE TABLE entrants ( - id integer DEFAULT unique, - name varchar(65536), - course_id integer, - PRIMARY KEY (id) -); -SET UNIQUE FOR entrants(id); - -CREATE TABLE colnametests ( - id integer DEFAULT unique, - "references" integer NOT NULL, - PRIMARY KEY (id) -); -SET UNIQUE FOR colnametests(id); - -CREATE TABLE mixins ( - id integer DEFAULT unique, - parent_id integer, - type character varying(100), - pos integer, - lft integer, - rgt integer, - root_id integer, - created_at timestamp, - updated_at timestamp, - PRIMARY KEY (id) -); -SET UNIQUE FOR mixins(id); - -CREATE TABLE people ( - id integer DEFAULT unique, - first_name varchar(65536), - lock_version integer default 0, - PRIMARY KEY (id) -); -SET UNIQUE FOR people(id); - -CREATE TABLE readers ( - id integer DEFAULT unique, - post_id INTEGER NOT NULL, - person_id INTEGER NOT NULL, - PRIMARY KEY (id) -); -SET UNIQUE FOR readers(id); - -CREATE TABLE binaries ( - id integer DEFAULT unique, - data BLOB, - PRIMARY KEY (id) -); -SET UNIQUE FOR binaries(id); - -CREATE TABLE computers ( - id integer DEFAULT unique, - developer integer NOT NULL, - "extendedWarranty" integer NOT NULL, - PRIMARY KEY (id) -); -SET UNIQUE FOR computers(id); - -CREATE TABLE posts ( - id integer DEFAULT unique, - author_id integer, - title varchar(255), - type varchar(255), - body varchar(65536), - PRIMARY KEY (id) -); -SET UNIQUE FOR posts(id); - -CREATE TABLE comments ( - id integer DEFAULT unique, - post_id integer, - type varchar(255), - body varchar(65536), - PRIMARY KEY (id) -); -SET UNIQUE FOR comments(id); - -CREATE TABLE authors ( - id integer DEFAULT unique, - name varchar(255) default NULL, - PRIMARY KEY (id) -); -SET UNIQUE FOR authors(id); - -CREATE TABLE tasks ( - id integer DEFAULT unique, - starting timestamp, - ending timestamp, - PRIMARY KEY (id) -); -SET UNIQUE FOR tasks(id); - -CREATE TABLE categories ( - id integer DEFAULT unique, - name varchar(255), - type varchar(255), - PRIMARY KEY (id) -); -SET UNIQUE FOR categories(id); - -CREATE TABLE categories_posts ( - category_id integer NOT NULL, - post_id integer NOT NULL -); - -CREATE TABLE fk_test_has_pk ( - id INTEGER NOT NULL PRIMARY KEY -); -SET UNIQUE FOR fk_test_has_pk(id); - -CREATE TABLE fk_test_has_fk ( - id INTEGER NOT NULL PRIMARY KEY, - fk_id INTEGER NOT NULL REFERENCES fk_test_has_fk(id) -); -SET UNIQUE FOR fk_test_has_fk(id); - -CREATE TABLE keyboards ( - key_number integer DEFAULT unique, - "name" character varying(50), - PRIMARY KEY (key_number) -); -SET UNIQUE FOR keyboards(key_number); - -create table "legacy_things" -( - "id" int, - "tps_report_number" int default NULL, - "version" int default 0 not null, - primary key ("id") -); -SET UNIQUE FOR legacy_things(id); - -CREATE TABLE "numeric_data" ( - "id" integer NOT NULL - "bank_balance" DECIMAL(10,2), - "big_bank_balance" DECIMAL(15,2), - "world_population" DECIMAL(10), - "my_house_population" DECIMAL(2), - "decimal_number_with_default" DECIMAL(3,2) DEFAULT 2.78, - primary key ("id") -); -SET UNIQUE FOR numeric_data(id); - -CREATE TABLE mixed_case_monkeys ( - "monkeyID" integer DEFAULT unique, - "fleaCount" integer -); -SET UNIQUE FOR mixed_case_monkeys("monkeyID"); - -CREATE TABLE minimalistics ( - "id" integer NOT NULL -); -SET UNIQUE FOR minimalistics("id"); diff --git a/activerecord/test/schema/frontbase2.drop.sql b/activerecord/test/schema/frontbase2.drop.sql deleted file mode 100644 index 17b9ad46d7eb7..0000000000000 --- a/activerecord/test/schema/frontbase2.drop.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE courses CASCADE; diff --git a/activerecord/test/schema/frontbase2.sql b/activerecord/test/schema/frontbase2.sql deleted file mode 100644 index 80063b5989db0..0000000000000 --- a/activerecord/test/schema/frontbase2.sql +++ /dev/null @@ -1,4 +0,0 @@ -CREATE TABLE courses ( - id integer DEFAULT unique, - name varchar(100) -); diff --git a/activerecord/test/schema/mysql_specific_schema.rb b/activerecord/test/schema/mysql_specific_schema.rb new file mode 100644 index 0000000000000..5ae062c97c129 --- /dev/null +++ b/activerecord/test/schema/mysql_specific_schema.rb @@ -0,0 +1,12 @@ +ActiveRecord::Schema.define do + create_table :binary_fields, :force => true do |t| + t.binary :tiny_blob, :limit => 255 + t.binary :normal_blob, :limit => 65535 + t.binary :medium_blob, :limit => 16777215 + t.binary :long_blob, :limit => 2147483647 + t.text :tiny_text, :limit => 255 + t.text :normal_text, :limit => 65535 + t.text :medium_text, :limit => 16777215 + t.text :long_text, :limit => 2147483647 + end +end \ No newline at end of file diff --git a/activerecord/test/schema/openbase.drop.sql b/activerecord/test/schema/openbase.drop.sql deleted file mode 100644 index fb40e3f213d42..0000000000000 --- a/activerecord/test/schema/openbase.drop.sql +++ /dev/null @@ -1,2 +0,0 @@ -DROP ALL -go \ No newline at end of file diff --git a/activerecord/test/schema/openbase.sql b/activerecord/test/schema/openbase.sql deleted file mode 100644 index cb804ae7b274b..0000000000000 --- a/activerecord/test/schema/openbase.sql +++ /dev/null @@ -1,318 +0,0 @@ -CREATE TABLE accounts ( - id integer NOT NULL UNIQUE INDEX DEFAULT _rowid, - firm_id integer, - credit_limit integer -) -go -CREATE PRIMARY KEY accounts (id) -go - -CREATE TABLE funny_jokes ( - id integer NOT NULL UNIQUE INDEX DEFAULT _rowid, - name char(50) DEFAULT NULL -) -go -CREATE PRIMARY KEY funny_jokes (id) -go - -CREATE TABLE companies ( - id integer NOT NULL UNIQUE INDEX DEFAULT _rowid, - type char(50), - ruby_type char(50), - firm_id integer, - name char(50), - client_of integer, - rating integer default 1 -) -go -CREATE PRIMARY KEY companies (id) -go - -CREATE TABLE developers_projects ( - developer_id integer NOT NULL, - project_id integer NOT NULL, - joined_on date, - access_level integer default 1 -) -go - -CREATE TABLE developers ( - id integer NOT NULL UNIQUE INDEX DEFAULT _rowid, - name char(100), - salary integer DEFAULT 70000, - created_at datetime, - updated_at datetime -) -go -CREATE PRIMARY KEY developers (id) -go - -CREATE TABLE projects ( - id integer NOT NULL UNIQUE INDEX DEFAULT _rowid, - name char(100), - type char(255) -) -go -CREATE PRIMARY KEY projects (id) -go - -CREATE TABLE topics ( - id integer NOT NULL UNIQUE INDEX DEFAULT _rowid, - title char(255), - author_name char(255), - author_email_address char(255), - written_on datetime, - bonus_time time, - last_read date, - content char(4096), - approved boolean default true, - replies_count integer default 0, - parent_id integer, - type char(50) -) -go -CREATE PRIMARY KEY topics (id) -go - -CREATE TABLE customers ( - id integer NOT NULL UNIQUE INDEX DEFAULT _rowid, - name char, - balance integer default 0, - address_street char, - address_city char, - address_country char, - gps_location char -) -go -CREATE PRIMARY KEY customers (id) -go - -CREATE TABLE orders ( - id integer NOT NULL UNIQUE INDEX DEFAULT _rowid, - name char, - billing_customer_id integer, - shipping_customer_id integer -) -go -CREATE PRIMARY KEY orders (id) -go - -CREATE TABLE movies ( - movieid integer NOT NULL UNIQUE INDEX DEFAULT _rowid, - name text -) -go -CREATE PRIMARY KEY movies (movieid) -go - -CREATE TABLE subscribers ( - nick CHAR(100) NOT NULL DEFAULT _rowid, - name CHAR(100) -) -go -CREATE PRIMARY KEY subscribers (nick) -go - -CREATE TABLE booleantests ( - id integer NOT NULL UNIQUE INDEX DEFAULT _rowid, - value boolean -) -go -CREATE PRIMARY KEY booleantests (id) -go - -CREATE TABLE defaults ( - id integer UNIQUE INDEX , - modified_date date default CURDATE(), - modified_date_function date default NOW(), - fixed_date date default '2004-01-01', - modified_time timestamp default NOW(), - modified_time_function timestamp default NOW(), - fixed_time timestamp default '2004-01-01 00:00:00.000000-00', - char1 char(1) default 'Y', - char2 char(50) default 'a char field', - char3 text default 'a text field', - positive_integer integer default 1, - negative_integer integer default -1, - decimal_number money default 2.78 -) -go -CREATE PRIMARY KEY defaults (id) -go - -CREATE TABLE auto_id_tests ( - auto_id integer NOT NULL UNIQUE INDEX DEFAULT _rowid, - value integer -) -go -CREATE PRIMARY KEY auto_id_tests (auto_id) -go - -CREATE TABLE entrants ( - id integer NOT NULL UNIQUE INDEX, - name text NOT NULL, - course_id integer NOT NULL -) -go -CREATE PRIMARY KEY entrants (id) -go - -CREATE TABLE colnametests ( - id integer UNIQUE INDEX , - references integer NOT NULL -) -go -CREATE PRIMARY KEY colnametests (id) -go - -CREATE TABLE mixins ( - id integer NOT NULL UNIQUE INDEX DEFAULT _rowid, - parent_id integer, - type char, - pos integer, - lft integer, - rgt integer, - root_id integer, - created_at timestamp, - updated_at timestamp -) -go -CREATE PRIMARY KEY mixins (id) -go - -CREATE TABLE people ( - id integer NOT NULL UNIQUE INDEX DEFAULT _rowid, - first_name text, - lock_version integer default 0 -) -go -CREATE PRIMARY KEY people (id) -go - -CREATE TABLE readers ( - id integer NOT NULL UNIQUE INDEX DEFAULT _rowid, - post_id integer NOT NULL, - person_id integer NOT NULL -) -go -CREATE PRIMARY KEY readers (id) -go - -CREATE TABLE binaries ( - id integer NOT NULL UNIQUE INDEX DEFAULT _rowid, - data object -) -go -CREATE PRIMARY KEY binaries (id) -go - -CREATE TABLE computers ( - id integer UNIQUE INDEX , - developer integer NOT NULL, - extendedWarranty integer NOT NULL -) -go - -CREATE TABLE posts ( - id integer UNIQUE INDEX , - author_id integer, - title char(255), - type char(255), - body text -) -go - -CREATE TABLE comments ( - id integer UNIQUE INDEX , - post_id integer, - type char(255), - body text -) -go - -CREATE TABLE authors ( - id integer UNIQUE INDEX , - name char(255) default NULL -) -go - -CREATE TABLE tasks ( - id integer NOT NULL UNIQUE INDEX DEFAULT _rowid, - starting datetime, - ending datetime -) -go -CREATE PRIMARY KEY tasks (id) -go - -CREATE TABLE categories ( - id integer UNIQUE INDEX , - name char(255), - type char(255) -) -go - -CREATE TABLE categories_posts ( - category_id integer NOT NULL, - post_id integer NOT NULL -) -go - -CREATE TABLE fk_test_has_pk ( - id INTEGER NOT NULL DEFAULT _rowid -) -go -CREATE PRIMARY KEY fk_test_has_pk (id) -go - -CREATE TABLE fk_test_has_fk ( - id INTEGER NOT NULL DEFAULT _rowid, - fk_id INTEGER NOT NULL REFERENCES fk_test_has_pk.id -) -go -CREATE PRIMARY KEY fk_test_has_fk (id) -go - -CREATE TABLE keyboards ( - key_number integer UNIQUE INDEX DEFAULT _rowid, - name char(50) -) -go -CREATE PRIMARY KEY keyboards (key_number) -go - -CREATE TABLE legacy_things ( - id INTEGER NOT NULL DEFAULT _rowid, - tps_report_number INTEGER default NULL, - version integer NOT NULL default 0 -) -go -CREATE PRIMARY KEY legacy_things (id) -go - -CREATE TABLE numeric_data ( - id INTEGER NOT NULL DEFAULT _rowid, - bank_balance MONEY, - big_bank_balance MONEY, - world_population longlong, - my_house_population longlong, - decimal_number_with_default MONEY DEFAULT 2.78 -); -go -CREATE PRIMARY KEY numeric_data (id) -go - -CREATE TABLE mixed_case_monkeys ( - monkeyID INTEGER NOT NULL DEFAULT _rowid, - fleaCount INTEGER -); -go -CREATE PRIMARY KEY mixed_case_monkeys (monkeyID) -go - -CREATE TABLE minimalistics ( - id INTEGER NOT NULL DEFAULT _rowid -); -go -CREATE PRIMARY KEY minimalistics (id) -go diff --git a/activerecord/test/schema/openbase2.drop.sql b/activerecord/test/schema/openbase2.drop.sql deleted file mode 100644 index ea1571da0bf94..0000000000000 --- a/activerecord/test/schema/openbase2.drop.sql +++ /dev/null @@ -1,2 +0,0 @@ -DROP TABLE courses -go diff --git a/activerecord/test/schema/openbase2.sql b/activerecord/test/schema/openbase2.sql deleted file mode 100644 index a37c4f4c313cc..0000000000000 --- a/activerecord/test/schema/openbase2.sql +++ /dev/null @@ -1,7 +0,0 @@ -CREATE TABLE courses ( - id integer UNIQUE INDEX DEFAULT _rowid, - name text -) -go -CREATE PRIMARY KEY courses (id) -go \ No newline at end of file diff --git a/activerecord/test/schema/oracle.drop.sql b/activerecord/test/schema/oracle.drop.sql deleted file mode 100644 index 21f40ed8d03c5..0000000000000 --- a/activerecord/test/schema/oracle.drop.sql +++ /dev/null @@ -1,67 +0,0 @@ -drop table accounts; -drop table funny_jokes; -drop table companies; -drop table topics; -drop synonym subjects; -drop table developers_projects; -drop table computers; -drop table developers; -drop table projects; -drop table customers; -drop table orders; -drop table movies; -drop table subscribers; -drop table booleantests; -drop table auto_id_tests; -drop table entrants; -drop table colnametests; -drop table mixins; -drop table people; -drop table readers; -drop table binaries; -drop table comments; -drop table authors; -drop table tasks; -drop table categories_posts; -drop table categories; -drop table posts; -drop table fk_test_has_pk; -drop table fk_test_has_fk; -drop table keyboards; -drop table legacy_things; -drop table numeric_data; -drop table mixed_case_monkeys; -drop table minimalistics; - -drop sequence accounts_seq; -drop sequence funny_jokes_seq; -drop sequence companies_nonstd_seq; -drop sequence topics_seq; -drop sequence developers_seq; -drop sequence projects_seq; -drop sequence developers_projects_seq; -drop sequence customers_seq; -drop sequence orders_seq; -drop sequence movies_seq; -drop sequence subscribers_seq; -drop sequence booleantests_seq; -drop sequence auto_id_tests_seq; -drop sequence entrants_seq; -drop sequence colnametests_seq; -drop sequence mixins_seq; -drop sequence people_seq; -drop sequence binaries_seq; -drop sequence posts_seq; -drop sequence comments_seq; -drop sequence authors_seq; -drop sequence tasks_seq; -drop sequence computers_seq; -drop sequence categories_seq; -drop sequence categories_posts_seq; -drop sequence fk_test_has_pk_seq; -drop sequence fk_test_has_fk_seq; -drop sequence keyboards_seq; -drop sequence legacy_things_seq; -drop sequence numeric_data_seq; -drop sequence mixed_case_monkeys_seq; -drop sequence minimalistics_seq; diff --git a/activerecord/test/schema/oracle.sql b/activerecord/test/schema/oracle.sql deleted file mode 100644 index 22ca0baa8deca..0000000000000 --- a/activerecord/test/schema/oracle.sql +++ /dev/null @@ -1,330 +0,0 @@ -create table companies ( - id integer not null, - type varchar(50) default null, - ruby_type varchar(50) default null, - firm_id integer default null references companies initially deferred disable, - name varchar(50) default null, - client_of integer default null references companies initially deferred disable, - companies_count integer default 0, - rating integer default 1, - primary key (id) -); - --- non-standard sequence name used to test set_sequence_name --- -create sequence companies_nonstd_seq minvalue 10000; - -create table funny_jokes ( - id integer not null, - name varchar(50) default null, - primary key (id) -); -create sequence funny_jokes_seq minvalue 10000; - -create table accounts ( - id integer not null, - firm_id integer default null references companies initially deferred disable, - credit_limit integer default null -); -create sequence accounts_seq minvalue 10000; - -create table topics ( - id integer not null, - title varchar(255) default null, - author_name varchar(255) default null, - author_email_address varchar(255) default null, - written_on timestamp default null, - bonus_time timestamp default null, - last_read timestamp default null, - content varchar(4000), - approved number(1) default 1, - replies_count integer default 0, - parent_id integer references topics initially deferred disable, - type varchar(50) default null, - primary key (id) -); --- try again for 8i -create table topics ( - id integer not null, - title varchar(255) default null, - author_name varchar(255) default null, - author_email_address varchar(255) default null, - written_on date default null, - bonus_time date default null, - last_read date default null, - content varchar(4000), - approved number(1) default 1, - replies_count integer default 0, - parent_id integer references topics initially deferred disable, - type varchar(50) default null, - primary key (id) -); -create sequence topics_seq minvalue 10000; - -create synonym subjects for topics; - -create table developers ( - id integer not null, - name varchar(100) default null, - salary integer default 70000, - created_at timestamp default null, - updated_at timestamp default null, - primary key (id) -); -create sequence developers_seq minvalue 10000; - -create table projects ( - id integer not null, - name varchar(100) default null, - type varchar(255) default null, - primary key (id) -); -create sequence projects_seq minvalue 10000; - -create table developers_projects ( - developer_id integer not null references developers initially deferred disable, - project_id integer not null references projects initially deferred disable, - joined_on timestamp default null, - access_level integer default 1 -); --- Try again for 8i -create table developers_projects ( - developer_id integer not null references developers initially deferred disable, - project_id integer not null references projects initially deferred disable, - joined_on date default null -); -create sequence developers_projects_seq minvalue 10000; - -create table orders ( - id integer not null, - name varchar(100) default null, - billing_customer_id integer default null, - shipping_customer_id integer default null, - primary key (id) -); -create sequence orders_seq minvalue 10000; - -create table customers ( - id integer not null, - name varchar(100) default null, - balance integer default 0, - address_street varchar(100) default null, - address_city varchar(100) default null, - address_country varchar(100) default null, - gps_location varchar(100) default null, - primary key (id) -); -create sequence customers_seq minvalue 10000; - -create table movies ( - movieid integer not null, - name varchar(100) default null, - primary key (movieid) -); -create sequence movies_seq minvalue 10000; - -create table subscribers ( - nick varchar(100) not null, - name varchar(100) default null, - primary key (nick) -); -create sequence subscribers_seq minvalue 10000; - -create table booleantests ( - id integer not null, - value integer default null, - primary key (id) -); -create sequence booleantests_seq minvalue 10000; - -CREATE TABLE defaults ( - id integer not null, - modified_date date default sysdate, - modified_date_function date default sysdate, - fixed_date date default to_date('2004-01-01', 'YYYY-MM-DD'), - modified_time date default sysdate, - modified_time_function date default sysdate, - fixed_time date default TO_DATE('2004-01-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS'), - char1 varchar2(1) default 'Y', - char2 varchar2(50) default 'a varchar field', - char3 clob default 'a text field', - positive_integer integer default 1, - negative_integer integer default -1, - decimal_number number(3,2) default 2.78 -); -create sequence defaults_seq minvalue 10000; - -create table auto_id_tests ( - auto_id integer not null, - value integer default null, - primary key (auto_id) -); -create sequence auto_id_tests_seq minvalue 10000; - -create table entrants ( - id integer not null primary key, - name varchar(255) not null, - course_id integer not null -); -create sequence entrants_seq minvalue 10000; - -create table colnametests ( - id integer not null, - references integer not null, - primary key (id) -); -create sequence colnametests_seq minvalue 10000; - -create table mixins ( - id integer not null, - parent_id integer default null references mixins initially deferred disable, - type varchar(40) default null, - pos integer default null, - lft integer default null, - rgt integer default null, - root_id integer default null, - created_at timestamp default null, - updated_at timestamp default null, - primary key (id) -); --- try again for 8i -create table mixins ( - id integer not null, - parent_id integer default null references mixins initially deferred disable, - type varchar(40) default null, - pos integer default null, - lft integer default null, - rgt integer default null, - root_id integer default null, - created_at date default null, - updated_at date default null, - primary key (id) -); -create sequence mixins_seq minvalue 10000; - -create table people ( - id integer not null, - first_name varchar(40) null, - lock_version integer default 0, - primary key (id) -); -create sequence people_seq minvalue 10000; - -create table readers ( - id integer not null, - post_id integer not null, - person_id integer not null, - primary key (id) -); -create sequence readers_seq minvalue 10000; - -create table binaries ( - id integer not null, - data blob null, - primary key (id) -); -create sequence binaries_seq minvalue 10000; - -create table computers ( - id integer not null primary key, - developer integer not null references developers initially deferred disable, - "extendedWarranty" integer not null -); -create sequence computers_seq minvalue 10000; - -create table posts ( - id integer not null primary key, - author_id integer default null, - title varchar(255) default null, - type varchar(255) default null, - body varchar(3000) default null -); -create sequence posts_seq minvalue 10000; - -create table comments ( - id integer not null primary key, - post_id integer default null, - type varchar(255) default null, - body varchar(3000) default null -); -create sequence comments_seq minvalue 10000; - -create table authors ( - id integer not null primary key, - name varchar(255) default null -); -create sequence authors_seq minvalue 10000; - -create table tasks ( - id integer not null primary key, - starting date default null, - ending date default null -); -create sequence tasks_seq minvalue 10000; - -create table categories ( - id integer not null primary key, - name varchar(255) default null, - type varchar(255) default null -); -create sequence categories_seq minvalue 10000; - -create table categories_posts ( - category_id integer not null references categories initially deferred disable, - post_id integer not null references posts initially deferred disable -); -create sequence categories_posts_seq minvalue 10000; - -create table fk_test_has_pk ( - id integer not null primary key -); -create sequence fk_test_has_pk_seq minvalue 10000; - -create table fk_test_has_fk ( - id integer not null primary key, - fk_id integer not null references fk_test_has_fk initially deferred disable -); -create sequence fk_test_has_fk_seq minvalue 10000; - -create table keyboards ( - key_number integer not null, - name varchar(50) default null -); -create sequence keyboards_seq minvalue 10000; - -create table test_oracle_defaults ( - id integer not null primary key, - test_char char(1) default 'X' not null, - test_string varchar2(20) default 'hello' not null, - test_int integer default 3 not null -); -create sequence test_oracle_defaults_seq minvalue 10000; - ---This table has an altered lock_version column name. -create table legacy_things ( - id integer not null primary key, - tps_report_number integer default null, - version integer default 0 -); -create sequence legacy_things_seq minvalue 10000; - -CREATE TABLE numeric_data ( - id integer NOT NULL PRIMARY KEY, - bank_balance decimal(10,2), - big_bank_balance decimal(15,2), - world_population decimal(10), - my_house_population decimal(2), - decimal_number_with_default decimal(3,2) DEFAULT 2.78 -); -create sequence numeric_data_seq minvalue 10000; - -CREATE TABLE mixed_case_monkeys ( - "monkeyID" INTEGER NOT NULL PRIMARY KEY, - "fleaCount" INTEGER -); -create sequence mixed_case_monkeys_seq minvalue 10000; - -CREATE TABLE minimalistics ( - id INTEGER NOT NULL PRIMARY KEY -); -create sequence minimalistics_seq minvalue 10000; diff --git a/activerecord/test/schema/oracle2.drop.sql b/activerecord/test/schema/oracle2.drop.sql deleted file mode 100644 index abe7e55c31e4f..0000000000000 --- a/activerecord/test/schema/oracle2.drop.sql +++ /dev/null @@ -1,2 +0,0 @@ -drop table courses; -drop sequence courses_seq; diff --git a/activerecord/test/schema/oracle2.sql b/activerecord/test/schema/oracle2.sql deleted file mode 100644 index 3c171f4f14aae..0000000000000 --- a/activerecord/test/schema/oracle2.sql +++ /dev/null @@ -1,6 +0,0 @@ -create table courses ( - id int not null primary key, - name varchar(255) not null -); - -create sequence courses_seq minvalue 10000; diff --git a/activerecord/test/schema/postgresql.drop.sql b/activerecord/test/schema/postgresql.drop.sql deleted file mode 100644 index 31e2d38743d46..0000000000000 --- a/activerecord/test/schema/postgresql.drop.sql +++ /dev/null @@ -1,44 +0,0 @@ -DROP TABLE accounts; -DROP SEQUENCE accounts_id_seq; -DROP TABLE funny_jokes; -DROP TABLE companies; -DROP SEQUENCE companies_nonstd_seq; -DROP TABLE topics; -DROP TABLE developers; -DROP TABLE projects; -DROP TABLE developers_projects; -DROP TABLE customers; -DROP TABLE orders; -DROP TABLE movies; -DROP TABLE subscribers; -DROP TABLE booleantests; -DROP TABLE auto_id_tests; -DROP TABLE entrants; -DROP TABLE colnametests; -DROP TABLE mixins; -DROP TABLE people; -DROP TABLE readers; -DROP TABLE binaries; -DROP TABLE computers; -DROP TABLE posts; -DROP TABLE comments; -DROP TABLE authors; -DROP TABLE tasks; -DROP TABLE categories; -DROP TABLE categories_posts; -DROP TABLE defaults; -DROP TABLE fk_test_has_fk; -DROP TABLE fk_test_has_pk; -DROP TABLE geometrics; -DROP TABLE keyboards; -DROP TABLE legacy_things; -DROP TABLE numeric_data; -DROP TABLE column_data; -DROP TABLE mixed_case_monkeys; -DROP TABLE postgresql_arrays; -DROP TABLE postgresql_moneys; -DROP TABLE postgresql_numbers; -DROP TABLE postgresql_times; -DROP TABLE postgresql_network_addresses; -DROP TABLE postgresql_bit_strings; -DROP TABLE postgresql_oids; diff --git a/activerecord/test/schema/postgresql.sql b/activerecord/test/schema/postgresql.sql deleted file mode 100644 index 885dab7a79966..0000000000000 --- a/activerecord/test/schema/postgresql.sql +++ /dev/null @@ -1,294 +0,0 @@ -CREATE SEQUENCE public.accounts_id_seq START 100; - -CREATE TABLE accounts ( - id integer primary key DEFAULT nextval('public.accounts_id_seq'), - firm_id integer, - credit_limit integer -); - -CREATE TABLE funny_jokes ( - id serial, - name character varying(50) -); - -CREATE SEQUENCE companies_nonstd_seq START 101; - -CREATE TABLE companies ( - id integer primary key DEFAULT nextval('companies_nonstd_seq'), - "type" character varying(50), - "ruby_type" character varying(50), - firm_id integer, - name character varying(50), - client_of integer, - rating integer default 1 -); - -CREATE TABLE developers_projects ( - developer_id integer NOT NULL, - project_id integer NOT NULL, - joined_on date, - access_level integer default 1 -); - -CREATE TABLE developers ( - id serial primary key, - name character varying(100), - salary integer DEFAULT 70000, - created_at timestamp, - updated_at timestamp -); -SELECT setval('developers_id_seq', 100); - -CREATE TABLE projects ( - id serial primary key, - name character varying(100), - type varchar(255) -); -SELECT setval('projects_id_seq', 100); - -CREATE TABLE topics ( - id serial primary key, - title character varying(255), - author_name character varying(255), - author_email_address character varying(255), - written_on timestamp without time zone, - bonus_time time, - last_read date, - content text, - approved boolean default true, - replies_count integer default 0, - parent_id integer, - "type" character varying(50) -); -SELECT setval('topics_id_seq', 100); - -CREATE TABLE customers ( - id serial primary key, - name character varying, - balance integer default 0, - address_street character varying, - address_city character varying, - address_country character varying, - gps_location character varying -); -SELECT setval('customers_id_seq', 100); - -CREATE TABLE orders ( - id serial primary key, - name character varying, - billing_customer_id integer, - shipping_customer_id integer -); -SELECT setval('orders_id_seq', 100); - -CREATE TABLE movies ( - movieid serial primary key, - name text -); - -CREATE TABLE subscribers ( - nick text primary key NOT NULL, - name text -); - -CREATE TABLE booleantests ( - id serial primary key, - value boolean -); - -CREATE TABLE defaults ( - id serial primary key, - modified_date date default CURRENT_DATE, - modified_date_function date default now(), - fixed_date date default '2004-01-01', - modified_time timestamp default CURRENT_TIMESTAMP, - modified_time_function timestamp default now(), - fixed_time timestamp default '2004-01-01 00:00:00.000000-00', - char1 char(1) default 'Y', - char2 character varying(50) default 'a varchar field', - char3 text default 'a text field', - positive_integer integer default 1, - negative_integer integer default -1, - decimal_number decimal(3,2) default 2.78, - multiline_default text DEFAULT '--- [] - -'::text -); - -CREATE TABLE auto_id_tests ( - auto_id serial primary key, - value integer -); - -CREATE TABLE entrants ( - id serial primary key, - name text not null, - course_id integer not null -); - -CREATE TABLE colnametests ( - id serial primary key, - "references" integer NOT NULL -); - -CREATE TABLE mixins ( - id serial primary key, - parent_id integer, - type character varying, - pos integer, - lft integer, - rgt integer, - root_id integer, - created_at timestamp, - updated_at timestamp -); - -CREATE TABLE people ( - id serial primary key, - first_name text, - lock_version integer default 0 -); - -CREATE TABLE readers ( - id serial primary key, - post_id integer NOT NULL, - person_id integer NOT NULL -); - -CREATE TABLE binaries ( - id serial primary key, - data bytea -); - -CREATE TABLE computers ( - id serial primary key, - developer integer NOT NULL, - "extendedWarranty" integer NOT NULL -); - -CREATE TABLE posts ( - id serial primary key, - author_id integer, - title varchar(255), - type varchar(255), - body text -); - -CREATE TABLE comments ( - id serial primary key, - post_id integer, - type varchar(255), - body text -); - -CREATE TABLE authors ( - id serial primary key, - name varchar(255) default NULL -); - -CREATE TABLE tasks ( - id serial primary key, - starting timestamp, - ending timestamp -); - -CREATE TABLE categories ( - id serial primary key, - name varchar(255), - type varchar(255) -); - -CREATE TABLE categories_posts ( - category_id integer NOT NULL, - post_id integer NOT NULL -); - -CREATE TABLE fk_test_has_pk ( - id INTEGER NOT NULL PRIMARY KEY -); - -CREATE TABLE fk_test_has_fk ( - id INTEGER NOT NULL PRIMARY KEY, - fk_id INTEGER NOT NULL REFERENCES fk_test_has_fk(id) -); - -CREATE TABLE geometrics ( - id serial primary key, - a_point point, - -- a_line line, (the line type is currently not implemented in postgresql) - a_line_segment lseg, - a_box box, - a_path path, - a_polygon polygon, - a_circle circle -); - -CREATE TABLE keyboards ( - key_number serial primary key, - "name" character varying(50) -); - ---Altered lock_version column name. -CREATE TABLE legacy_things ( - id serial primary key, - tps_report_number integer, - version integer default 0 -); - -CREATE TABLE numeric_data ( - id serial primary key, - bank_balance decimal(10,2), - big_bank_balance decimal(15,2), - world_population decimal(10), - my_house_population decimal(2), - decimal_number_with_default decimal(3,2) default 2.78 -); - -CREATE TABLE mixed_case_monkeys ( - "monkeyID" INTEGER PRIMARY KEY, - "fleaCount" INTEGER -); - -CREATE TABLE postgresql_arrays ( - id SERIAL PRIMARY KEY, - commission_by_quarter INTEGER[], - nicknames TEXT[] -); - -CREATE TABLE postgresql_moneys ( - id SERIAL PRIMARY KEY, - wealth MONEY -); - -CREATE TABLE postgresql_numbers ( - id SERIAL PRIMARY KEY, - single REAL, - double DOUBLE PRECISION -); - -CREATE TABLE postgresql_times ( - id SERIAL PRIMARY KEY, - time_interval INTERVAL -); - -CREATE TABLE postgresql_network_addresses ( - id SERIAL PRIMARY KEY, - cidr_address CIDR, - inet_address INET, - mac_address MACADDR -); - -CREATE TABLE postgresql_bit_strings ( - id SERIAL PRIMARY KEY, - bit_string BIT(8), - bit_string_varying BIT VARYING(8) -); - -CREATE TABLE postgresql_oids ( - id SERIAL PRIMARY KEY, - obj_id OID -); - -CREATE TABLE minimalistics ( - id serial primary key -); diff --git a/activerecord/test/schema/postgresql2.drop.sql b/activerecord/test/schema/postgresql2.drop.sql deleted file mode 100644 index 09681bf4460fd..0000000000000 --- a/activerecord/test/schema/postgresql2.drop.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE courses; diff --git a/activerecord/test/schema/postgresql2.sql b/activerecord/test/schema/postgresql2.sql deleted file mode 100644 index 4605b9384e54b..0000000000000 --- a/activerecord/test/schema/postgresql2.sql +++ /dev/null @@ -1,4 +0,0 @@ -CREATE TABLE courses ( - id serial primary key, - name text -); diff --git a/activerecord/test/schema/postgresql_specific_schema.rb b/activerecord/test/schema/postgresql_specific_schema.rb new file mode 100644 index 0000000000000..35e9ecf64d824 --- /dev/null +++ b/activerecord/test/schema/postgresql_specific_schema.rb @@ -0,0 +1,103 @@ +ActiveRecord::Schema.define do + + %w(postgresql_arrays postgresql_moneys postgresql_numbers postgresql_times postgresql_network_addresses postgresql_bit_strings + postgresql_oids defaults geometrics).each do |table_name| + drop_table table_name + end + + execute 'DROP SEQUENCE IF EXISTS companies_nonstd_seq CASCADE' + execute 'CREATE SEQUENCE companies_nonstd_seq START 101 OWNED BY companies.id' + execute "ALTER TABLE companies ALTER COLUMN id SET DEFAULT nextval('companies_nonstd_seq')" + execute 'DROP SEQUENCE IF EXISTS companies_id_seq' + + %w(accounts_id_seq developers_id_seq projects_id_seq topics_id_seq customers_id_seq orders_id_seq).each do |seq_name| + execute "SELECT setval('#{seq_name}', 100)" + end + + execute <<_SQL + CREATE TABLE defaults ( + id serial primary key, + modified_date date default CURRENT_DATE, + modified_date_function date default now(), + fixed_date date default '2004-01-01', + modified_time timestamp default CURRENT_TIMESTAMP, + modified_time_function timestamp default now(), + fixed_time timestamp default '2004-01-01 00:00:00.000000-00', + char1 char(1) default 'Y', + char2 character varying(50) default 'a varchar field', + char3 text default 'a text field', + positive_integer integer default 1, + negative_integer integer default -1, + decimal_number decimal(3,2) default 2.78, + multiline_default text DEFAULT '--- [] + +'::text +); +_SQL + + execute <<_SQL + CREATE TABLE geometrics ( + id serial primary key, + a_point point, + -- a_line line, (the line type is currently not implemented in postgresql) + a_line_segment lseg, + a_box box, + a_path path, + a_polygon polygon, + a_circle circle + ); +_SQL + + execute <<_SQL + CREATE TABLE postgresql_arrays ( + id SERIAL PRIMARY KEY, + commission_by_quarter INTEGER[], + nicknames TEXT[] + ); +_SQL + execute <<_SQL + CREATE TABLE postgresql_moneys ( + id SERIAL PRIMARY KEY, + wealth MONEY + ); +_SQL + + execute <<_SQL + CREATE TABLE postgresql_numbers ( + id SERIAL PRIMARY KEY, + single REAL, + double DOUBLE PRECISION + ); +_SQL + + execute <<_SQL + CREATE TABLE postgresql_times ( + id SERIAL PRIMARY KEY, + time_interval INTERVAL + ); +_SQL + + execute <<_SQL + CREATE TABLE postgresql_network_addresses ( + id SERIAL PRIMARY KEY, + cidr_address CIDR, + inet_address INET, + mac_address MACADDR + ); +_SQL + + execute <<_SQL + CREATE TABLE postgresql_bit_strings ( + id SERIAL PRIMARY KEY, + bit_string BIT(8), + bit_string_varying BIT VARYING(8) + ); +_SQL + + execute <<_SQL + CREATE TABLE postgresql_oids ( + id SERIAL PRIMARY KEY, + obj_id OID + ); +_SQL +end \ No newline at end of file diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index 856f2fd6081dd..2e78844c9b945 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -1,322 +1,251 @@ -ActiveRecord::Schema.define do - - # adapter name is checked because we are under a transition of - # moving the sql files under activerecord/test/fixtures/db_definitions - # to this file, schema.rb. - if adapter_name == "MySQL" - - # Please keep these create table statements in alphabetical order - # unless the ordering matters. In which case, define them below - create_table :accounts, :force => true do |t| - t.integer :firm_id - t.integer :credit_limit - end - - create_table :authors, :force => true do |t| - t.string :name, :null => false - end - - create_table :auto_id_tests, :force => true, :id => false do |t| - t.primary_key :auto_id - t.integer :value - end - - create_table :binaries, :force => true do |t| - t.binary :data - end - create_table :binary_fields, :force => true do |t| - t.binary :tiny_blob, :limit => 255 - t.binary :normal_blob, :limit => 65535 - t.binary :medium_blob, :limit => 16777215 - t.binary :long_blob, :limit => 2147483647 - t.text :tiny_text, :limit => 255 - t.text :normal_text, :limit => 65535 - t.text :medium_text, :limit => 16777215 - t.text :long_text, :limit => 2147483647 - end - - create_table :booleantests, :force => true do |t| - t.integer :value - end - - create_table :categories, :force => true do |t| - t.string :name, :null => false - t.string :type - end - - create_table :categories_posts, :force => true, :id => false do |t| - t.integer :category_id, :null => false - t.integer :post_id, :null => false - end - - create_table :colnametests, :force => true do |t| - t.integer :references, :null => false - end - - create_table :comments, :force => true do |t| - t.integer :post_id, :null => false - t.text :body, :null => false - t.string :type - end - - create_table :companies, :force => true do |t| - t.string :type - t.string :ruby_type - t.integer :firm_id - t.string :name - t.integer :client_of - t.integer :rating, :default => 1 +ActiveRecord::Schema.define do + def except(adapter_names_to_exclude) + unless [adapter_names_to_exclude].flatten.include?(adapter_name) + yield end + end - create_table :computers, :force => true do |t| - t.integer :developer, :null => false - t.integer :extendedWarranty, :null => false + #put adapter specific setup here + case adapter_name + # For Firebird, set the sequence values 10000 when create_table is called; + # this prevents primary key collisions between "normally" created records + # and fixture-based (YAML) records. + when "Firebird" + def create_table(*args, &block) + ActiveRecord::Base.connection.create_table(*args, &block) + ActiveRecord::Base.connection.execute "SET GENERATOR #{args.first}_seq TO 10000" end + end - create_table :customers, :force => true do |t| - t.string :name - t.integer :balance, :default => 0 - t.string :address_street - t.string :address_city - t.string :address_country - t.string :gps_location - end - - create_table :developers, :force => true do |t| - t.string :name - t.integer :salary, :default => 70000 - t.datetime :created_at - t.datetime :updated_at - end + # Please keep these create table statements in alphabetical order + # unless the ordering matters. In which case, define them below + create_table :accounts, :force => true do |t| + t.integer :firm_id + t.integer :credit_limit + end - create_table :developers_projects, :force => true, :id => false do |t| - t.integer :developer_id, :null => false - t.integer :project_id, :null => false - t.date :joined_on - t.integer :access_level, :default => 1 - end + create_table :audit_logs, :force => true do |t| + t.column :message, :string, :null=>false + t.column :developer_id, :integer, :null=>false + end - create_table :entrants, :force => true do |t| - t.string :name, :null => false - t.integer :course_id, :null => false - end + create_table :authors, :force => true do |t| + t.string :name, :null => false + t.integer :author_address_id + t.integer :author_address_extra_id + end - create_table :funny_jokes, :force => true do |t| - t.string :name - end + create_table :author_addresses, :force => true do |t| + end - create_table :keyboards, :force => true, :id => false do |t| - t.primary_key :key_number - t.string :name - end + create_table :author_favorites, :force => true do |t| + t.column :author_id, :integer + t.column :favorite_author_id, :integer + end - create_table :legacy_things, :force => true do |t| - t.integer :tps_report_number - t.integer :version, :null => false, :default => 0 - end - create_table :minimalistics, :force => true do |t| - end + create_table :auto_id_tests, :force => true, :id => false do |t| + t.primary_key :auto_id + t.integer :value + end - create_table :mixed_case_monkeys, :force => true, :id => false do |t| - t.primary_key :monkeyID - t.integer :fleaCount - end + create_table :binaries, :force => true do |t| + t.binary :data + end - create_table :mixins, :force => true do |t| - t.integer :parent_id - t.integer :pos - t.datetime :created_at - t.datetime :updated_at - t.integer :lft - t.integer :rgt - t.integer :root_id - t.string :type - end + create_table :books, :force => true do |t| + t.column :name, :string + end - create_table :movies, :force => true, :id => false do |t| - t.primary_key :movieid - t.string :name - end + create_table :booleantests, :force => true do |t| + t.integer :value + end - create_table :numeric_data, :force => true do |t| - t.decimal :bank_balance, :precision => 10, :scale => 2 - t.decimal :big_bank_balance, :precision => 15, :scale => 2 - t.decimal :world_population, :precision => 10, :scale => 0 - t.decimal :my_house_population, :precision => 2, :scale => 0 - t.decimal :decimal_number_with_default, :precision => 3, :scale => 2, :default => 2.78 - end + create_table :categories, :force => true do |t| + t.string :name, :null => false + t.string :type + end - create_table :orders, :force => true do |t| - t.string :name - t.integer :billing_customer_id - t.integer :shipping_customer_id - end + create_table :categories_posts, :force => true, :id => false do |t| + t.integer :category_id, :null => false + t.integer :post_id, :null => false + end - create_table :people, :force => true do |t| - t.string :first_name, :null => false - t.integer :lock_version, :null => false, :default => 0 - end + create_table :categorizations, :force => true do |t| + t.column :category_id, :integer + t.column :post_id, :integer + t.column :author_id, :integer + end - create_table :posts, :force => true do |t| - t.integer :author_id - t.string :title, :null => false - t.text :body, :null => false - t.string :type - t.integer :comments_count, :default => 0 - end + create_table :citations, :force => true do |t| + t.column :book1_id, :integer + t.column :book2_id, :integer + end - create_table :projects, :force => true do |t| - t.string :name - t.string :type - end + create_table :clubs, :force => true do |t| + t.string :name + end - create_table :readers, :force => true do |t| - t.integer :post_id, :null => false - t.integer :person_id, :null => false - end + create_table :colnametests, :force => true do |t| + t.integer :references, :null => false + end - create_table :subscribers, :force => true, :id => false do |t| - t.string :nick, :null => false - t.string :name - end - add_index :subscribers, :nick, :unique => true + create_table :comments, :force => true do |t| + t.integer :post_id, :null => false + t.text :body, :null => false + t.string :type + end - create_table :tasks, :force => true do |t| - t.datetime :starting - t.datetime :ending - end + create_table :companies, :force => true do |t| + t.string :type + t.string :ruby_type + t.integer :firm_id + t.string :name + t.integer :client_of + t.integer :rating, :default => 1 + end - create_table :topics, :force => true do |t| - t.string :title - t.string :author_name - t.string :author_email_address - t.datetime :written_on - t.time :bonus_time - t.date :last_read - t.text :content - t.boolean :approved, :default => true - t.integer :replies_count, :default => 0 - t.integer :parent_id - t.string :type - end + create_table :computers, :force => true do |t| + t.integer :developer, :null => false + t.integer :extendedWarranty, :null => false + end + create_table :customers, :force => true do |t| + t.string :name + t.integer :balance, :default => 0 + t.string :address_street + t.string :address_city + t.string :address_country + t.string :gps_location + end - ### These tables are created last as the order is significant + create_table :developers, :force => true do |t| + t.string :name + t.integer :salary, :default => 70000 + t.datetime :created_at + t.datetime :updated_at + end - # fk_test_has_fk should be before fk_test_has_pk - create_table :fk_test_has_fk, :force => true do |t| - t.integer :fk_id, :null => false - end + create_table :developers_projects, :force => true, :id => false do |t| + t.integer :developer_id, :null => false + t.integer :project_id, :null => false + t.date :joined_on + t.integer :access_level, :default => 1 + end - create_table :fk_test_has_pk, :force => true do |t| - end + create_table :edges, :force => true do |t| + t.column :source_id, :integer, :null => false + t.column :sink_id, :integer, :null => false + end + add_index :edges, [:source_id, :sink_id], :unique => true, :name => 'unique_edge_index' - execute 'alter table fk_test_has_fk - add FOREIGN KEY (`fk_id`) REFERENCES `fk_test_has_pk`(`id`)' + create_table :entrants, :force => true do |t| + t.string :name, :null => false + t.integer :course_id, :null => false + end - else - add_column :posts, :comments_count, :integer, :default => 0 + create_table :funny_jokes, :force => true do |t| + t.string :name end - # For Firebird, set the sequence values 10000 when create_table is called; - # this prevents primary key collisions between "normally" created records - # and fixture-based (YAML) records. - if adapter_name == "Firebird" - def create_table(*args, &block) - ActiveRecord::Base.connection.create_table(*args, &block) - ActiveRecord::Base.connection.execute "SET GENERATOR #{args.first}_seq TO 10000" - end + create_table :items, :force => true do |t| + t.column :name, :integer end - create_table :taggings, :force => true do |t| - t.column :tag_id, :integer - t.column :super_tag_id, :integer - t.column :taggable_type, :string - t.column :taggable_id, :integer + create_table :inept_wizards, :force => true do |t| + t.column :name, :string, :null => false + t.column :city, :string, :null => false + t.column :type, :string end - create_table :tags, :force => true do |t| - t.column :name, :string - t.column :taggings_count, :integer, :default => 0 + create_table :keyboards, :force => true, :id => false do |t| + t.primary_key :key_number + t.string :name end - create_table :categorizations, :force => true do |t| - t.column :category_id, :integer - t.column :post_id, :integer - t.column :author_id, :integer + create_table :legacy_things, :force => true do |t| + t.integer :tps_report_number + t.integer :version, :null => false, :default => 0 end - add_column :posts, :taggings_count, :integer, :default => 0 - add_column :authors, :author_address_id, :integer - add_column :authors, :author_address_extra_id, :integer + create_table :lock_without_defaults, :force => true do |t| + t.column :lock_version, :integer + end - create_table :author_addresses, :force => true do |t| + create_table :lock_without_defaults_cust, :force => true do |t| + t.column :custom_lock_version, :integer end - create_table :author_favorites, :force => true do |t| - t.column :author_id, :integer - t.column :favorite_author_id, :integer + create_table :mateys, :id => false, :force => true do |t| + t.column :pirate_id, :integer + t.column :target_id, :integer + t.column :weight, :integer end - create_table :vertices, :force => true do |t| - t.column :label, :string + create_table :members, :force => true do |t| + t.string :name end - create_table :edges, :force => true do |t| - t.column :source_id, :integer, :null => false - t.column :sink_id, :integer, :null => false + create_table :memberships, :force => true do |t| + t.datetime :joined_on + t.integer :club_id, :member_id + t.boolean :favourite, :default => false + t.string :type end - add_index :edges, [:source_id, :sink_id], :unique => true, :name => 'unique_edge_index' - create_table :lock_without_defaults, :force => true do |t| - t.column :lock_version, :integer + create_table :minimalistics, :force => true do |t| end - create_table :lock_without_defaults_cust, :force => true do |t| - t.column :custom_lock_version, :integer + create_table :mixed_case_monkeys, :force => true, :id => false do |t| + t.primary_key :monkeyID + t.integer :fleaCount end - create_table :items, :force => true do |t| - t.column :name, :integer + create_table :mixins, :force => true do |t| + t.integer :parent_id + t.integer :pos + t.datetime :created_at + t.datetime :updated_at + t.integer :lft + t.integer :rgt + t.integer :root_id + t.string :type end - # For sqlite 3.1.0+, make a table with a autoincrement column - if adapter_name == 'SQLite' and supports_autoincrement? - create_table :table_with_autoincrement, :force => true do |t| - t.column :name, :string - end + create_table :movies, :force => true, :id => false do |t| + t.primary_key :movieid + t.string :name end - # For sqlserver 2000+, ensure real columns can be used - if adapter_name.starts_with?("SQLServer") - create_table :table_with_real_columns, :force => true do |t| - t.column :real_number, :real - end + create_table :numeric_data, :force => true do |t| + t.decimal :bank_balance, :precision => 10, :scale => 2 + t.decimal :big_bank_balance, :precision => 15, :scale => 2 + t.decimal :world_population, :precision => 10, :scale => 0 + t.decimal :my_house_population, :precision => 2, :scale => 0 + t.decimal :decimal_number_with_default, :precision => 3, :scale => 2, :default => 2.78 end - create_table :audit_logs, :force => true do |t| - t.column :message, :string, :null=>false - t.column :developer_id, :integer, :null=>false + create_table :orders, :force => true do |t| + t.string :name + t.integer :billing_customer_id + t.integer :shipping_customer_id end - create_table :books, :force => true do |t| - t.column :name, :string + create_table :owners, :primary_key => :owner_id ,:force => true do |t| + t.string :name end - create_table :citations, :force => true do |t| - t.column :book1_id, :integer - t.column :book2_id, :integer + + create_table :paint_colors, :force => true do |t| + t.integer :non_poly_one_id end - create_table :inept_wizards, :force => true do |t| - t.column :name, :string, :null => false - t.column :city, :string, :null => false - t.column :type, :string + create_table :paint_textures, :force => true do |t| + t.integer :non_poly_two_id end create_table :parrots, :force => true do |t| @@ -329,54 +258,40 @@ def create_table(*args, &block) t.column :updated_on, :datetime end - create_table :pirates, :force => true do |t| - t.column :catchphrase, :string - t.column :parrot_id, :integer - t.column :created_on, :datetime - t.column :updated_on, :datetime - end - create_table :parrots_pirates, :id => false, :force => true do |t| t.column :parrot_id, :integer t.column :pirate_id, :integer end - create_table :treasures, :force => true do |t| - t.column :name, :string - t.column :looter_id, :integer - t.column :looter_type, :string - end - create_table :parrots_treasures, :id => false, :force => true do |t| t.column :parrot_id, :integer t.column :treasure_id, :integer end - create_table :mateys, :id => false, :force => true do |t| - t.column :pirate_id, :integer - t.column :target_id, :integer - t.column :weight, :integer + create_table :people, :force => true do |t| + t.string :first_name, :null => false + t.integer :lock_version, :null => false, :default => 0 end - create_table :ships, :force => true do |t| + create_table :pets, :primary_key => :pet_id ,:force => true do |t| t.string :name - t.datetime :created_at - t.datetime :created_on - t.datetime :updated_at - t.datetime :updated_on + t.integer :owner_id, :integer end - create_table 'warehouse-things', :force => true do |t| - t.integer :value + create_table :pirates, :force => true do |t| + t.column :catchphrase, :string + t.column :parrot_id, :integer + t.column :created_on, :datetime + t.column :updated_on, :datetime end - create_table :owners, :primary_key => :owner_id ,:force => true do |t| - t.string :name - end - - create_table :pets, :primary_key => :pet_id ,:force => true do |t| - t.string :name - t.integer :owner_id, :integer + create_table :posts, :force => true do |t| + t.integer :author_id + t.string :title, :null => false + t.text :body, :null => false + t.string :type + t.integer :comments_count, :default => 0 + t.integer :taggings_count, :default => 0 end create_table :price_estimates, :force => true do |t| @@ -385,8 +300,14 @@ def create_table(*args, &block) t.integer :price end - [:circles, :squares, :triangles, :non_poly_ones, :non_poly_twos].each do |t| - create_table(t, :force => true) { } + create_table :projects, :force => true do |t| + t.string :name + t.string :type + end + + create_table :readers, :force => true do |t| + t.integer :post_id, :null => false + t.integer :person_id, :null => false end create_table :shape_expressions, :force => true do |t| @@ -396,32 +317,84 @@ def create_table(*args, &block) t.integer :shape_id end - create_table :paint_colors, :force => true do |t| - t.integer :non_poly_one_id + create_table :ships, :force => true do |t| + t.string :name + t.datetime :created_at + t.datetime :created_on + t.datetime :updated_at + t.datetime :updated_on end - create_table :paint_textures, :force => true do |t| - t.integer :non_poly_two_id + create_table :sponsors, :force => true do |t| + t.integer :club_id + t.integer :sponsorable_id + t.string :sponsorable_type end - create_table :clubs, :force => true do |t| + create_table :subscribers, :force => true, :id => false do |t| + t.string :nick, :null => false t.string :name end + add_index :subscribers, :nick, :unique => true - create_table :members, :force => true do |t| - t.string :name + create_table :tasks, :force => true do |t| + t.datetime :starting + t.datetime :ending end - create_table :memberships, :force => true do |t| - t.datetime :joined_on - t.integer :club_id, :member_id - t.boolean :favourite, :default => false - t.string :type + create_table :topics, :force => true do |t| + t.string :title + t.string :author_name + t.string :author_email_address + t.datetime :written_on + t.time :bonus_time + t.date :last_read + t.text :content + t.boolean :approved, :default => true + t.integer :replies_count, :default => 0 + t.integer :parent_id + t.string :type end - create_table :sponsors, :force => true do |t| - t.integer :club_id - t.integer :sponsorable_id - t.string :sponsorable_type + create_table :taggings, :force => true do |t| + t.column :tag_id, :integer + t.column :super_tag_id, :integer + t.column :taggable_type, :string + t.column :taggable_id, :integer + end + + create_table :tags, :force => true do |t| + t.column :name, :string + t.column :taggings_count, :integer, :default => 0 + end + + create_table :treasures, :force => true do |t| + t.column :name, :string + t.column :looter_id, :integer + t.column :looter_type, :string + end + + create_table :vertices, :force => true do |t| + t.column :label, :string + end + + create_table 'warehouse-things', :force => true do |t| + t.integer :value + end + + [:circles, :squares, :triangles, :non_poly_ones, :non_poly_twos].each do |t| + create_table(t, :force => true) { } + end + + except 'SQLite' do + # fk_test_has_fk should be before fk_test_has_pk + create_table :fk_test_has_fk, :force => true do |t| + t.integer :fk_id, :null => false + end + + create_table :fk_test_has_pk, :force => true do |t| + 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'})" end end diff --git a/activerecord/test/schema/schema2.rb b/activerecord/test/schema/schema2.rb index 863237d27152a..8527f7ba8f005 100644 --- a/activerecord/test/schema/schema2.rb +++ b/activerecord/test/schema/schema2.rb @@ -1,11 +1,6 @@ ActiveRecord::Schema.define do - # adapter name is checked because we are under a transition of - # moving the sql files under activerecord/test/fixtures/db_definitions - # to this file, schema.rb. - if adapter_name == "MySQL" - Course.connection.create_table :courses, :force => true do |t| - t.column :name, :string, :null => false - end + Course.connection.create_table :courses, :force => true do |t| + t.column :name, :string, :null => false end end diff --git a/activerecord/test/schema/sqlite.drop.sql b/activerecord/test/schema/sqlite.drop.sql deleted file mode 100644 index 419cdaa52cd8b..0000000000000 --- a/activerecord/test/schema/sqlite.drop.sql +++ /dev/null @@ -1,33 +0,0 @@ -DROP TABLE accounts; -DROP TABLE funny_jokes; -DROP TABLE companies; -DROP TABLE topics; -DROP TABLE developers; -DROP TABLE projects; -DROP TABLE developers_projects; -DROP TABLE customers; -DROP TABLE orders; -DROP TABLE movies; -DROP TABLE subscribers; -DROP TABLE booleantests; -DROP TABLE auto_id_tests; -DROP TABLE entrants; -DROP TABLE colnametests; -DROP TABLE mixins; -DROP TABLE people; -DROP TABLE readers; -DROP TABLE binaries; -DROP TABLE computers; -DROP TABLE tasks; -DROP TABLE posts; -DROP TABLE comments; -DROP TABLE authors; -DROP TABLE categories; -DROP TABLE categories_posts; -DROP TABLE fk_test_has_fk; -DROP TABLE fk_test_has_pk; -DROP TABLE keyboards; -DROP TABLE legacy_things; -DROP TABLE numeric_data; -DROP TABLE mixed_case_monkeys; -DROP TABLE minimalistics; diff --git a/activerecord/test/schema/sqlite.sql b/activerecord/test/schema/sqlite.sql deleted file mode 100644 index 27966790b807e..0000000000000 --- a/activerecord/test/schema/sqlite.sql +++ /dev/null @@ -1,219 +0,0 @@ -CREATE TABLE 'accounts' ( - 'id' INTEGER PRIMARY KEY NOT NULL, - 'firm_id' INTEGER DEFAULT NULL, - 'credit_limit' INTEGER DEFAULT NULL -); - -CREATE TABLE 'funny_jokes' ( - 'id' INTEGER PRIMARY KEY NOT NULL, - 'name' TEXT DEFAULT NULL -); - -CREATE TABLE 'companies' ( - 'id' INTEGER PRIMARY KEY NOT NULL, - 'type' VARCHAR(255) DEFAULT NULL, - 'ruby_type' VARCHAR(255) DEFAULT NULL, - 'firm_id' INTEGER DEFAULT NULL, - 'name' TEXT DEFAULT NULL, - 'client_of' INTEGER DEFAULT NULL, - 'rating' INTEGER DEFAULT 1 -); - - -CREATE TABLE 'topics' ( - 'id' INTEGER PRIMARY KEY NOT NULL, - 'title' VARCHAR(255) DEFAULT NULL, - 'author_name' VARCHAR(255) DEFAULT NULL, - 'author_email_address' VARCHAR(255) DEFAULT NULL, - 'written_on' DATETIME DEFAULT NULL, - 'bonus_time' TIME DEFAULT NULL, - 'last_read' DATE DEFAULT NULL, - 'content' TEXT, - 'approved' boolean DEFAULT 't', - 'replies_count' INTEGER DEFAULT 0, - 'parent_id' INTEGER DEFAULT NULL, - 'type' VARCHAR(255) DEFAULT NULL -); - -CREATE TABLE 'developers' ( - 'id' INTEGER PRIMARY KEY NOT NULL, - 'name' TEXT DEFAULT NULL, - 'salary' INTEGER DEFAULT 70000, - 'created_at' DATETIME DEFAULT NULL, - 'updated_at' DATETIME DEFAULT NULL -); - -CREATE TABLE 'projects' ( - 'id' INTEGER PRIMARY KEY NOT NULL, - 'name' TEXT DEFAULT NULL, - 'type' VARCHAR(255) DEFAULT NULL -); - -CREATE TABLE 'developers_projects' ( - 'developer_id' INTEGER NOT NULL, - 'project_id' INTEGER NOT NULL, - 'joined_on' DATE DEFAULT NULL, - 'access_level' INTEGER DEFAULT 1 -); - - -CREATE TABLE 'orders' ( - 'id' INTEGER PRIMARY KEY NOT NULL, - 'name' VARCHAR(255) DEFAULT NULL, - 'billing_customer_id' INTEGER DEFAULT NULL, - 'shipping_customer_id' INTEGER DEFAULT NULL -); - -CREATE TABLE 'customers' ( - 'id' INTEGER PRIMARY KEY NOT NULL, - 'name' VARCHAR(255) DEFAULT NULL, - 'balance' INTEGER DEFAULT 0, - 'address_street' TEXT DEFAULT NULL, - 'address_city' TEXT DEFAULT NULL, - 'address_country' TEXT DEFAULT NULL, - 'gps_location' TEXT DEFAULT NULL -); - -CREATE TABLE 'movies' ( - 'movieid' INTEGER PRIMARY KEY NOT NULL, - 'name' VARCHAR(255) DEFAULT NULL -); - -CREATE TABLE subscribers ( - 'nick' VARCHAR(255) PRIMARY KEY NOT NULL, - 'name' VARCHAR(255) DEFAULT NULL -); - -CREATE TABLE 'booleantests' ( - 'id' INTEGER PRIMARY KEY NOT NULL, - 'value' INTEGER DEFAULT NULL -); - -CREATE TABLE 'auto_id_tests' ( - 'auto_id' INTEGER PRIMARY KEY NOT NULL, - 'value' INTEGER DEFAULT NULL -); - -CREATE TABLE 'entrants' ( - 'id' INTEGER NOT NULL PRIMARY KEY, - 'name' VARCHAR(255) NOT NULL, - 'course_id' INTEGER NOT NULL -); - -CREATE TABLE 'colnametests' ( - 'id' INTEGER NOT NULL PRIMARY KEY, - 'references' INTEGER NOT NULL -); - -CREATE TABLE 'mixins' ( - 'id' INTEGER NOT NULL PRIMARY KEY, - 'parent_id' INTEGER DEFAULT NULL, - 'type' VARCHAR(40) DEFAULT NULL, - 'pos' INTEGER DEFAULT NULL, - 'lft' INTEGER DEFAULT NULL, - 'rgt' INTEGER DEFAULT NULL, - 'root_id' INTEGER DEFAULT NULL, - 'created_at' DATETIME DEFAULT NULL, - 'updated_at' DATETIME DEFAULT NULL -); - -CREATE TABLE 'people' ( - 'id' INTEGER NOT NULL PRIMARY KEY, - 'first_name' VARCHAR(40) DEFAULT NULL, - 'lock_version' INTEGER NOT NULL DEFAULT 0 -); - -CREATE TABLE 'readers' ( - 'id' INTEGER NOT NULL PRIMARY KEY, - 'post_id' INTEGER NOT NULL, - 'person_id' INTEGER NOT NULL -); - -CREATE TABLE 'binaries' ( - 'id' INTEGER NOT NULL PRIMARY KEY, - 'data' BLOB DEFAULT NULL -); - -CREATE TABLE 'computers' ( - 'id' INTEGER NOT NULL PRIMARY KEY, - 'developer' INTEGER NOT NULL, - 'extendedWarranty' INTEGER NOT NULL -); - -CREATE TABLE 'posts' ( - 'id' INTEGER NOT NULL PRIMARY KEY, - 'author_id' INTEGER, - 'title' VARCHAR(255) NOT NULL, - 'type' VARCHAR(255) DEFAULT NULL, - 'body' TEXT NOT NULL -); - -CREATE TABLE 'comments' ( - 'id' INTEGER NOT NULL PRIMARY KEY, - 'post_id' INTEGER NOT NULL, - 'type' VARCHAR(255) DEFAULT NULL, - 'body' TEXT NOT NULL -); - -CREATE TABLE 'authors' ( - 'id' INTEGER NOT NULL PRIMARY KEY, - 'name' VARCHAR(255) NOT NULL -); - -CREATE TABLE 'tasks' ( - 'id' INTEGER NOT NULL PRIMARY KEY, - 'starting' DATETIME DEFAULT NULL, - 'ending' DATETIME DEFAULT NULL -); - -CREATE TABLE 'categories' ( - 'id' INTEGER NOT NULL PRIMARY KEY, - 'name' VARCHAR(255) NOT NULL, - 'type' VARCHAR(255) DEFAULT NULL -); - -CREATE TABLE 'categories_posts' ( - 'category_id' INTEGER NOT NULL, - 'post_id' INTEGER NOT NULL -); - -CREATE TABLE 'fk_test_has_pk' ( - 'id' INTEGER NOT NULL PRIMARY KEY -); - -CREATE TABLE 'fk_test_has_fk' ( - 'id' INTEGER NOT NULL PRIMARY KEY, - 'fk_id' INTEGER NOT NULL, - - FOREIGN KEY ('fk_id') REFERENCES 'fk_test_has_pk'('id') -); - -CREATE TABLE 'keyboards' ( - 'key_number' INTEGER PRIMARY KEY NOT NULL, - 'name' VARCHAR(255) DEFAULT NULL -); - ---Altered lock_version column name. -CREATE TABLE 'legacy_things' ( - 'id' INTEGER NOT NULL PRIMARY KEY, - 'tps_report_number' INTEGER DEFAULT NULL, - 'version' INTEGER NOT NULL DEFAULT 0 -); - -CREATE TABLE 'numeric_data' ( - 'id' INTEGER NOT NULL PRIMARY KEY, - 'bank_balance' DECIMAL(10,2), - 'big_bank_balance' DECIMAL(15,2), - 'world_population' DECIMAL(10), - 'my_house_population' DECIMAL(2), - 'decimal_number_with_default' DECIMAL(3,2) DEFAULT 2.78 -); - -CREATE TABLE mixed_case_monkeys ( - 'monkeyID' INTEGER NOT NULL PRIMARY KEY, - 'fleaCount' INTEGER -); - -CREATE TABLE minimalistics ( - 'id' INTEGER NOT NULL PRIMARY KEY -); diff --git a/activerecord/test/schema/sqlite2.drop.sql b/activerecord/test/schema/sqlite2.drop.sql deleted file mode 100644 index 09681bf4460fd..0000000000000 --- a/activerecord/test/schema/sqlite2.drop.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE courses; diff --git a/activerecord/test/schema/sqlite2.sql b/activerecord/test/schema/sqlite2.sql deleted file mode 100644 index 19b123968ae21..0000000000000 --- a/activerecord/test/schema/sqlite2.sql +++ /dev/null @@ -1,4 +0,0 @@ -CREATE TABLE 'courses' ( - 'id' INTEGER NOT NULL PRIMARY KEY, - 'name' VARCHAR(255) NOT NULL -); diff --git a/activerecord/test/schema/sqlite_specific_schema.rb b/activerecord/test/schema/sqlite_specific_schema.rb new file mode 100644 index 0000000000000..ea05b35fe0f50 --- /dev/null +++ b/activerecord/test/schema/sqlite_specific_schema.rb @@ -0,0 +1,25 @@ +ActiveRecord::Schema.define do + # For sqlite 3.1.0+, make a table with a autoincrement column + if supports_autoincrement? + create_table :table_with_autoincrement, :force => true do |t| + t.column :name, :string + end + end + + execute "DROP TABLE fk_test_has_fk" rescue nil + execute "DROP TABLE fk_test_has_pk" rescue nil + execute <<_SQL + CREATE TABLE 'fk_test_has_pk' ( + 'id' INTEGER NOT NULL PRIMARY KEY + ); +_SQL + + execute <<_SQL + CREATE TABLE 'fk_test_has_fk' ( + 'id' INTEGER NOT NULL PRIMARY KEY, + 'fk_id' INTEGER NOT NULL, + + FOREIGN KEY ('fk_id') REFERENCES 'fk_test_has_pk'('id') + ); +_SQL +end \ No newline at end of file diff --git a/activerecord/test/schema/sqlserver_specific_schema.rb b/activerecord/test/schema/sqlserver_specific_schema.rb new file mode 100644 index 0000000000000..cd8aca2fe5226 --- /dev/null +++ b/activerecord/test/schema/sqlserver_specific_schema.rb @@ -0,0 +1,5 @@ +ActiveRecord::Schema.define do + create_table :table_with_real_columns, :force => true do |t| + t.column :real_number, :real + end +end \ No newline at end of file diff --git a/activerecord/test/schema/sybase.drop.sql b/activerecord/test/schema/sybase.drop.sql deleted file mode 100644 index 1a2cc9ff563e4..0000000000000 --- a/activerecord/test/schema/sybase.drop.sql +++ /dev/null @@ -1,35 +0,0 @@ -DROP TABLE accounts -DROP TABLE funny_jokes -DROP TABLE companies -DROP TABLE topics -DROP TABLE developers -DROP TABLE projects -DROP TABLE developers_projects -DROP TABLE customers -DROP TABLE orders -DROP TABLE movies -DROP TABLE subscribers -DROP TABLE booleantests -DROP TABLE auto_id_tests -DROP TABLE entrants -DROP TABLE colnametests -DROP TABLE mixins -DROP TABLE people -DROP TABLE readers -DROP TABLE binaries -DROP TABLE computers -DROP TABLE tasks -DROP TABLE posts -DROP TABLE comments -DROP TABLE authors -DROP TABLE categories -DROP TABLE categories_posts -DROP TABLE fk_test_has_fk -DROP TABLE fk_test_has_pk -DROP TABLE keyboards -DROP TABLE legacy_things -DROP TABLE numeric_data -DROP TABLE mixed_case_monkeys -DROP TABLE minimalistics -DROP TABLE schema_migrations -go diff --git a/activerecord/test/schema/sybase.sql b/activerecord/test/schema/sybase.sql deleted file mode 100644 index 9f0cb3ebe2bf1..0000000000000 --- a/activerecord/test/schema/sybase.sql +++ /dev/null @@ -1,222 +0,0 @@ -CREATE TABLE accounts ( - id numeric(9,0) IDENTITY PRIMARY KEY, - firm_id int NULL, - credit_limit int NULL -) - -CREATE TABLE funny_jokes ( -id numeric(9,0) IDENTITY PRIMARY KEY, - name varchar(50) NULL -) - -CREATE TABLE companies ( - id numeric(9,0) IDENTITY PRIMARY KEY, - type varchar(50) NULL, - ruby_type varchar(50) NULL, - firm_id int NULL, - name varchar(50) NULL, - client_of int NULL, - rating int default 1 -) - - -CREATE TABLE topics ( - id numeric(9,0) IDENTITY PRIMARY KEY, - title varchar(255) NULL, - author_name varchar(255) NULL, - author_email_address varchar(255) NULL, - written_on datetime NULL, - bonus_time datetime NULL, - last_read datetime NULL, - content varchar(255) NULL, - approved bit default 1, - replies_count int default 0, - parent_id int NULL, - type varchar(50) NULL -) - -CREATE TABLE developers ( - id numeric(9,0) IDENTITY PRIMARY KEY, - name varchar(100) NULL, - salary int default 70000, - created_at datetime NULL, - updated_at datetime NULL -) - -CREATE TABLE projects ( - id numeric(9,0) IDENTITY PRIMARY KEY, - name varchar(100) NULL, - type varchar(255) NULL -) - -CREATE TABLE developers_projects ( - developer_id int NOT NULL, - project_id int NOT NULL, - joined_on datetime NULL, - access_level smallint default 1 -) - -CREATE TABLE orders ( - id numeric(9,0) IDENTITY PRIMARY KEY, - name varchar(100) NULL, - billing_customer_id int NULL, - shipping_customer_id int NULL -) - -CREATE TABLE customers ( - id numeric(9,0) IDENTITY PRIMARY KEY, - name varchar(100) NULL, - balance int default 0, - address_street varchar(100) NULL, - address_city varchar(100) NULL, - address_country varchar(100) NULL, - gps_location varchar(100) NULL -) - -CREATE TABLE movies ( - movieid numeric(9,0) IDENTITY PRIMARY KEY, - name varchar(100) NULL -) - -CREATE TABLE subscribers ( - nick varchar(100) PRIMARY KEY, - name varchar(100) NULL -) - -CREATE TABLE booleantests ( - id numeric(9,0) IDENTITY PRIMARY KEY, - value int NULL -) - -CREATE TABLE auto_id_tests ( - auto_id numeric(9,0) IDENTITY PRIMARY KEY, - value int NULL -) - -CREATE TABLE entrants ( - id numeric(9,0) IDENTITY PRIMARY KEY, - name varchar(255) NOT NULL, - course_id int NOT NULL -) - -CREATE TABLE colnametests ( - id numeric(9,0) IDENTITY PRIMARY KEY, - [references] int NOT NULL -) - -CREATE TABLE mixins ( - id numeric(9,0) IDENTITY PRIMARY KEY, - parent_id int NULL, - pos int NULL, - created_at datetime NULL, - updated_at datetime NULL, - lft int NULL, - rgt int NULL, - root_id int NULL, - type varchar(40) NULL -) - -CREATE TABLE people ( - id numeric(9,0) IDENTITY PRIMARY KEY, - first_name varchar(40) NULL, - lock_version int DEFAULT 0 -) - -CREATE TABLE readers ( - id numeric(9,0) IDENTITY PRIMARY KEY, - post_id int NOT NULL, - person_id int NOT NULL -) - -CREATE TABLE binaries ( - id numeric(9,0) IDENTITY PRIMARY KEY, - data image NULL -) - -CREATE TABLE computers ( - id numeric(9,0) IDENTITY PRIMARY KEY, - developer int NOT NULL, - extendedWarranty int NOT NULL -) - -CREATE TABLE posts ( - id numeric(9,0) IDENTITY PRIMARY KEY, - author_id int NULL, - title varchar(255) NOT NULL, - body varchar(2048) NOT NULL, - type varchar(255) NOT NULL -) - -CREATE TABLE comments ( - id numeric(9,0) IDENTITY PRIMARY KEY, - post_id int NOT NULL, - body varchar(2048) NOT NULL, - type varchar(255) NOT NULL -) - -CREATE TABLE authors ( - id numeric(9,0) IDENTITY PRIMARY KEY, - name varchar(255) NOT NULL -) - -CREATE TABLE tasks ( - id numeric(9,0) IDENTITY PRIMARY KEY, - starting datetime NULL, - ending datetime NULL -) - -CREATE TABLE categories ( - id numeric(9,0) IDENTITY PRIMARY KEY, - name varchar(255) NOT NULL, - type varchar(255) NOT NULL -) - -CREATE TABLE categories_posts ( - category_id int NOT NULL, - post_id int NOT NULL -) - -CREATE TABLE fk_test_has_pk ( - id numeric(9,0) IDENTITY PRIMARY KEY -) - -CREATE TABLE fk_test_has_fk ( - id numeric(9,0) PRIMARY KEY, - fk_id numeric(9,0) NOT NULL, - - FOREIGN KEY (fk_id) REFERENCES fk_test_has_pk(id) -) - - -CREATE TABLE keyboards ( - key_number numeric(9,0) IDENTITY PRIMARY KEY, - name varchar(50) NULL -) - ---This table has an altered lock_version column name. -CREATE TABLE legacy_things ( - id numeric(9,0) IDENTITY PRIMARY KEY, - tps_report_number int default NULL, - version int default 0 -) - - -CREATE TABLE numeric_data ( - id numeric(9,0) IDENTITY PRIMARY KEY, - bank_balance numeric(10,2), - big_bank_balance numeric(15,2), - world_population numeric(10), - my_house_population numeric(2), - decimal_number_with_default numeric(3,2) DEFAULT 2.78 -) - -CREATE TABLE mixed_case_monkeys ( - [monkeyID] numeric(9,0) IDENTITY PRIMARY KEY, - [fleaCount] numeric(9,0) -); - -CREATE TABLE minimalistics ( - id numeric(9,0) IDENTITY PRIMARY KEY -); - -go diff --git a/activerecord/test/schema/sybase2.drop.sql b/activerecord/test/schema/sybase2.drop.sql deleted file mode 100644 index ea1571da0bf94..0000000000000 --- a/activerecord/test/schema/sybase2.drop.sql +++ /dev/null @@ -1,2 +0,0 @@ -DROP TABLE courses -go diff --git a/activerecord/test/schema/sybase2.sql b/activerecord/test/schema/sybase2.sql deleted file mode 100644 index 88f9d329a3286..0000000000000 --- a/activerecord/test/schema/sybase2.sql +++ /dev/null @@ -1,5 +0,0 @@ -CREATE TABLE courses ( - id int NOT NULL PRIMARY KEY, - name varchar(255) NOT NULL -) -go From bf1b1e0925085811f0b58bb4093e678438ea0236 Mon Sep 17 00:00:00 2001 From: Francesc Esplugas Date: Tue, 22 Apr 2008 15:44:13 -0500 Subject: [PATCH 43/48] Rails Edge info returns the latest git commit hash [#36 state:resolved] Signed-off-by: Joshua Peek --- railties/CHANGELOG | 2 + railties/builtin/rails_info/rails/info.rb | 10 ++-- railties/test/rails_info_test.rb | 70 +++++++++++------------ 3 files changed, 39 insertions(+), 43 deletions(-) diff --git a/railties/CHANGELOG b/railties/CHANGELOG index a21bfc72ddc30..6cd2b5364f20b 100644 --- a/railties/CHANGELOG +++ b/railties/CHANGELOG @@ -1,5 +1,7 @@ *SVN* +* Rails Edge info returns the latest git commit hash [Francesc Esplugas] + * Added Rails.public_path to control where HTML and assets are expected to be loaded from (defaults to Rails.root + "/public") #11581 [nicksieger] * rake time:zones:local finds correct base utc offset for zones in the Southern Hemisphere [Geoff Buesing] diff --git a/railties/builtin/rails_info/rails/info.rb b/railties/builtin/rails_info/rails/info.rb index 2bd9b55617216..4cbd2cca4a3d8 100644 --- a/railties/builtin/rails_info/rails/info.rb +++ b/railties/builtin/rails_info/rails/info.rb @@ -29,8 +29,8 @@ def component_version(component) "#{component.classify}::VERSION::STRING".constantize end - def edge_rails_revision(info = svn_info) - info[/^Revision: (\d+)/, 1] || freeze_edge_version + def edge_rails_revision(info = git_info) + info[/commit ([a-z0-9-]+)/, 1] || freeze_edge_version end def freeze_edge_version @@ -67,10 +67,10 @@ def rails_vendor_root @rails_vendor_root ||= "#{RAILS_ROOT}/vendor/rails" end - def svn_info + def git_info env_lang, ENV['LC_ALL'] = ENV['LC_ALL'], 'C' Dir.chdir(rails_vendor_root) do - silence_stderr { `svn info` } + silence_stderr { `git log -n 1` } end ensure ENV['LC_ALL'] = env_lang @@ -98,7 +98,7 @@ def svn_info end end - # The Rails SVN revision, if it's checked out into vendor/rails. + # The Rails Git revision, if it's checked out into vendor/rails. property 'Edge Rails revision' do edge_rails_revision end diff --git a/railties/test/rails_info_test.rb b/railties/test/rails_info_test.rb index a212046586dbb..3e91e2f2eed92 100644 --- a/railties/test/rails_info_test.rb +++ b/railties/test/rails_info_test.rb @@ -23,27 +23,21 @@ def test_edge_rails_revision_not_set_when_svn_info_is_empty end assert !property_defined?('Test that this will not be defined') end - + def test_edge_rails_revision_extracted_from_svn_info Rails::Info.property 'Test Edge Rails revision' do Rails::Info.edge_rails_revision <<-EOS -Path: . -URL: http://www.rubyonrails.com/svn/rails/trunk -Repository UUID: 5ecf4fe2-1ee6-0310-87b1-e25e094e27de -Revision: 2881 -Node Kind: directory -Schedule: normal -Last Changed Author: sam -Last Changed Rev: 2881 -Last Changed Date: 2005-11-04 21:04:41 -0600 (Fri, 04 Nov 2005) -Properties Last Updated: 2005-10-28 19:30:00 -0500 (Fri, 28 Oct 2005) + commit 420c4b3d8878156d04f45e47050ddc62ae00c68c + Author: David Heinemeier Hansson + Date: Sun Apr 13 17:33:27 2008 -0500 + Added Rails.public_path to control where HTML and assets are expected to be loaded from EOS end - - assert_property 'Test Edge Rails revision', '2881' + + assert_property 'Test Edge Rails revision', '420c4b3d8878156d04f45e47050ddc62ae00c68c' end - + def test_property_with_block_swallows_exceptions_and_ignores_property assert_nothing_raised do Rails::Info.module_eval do @@ -52,25 +46,25 @@ def test_property_with_block_swallows_exceptions_and_ignores_property end assert !property_defined?('Bogus') end - + def test_property_with_string Rails::Info.module_eval do property 'Hello', 'World' end assert_property 'Hello', 'World' end - + def test_property_with_block Rails::Info.module_eval do property('Goodbye') {'World'} end assert_property 'Goodbye', 'World' end - + def test_component_version assert_property 'Active Support version', ActiveSupport::VERSION::STRING end - + def test_components_exist Rails::Info.components.each do |component| dir = File.dirname(__FILE__) + "/../../" + component.gsub('_', '') @@ -78,28 +72,28 @@ def test_components_exist end end -protected - def svn_info=(info) - Rails::Info.module_eval do - class << self - def svn_info - info + protected + def svn_info=(info) + Rails::Info.module_eval do + class << self + def svn_info + info + end end end end - end - - def properties - Rails::Info.properties - end - def property_defined?(property_name) - properties.names.include? property_name - end - - def assert_property(property_name, value) - raise "Property #{property_name.inspect} not defined" unless - property_defined? property_name - assert_equal value, properties.value_for(property_name) - end + def properties + Rails::Info.properties + end + + def property_defined?(property_name) + properties.names.include? property_name + end + + def assert_property(property_name, value) + raise "Property #{property_name.inspect} not defined" unless + property_defined? property_name + assert_equal value, properties.value_for(property_name) + end end From ae51013c3f7b8a8579fcb99d889ed80e9dd75797 Mon Sep 17 00:00:00 2001 From: Frederick Cheung Date: Wed, 23 Apr 2008 14:23:53 +1200 Subject: [PATCH 44/48] Provide data for the key column otherwise adding a unique index will fail. [#30 state:closed] --- activerecord/test/cases/migration_test.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb index c270230d67a50..f99e736c554e8 100644 --- a/activerecord/test/cases/migration_test.rb +++ b/activerecord/test/cases/migration_test.rb @@ -79,6 +79,7 @@ def test_add_index # Note: changed index name from "key" to "key_idx" since "key" is a Firebird reserved word # OpenBase does not have named indexes. You must specify a single column name unless current_adapter?(:OpenBaseAdapter) + Person.update_all "#{Person.connection.quote_column_name 'key'}=#{Person.connection.quote_column_name 'id'}" #some databases (including sqlite2 won't add a unique index if existing data non unique) assert_nothing_raised { Person.connection.add_index("people", ["key"], :name => "key_idx", :unique => true) } assert_nothing_raised { Person.connection.remove_index("people", :name => "key_idx", :unique => true) } end From b6aa0e13b4e590b82550a6464924f431e57229df Mon Sep 17 00:00:00 2001 From: Joshua Bates Date: Thu, 17 Apr 2008 11:58:32 -0700 Subject: [PATCH 45/48] Fix include? on has_many collections with finder_sql to fall back to Array include? rather than try to use SQL. [#18 state:resolved] --- .../associations/association_collection.rb | 1 + .../cases/associations/has_many_associations_test.rb | 11 +++++++++++ 2 files changed, 12 insertions(+) diff --git a/activerecord/lib/active_record/associations/association_collection.rb b/activerecord/lib/active_record/associations/association_collection.rb index 9c724d2117669..7e47bf7bdf512 100644 --- a/activerecord/lib/active_record/associations/association_collection.rb +++ b/activerecord/lib/active_record/associations/association_collection.rb @@ -214,6 +214,7 @@ def replace(other_array) def include?(record) return false unless record.is_a?(@reflection.klass) + load_target if @reflection.options[:finder_sql] && !loaded? return @target.include?(record) if loaded? exists?(record) end diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 6f0190e8d9fdb..7b97afe42cfbe 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -832,6 +832,17 @@ def test_include_checks_if_record_exists_if_target_not_loaded assert ! firm.clients.loaded? end + def test_include_loads_collection_if_target_uses_finder_sql + firm = companies(:first_firm) + client = firm.clients_using_sql.first + + firm.reload + assert ! firm.clients_using_sql.loaded? + assert firm.clients_using_sql.include?(client) + assert firm.clients_using_sql.loaded? + end + + def test_include_returns_false_for_non_matching_record_to_verify_scoping firm = companies(:first_firm) client = Client.create!(:name => 'Not Associated') From e6a3ce3392812f707b78d64ffb04ee52f4517d20 Mon Sep 17 00:00:00 2001 From: Eugene Pimenov Date: Fri, 18 Apr 2008 15:45:33 +0400 Subject: [PATCH 46/48] Make sure member names aren't mistakenly set to nil when providing :path_names [#19 state:resolved] Signed-off-by: Michael Koziarski --- actionpack/lib/action_controller/resources.rb | 2 +- actionpack/test/controller/resources_test.rb | 45 ++++++++++++++++--- 2 files changed, 39 insertions(+), 8 deletions(-) diff --git a/actionpack/lib/action_controller/resources.rb b/actionpack/lib/action_controller/resources.rb index df7d6ead1b551..d3cedfdac726a 100644 --- a/actionpack/lib/action_controller/resources.rb +++ b/actionpack/lib/action_controller/resources.rb @@ -527,7 +527,7 @@ def map_member_actions(map, resource) action_path = action if resource.options[:path_names] action_path = resource.options[:path_names][action] - action_path ||= Base.resources_path_names[action] + action_path ||= Base.resources_path_names[action] || action end map.named_route("#{action}_#{resource.name_prefix}#{resource.singular}", "#{resource.member_path}#{resource.action_separator}#{action_path}", action_options) diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb index 0f1ac30f04b6c..b138cee29fbaa 100644 --- a/actionpack/test/controller/resources_test.rb +++ b/actionpack/test/controller/resources_test.rb @@ -209,6 +209,23 @@ def test_with_member_action end end + def test_member_when_override_paths_for_default_restful_actions_with + [:put, :post].each do |method| + with_restful_routing :messages, :member => { :mark => method }, :path_names => {:new => 'nuevo'} do + mark_options = {:action => 'mark', :id => '1', :controller => "messages"} + mark_path = "/messages/1/mark" + + assert_restful_routes_for :messages, :path_names => {:new => 'nuevo'} do |options| + assert_recognizes(options.merge(mark_options), :path => mark_path, :method => method) + end + + assert_restful_named_routes_for :messages, :path_names => {:new => 'nuevo'} do |options| + assert_named_route mark_path, :mark_message_path, mark_options + end + end + end + end + def test_with_two_member_actions_with_same_method [:put, :post].each do |method| with_restful_routing :messages, :member => { :mark => method, :unmark => method } do @@ -674,11 +691,18 @@ def assert_restful_routes_for(controller_name, options = {}) options[:options] ||= {} options[:options][:controller] = options[:controller] || controller_name.to_s + new_action = "new" + edit_action = "edit" + if options[:path_names] + new_action = options[:path_names][:new] || "new" + edit_action = options[:path_names][:edit] || "edit" + end + collection_path = "/#{options[:path_prefix]}#{options[:as] || controller_name}" member_path = "#{collection_path}/1" - new_path = "#{collection_path}/new" - edit_member_path = "#{member_path}/edit" - formatted_edit_member_path = "#{member_path}/edit.xml" + new_path = "#{collection_path}/#{new_action}" + edit_member_path = "#{member_path}/#{edit_action}" + formatted_edit_member_path = "#{member_path}/#{edit_action}.xml" with_options(options[:options]) do |controller| controller.assert_routing collection_path, :action => 'index' @@ -730,15 +754,22 @@ def assert_restful_named_routes_for(controller_name, singular_name = nil, option full_prefix = "/#{options[:path_prefix]}#{options[:as] || controller_name}" name_prefix = options[:name_prefix] + new_action = "new" + edit_action = "edit" + if options[:path_names] + new_action = options[:path_names][:new] || "new" + edit_action = options[:path_names][:edit] || "edit" + end + assert_named_route "#{full_prefix}", "#{name_prefix}#{controller_name}_path", options[:options] assert_named_route "#{full_prefix}.xml", "formatted_#{name_prefix}#{controller_name}_path", options[:options].merge( :format => 'xml') assert_named_route "#{full_prefix}/1", "#{name_prefix}#{singular_name}_path", options[:options].merge(:id => '1') assert_named_route "#{full_prefix}/1.xml", "formatted_#{name_prefix}#{singular_name}_path", options[:options].merge(:id => '1', :format => 'xml') - assert_named_route "#{full_prefix}/new", "new_#{name_prefix}#{singular_name}_path", options[:options] - assert_named_route "#{full_prefix}/new.xml", "formatted_new_#{name_prefix}#{singular_name}_path", options[:options].merge( :format => 'xml') - assert_named_route "#{full_prefix}/1/edit", "edit_#{name_prefix}#{singular_name}_path", options[:options].merge(:id => '1') - assert_named_route "#{full_prefix}/1/edit.xml", "formatted_edit_#{name_prefix}#{singular_name}_path", options[:options].merge(:id => '1', :format => 'xml') + assert_named_route "#{full_prefix}/#{new_action}", "new_#{name_prefix}#{singular_name}_path", options[:options] + assert_named_route "#{full_prefix}/#{new_action}.xml", "formatted_new_#{name_prefix}#{singular_name}_path", options[:options].merge( :format => 'xml') + assert_named_route "#{full_prefix}/1/#{edit_action}", "edit_#{name_prefix}#{singular_name}_path", options[:options].merge(:id => '1') + assert_named_route "#{full_prefix}/1/#{edit_action}.xml", "formatted_edit_#{name_prefix}#{singular_name}_path", options[:options].merge(:id => '1', :format => 'xml') yield options[:options] if block_given? end From 30ad1827a66b8578cabc8f14a67c69b0ab17cf92 Mon Sep 17 00:00:00 2001 From: Sam Granieri Date: Tue, 22 Apr 2008 16:35:21 -0500 Subject: [PATCH 47/48] preventing generated documentation from being picked up by git. [#37 state:resolved] Signed-off-by: Michael Koziarski --- .gitignore | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 2bf1ef8c0e06a..d19b982f85fac 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,7 @@ -debug.log \ No newline at end of file +debug.log +activeresource/doc +activerecord/doc +actionpack/doc +actionmailer/doc +activesupport/doc +railties/doc From 6c1c16bfd9eb865dffa68c12c7df66d5a59a8714 Mon Sep 17 00:00:00 2001 From: David Dollar Date: Sun, 13 Apr 2008 03:36:37 -0400 Subject: [PATCH 48/48] Fixes a subtle bug when using symbols for key definitions in habtm associations --- .../has_and_belongs_to_many_association.rb | 6 ++-- ...s_and_belongs_to_many_associations_test.rb | 29 +++++++++++++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb index d4143e0645dfb..4fa8e9d0a84ee 100644 --- a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb +++ b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb @@ -35,10 +35,10 @@ def insert_record(record, force=true) columns = @owner.connection.columns(@reflection.options[:join_table], "#{@reflection.options[:join_table]} Columns") attributes = columns.inject({}) do |attrs, column| - case column.name - when @reflection.primary_key_name + case column.name.to_s + when @reflection.primary_key_name.to_s attrs[column.name] = @owner.quoted_id - when @reflection.association_foreign_key + when @reflection.association_foreign_key.to_s attrs[column.name] = record.quoted_id else if record.has_attribute?(column.name) diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb index 7867727e2c0c2..64565141f99e7 100644 --- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb @@ -50,6 +50,23 @@ class DeveloperForProjectWithAfterCreateHook < ActiveRecord::Base :foreign_key => "developer_id" end +class ProjectWithSymbolsForKeys < ActiveRecord::Base + set_table_name 'projects' + has_and_belongs_to_many :developers, + :class_name => "DeveloperWithSymbolsForKeys", + :join_table => :developers_projects, + :foreign_key => :project_id, + :association_foreign_key => "developer_id" +end + +class DeveloperWithSymbolsForKeys < ActiveRecord::Base + set_table_name 'developers' + has_and_belongs_to_many :projects, + :class_name => "ProjectWithSymbolsForKeys", + :join_table => :developers_projects, + :association_foreign_key => :project_id, + :foreign_key => "developer_id" +end class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase fixtures :accounts, :companies, :categories, :posts, :categories_posts, :developers, :projects, :developers_projects, @@ -650,4 +667,16 @@ def test_scoped_find_on_through_association_doesnt_return_read_only_records def test_has_many_through_polymorphic_has_manys_works assert_equal [10, 20].to_set, pirates(:redbeard).treasure_estimates.map(&:price).to_set end + + def test_symbols_as_keys + developer = DeveloperWithSymbolsForKeys.new(:name => 'David') + project = ProjectWithSymbolsForKeys.new(:name => 'Rails Testing') + project.developers << developer + project.save! + + assert_equal 1, project.developers.size + assert_equal 1, developer.projects.size + assert_equal developer, project.developers.find(:first) + assert_equal project, developer.projects.find(:first) + end end