diff options
Diffstat (limited to 'railties')
92 files changed, 1001 insertions, 2060 deletions
diff --git a/railties/CHANGELOG b/railties/CHANGELOG index 0bc1ea32bc..fc9277bd28 100644 --- a/railties/CHANGELOG +++ b/railties/CHANGELOG @@ -1,5 +1,9 @@ *Edge* +* Removed config/initializers/new_rails_defaults.rb as all frameworks now follow the settings from it [DHH] + +* Set config.time_zone to UTC by default [DHH] + * Added default .gitignore (this is just recognizing Git market share, don't throw a hissy if you use another SCM) [DHH] * Added cookies.permanent, cookies.signed, and cookies.permanent.signed accessor for common cookie actions [DHH]. Examples: diff --git a/railties/builtin/rails_info/rails/info.rb b/railties/builtin/rails_info/rails/info.rb index c3784cff32..269fe488b0 100644 --- a/railties/builtin/rails_info/rails/info.rb +++ b/railties/builtin/rails_info/rails/info.rb @@ -129,12 +129,12 @@ module Rails # The current Rails environment (development, test, or production). property 'Environment' do - RAILS_ENV + Rails.env end # The name of the database adapter for the current environment. property 'Database adapter' do - ActiveRecord::Base.configurations[RAILS_ENV]['adapter'] + ActiveRecord::Base.configurations[Rails.env]['adapter'] end property 'Database schema version' do diff --git a/railties/builtin/rails_info/rails_info_controller.rb b/railties/builtin/rails_info/rails_info_controller.rb deleted file mode 100644 index 2009eb3a99..0000000000 --- a/railties/builtin/rails_info/rails_info_controller.rb +++ /dev/null @@ -1,2 +0,0 @@ -# Alias to ensure old public.html still works. -RailsInfoController = Rails::InfoController diff --git a/railties/guides/rails_guides/generator.rb b/railties/guides/rails_guides/generator.rb index d4796b65c1..bd25111405 100644 --- a/railties/guides/rails_guides/generator.rb +++ b/railties/guides/rails_guides/generator.rb @@ -101,7 +101,7 @@ module RailsGuides view.content_tag(:li, l) end - children_ul = view.content_tag(:ul, children) + children_ul = view.content_tag(:ul, children.join(" ")) index << view.content_tag(:li, link + children_ul) end diff --git a/railties/guides/rails_guides/indexer.rb b/railties/guides/rails_guides/indexer.rb index 5b5ad3fee1..939404c85f 100644 --- a/railties/guides/rails_guides/indexer.rb +++ b/railties/guides/rails_guides/indexer.rb @@ -19,9 +19,9 @@ module RailsGuides level_hash = ActiveSupport::OrderedHash.new while !s.eos? - s.match?(/\h[0-9]\..*$/) + s.match?(/h[0-9]\..*$/) if matched = s.matched - matched =~ /\h([0-9])\.(.*)$/ + matched =~ /h([0-9])\.(.*)$/ level, title = $1.to_i, $2 if level < current_level diff --git a/railties/guides/source/layout.html.erb b/railties/guides/source/layout.html.erb index eb66366d07..7dfcf4a507 100644 --- a/railties/guides/source/layout.html.erb +++ b/railties/guides/source/layout.html.erb @@ -87,7 +87,7 @@ <div id="container"> <div class="wrapper"> <div id="mainCol"> - <%= yield %> + <%= yield.html_safe! %> </div> </div> </div> diff --git a/railties/lib/rails.rb b/railties/lib/rails.rb index d69e3eea6a..4ded2515fc 100644 --- a/railties/lib/rails.rb +++ b/railties/lib/rails.rb @@ -15,6 +15,7 @@ require 'rails/rack' require 'rails/paths' require 'rails/configuration' require 'rails/deprecation' +require 'rails/subscriber' require 'rails/ruby_version_check' # For Ruby 1.8, this initialization sets $KCODE to 'u' to enable the @@ -29,14 +30,9 @@ else Encoding.default_external = Encoding::UTF_8 end -RAILS_ENV = (ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development").dup unless defined?(RAILS_ENV) - module Rails - # Needs to be duplicated from Active Support since its needed before Active - # Support is available. Here both Options and Hash are namespaced to prevent - # conflicts with other implementations AND with the classes residing in Active Support. - # --- - # TODO: w0t? + autoload :Bootstrap, 'rails/bootstrap' + class << self def application @@application ||= nil @@ -48,7 +44,7 @@ module Rails # The Configuration instance used to configure the Rails environment def configuration - application.configuration + application.config end def initialize! @@ -56,19 +52,19 @@ module Rails end def initialized? - @initialized || false + @@initialized || false end def initialized=(initialized) - @initialized ||= initialized + @@initialized ||= initialized end def logger - if defined?(RAILS_DEFAULT_LOGGER) - RAILS_DEFAULT_LOGGER - else - nil - end + @@logger ||= nil + end + + def logger=(logger) + @@logger = logger end def backtrace_cleaner @@ -84,7 +80,7 @@ module Rails end def env - @_env ||= ActiveSupport::StringInquirer.new(RAILS_ENV) + @_env ||= ActiveSupport::StringInquirer.new(ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development") end def cache diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb index 5401251397..c95316a4da 100644 --- a/railties/lib/rails/application.rb +++ b/railties/lib/rails/application.rb @@ -83,17 +83,19 @@ module Rails end def initializers - initializers = super + initializers = Bootstrap.new(self).initializers plugins.each { |p| initializers += p.initializers } + initializers += super initializers end # TODO: Fix this method def plugins @plugins ||= begin - plugin_names = config.plugins || [:all] - Railtie.plugins.select { |p| plugin_names.include?(:all) || plugin_names.include?(p.plugin_name) }.map { |p| p.new } + - Plugin.all(config.plugins || [:all], config.paths.vendor.plugins) + plugin_names = (config.plugins || [:all]).map { |p| p.to_sym } + Railtie.plugins.select { |p| + plugin_names.include?(:all) || plugin_names.include?(p.plugin_name) + }.map { |p| p.new } + Plugin.all(plugin_names, config.paths.vendor.plugins) end end @@ -102,140 +104,6 @@ module Rails @app.call(env) end - initializer :load_all_active_support do - require "active_support/all" unless config.active_support.bare - end - - # Set the <tt>$LOAD_PATH</tt> based on the value of - # Configuration#load_paths. Duplicates are removed. - initializer :set_load_path do - config.paths.add_to_load_path - $LOAD_PATH.uniq! - end - - # Set the paths from which Rails will automatically load source files, and - # the load_once paths. - initializer :set_autoload_paths do - require 'active_support/dependencies' - ActiveSupport::Dependencies.load_paths = config.load_paths.uniq - ActiveSupport::Dependencies.load_once_paths = config.load_once_paths.uniq - - extra = ActiveSupport::Dependencies.load_once_paths - ActiveSupport::Dependencies.load_paths - unless extra.empty? - abort <<-end_error - load_once_paths must be a subset of the load_paths. - Extra items in load_once_paths: #{extra * ','} - end_error - end - - # Freeze the arrays so future modifications will fail rather than do nothing mysteriously - config.load_once_paths.freeze - end - - # Create tmp directories - initializer :ensure_tmp_directories_exist do - %w(cache pids sessions sockets).each do |dir_to_make| - FileUtils.mkdir_p(File.join(root, 'tmp', dir_to_make)) - end - end - - # Preload all frameworks specified by the Configuration#frameworks. - # Used by Passenger to ensure everything's loaded before forking and - # to avoid autoload race conditions in JRuby. - initializer :preload_frameworks do - ActiveSupport::Autoload.eager_autoload! if config.preload_frameworks - end - - initializer :initialize_cache do - unless defined?(RAILS_CACHE) - silence_warnings { Object.const_set "RAILS_CACHE", ActiveSupport::Cache.lookup_store(config.cache_store) } - - if RAILS_CACHE.respond_to?(:middleware) - # Insert middleware to setup and teardown local cache for each request - config.middleware.insert_after(:"Rack::Lock", RAILS_CACHE.middleware) - end - end - end - - initializer :initialize_logger do - # if the environment has explicitly defined a logger, use it - next if Rails.logger - - unless logger = config.logger - begin - logger = ActiveSupport::BufferedLogger.new(config.log_path) - logger.level = ActiveSupport::BufferedLogger.const_get(config.log_level.to_s.upcase) - if RAILS_ENV == "production" - logger.auto_flushing = false - end - rescue StandardError => e - logger = ActiveSupport::BufferedLogger.new(STDERR) - logger.level = ActiveSupport::BufferedLogger::WARN - logger.warn( - "Rails Error: Unable to access log file. Please ensure that #{config.log_path} exists and is chmod 0666. " + - "The log level has been raised to WARN and the output directed to STDERR until the problem is fixed." - ) - end - end - - # TODO: Why are we silencing warning here? - silence_warnings { Object.const_set "RAILS_DEFAULT_LOGGER", logger } - end - - # Sets the logger for Active Record, Action Controller, and Action Mailer - # (but only for those frameworks that are to be loaded). If the framework's - # logger is already set, it is not changed, otherwise it is set to use - # RAILS_DEFAULT_LOGGER. - initializer :initialize_framework_logging do - ActiveSupport::Dependencies.logger ||= Rails.logger - Rails.cache.logger ||= Rails.logger - end - - # Sets the dependency loading mechanism based on the value of - # Configuration#cache_classes. - initializer :initialize_dependency_mechanism do - # TODO: Remove files from the $" and always use require - ActiveSupport::Dependencies.mechanism = config.cache_classes ? :require : :load - end - - # Loads support for "whiny nil" (noisy warnings when methods are invoked - # on +nil+ values) if Configuration#whiny_nils is true. - initializer :initialize_whiny_nils do - require('active_support/whiny_nil') if config.whiny_nils - end - - # Sets the default value for Time.zone - # If assigned value cannot be matched to a TimeZone, an exception will be raised. - initializer :initialize_time_zone do - if config.time_zone - require 'active_support/core_ext/time/zones' - zone_default = Time.__send__(:get_zone, config.time_zone) - - unless zone_default - raise \ - 'Value assigned to config.time_zone not recognized.' + - 'Run "rake -D time" for a list of tasks for finding appropriate time zone names.' - end - - Time.zone_default = zone_default - end - end - - # Set the i18n configuration from config.i18n but special-case for the load_path which should be - # appended to what's already set instead of overwritten. - initializer :initialize_i18n do - config.i18n.each do |setting, value| - if setting == :load_path - I18n.load_path += value - else - I18n.send("#{setting}=", value) - end - end - end - - # # bail out if gems are missing - note that check_gem_dependencies will have - # # already called abort() unless $gems_rake_task is set - # return unless gems_dependencies_loaded initializer :load_application_initializers do Dir["#{root}/config/initializers/**/*.rb"].sort.each do |initializer| load(initializer) diff --git a/railties/lib/rails/bootstrap.rb b/railties/lib/rails/bootstrap.rb new file mode 100644 index 0000000000..b7cf70747a --- /dev/null +++ b/railties/lib/rails/bootstrap.rb @@ -0,0 +1,156 @@ +module Rails + class Bootstrap #< Railtie + include Initializable + + def initialize(application) + @application = application + end + + delegate :config, :root, :to => :'@application' + + initializer :load_all_active_support do + require "active_support/all" unless config.active_support.bare + end + + # Set the <tt>$LOAD_PATH</tt> based on the value of + # Configuration#load_paths. Duplicates are removed. + initializer :set_load_path do + config.paths.add_to_load_path + $LOAD_PATH.uniq! + end + + # Set the paths from which Rails will automatically load source files, and + # the load_once paths. + initializer :set_autoload_paths do + require 'active_support/dependencies' + ActiveSupport::Dependencies.load_paths = config.load_paths.uniq + ActiveSupport::Dependencies.load_once_paths = config.load_once_paths.uniq + + extra = ActiveSupport::Dependencies.load_once_paths - ActiveSupport::Dependencies.load_paths + unless extra.empty? + abort <<-end_error + load_once_paths must be a subset of the load_paths. + Extra items in load_once_paths: #{extra * ','} + end_error + end + + # Freeze the arrays so future modifications will fail rather than do nothing mysteriously + config.load_once_paths.freeze + end + + # Create tmp directories + initializer :ensure_tmp_directories_exist do + %w(cache pids sessions sockets).each do |dir_to_make| + FileUtils.mkdir_p(File.join(root, 'tmp', dir_to_make)) + end + end + + # Preload all frameworks specified by the Configuration#frameworks. + # Used by Passenger to ensure everything's loaded before forking and + # to avoid autoload race conditions in JRuby. + initializer :preload_frameworks do + ActiveSupport::Autoload.eager_autoload! if config.preload_frameworks + end + + initializer :initialize_cache do + unless defined?(RAILS_CACHE) + silence_warnings { Object.const_set "RAILS_CACHE", ActiveSupport::Cache.lookup_store(config.cache_store) } + + if RAILS_CACHE.respond_to?(:middleware) + # Insert middleware to setup and teardown local cache for each request + config.middleware.insert_after(:"Rack::Lock", RAILS_CACHE.middleware) + end + end + end + + initializer :initialize_logger do + Rails.logger ||= config.logger || begin + logger = ActiveSupport::BufferedLogger.new(config.log_path) + logger.level = ActiveSupport::BufferedLogger.const_get(config.log_level.to_s.upcase) + logger.auto_flushing = false if Rails.env.production? + logger + rescue StandardError => e + logger = ActiveSupport::BufferedLogger.new(STDERR) + logger.level = ActiveSupport::BufferedLogger::WARN + logger.warn( + "Rails Error: Unable to access log file. Please ensure that #{config.log_path} exists and is chmod 0666. " + + "The log level has been raised to WARN and the output directed to STDERR until the problem is fixed." + ) + logger + end + end + + # Sets the logger for dependencies and cache store. + initializer :initialize_framework_logging do + ActiveSupport::Dependencies.logger ||= Rails.logger + Rails.cache.logger ||= Rails.logger + end + + # Sets the dependency loading mechanism based on the value of + # Configuration#cache_classes. + initializer :initialize_dependency_mechanism do + # TODO: Remove files from the $" and always use require + ActiveSupport::Dependencies.mechanism = config.cache_classes ? :require : :load + end + + # Loads support for "whiny nil" (noisy warnings when methods are invoked + # on +nil+ values) if Configuration#whiny_nils is true. + initializer :initialize_whiny_nils do + require 'active_support/whiny_nil' if config.whiny_nils + end + + # Sets the default value for Time.zone + # If assigned value cannot be matched to a TimeZone, an exception will be raised. + initializer :initialize_time_zone do + require 'active_support/core_ext/time/zones' + zone_default = Time.__send__(:get_zone, config.time_zone) + + unless zone_default + raise \ + 'Value assigned to config.time_zone not recognized.' + + 'Run "rake -D time" for a list of tasks for finding appropriate time zone names.' + end + + Time.zone_default = zone_default + end + + # Set the i18n configuration from config.i18n but special-case for the load_path which should be + # appended to what's already set instead of overwritten. + initializer :initialize_i18n do + require 'active_support/i18n' + + config.i18n.each do |setting, value| + if setting == :load_path + I18n.load_path += value + else + I18n.send("#{setting}=", value) + end + end + + ActionDispatch::Callbacks.to_prepare do + I18n.reload! + end + end + + initializer :set_clear_dependencies_hook do + unless config.cache_classes + ActionDispatch::Callbacks.after do + ActiveSupport::Dependencies.clear + end + end + end + + initializer :initialize_notifications do + require 'active_support/notifications' + + if config.colorize_logging == false + Rails::Subscriber.colorize_logging = false + config.generators.colorize_logging = false + end + + ActiveSupport::Notifications.subscribe do |*args| + Rails::Subscriber.dispatch(args) + end + end + end +end diff --git a/railties/lib/rails/commands/console.rb b/railties/lib/rails/commands/console.rb index 37eb6d40ea..27ac7fd20a 100644 --- a/railties/lib/rails/commands/console.rb +++ b/railties/lib/rails/commands/console.rb @@ -4,8 +4,6 @@ require "irb/completion" module Rails class Console - ENVIRONMENTS = %w(production development test) - def self.start(app) new(app).start end @@ -25,10 +23,6 @@ module Rails opt.parse!(ARGV) end - if env = ARGV.first - ENV['RAILS_ENV'] = ENVIRONMENTS.find { |e| e.index(env) } || env - end - @app.initialize! require "rails/console_app" require "rails/console_sandbox" if options[:sandbox] @@ -54,3 +48,8 @@ module Rails end end end + +# Has to set the RAILS_ENV before config/application is required +if ARGV.first && !ARGV.first.index("-") && env = ARGV.pop # has to pop the env ARGV so IRB doesn't freak + ENV['RAILS_ENV'] = %w(production development test).find { |e| e.index(env) } || env +end diff --git a/railties/lib/rails/commands/dbconsole.rb b/railties/lib/rails/commands/dbconsole.rb index 77c3404343..593e2d8ee3 100644 --- a/railties/lib/rails/commands/dbconsole.rb +++ b/railties/lib/rails/commands/dbconsole.rb @@ -34,9 +34,8 @@ module Rails abort opt.to_s unless (0..1).include?(ARGV.size) end - env = ARGV.first || ENV['RAILS_ENV'] || 'development' - unless config = YAML::load(ERB.new(IO.read("#{@app.root}/config/database.yml")).result)[env] - abort "No database is configured for the environment '#{env}'" + unless config = YAML::load(ERB.new(IO.read("#{@app.root}/config/database.yml")).result)[Rails.env] + abort "No database is configured for the environment '#{Rails.env}'" end @@ -97,4 +96,9 @@ module Rails end end end +end + +# Has to set the RAILS_ENV before config/application is required +if ARGV.first && !ARGV.first.index("-") && env = ARGV.first + ENV['RAILS_ENV'] = %w(production development test).find { |e| e.index(env) } || env end
\ No newline at end of file diff --git a/railties/lib/rails/commands/destroy.rb b/railties/lib/rails/commands/destroy.rb index f85c17bb94..a2eff377ce 100644 --- a/railties/lib/rails/commands/destroy.rb +++ b/railties/lib/rails/commands/destroy.rb @@ -7,4 +7,4 @@ if ARGV.size == 0 end name = ARGV.shift -Rails::Generators.invoke name, ARGV, :behavior => :revoke +Rails::Generators.invoke name, ARGV, :behavior => :revoke, :destination_root => Rails.root diff --git a/railties/lib/rails/commands/generate.rb b/railties/lib/rails/commands/generate.rb index c5e3ae3529..c1120aad74 100755 --- a/railties/lib/rails/commands/generate.rb +++ b/railties/lib/rails/commands/generate.rb @@ -7,4 +7,4 @@ if ARGV.size == 0 end name = ARGV.shift -Rails::Generators.invoke name, ARGV, :behavior => :invoke +Rails::Generators.invoke name, ARGV, :behavior => :invoke, :destination_root => Rails.root diff --git a/railties/lib/rails/commands/runner.rb b/railties/lib/rails/commands/runner.rb index 0246348c77..4487d2e7b1 100644 --- a/railties/lib/rails/commands/runner.rb +++ b/railties/lib/rails/commands/runner.rb @@ -34,7 +34,6 @@ end ARGV.delete(code_or_file) ENV["RAILS_ENV"] = options[:environment] -RAILS_ENV.replace(options[:environment]) if defined?(RAILS_ENV) begin if code_or_file.nil? diff --git a/railties/lib/rails/commands/server.rb b/railties/lib/rails/commands/server.rb index 09d7207d51..115499db05 100644 --- a/railties/lib/rails/commands/server.rb +++ b/railties/lib/rails/commands/server.rb @@ -38,15 +38,15 @@ module Rails end def start + ENV["RAILS_ENV"] = options[:environment] + puts "=> Booting #{ActiveSupport::Inflector.demodulize(server)}" - puts "=> Rails #{Rails.version} application starting on http://#{options[:Host]}:#{options[:Port]}" + puts "=> Rails #{Rails.version} application starting in #{Rails.env} on http://#{options[:Host]}:#{options[:Port]}" puts "=> Call with -d to detach" unless options[:daemonize] trap(:INT) { exit } puts "=> Ctrl-C to shutdown server" unless options[:daemonize] - ENV["RAILS_ENV"] = options[:environment] - RAILS_ENV.replace(options[:environment]) if defined?(RAILS_ENV) - + initialize_log_tailer! unless options[:daemonize] super ensure puts 'Exiting' unless options[:daemonize] @@ -54,7 +54,6 @@ module Rails def middleware middlewares = [] - middlewares << [Rails::Rack::LogTailer, log_path] unless options[:daemonize] middlewares << [Rails::Rack::Debugger] if options[:debugger] Hash.new(middlewares) end @@ -72,5 +71,14 @@ module Rails :pid => "tmp/pids/server.pid" }) end + + protected + + # LogTailer should not be used as a middleware since the logging happens + # async in a request and the middleware calls are sync. So we send it + # to subscriber which will be responsible for calling tail! in the log tailer. + def initialize_log_tailer! + Rails::Subscriber.log_tailer = Rails::Rack::LogTailer.new(nil, log_path) + end end end diff --git a/railties/lib/rails/configuration.rb b/railties/lib/rails/configuration.rb index f0a0d5e55e..a2fab120cf 100644 --- a/railties/lib/rails/configuration.rb +++ b/railties/lib/rails/configuration.rb @@ -4,11 +4,25 @@ module Rails # Temporarily separate the plugin configuration class from the main # configuration class while this bit is being cleaned up. class Railtie::Configuration - def self.default @default ||= new end + def self.default_middleware_stack + ActionDispatch::MiddlewareStack.new.tap do |middleware| + middleware.use('ActionDispatch::Static', lambda { Rails.public_path }, :if => lambda { Rails.application.config.serve_static_assets }) + middleware.use('::Rack::Lock', :if => lambda { !ActionController::Base.allow_concurrency }) + middleware.use('::Rack::Runtime') + middleware.use('ActionDispatch::ShowExceptions', lambda { ActionController::Base.consider_all_requests_local }) + middleware.use('ActionDispatch::Callbacks', lambda { ActionController::Dispatcher.prepare_each_request }) + middleware.use(lambda { ActionController::Base.session_store }, lambda { ActionController::Base.session_options }) + middleware.use('ActionDispatch::Flash', :if => lambda { ActionController::Base.session_store }) + middleware.use('ActionDispatch::ParamsParser') + middleware.use('::Rack::MethodOverride') + middleware.use('::ActionDispatch::Head') + end + end + attr_reader :middleware def initialize(base = nil) @@ -17,7 +31,7 @@ module Rails @middleware = base.middleware.dup else @options = Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new } - @middleware = ActionDispatch::MiddlewareStack.new + @middleware = self.class.default_middleware_stack end end @@ -51,17 +65,16 @@ module Rails end class Configuration < Railtie::Configuration - attr_accessor :after_initialize_blocks, :cache_classes, - :consider_all_requests_local, :dependency_loading, :gems, + attr_accessor :after_initialize_blocks, :cache_classes, :colorize_logging, + :consider_all_requests_local, :dependency_loading, :load_once_paths, :logger, :metals, :plugins, :preload_frameworks, :reload_plugins, :serve_static_assets, :time_zone, :whiny_nils attr_writer :cache_store, :controller_paths, :database_configuration_file, :eager_load_paths, - :i18n, :load_paths, - :log_level, :log_path, :paths, :routes_configuration_file, - :view_path + :i18n, :load_paths, :log_level, :log_path, :paths, + :routes_configuration_file, :view_path def initialize(base = nil) super @@ -114,14 +127,14 @@ module Rails paths.tmp.cache "tmp/cache" paths.config "config" paths.config.locales "config/locales" - paths.config.environments "config/environments", :glob => "#{RAILS_ENV}.rb" + paths.config.environments "config/environments", :glob => "#{Rails.env}.rb" paths end end def frameworks(*args) - raise "config.frameworks in no longer supported. See the generated" \ - "config/boot.rb for steps on how to limit the frameworks that" \ + raise "config.frameworks in no longer supported. See the generated " \ + "config/boot.rb for steps on how to limit the frameworks that " \ "will be loaded" end alias frameworks= frameworks @@ -197,7 +210,7 @@ module Rails paths = [] # Add the old mock paths only if the directories exists - paths.concat(Dir["#{root}/test/mocks/#{RAILS_ENV}"]) if File.exists?("#{root}/test/mocks/#{RAILS_ENV}") + paths.concat(Dir["#{root}/test/mocks/#{Rails.env}"]) if File.exists?("#{root}/test/mocks/#{Rails.env}") # Add the app's controller directory paths.concat(Dir["#{root}/app/controllers/"]) @@ -220,15 +233,19 @@ module Rails def builtin_directories # Include builtins only in the development environment. - (RAILS_ENV == 'development') ? Dir["#{RAILTIES_PATH}/builtin/*/"] : [] + Rails.env.development? ? Dir["#{RAILTIES_PATH}/builtin/*/"] : [] end def log_path - @log_path ||= File.join(root, 'log', "#{RAILS_ENV}.log") + @log_path ||= File.join(root, 'log', "#{Rails.env}.log") end def log_level - @log_level ||= RAILS_ENV == 'production' ? :info : :debug + @log_level ||= Rails.env.production? ? :info : :debug + end + + def time_zone + @time_zone ||= "UTC" end def i18n @@ -246,7 +263,7 @@ module Rails end def environment_path - "#{root}/config/environments/#{RAILS_ENV}.rb" + "#{root}/config/environments/#{Rails.env}.rb" end # Holds generators configuration: @@ -270,10 +287,14 @@ module Rails end end - # Allows Notifications queue to be modified. + # Allow Notifications queue to be modified or add subscriptions: # # config.notifications.queue = MyNewQueue.new # + # config.notifications.subscribe /action_dispatch.show_exception/ do |*args| + # ExceptionDeliver.deliver_exception(args) + # end + # def notifications ActiveSupport::Notifications end diff --git a/railties/lib/rails/deprecation.rb b/railties/lib/rails/deprecation.rb index 3c5b8bdec7..43f08d13df 100644 --- a/railties/lib/rails/deprecation.rb +++ b/railties/lib/rails/deprecation.rb @@ -6,8 +6,8 @@ RAILS_ROOT = (Class.new(ActiveSupport::Deprecation::DeprecationProxy) do Rails.root end - def replace(val) - puts OMG + def replace(*args) + warn(caller, :replace, *args) end def warn(callstack, called, args) @@ -16,10 +16,32 @@ RAILS_ROOT = (Class.new(ActiveSupport::Deprecation::DeprecationProxy) do end end).new -module Rails - class Configuration - def gem(*args) - ActiveSupport::Deprecation.warn("config.gem has been deprecated in favor of the Gemfile.") - end +RAILS_ENV = (Class.new(ActiveSupport::Deprecation::DeprecationProxy) do + def target + Rails.env + end + + def replace(*args) + warn(caller, :replace, *args) + end + + def warn(callstack, called, args) + msg = "RAILS_ENV is deprecated! Use Rails.env instead." + ActiveSupport::Deprecation.warn(msg, callstack) + end +end).new + +RAILS_DEFAULT_LOGGER = (Class.new(ActiveSupport::Deprecation::DeprecationProxy) do + def target + Rails.logger end -end
\ No newline at end of file + + def replace(*args) + warn(caller, :replace, *args) + end + + def warn(callstack, called, args) + msg = "RAILS_DEFAULT_LOGGER is deprecated! Use Rails.logger instead." + ActiveSupport::Deprecation.warn(msg, callstack) + end +end).new diff --git a/railties/lib/rails/dispatcher.rb b/railties/lib/rails/dispatcher.rb index 7f9a6221d9..5d383eacd1 100644 --- a/railties/lib/rails/dispatcher.rb +++ b/railties/lib/rails/dispatcher.rb @@ -20,5 +20,5 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #++ -require 'action_controller/dispatch/dispatcher' +require 'action_controller/deprecated/dispatcher' Dispatcher = ActionController::Dispatcher diff --git a/railties/lib/rails/generators/base.rb b/railties/lib/rails/generators/base.rb index 5e8c2730fd..26abb46644 100644 --- a/railties/lib/rails/generators/base.rb +++ b/railties/lib/rails/generators/base.rb @@ -12,16 +12,6 @@ module Rails add_runtime_options! - # Always move to rails source root. - # - def initialize(*args) #:nodoc: - if !invoked?(args) && defined?(Rails.root) && Rails.root - self.destination_root = Rails.root - FileUtils.cd(destination_root) - end - super - end - # Automatically sets the source root based on the class name. # def self.source_root @@ -268,13 +258,6 @@ module Rails end end - # Check if this generator was invoked from another one by inspecting - # parameters. - # - def invoked?(args) - args.last.is_a?(Hash) && (args.last.key?(:invocations) || args.last.key?(:destination_root)) - end - # Use Rails default banner. # def self.banner diff --git a/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb b/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb index d02028d983..9c19a09616 100644 --- a/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb +++ b/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb @@ -8,10 +8,6 @@ </div> <% end -%> <div class="actions"> - <%% if @<%= singular_name %>.new_record? %> - <%%= f.submit 'Create' %> - <%% else %> - <%%= f.submit 'Update' %> - <%% end %> + <%%= f.submit %> </div> <%% end %> diff --git a/railties/lib/rails/generators/erb/scaffold/templates/layout.html.erb b/railties/lib/rails/generators/erb/scaffold/templates/layout.html.erb index 51c4ad0e2e..7aa049fe80 100644 --- a/railties/lib/rails/generators/erb/scaffold/templates/layout.html.erb +++ b/railties/lib/rails/generators/erb/scaffold/templates/layout.html.erb @@ -1,7 +1,6 @@ <!DOCTYPE html> <html> <head> - <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <title><%= controller_class_name %>: <%%= controller.action_name %></title> <%%= stylesheet_link_tag 'scaffold' %> </head> diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb index fc6a3cdee8..d58d245168 100644 --- a/railties/lib/rails/generators/rails/app/app_generator.rb +++ b/railties/lib/rails/generators/rails/app/app_generator.rb @@ -168,12 +168,14 @@ module Rails::Generators raise Error, "The template [#{rails_template}] could not be loaded. Error: #{e}" end + def bundle_if_dev_or_edge + run "gem bundle" if dev_or_edge? + end + protected attr_accessor :rails_template def set_default_accessors! - app_name # Cache app name - self.rails_template = case options[:template] when /^http:\/\// options[:template] @@ -193,8 +195,12 @@ module Rails::Generators @app_name ||= File.basename(destination_root) end + def app_const_base + @app_const_base ||= app_name.gsub(/\W/, '_').squeeze('_').camelize + end + def app_const - @app_const ||= "#{app_name.gsub(/\W/, '_').squeeze('_').classify}::Application" + @app_const ||= "#{app_const_base}::Application" end def valid_app_const? diff --git a/railties/lib/rails/generators/rails/app/templates/Gemfile b/railties/lib/rails/generators/rails/app/templates/Gemfile index 59c6d333e2..7b5c89c3e2 100644 --- a/railties/lib/rails/generators/rails/app/templates/Gemfile +++ b/railties/lib/rails/generators/rails/app/templates/Gemfile @@ -5,7 +5,8 @@ gem "rails", "<%= Rails::VERSION::STRING %>" ## Bundle edge rails: <%- if options.dev? -%> -gem "rails", :path => "<%= Rails::Generators::RAILS_DEV_PATH %>" +directory "<%= Rails::Generators::RAILS_DEV_PATH %>", :glob => "{*/,}*.gemspec" +gem "rails", "<%= Rails::VERSION::STRING %>" <%- else -%> <%= "# " unless options.edge? %>gem "rails", :git => "git://github.com/rails/rails.git" <%- end -%> diff --git a/railties/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb b/railties/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb index 9889b52893..2cdf4eae54 100644 --- a/railties/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb +++ b/railties/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb @@ -1,8 +1,4 @@ -# Filters added to this controller apply to all controllers in the application. -# Likewise, all the methods added will be available for all controllers. - class ApplicationController < ActionController::Base - helper :all protect_from_forgery filter_parameter_logging :password end diff --git a/railties/lib/rails/generators/rails/app/templates/app/helpers/application_helper.rb b/railties/lib/rails/generators/rails/app/templates/app/helpers/application_helper.rb index 22a7940eb2..de6be7945c 100644 --- a/railties/lib/rails/generators/rails/app/templates/app/helpers/application_helper.rb +++ b/railties/lib/rails/generators/rails/app/templates/app/helpers/application_helper.rb @@ -1,3 +1,2 @@ -# Methods added to this helper will be available to all templates in the application. module ApplicationHelper end diff --git a/railties/lib/rails/generators/rails/app/templates/config.ru b/railties/lib/rails/generators/rails/app/templates/config.ru index acb8435446..2ab821e38d 100644 --- a/railties/lib/rails/generators/rails/app/templates/config.ru +++ b/railties/lib/rails/generators/rails/app/templates/config.ru @@ -1,5 +1,4 @@ -# Require your environment file to bootstrap Rails -require ::File.expand_path('../config/environment', __FILE__) +# This file is used by Rack-based servers to start the application. -# Dispatch the request +require ::File.expand_path('../config/environment', __FILE__) run <%= app_const %>.instance diff --git a/railties/lib/rails/generators/rails/app/templates/config/application.rb b/railties/lib/rails/generators/rails/app/templates/config/application.rb index 4097f766a6..334820826f 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/application.rb +++ b/railties/lib/rails/generators/rails/app/templates/config/application.rb @@ -1,6 +1,6 @@ require File.expand_path('../boot', __FILE__) -module <%= app_name.classify %> +module <%= app_const_base %> class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers @@ -17,15 +17,14 @@ module <%= app_name.classify %> # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. - # Run "rake -D time" for a list of tasks for finding time zone names. - config.time_zone = 'UTC' + # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. + # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')] # config.i18n.default_locale = :de - # Configure generators values. Many other options are available, be sure to - # check the documentation. + # Configure generators values. Many other options are available, be sure to check the documentation. # config.generators do |g| # g.orm :active_record # g.template_engine :erb diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/cookie_verification_secret.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/initializers/cookie_verification_secret.rb.tt index 9f05cd5a31..451dbe1d1c 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/initializers/cookie_verification_secret.rb.tt +++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/cookie_verification_secret.rb.tt @@ -4,4 +4,4 @@ # If you change this key, all old signed cookies will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. -ActionController::Base.cookie_verifier_secret = '<%= app_secret %>'; +ActionController::Base.cookie_verifier_secret = '<%= app_secret %>' diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/new_rails_defaults.rb b/railties/lib/rails/generators/rails/app/templates/config/initializers/new_rails_defaults.rb deleted file mode 100644 index 8ec3186c84..0000000000 --- a/railties/lib/rails/generators/rails/app/templates/config/initializers/new_rails_defaults.rb +++ /dev/null @@ -1,19 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# These settings change the behavior of Rails 2 apps and will be defaults -# for Rails 3. You can remove this initializer when Rails 3 is released. - -if defined?(ActiveRecord) - # Include Active Record class name as root for JSON serialized output. - ActiveRecord::Base.include_root_in_json = true - - # Store the full class name (including module namespace) in STI type column. - ActiveRecord::Base.store_full_sti_class = true -end - -# Use ISO 8601 format for JSON serialized times and dates. -ActiveSupport.use_standard_json_time_format = true - -# Don't escape HTML entities in JSON, leave that for the #json_escape helper. -# if you're including raw json in an HTML page. -ActiveSupport.escape_html_entities_in_json = false
\ No newline at end of file diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt index 4499ab84b6..baff704d3e 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt +++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt @@ -5,8 +5,8 @@ # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. ActionController::Base.session = { - :key => '_<%= app_name %>_session', - :secret => '<%= app_secret %>' + :key => '_<%= app_name %>_session', + :secret => '<%= app_secret %>' } # Use the database for sessions instead of the cookie-based default, diff --git a/railties/lib/rails/generators/rails/app/templates/public/404.html b/railties/lib/rails/generators/rails/app/templates/public/404.html index 88ee108e90..9a48320a5f 100644 --- a/railties/lib/rails/generators/rails/app/templates/public/404.html +++ b/railties/lib/rails/generators/rails/app/templates/public/404.html @@ -1,7 +1,6 @@ <!DOCTYPE html> <html> <head> - <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <title>The page you were looking for doesn't exist (404)</title> <style type="text/css"> body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; } diff --git a/railties/lib/rails/generators/rails/app/templates/public/422.html b/railties/lib/rails/generators/rails/app/templates/public/422.html index 9c3c96670b..83660ab187 100644 --- a/railties/lib/rails/generators/rails/app/templates/public/422.html +++ b/railties/lib/rails/generators/rails/app/templates/public/422.html @@ -1,7 +1,6 @@ <!DOCTYPE html> <html> <head> - <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <title>The change you wanted was rejected (422)</title> <style type="text/css"> body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; } diff --git a/railties/lib/rails/generators/rails/app/templates/public/500.html b/railties/lib/rails/generators/rails/app/templates/public/500.html index f71c86e652..b80307fc16 100644 --- a/railties/lib/rails/generators/rails/app/templates/public/500.html +++ b/railties/lib/rails/generators/rails/app/templates/public/500.html @@ -1,7 +1,6 @@ <!DOCTYPE html> <html> <head> - <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <title>We're sorry, but something went wrong (500)</title> <style type="text/css"> body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; } diff --git a/railties/lib/rails/generators/rails/app/templates/public/index.html b/railties/lib/rails/generators/rails/app/templates/public/index.html index ff2dfd3193..b153ae392f 100644 --- a/railties/lib/rails/generators/rails/app/templates/public/index.html +++ b/railties/lib/rails/generators/rails/app/templates/public/index.html @@ -1,7 +1,6 @@ <!DOCTYPE html> <html> <head> - <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <title>Ruby on Rails: Welcome aboard</title> <style type="text/css" media="screen"> body { diff --git a/railties/lib/rails/generators/rails/app/templates/script/console.tt b/railties/lib/rails/generators/rails/app/templates/script/console.tt index 9ddd4cfe62..daba8ba2f1 100755 --- a/railties/lib/rails/generators/rails/app/templates/script/console.tt +++ b/railties/lib/rails/generators/rails/app/templates/script/console.tt @@ -1,3 +1,5 @@ -require File.expand_path('../../config/application', __FILE__) +require File.expand_path('../../config/boot', __FILE__) require 'rails/commands/console' +require File.expand_path('../../config/application', __FILE__) + Rails::Console.start(<%= app_const %>.instance) diff --git a/railties/lib/rails/generators/rails/app/templates/script/dbconsole.tt b/railties/lib/rails/generators/rails/app/templates/script/dbconsole.tt index 96e0bc191b..a7f114a97f 100755 --- a/railties/lib/rails/generators/rails/app/templates/script/dbconsole.tt +++ b/railties/lib/rails/generators/rails/app/templates/script/dbconsole.tt @@ -1,3 +1,5 @@ -require File.expand_path('../../config/application', __FILE__) +require File.expand_path('../../config/boot', __FILE__) require 'rails/commands/dbconsole' +require File.expand_path('../../config/application', __FILE__) + Rails::DBConsole.start(<%= app_const %>.instance) diff --git a/railties/lib/rails/generators/rails/app/templates/script/runner b/railties/lib/rails/generators/rails/app/templates/script/runner index 7a70828e90..3354ed4a28 100755 --- a/railties/lib/rails/generators/rails/app/templates/script/runner +++ b/railties/lib/rails/generators/rails/app/templates/script/runner @@ -1,2 +1,3 @@ -require File.expand_path('../../config/environment', __FILE__) +require File.expand_path('../../config/boot', __FILE__) require 'rails/commands/runner' +require File.expand_path('../../config/environment', __FILE__) diff --git a/railties/lib/rails/generators/rails/app/templates/test/test_helper.rb b/railties/lib/rails/generators/rails/app/templates/test/test_helper.rb index a16f587d8b..45b551fc7d 100644 --- a/railties/lib/rails/generators/rails/app/templates/test/test_helper.rb +++ b/railties/lib/rails/generators/rails/app/templates/test/test_helper.rb @@ -3,31 +3,6 @@ require File.expand_path(File.dirname(__FILE__) + "/../config/environment") require 'rails/test_help' class ActiveSupport::TestCase - # Transactional fixtures accelerate your tests by wrapping each test method - # in a transaction that's rolled back on completion. This ensures that the - # test database remains unchanged so your fixtures don't have to be reloaded - # between every test method. Fewer database queries means faster tests. - # - # Read Mike Clark's excellent walkthrough at - # http://clarkware.com/cgi/blosxom/2005/10/24#Rails10FastTesting - # - # Every Active Record database supports transactions except MyISAM tables - # in MySQL. Turn off transactional fixtures in this case; however, if you - # don't care one way or the other, switching from MyISAM to InnoDB tables - # is recommended. - # - # The only drawback to using transactional fixtures is when you actually - # need to test transactions. Since your test is bracketed by a transaction, - # any transactions started in your code will be automatically rolled back. - self.use_transactional_fixtures = true - - # Instantiated fixtures are slow, but give you @david where otherwise you - # would need people(:david). If you don't want to migrate your existing - # test cases which use the @david style and don't mind the speed hit (each - # instantiated fixtures translates to a database query per test method), - # then set this back to true. - self.use_instantiated_fixtures = false - # Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order. # # Note: You'll currently still have to declare fixtures explicitly in integration tests diff --git a/railties/lib/rails/generators/test_case.rb b/railties/lib/rails/generators/test_case.rb index 643d7856c5..38a3cbb035 100644 --- a/railties/lib/rails/generators/test_case.rb +++ b/railties/lib/rails/generators/test_case.rb @@ -1,4 +1,3 @@ -require 'active_support/test_case' require 'active_support/core_ext/class/inheritable_attributes' require 'active_support/core_ext/hash/reverse_merge' require 'rails/generators' @@ -76,7 +75,7 @@ module Rails eval "$#{stream} = StringIO.new" yield result = eval("$#{stream}").string - ensure + ensure eval("$#{stream} = #{stream.upcase}") end @@ -137,9 +136,9 @@ module Rails # # assert_migration "db/migrate/create_products.rb" # - # This method manipulates the given path and tries to find any migration which + # This method manipulates the given path and tries to find any migration which # matches the migration name. For example, the call above is converted to: - # + # # assert_file "db/migrate/003_create_products.rb" # # Consequently, assert_migration accepts the same arguments has assert_file. @@ -236,4 +235,4 @@ module Rails end end end -end
\ No newline at end of file +end diff --git a/railties/lib/rails/generators/test_unit/plugin/templates/test_helper.rb b/railties/lib/rails/generators/test_unit/plugin/templates/test_helper.rb index 348ec33582..2ca36a1e44 100644 --- a/railties/lib/rails/generators/test_unit/plugin/templates/test_helper.rb +++ b/railties/lib/rails/generators/test_unit/plugin/templates/test_helper.rb @@ -1,5 +1,3 @@ require 'rubygems' require 'test/unit' require 'active_support' -require 'active_support/test_case' - diff --git a/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb b/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb index e4bf4035da..9380aa49b6 100644 --- a/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb +++ b/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb @@ -16,7 +16,7 @@ class <%= controller_class_name %>ControllerTest < ActionController::TestCase test "should create <%= file_name %>" do assert_difference('<%= class_name %>.count') do - post :create, :<%= file_name %> => { } + post :create, :<%= file_name %> => <%= table_name %>(:one).attributes end assert_redirected_to <%= file_name %>_path(assigns(:<%= file_name %>)) @@ -33,7 +33,7 @@ class <%= controller_class_name %>ControllerTest < ActionController::TestCase end test "should update <%= file_name %>" do - put :update, :id => <%= table_name %>(:one).to_param, :<%= file_name %> => { } + put :update, :id => <%= table_name %>(:one).to_param, :<%= file_name %> => <%= table_name %>(:one).attributes assert_redirected_to <%= file_name %>_path(assigns(:<%= file_name %>)) end diff --git a/railties/lib/rails/plugin.rb b/railties/lib/rails/plugin.rb index 9cc6b9c35b..a057b8f701 100644 --- a/railties/lib/rails/plugin.rb +++ b/railties/lib/rails/plugin.rb @@ -53,6 +53,7 @@ module Rails ActionController::Base.view_paths.concat ["#{path}/app/views"] if File.directory?("#{path}/app/views") end + # TODO Isn't it supposed to be :after => "action_controller.initialize_routing" ? initializer :add_routing_file, :after => :initialize_routing do |app| routing_file = "#{path}/config/routes.rb" if File.exist?(routing_file) diff --git a/railties/lib/rails/rack.rb b/railties/lib/rails/rack.rb index 9705f65e52..d487bd0542 100644 --- a/railties/lib/rails/rack.rb +++ b/railties/lib/rails/rack.rb @@ -2,7 +2,6 @@ module Rails module Rack autoload :Debugger, "rails/rack/debugger" autoload :LogTailer, "rails/rack/log_tailer" - autoload :Metal, "rails/rack/metal" autoload :Static, "rails/rack/static" end end diff --git a/railties/lib/rails/rack/log_tailer.rb b/railties/lib/rails/rack/log_tailer.rb index 077311be3c..3fa45156c3 100644 --- a/railties/lib/rails/rack/log_tailer.rb +++ b/railties/lib/rails/rack/log_tailer.rb @@ -13,11 +13,11 @@ module Rails def call(env) response = @app.call(env) - tail_log + tail! response end - def tail_log + def tail! @file.seek @cursor mod = @file.mtime.to_f diff --git a/railties/lib/rails/rack/metal.rb b/railties/lib/rails/rack/metal.rb deleted file mode 100644 index 6c0732f732..0000000000 --- a/railties/lib/rails/rack/metal.rb +++ /dev/null @@ -1,59 +0,0 @@ -require 'active_support/ordered_hash' -require 'active_support/core_ext/class/attribute_accessors' -require 'active_support/dependencies' - -module Rails - module Rack - class Metal - NotFoundResponse = [404, {}, []].freeze - NotFound = lambda { NotFoundResponse } - - cattr_accessor :metal_paths - self.metal_paths = ["#{Rails.root}/app/metal"] - cattr_accessor :requested_metals - - cattr_accessor :pass_through_on - self.pass_through_on = 404 - - def self.metals - matcher = /#{Regexp.escape('/app/metal/')}(.*)\.rb\Z/ - metal_glob = metal_paths.map{ |base| "#{base}/**/*.rb" } - all_metals = {} - - metal_glob.each do |glob| - Dir[glob].sort.map do |file| - file = file.match(matcher)[1] - all_metals[file.camelize] = file - end - end - - load_list = requested_metals || all_metals.keys - - load_list.map do |requested_metal| - if metal = all_metals[requested_metal] - require_dependency metal - requested_metal.constantize - end - end.compact - end - - def initialize(app) - @app = app - @pass_through_on = {} - [*self.class.pass_through_on].each { |status| @pass_through_on[status] = true } - - @metals = ActiveSupport::OrderedHash.new - self.class.metals.each { |app| @metals[app] = true } - freeze - end - - def call(env) - @metals.keys.each do |app| - result = app.call(env) - return result unless @pass_through_on.include?(result[0].to_i) - end - @app.call(env) - end - end - end -end diff --git a/railties/lib/rails/railtie.rb b/railties/lib/rails/railtie.rb index ff28ade35d..43a0303c5b 100644 --- a/railties/lib/rails/railtie.rb +++ b/railties/lib/rails/railtie.rb @@ -25,6 +25,10 @@ module Rails Configuration.default end + def self.subscriber(subscriber) + Rails::Subscriber.add(plugin_name, subscriber) + end + def self.rake_tasks(&blk) @rake_tasks ||= [] @rake_tasks << blk if blk diff --git a/railties/lib/rails/subscriber.rb b/railties/lib/rails/subscriber.rb new file mode 100644 index 0000000000..e8d13babf0 --- /dev/null +++ b/railties/lib/rails/subscriber.rb @@ -0,0 +1,109 @@ +require 'active_support/core_ext/class/inheritable_attributes' +require 'active_support/notifications' + +module Rails + # Rails::Subscriber is an object set to consume ActiveSupport::Notifications + # on initialization with solely purpose of logging. The subscriber dispatches + # notifications to a regirested object based on its given namespace. + # + # An example would be ActiveRecord subscriber responsible for logging queries: + # + # module ActiveRecord + # class Railtie + # class Subscriber < Rails::Subscriber + # def sql(event) + # "#{event.payload[:name]} (#{event.duration}) #{event.payload[:sql]}" + # end + # end + # end + # end + # + # It's finally registed as: + # + # Rails::Subscriber.add :active_record, ActiveRecord::Railtie::Subscriber.new + # + # So whenever a "active_record.sql" notification arrive to Rails::Subscriber, + # it will properly dispatch the event (ActiveSupport::Notifications::Event) to + # the sql method. + # + # This is useful because it avoids spanning several subscribers just for logging + # purposes(which slows down the main thread). Besides of providing a centralized + # facility on top of Rails.logger. + # + # Subscriber also has some helpers to deal with logging and automatically flushes + # all logs when the request finishes (via action_dispatch.callback notification). + class Subscriber + mattr_accessor :colorize_logging, :log_tailer + self.colorize_logging = true + + # Embed in a String to clear all previous ANSI sequences. + CLEAR = "\e[0m" + BOLD = "\e[1m" + + # Colors + BLACK = "\e[30m" + RED = "\e[31m" + GREEN = "\e[32m" + YELLOW = "\e[33m" + BLUE = "\e[34m" + MAGENTA = "\e[35m" + CYAN = "\e[36m" + WHITE = "\e[37m" + + def self.add(namespace, subscriber) + subscribers[namespace.to_sym] = subscriber + end + + def self.subscribers + @subscribers ||= {} + end + + def self.dispatch(args) + namespace, name = args[0].split(".") + subscriber = subscribers[namespace.to_sym] + + if subscriber.respond_to?(name) && subscriber.logger + subscriber.send(name, ActiveSupport::Notifications::Event.new(*args)) + end + + if args[0] == "action_dispatch.callback" && !subscribers.empty? + flush_all! + log_tailer.tail! if log_tailer + end + end + + # Flush all subscribers' logger. + def self.flush_all! + loggers = subscribers.values.map(&:logger) + loggers.uniq! + loggers.each { |l| l.flush if l.respond_to?(:flush) } + end + + # By default, we use the Rails.logger for logging. + def logger + Rails.logger + end + + protected + + %w(info debug warn error fatal unknown).each do |level| + class_eval <<-METHOD, __FILE__, __LINE__ + 1 + def #{level}(*args, &block) + logger.#{level}(*args, &block) + end + METHOD + end + + # Set color by using a string or one of the defined constants. If a third + # option is set to true, it also adds bold to the string. This is based + # on Highline implementation and it automatically appends CLEAR to the end + # of the returned String. + # + def color(text, color, bold=false) + return text unless colorize_logging + color = self.class.const_get(color.to_s.upcase) if color.is_a?(Symbol) + bold = bold ? BOLD : "" + "#{bold}#{color}#{text}#{CLEAR}" + end + end +end
\ No newline at end of file diff --git a/railties/lib/rails/subscriber/test_helper.rb b/railties/lib/rails/subscriber/test_helper.rb new file mode 100644 index 0000000000..1464767ed9 --- /dev/null +++ b/railties/lib/rails/subscriber/test_helper.rb @@ -0,0 +1,118 @@ +require 'rails/subscriber' +require 'active_support/notifications' + +module Rails + class Subscriber + # Provides some helpers to deal with testing subscribers by setting up + # notifications. Take for instance ActiveRecord subscriber tests: + # + # module SubscriberTest + # Rails::Subscriber.add(:active_record, ActiveRecord::Railties::Subscriber.new) + # + # def test_basic_query_logging + # Developer.all + # wait + # assert_equal 1, @logger.logged(:debug).size + # assert_match /Developer Load/, @logger.logged(:debug).last + # assert_match /SELECT \* FROM "developers"/, @logger.logged(:debug).last + # end + # + # class SyncSubscriberTest < ActiveSupport::TestCase + # include Rails::Subscriber::SyncTestHelper + # include SubscriberTest + # end + # + # class AsyncSubscriberTest < ActiveSupport::TestCase + # include Rails::Subscriber::AsyncTestHelper + # include SubscriberTest + # end + # end + # + # All you need to do is to ensure that your subscriber is added to Rails::Subscriber, + # as in the second line of the code above. The test helpers is reponsible for setting + # up the queue, subscriptions and turning colors in logs off. + # + # The messages are available in the @logger instance, which is a logger with limited + # powers (it actually do not send anything to your output), and you can collect them + # doing @logger.logged(level), where level is the level used in logging, like info, + # debug, warn and so on. + # + module TestHelper + def setup + Thread.abort_on_exception = true + + @logger = MockLogger.new + @notifier = ActiveSupport::Notifications::Notifier.new(queue) + + Rails::Subscriber.colorize_logging = false + @notifier.subscribe { |*args| Rails::Subscriber.dispatch(args) } + + set_logger(@logger) + ActiveSupport::Notifications.notifier = @notifier + end + + def teardown + set_logger(nil) + ActiveSupport::Notifications.notifier = nil + Thread.abort_on_exception = false + end + + class MockLogger + attr_reader :flush_count + + def initialize + @flush_count = 0 + @logged = Hash.new { |h,k| h[k] = [] } + end + + def method_missing(level, message) + @logged[level] << message + end + + def logged(level) + @logged[level].compact.map { |l| l.to_s.strip } + end + + def flush + @flush_count += 1 + end + end + + # Wait notifications to be published. + def wait + @notifier.wait + end + + # Overwrite if you use another logger in your subscriber: + # + # def logger + # ActiveRecord::Base.logger = @logger + # end + # + def set_logger(logger) + Rails.logger = logger + end + end + + module SyncTestHelper + include TestHelper + + def queue + ActiveSupport::Notifications::Fanout.new(true) + end + end + + module AsyncTestHelper + include TestHelper + + def queue + ActiveSupport::Notifications::Fanout.new(false) + end + + def wait + sleep(0.01) + super + end + end + end +end
\ No newline at end of file diff --git a/railties/lib/rails/tasks/misc.rake b/railties/lib/rails/tasks/misc.rake index 9433b3556a..4696f02a98 100644 --- a/railties/lib/rails/tasks/misc.rake +++ b/railties/lib/rails/tasks/misc.rake @@ -1,6 +1,7 @@ task :default => :test task :rails_env do + # TODO Do we really need this? unless defined? RAILS_ENV RAILS_ENV = ENV['RAILS_ENV'] ||= 'development' end diff --git a/railties/lib/rails/test_help.rb b/railties/lib/rails/test_help.rb index 2601765065..350d0b3961 100644 --- a/railties/lib/rails/test_help.rb +++ b/railties/lib/rails/test_help.rb @@ -1,29 +1,14 @@ # Make double-sure the RAILS_ENV is set to test, # so fixtures are loaded to the right database -silence_warnings { RAILS_ENV = "test" } - -require 'rack' -require 'rack/test' +exit("Abort testing: Your Rails environment is not running in test mode!") unless Rails.env.test? require 'test/unit' require 'active_support/core_ext/kernel/requires' -# AP is always present -require 'action_controller/test_case' -require 'action_view/test_case' - -require 'action_mailer/test_case' if defined?(ActionMailer) -require 'active_model/test_case' if defined?(ActiveModel) - if defined?(ActiveRecord) - require 'active_record/test_case' - require 'active_record/fixtures' - class ActiveSupport::TestCase include ActiveRecord::TestFixtures self.fixture_path = "#{Rails.root}/test/fixtures/" - self.use_instantiated_fixtures = false - self.use_transactional_fixtures = true end ActionController::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path diff --git a/railties/lib/rails/vendor/bundler/LICENSE b/railties/lib/rails/vendor/bundler/LICENSE deleted file mode 100644 index 41decca113..0000000000 --- a/railties/lib/rails/vendor/bundler/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2009 Engine Yard - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file diff --git a/railties/lib/rails/vendor/bundler/README.markdown b/railties/lib/rails/vendor/bundler/README.markdown deleted file mode 100644 index 26863e96f2..0000000000 --- a/railties/lib/rails/vendor/bundler/README.markdown +++ /dev/null @@ -1,162 +0,0 @@ -## Bundler : A gem to bundle gems - - Github: http://github.com/wycats/bundler - Mailing list: http://groups.google.com/group/ruby-bundler - IRC: #carlhuda on freenode - -## Intro - -Bundler is a tool that manages gem dependencies for your ruby application. It -takes a gem manifest file and is able to fetch, download, and install the gems -and all child dependencies specified in this manifest. It can manage any update -to the gem manifest file and update the bundled gems accordingly. It also lets -you run any ruby code in context of the bundled gem environment. - -## Disclaimer - -This project is under rapid development. It is usable today, but there will be -many changes in the near future, including to the Gemfile DSL. We will bump up -versions with changes though. We greatly appreciate feedback. - -## Installation - -Bundler has no dependencies. Just clone the git repository and install the gem -with the following rake task: - - rake install - -## Usage - -Bundler requires a gem manifest file to be created. This should be a file named -`Gemfile` located in the root directory of your application. After the manifest -has been created, in your shell, cd into your application's directory and run -`gem bundle`. This will start the bundling process. - -### Manifest file - -This is where you specify all of your application's dependencies. By default -this should be in a file named `Gemfile` located in your application's root -directory. The following is an example of a potential `Gemfile`. For more -information, please refer to Bundler::ManifestBuilder. - - # Specify a dependency on rails. When the bundler downloads gems, - # it will download rails as well as all of rails' dependencies (such as - # activerecord, actionpack, etc...) - # - # At least one dependency must be specified - gem "rails" - - # Specify a dependency on rack v.1.0.0. The version is optional. If present, - # it can be specified the same way as with rubygems' #gem method. - gem "rack", "1.0.0" - - # Specify a dependency rspec, but only activate that gem in the "testing" - # environment (read more about environments later). :except is also a valid - # option to specify environment restrictions. - gem "rspec", :only => :testing - - # Add http://gems.github.com as a source that the bundler will use - # to find gems listed in the manifest. By default, - # http://gems.rubyforge.org is already added to the list. - # - # This is an optional setting. - source "http://gems.github.com" - - # Specify where the bundled gems should be stashed. This directory will - # be a gem repository where all gems are downloaded to and installed to. - # - # This is an optional setting. - # The default is: vendor/gems - bundle_path "my/bundled/gems" - - # Specify where gem executables should be copied to. - # - # This is an optional setting. - # The default is: bin - bin_path "my/executables" - - # Specify that rubygems should be completely disabled. This means that it - # will be impossible to require it and that available gems will be - # limited exclusively to gems that have been bundled. - # - # The default is to automatically require rubygems. There is also a - # `disable_system_gems` option that will limit available rubygems to - # the ones that have been bundled. - disable_rubygems - -### Running Bundler - -Once a manifest file has been created, the only thing that needs to be done -is to run the `gem bundle` command anywhere in your application. The script -will load the manifest file, resole all the dependencies, download all -needed gems, and install them into the specified directory. - -Every time an update is made to the manifest file, run `gem bundle` again to -get the changes installed. This will only check the remote sources if your -currently installed gems do not satisfy the `Gemfile`. If you want to force -checking for updates on the remote sources, use the `--update` option. - -### Running your application - -The easiest way to run your application is to start it with an executable -copied to the specified bin directory (by default, simply bin). For example, -if the application in question is a rack app, start it with `bin/rackup`. -This will automatically set the gem environment correctly. - -Another way to run arbitrary ruby code in context of the bundled gems is to -run it with the `gem exec` command. For example: - - gem exec ruby my_ruby_script.rb - -Yet another way is to manually require the environment file first. This is -located in `[bundle_path]/environments/default.rb`. For example: - - ruby -r vendor/gems/environment.rb my_ruby_script.rb - -### Using Bundler with Rails today - -It should be possible to use Bundler with Rails today. Here are the steps -to follow. - -* In your rails app, create a Gemfile and specify the gems that your - application depends on. Make sure to specify rails as well: - - gem "rails", "2.1.2" - gem "will_paginate" - - # Optionally, you can disable system gems all together and only - # use bundled gems. - disable_system_gems - -* Run `gem bundle` - -* You can now use rails if you prepend `gem exec` to every call to `script/*` - but that isn't fun. - -* At the top of `config/boot.rb`, add the following line: - - require File.expand_path(File.join(File.dirname(__FILE__), '..', 'vendor', 'gems', 'environment')) - -In theory, this should be enough to get going. - -## To require rubygems or not - -Ideally, no gem would assume the presence of rubygems at runtime. Rubygems provides -enough features so that this isn't necessary. However, there are a number of gems -that require specific rubygem features. - -If the `disable_rubygems` option is used, Bundler will stub out the most common -of these features, but it is possible that things will not go as intended quite -yet. So, if you are brave, try your code without rubygems at runtime. - -## Known Issues - -* When a gem points to a git repository, the git repository will be cloned - every time Bundler does a gem dependency resolve. - -## Reporting bugs - -Please report all bugs on the github issue tracker for the project located -at: - - http://github.com/wycats/bundler/issues/
\ No newline at end of file diff --git a/railties/lib/rails/vendor/bundler/Rakefile b/railties/lib/rails/vendor/bundler/Rakefile deleted file mode 100644 index dc4c3d6d46..0000000000 --- a/railties/lib/rails/vendor/bundler/Rakefile +++ /dev/null @@ -1,57 +0,0 @@ -require 'rubygems' unless ENV['NO_RUBYGEMS'] -require 'rubygems/specification' -require 'date' - -spec = Gem::Specification.new do |s| - s.name = "bundler" - s.version = "0.5.0.pre" - s.author = "Yehuda Katz" - s.email = "wycats@gmail.com" - s.homepage = "http://github.com/wycats/bundler" - s.description = s.summary = "An easy way to vendor gem dependencies" - - s.platform = Gem::Platform::RUBY - s.has_rdoc = true - s.extra_rdoc_files = ["README.markdown", "LICENSE"] - - s.required_rubygems_version = ">= 1.3.5" - - s.require_path = 'lib' - s.files = %w(LICENSE README.markdown Rakefile) + Dir.glob("lib/**/*") -end - -task :default => :spec - -begin - require 'spec/rake/spectask' -rescue LoadError - task(:spec) { $stderr.puts '`gem install rspec` to run specs' } -else - desc "Run specs" - Spec::Rake::SpecTask.new do |t| - t.spec_files = FileList['spec/**/*_spec.rb'] - FileList['spec/fixtures/**/*_spec.rb'] - t.spec_opts = %w(-fs --color) - end -end - -begin - require 'rake/gempackagetask' -rescue LoadError - task(:gem) { $stderr.puts '`gem install rake` to package gems' } -else - Rake::GemPackageTask.new(spec) do |pkg| - pkg.gem_spec = spec - end -end - -desc "install the gem locally" -task :install => [:package] do - sh %{gem install pkg/#{spec.name}-#{spec.version}} -end - -desc "create a gemspec file" -task :make_spec do - File.open("#{spec.name}.gemspec", "w") do |file| - file.puts spec.to_ruby - end -end diff --git a/railties/lib/rails/vendor/bundler/lib/bundler.rb b/railties/lib/rails/vendor/bundler/lib/bundler.rb deleted file mode 100644 index 1ede3517dd..0000000000 --- a/railties/lib/rails/vendor/bundler/lib/bundler.rb +++ /dev/null @@ -1,34 +0,0 @@ -require 'pathname' -require 'logger' -require 'set' -require 'erb' -# Required elements of rubygems -require "rubygems/remote_fetcher" -require "rubygems/installer" - -require "bundler/gem_bundle" -require "bundler/source" -require "bundler/finder" -require "bundler/gem_ext" -require "bundler/resolver" -require "bundler/environment" -require "bundler/dsl" -require "bundler/cli" -require "bundler/repository" -require "bundler/dependency" - -module Bundler - VERSION = "0.5.0" - - class << self - attr_writer :logger - - def logger - @logger ||= begin - logger = Logger.new(STDOUT, Logger::INFO) - logger.formatter = proc {|_,_,_,msg| "#{msg}\n" } - logger - end - end - end -end diff --git a/railties/lib/rails/vendor/bundler/lib/bundler/cli.rb b/railties/lib/rails/vendor/bundler/lib/bundler/cli.rb deleted file mode 100644 index df9181fbc4..0000000000 --- a/railties/lib/rails/vendor/bundler/lib/bundler/cli.rb +++ /dev/null @@ -1,44 +0,0 @@ -require "optparse" - -module Bundler - class CLI - def self.run(command, options = {}) - new(options).run(command) - rescue DefaultManifestNotFound => e - Bundler.logger.error "Could not find a Gemfile to use" - exit 2 - rescue InvalidEnvironmentName => e - Bundler.logger.error "Gemfile error: #{e.message}" - exit - rescue InvalidRepository => e - Bundler.logger.error e.message - exit - rescue VersionConflict => e - Bundler.logger.error e.message - exit - rescue GemNotFound => e - Bundler.logger.error e.message - exit - end - - def initialize(options) - @options = options - @manifest = Bundler::Environment.load(@options[:manifest]) - end - - def bundle - @manifest.install(@options[:update]) - end - - def exec - @manifest.setup_environment - # w0t? - super(*@options[:args]) - end - - def run(command) - send(command) - end - - end -end diff --git a/railties/lib/rails/vendor/bundler/lib/bundler/commands/bundle_command.rb b/railties/lib/rails/vendor/bundler/lib/bundler/commands/bundle_command.rb deleted file mode 100644 index a1f9590f75..0000000000 --- a/railties/lib/rails/vendor/bundler/lib/bundler/commands/bundle_command.rb +++ /dev/null @@ -1,31 +0,0 @@ -class Gem::Commands::BundleCommand < Gem::Command - - def initialize - super('bundle', 'Create a gem bundle based on your Gemfile', {:manifest => nil, :update => false}) - - add_option('-m', '--manifest MANIFEST', "Specify the path to the manifest file") do |manifest, options| - options[:manifest] = manifest - end - - add_option('-u', '--update', "Force a remote check for newer gems") do - options[:update] = true - end - end - - def usage - "#{program_name}" - end - - def description # :nodoc: - <<-EOF -Bundle stuff - EOF - end - - def execute - # Prevent the bundler from getting required unless it is actually being used - require 'bundler' - Bundler::CLI.run(:bundle, options) - end - -end
\ No newline at end of file diff --git a/railties/lib/rails/vendor/bundler/lib/bundler/commands/exec_command.rb b/railties/lib/rails/vendor/bundler/lib/bundler/commands/exec_command.rb deleted file mode 100644 index 228aa60619..0000000000 --- a/railties/lib/rails/vendor/bundler/lib/bundler/commands/exec_command.rb +++ /dev/null @@ -1,31 +0,0 @@ -class Gem::Commands::ExecCommand < Gem::Command - - def initialize - super('exec', 'Run a command in context of a gem bundle', {:manifest => nil}) - - add_option('-m', '--manifest MANIFEST', "Specify the path to the manifest file") do |manifest, options| - options[:manifest] = manifest - end - end - - def usage - "#{program_name} COMMAND" - end - - def arguments # :nodoc: - "COMMAND command to run in context of the gem bundle" - end - - def description # :nodoc: - <<-EOF.gsub(' ', '') - Run in context of a bundle - EOF - end - - def execute - # Prevent the bundler from getting required unless it is actually being used - require 'bundler' - Bundler::CLI.run(:exec, options) - end - -end
\ No newline at end of file diff --git a/railties/lib/rails/vendor/bundler/lib/bundler/dependency.rb b/railties/lib/rails/vendor/bundler/lib/bundler/dependency.rb deleted file mode 100644 index b627b58662..0000000000 --- a/railties/lib/rails/vendor/bundler/lib/bundler/dependency.rb +++ /dev/null @@ -1,56 +0,0 @@ -module Bundler - class InvalidEnvironmentName < StandardError; end - - class Dependency - attr_reader :name, :version, :require_as, :only, :except - - def initialize(name, options = {}, &block) - options.each do |k, v| - options[k.to_s] = v - end - - @name = name - @version = options["version"] || ">= 0" - @require_as = Array(options["require_as"] || name) - @only = options["only"] - @except = options["except"] - @block = block - - if (@only && @only.include?("rubygems")) || (@except && @except.include?("rubygems")) - raise InvalidEnvironmentName, "'rubygems' is not a valid environment name" - end - end - - def in?(environment) - environment = environment.to_s - - return false unless !@only || @only.include?(environment) - return false if @except && @except.include?(environment) - true - end - - def to_s - to_gem_dependency.to_s - end - - def require(environment) - return unless in?(environment) - - @require_as.each do |file| - super(file) - end - - @block.call if @block - end - - def to_gem_dependency - @gem_dep ||= Gem::Dependency.new(name, version) - end - - def ==(o) - [name, version, require_as, only, except] == - [o.name, o.version, o.require_as, o.only, o.except] - end - - end -end diff --git a/railties/lib/rails/vendor/bundler/lib/bundler/dsl.rb b/railties/lib/rails/vendor/bundler/lib/bundler/dsl.rb deleted file mode 100644 index d9a86ee1fd..0000000000 --- a/railties/lib/rails/vendor/bundler/lib/bundler/dsl.rb +++ /dev/null @@ -1,109 +0,0 @@ -module Bundler - class ManifestFileNotFound < StandardError; end - - class Dsl - def initialize(environment) - @environment = environment - @sources = Hash.new { |h,k| h[k] = {} } - end - - def bundle_path(path) - path = Pathname.new(path) - @environment.gem_path = (path.relative? ? - @environment.root.join(path) : path).expand_path - end - - def bin_path(path) - path = Pathname.new(path) - @environment.bindir = (path.relative? ? - @environment.root.join(path) : path).expand_path - end - - def disable_rubygems - @environment.rubygems = false - end - - def disable_system_gems - @environment.system_gems = false - end - - def source(source) - source = GemSource.new(:uri => source) - unless @environment.sources.include?(source) - @environment.add_source(source) - end - end - - def only(env) - old, @only = @only, _combine_onlys(env) - yield - @only = old - end - - def except(env) - old, @except = @except, _combine_excepts(env) - yield - @except = old - end - - def clear_sources - @environment.clear_sources - end - - def gem(name, *args) - options = args.last.is_a?(Hash) ? args.pop : {} - version = args.last - - options[:only] = _combine_onlys(options[:only] || options["only"]) - options[:except] = _combine_excepts(options[:except] || options["except"]) - - dep = Dependency.new(name, options.merge(:version => version)) - - # OMG REFACTORZ. KTHX - if vendored_at = options[:vendored_at] - vendored_at = Pathname.new(vendored_at) - vendored_at = @environment.filename.dirname.join(vendored_at) if vendored_at.relative? - - @sources[:directory][vendored_at.to_s] ||= begin - source = DirectorySource.new( - :name => name, - :version => version, - :location => vendored_at - ) - @environment.add_priority_source(source) - true - end - elsif git = options[:git] - @sources[:git][git] ||= begin - source = GitSource.new( - :name => name, - :version => version, - :uri => git, - :ref => options[:commit] || options[:tag], - :branch => options[:branch] - ) - @environment.add_priority_source(source) - true - end - end - - @environment.dependencies << dep - end - - private - - def _combine_onlys(only) - return @only unless only - only = [only].flatten.compact.uniq.map { |o| o.to_s } - only &= @only if @only - only - end - - def _combine_excepts(except) - return @except unless except - except = [except].flatten.compact.uniq.map { |o| o.to_s } - except |= @except if @except - except - end - end -end diff --git a/railties/lib/rails/vendor/bundler/lib/bundler/environment.rb b/railties/lib/rails/vendor/bundler/lib/bundler/environment.rb deleted file mode 100644 index f07a9e2c6f..0000000000 --- a/railties/lib/rails/vendor/bundler/lib/bundler/environment.rb +++ /dev/null @@ -1,111 +0,0 @@ -require "rubygems/source_index" - -module Bundler - class DefaultManifestNotFound < StandardError; end - - class Environment - attr_reader :filename, :dependencies - attr_accessor :rubygems, :system_gems, :gem_path, :bindir - - def self.load(gemfile = nil) - gemfile = gemfile ? Pathname.new(gemfile) : default_manifest_file - - unless gemfile.file? - raise ManifestFileNotFound, "#{filename.inspect} does not exist" - end - - new(gemfile) - end - - def self.default_manifest_file - current = Pathname.new(Dir.pwd) - - until current.root? - filename = current.join("Gemfile") - return filename if filename.exist? - current = current.parent - end - - raise DefaultManifestNotFound - end - - def initialize(filename) #, sources, dependencies, bindir, path, rubygems, system_gems) - @filename = filename - @default_sources = [GemSource.new(:uri => "http://gems.rubyforge.org")] - @sources = [] - @priority_sources = [] - @dependencies = [] - @rubygems = true - @system_gems = true - - # Evaluate the Gemfile - builder = Dsl.new(self) - builder.instance_eval(File.read(filename)) - end - - def install(update = false) - begin - tmp_path = filename.dirname.join(".tmp") - FileUtils.mkdir_p(tmp_path) - sources.each { |s| s.tmp_path = tmp_path } - repository.install(gem_dependencies, sources, - :rubygems => rubygems, - :system_gems => system_gems, - :manifest => filename, - :update => update - ) - ensure - FileUtils.rm_rf(tmp_path) - end - Bundler.logger.info "Done." - end - - def setup_environment - unless system_gems - ENV["GEM_HOME"] = gem_path - ENV["GEM_PATH"] = gem_path - end - ENV["PATH"] = "#{bindir}:#{ENV["PATH"]}" - ENV["RUBYOPT"] = "-r#{gem_path}/environment #{ENV["RUBYOPT"]}" - end - - def root - filename.parent - end - - def gem_path - @gem_path ||= root.join("vendor", "gems") - end - - def bindir - @bindir ||= root.join("bin") - end - - def sources - @priority_sources + @sources + @default_sources - end - - def add_source(source) - @sources << source - end - - def add_priority_source(source) - @priority_sources << source - end - - def clear_sources - @sources.clear - @default_sources.clear - end - - private - - def repository - @repository ||= Repository.new(gem_path, bindir) - end - - def gem_dependencies - @gem_dependencies ||= dependencies.map { |d| d.to_gem_dependency } - end - end -end diff --git a/railties/lib/rails/vendor/bundler/lib/bundler/finder.rb b/railties/lib/rails/vendor/bundler/lib/bundler/finder.rb deleted file mode 100644 index b77ca65709..0000000000 --- a/railties/lib/rails/vendor/bundler/lib/bundler/finder.rb +++ /dev/null @@ -1,51 +0,0 @@ -module Bundler - # Finder behaves like a rubygems source index in that it responds - # to #search. It also resolves a list of dependencies finding the - # best possible configuration of gems that satisifes all requirements - # without causing any gem activation errors. - class Finder - - # Takes an array of gem sources and fetches the full index of - # gems from each one. It then combines the indexes together keeping - # track of the original source so that any resolved gem can be - # fetched from the correct source. - # - # ==== Parameters - # *sources<String>:: URI pointing to the gem repository - def initialize(*sources) - @cache = {} - @index = {} - @sources = sources - end - - # Searches for a gem that matches the dependency - # - # ==== Parameters - # dependency<Gem::Dependency>:: The gem dependency to search for - # - # ==== Returns - # [Gem::Specification]:: A collection of gem specifications - # matching the search - def search(dependency) - @cache[dependency.hash] ||= begin - find_by_name(dependency.name).select do |spec| - dependency =~ spec - end.sort_by {|s| s.version } - end - end - - private - - def find_by_name(name) - matches = @index[name] ||= begin - versions = {} - @sources.reverse_each do |source| - versions.merge! source.specs[name] || {} - end - versions - end - matches.values - end - - end -end
\ No newline at end of file diff --git a/railties/lib/rails/vendor/bundler/lib/bundler/gem_bundle.rb b/railties/lib/rails/vendor/bundler/lib/bundler/gem_bundle.rb deleted file mode 100644 index 80d7710683..0000000000 --- a/railties/lib/rails/vendor/bundler/lib/bundler/gem_bundle.rb +++ /dev/null @@ -1,11 +0,0 @@ -module Bundler - class GemBundle < Array - def download(repository) - sort_by {|s| s.full_name.downcase }.each do |spec| - spec.source.download(spec, repository) - end - - self - end - end -end
\ No newline at end of file diff --git a/railties/lib/rails/vendor/bundler/lib/bundler/gem_ext.rb b/railties/lib/rails/vendor/bundler/lib/bundler/gem_ext.rb deleted file mode 100644 index 155ad04c7e..0000000000 --- a/railties/lib/rails/vendor/bundler/lib/bundler/gem_ext.rb +++ /dev/null @@ -1,25 +0,0 @@ -module Gem - class Installer - def app_script_text(bin_file_name) - path = @gem_home - template = File.read(File.join(File.dirname(__FILE__), "templates", "app_script.erb")) - erb = ERB.new(template, nil, '-') - erb.result(binding) - end - end - - class Specification - attr_accessor :source - attr_accessor :location - - # Hack to fix github's strange marshal file - def specification_version - @specification_version && @specification_version.to_i - end - - alias full_gem_path_without_location full_gem_path - def full_gem_path - @location ? @location : full_gem_path_without_location - end - end -end diff --git a/railties/lib/rails/vendor/bundler/lib/bundler/repository.rb b/railties/lib/rails/vendor/bundler/lib/bundler/repository.rb deleted file mode 100644 index 1a1dc7497d..0000000000 --- a/railties/lib/rails/vendor/bundler/lib/bundler/repository.rb +++ /dev/null @@ -1,151 +0,0 @@ -require "bundler/repository/gem_repository" -require "bundler/repository/directory_repository" - -module Bundler - class InvalidRepository < StandardError ; end - - class Repository - attr_reader :path - - def initialize(path, bindir) - FileUtils.mkdir_p(path) - - @path = Pathname.new(path) - @bindir = Pathname.new(bindir) - - @repos = { - :gem => Gems.new(@path, @bindir), - :directory => Directory.new(@path.join("dirs"), @bindir) - } - end - - def install(dependencies, sources, options = {}) - if options[:update] || !satisfies?(dependencies) - fetch(dependencies, sources) - expand(options) - else - # Remove any gems that are still around if the Gemfile changed without - # requiring new gems to be download (e.g. a line in the Gemfile was - # removed) - cleanup(Resolver.resolve(dependencies, [source_index])) - end - configure(options) - sync - end - - def gems - gems = [] - each_repo do |repo| - gems.concat repo.gems - end - gems - end - - def satisfies?(dependencies) - index = source_index - dependencies.all? { |dep| index.search(dep).size > 0 } - end - - def source_index - index = Gem::SourceIndex.new - - each_repo do |repo| - index.gems.merge!(repo.source_index.gems) - end - - index - end - - def add_spec(type, spec) - @repos[type].add_spec(spec) - end - - def download_path_for(type) - @repos[type].download_path_for - end - - private - - def cleanup(bundle) - each_repo do |repo| - repo.cleanup(bundle) - end - end - - def each_repo - @repos.each do |k, repo| - yield repo - end - end - - def fetch(dependencies, sources) - bundle = Resolver.resolve(dependencies, sources) - # Cleanup here to remove any gems that could cause problem in the expansion - # phase - # - # TODO: Try to avoid double cleanup - cleanup(bundle) - bundle.download(self) - end - - def sync - glob = gems.map { |g| g.executables }.flatten.join(',') - - (Dir[@bindir.join("*")] - Dir[@bindir.join("{#{glob}}")]).each do |file| - Bundler.logger.info "Deleting bin file: #{File.basename(file)}" - FileUtils.rm_rf(file) - end - end - - def expand(options) - each_repo do |repo| - repo.expand(options) - end - end - - def configure(options) - generate_environment(options) - end - - def generate_environment(options) - FileUtils.mkdir_p(path) - - specs = gems - load_paths = load_paths_for_specs(specs) - bindir = @bindir.relative_path_from(path).to_s - filename = options[:manifest].relative_path_from(path).to_s - spec_files = specs.inject({}) do |hash, spec| - relative = spec.loaded_from.relative_path_from(@path).to_s - hash.merge!(spec.name => relative) - end - - File.open(path.join("environment.rb"), "w") do |file| - template = File.read(File.join(File.dirname(__FILE__), "templates", "environment.erb")) - erb = ERB.new(template, nil, '-') - file.puts erb.result(binding) - end - end - - def load_paths_for_specs(specs) - load_paths = [] - specs.each do |spec| - gem_path = Pathname.new(spec.full_gem_path) - if spec.bindir - load_paths << gem_path.join(spec.bindir).relative_path_from(@path).to_s - end - spec.require_paths.each do |path| - load_paths << gem_path.join(path).relative_path_from(@path).to_s - end - end - load_paths - end - - def require_code(file, dep) - constraint = case - when dep.only then %{ if #{dep.only.inspect}.include?(env)} - when dep.except then %{ unless #{dep.except.inspect}.include?(env)} - end - "require #{file.inspect}#{constraint}" - end - end -end
\ No newline at end of file diff --git a/railties/lib/rails/vendor/bundler/lib/bundler/repository/directory_repository.rb b/railties/lib/rails/vendor/bundler/lib/bundler/repository/directory_repository.rb deleted file mode 100644 index e97dd38dd5..0000000000 --- a/railties/lib/rails/vendor/bundler/lib/bundler/repository/directory_repository.rb +++ /dev/null @@ -1,46 +0,0 @@ -module Bundler - class Repository - class Directory - attr_reader :path, :bindir - - def initialize(path, bindir) - @path = path - @bindir = bindir - - FileUtils.mkdir_p(path.to_s) - end - - def source_index - index = Gem::SourceIndex.from_gems_in(@path.join("specifications")) - index.each { |n, spec| spec.loaded_from = @path.join("specifications", "#{spec.full_name}.gemspec") } - index - end - - def gems - source_index.gems.values - end - - def add_spec(spec) - destination = path.join('specifications') - destination.mkdir unless destination.exist? - - File.open(destination.join("#{spec.full_name}.gemspec"), 'w') do |f| - f.puts spec.to_ruby - end - end - - def download_path_for - @path.join("dirs") - end - - # Checks whether a gem is installed - def expand(options) - # raise NotImplementedError - end - - def cleanup(gems) - # raise NotImplementedError - end - end - end -end
\ No newline at end of file diff --git a/railties/lib/rails/vendor/bundler/lib/bundler/repository/gem_repository.rb b/railties/lib/rails/vendor/bundler/lib/bundler/repository/gem_repository.rb deleted file mode 100644 index 90de49d83d..0000000000 --- a/railties/lib/rails/vendor/bundler/lib/bundler/repository/gem_repository.rb +++ /dev/null @@ -1,108 +0,0 @@ -module Bundler - class Repository - class Gems - attr_reader :path, :bindir - - def initialize(path, bindir) - @path = path - @bindir = bindir - end - - # Returns the source index for all gems installed in the - # repository - def source_index - index = Gem::SourceIndex.from_gems_in(@path.join("specifications")) - index.each { |n, spec| spec.loaded_from = @path.join("specifications", "#{spec.full_name}.gemspec") } - index - end - - def gems - source_index.gems.values - end - - # Checks whether a gem is installed - def expand(options) - cached_gems.each do |name, version| - unless installed?(name, version) - install_cached_gem(name, version, options) - end - end - end - - def cleanup(gems) - glob = gems.map { |g| g.full_name }.join(',') - base = path.join("{cache,specifications,gems}") - - (Dir[base.join("*")] - Dir[base.join("{#{glob}}{.gemspec,.gem,}")]).each do |file| - if File.basename(file) =~ /\.gem$/ - name = File.basename(file, '.gem') - Bundler.logger.info "Deleting gem: #{name}" - end - FileUtils.rm_rf(file) - end - end - - def add_spec(spec) - raise NotImplementedError - end - - def download_path_for - path - end - - private - - def cache_path - @path.join("cache") - end - - def cache_files - Dir[cache_path.join("*.gem")] - end - - def cached_gems - cache_files.map do |f| - full_name = File.basename(f).gsub(/\.gem$/, '') - full_name.split(/-(?=[^-]+$)/) - end - end - - def spec_path - @path.join("specifications") - end - - def spec_files - Dir[spec_path.join("*.gemspec")] - end - - def gem_path - @path.join("gems") - end - - def gem_paths - Dir[gem_path.join("*")] - end - - def installed?(name, version) - spec_files.any? { |g| File.basename(g) == "#{name}-#{version}.gemspec" } && - gem_paths.any? { |g| File.basename(g) == "#{name}-#{version}" } - end - - def install_cached_gem(name, version, options = {}) - cached_gem = cache_path.join("#{name}-#{version}.gem") - # TODO: Add a warning if cached_gem is not a file - if cached_gem.file? - Bundler.logger.info "Installing #{name}-#{version}.gem" - installer = Gem::Installer.new(cached_gem.to_s, options.merge( - :install_dir => @path, - :ignore_dependencies => true, - :env_shebang => true, - :wrappers => true, - :bin_dir => @bindir - )) - installer.install - end - end - end - end -end
\ No newline at end of file diff --git a/railties/lib/rails/vendor/bundler/lib/bundler/resolver.rb b/railties/lib/rails/vendor/bundler/lib/bundler/resolver.rb deleted file mode 100644 index 2a6a6371c2..0000000000 --- a/railties/lib/rails/vendor/bundler/lib/bundler/resolver.rb +++ /dev/null @@ -1,189 +0,0 @@ -# This is the latest iteration of the gem dependency resolving algorithm. As of now, -# it can resolve (as a success of failure) any set of gem dependencies we throw at it -# in a reasonable amount of time. The most iterations I've seen it take is about 150. -# The actual implementation of the algorithm is not as good as it could be yet, but that -# can come later. - -# Extending Gem classes to add necessary tracking information -module Gem - class Dependency - def required_by - @required_by ||= [] - end - end - class Specification - def required_by - @required_by ||= [] - end - end -end - -module Bundler - class GemNotFound < StandardError; end - class VersionConflict < StandardError; end - - class Resolver - - attr_reader :errors - - # Figures out the best possible configuration of gems that satisfies - # the list of passed dependencies and any child dependencies without - # causing any gem activation errors. - # - # ==== Parameters - # *dependencies<Gem::Dependency>:: The list of dependencies to resolve - # - # ==== Returns - # <GemBundle>,nil:: If the list of dependencies can be resolved, a - # collection of gemspecs is returned. Otherwise, nil is returned. - def self.resolve(requirements, sources) - Bundler.logger.info "Calculating dependencies..." - - resolver = new(sources) - result = catch(:success) do - resolver.resolve(requirements, {}) - output = resolver.errors.inject("") do |o, (conflict, (origin, requirement))| - o << " Conflict on: #{conflict.inspect}:\n" - o << " * #{conflict} (#{origin.version}) activated by #{origin.required_by.first}\n" - o << " * #{requirement} required by #{requirement.required_by.first}\n" - o << " All possible versions of origin requirements conflict." - end - raise VersionConflict, "No compatible versions could be found for required dependencies:\n #{output}" - nil - end - result && GemBundle.new(result.values) - end - - def initialize(sources) - @errors = {} - @stack = [] - @specs = Hash.new { |h,k| h[k] = {} } - @cache = {} - @index = {} - - sources.reverse_each do |source| - source.gems.values.each do |spec| - # TMP HAX FOR OPTZ - spec.source = source - next unless Gem::Platform.match(spec.platform) - @specs[spec.name][spec.version] = spec - end - end - end - - def resolve(reqs, activated) - # If the requirements are empty, then we are in a success state. Aka, all - # gem dependencies have been resolved. - throw :success, activated if reqs.empty? - - # Sort requirements so that the ones that are easiest to resolve are first. - # Easiest to resolve is defined by: Is this gem already activated? Otherwise, - # check the number of child dependencies this requirement has. - reqs = reqs.sort_by do |req| - activated[req.name] ? 0 : search(req).size - end - - activated = activated.dup - # Pull off the first requirement so that we can resolve it - current = reqs.shift - - # Check if the gem has already been activated, if it has, we will make sure - # that the currently activated gem satisfies the requirement. - if existing = activated[current.name] - if current.version_requirements.satisfied_by?(existing.version) - @errors.delete(existing.name) - # Since the current requirement is satisfied, we can continue resolving - # the remaining requirements. - resolve(reqs, activated) - else - @errors[existing.name] = [existing, current] - # Since the current requirement conflicts with an activated gem, we need - # to backtrack to the current requirement's parent and try another version - # of it (maybe the current requirement won't be present anymore). If the - # current requirement is a root level requirement, we need to jump back to - # where the conflicting gem was activated. - parent = current.required_by.last || existing.required_by.last - # We track the spot where the current gem was activated because we need - # to keep a list of every spot a failure happened. - throw parent.name, existing.required_by.last.name - end - else - # There are no activated gems for the current requirement, so we are going - # to find all gems that match the current requirement and try them in decending - # order. We also need to keep a set of all conflicts that happen while trying - # this gem. This is so that if no versions work, we can figure out the best - # place to backtrack to. - conflicts = Set.new - - # Fetch all gem versions matching the requirement - # - # TODO: Warn / error when no matching versions are found. - matching_versions = search(current) - - if matching_versions.empty? - if current.required_by.empty? - raise GemNotFound, "Could not find gem '#{current}' in any of the sources" - end - Bundler.logger.warn "Could not find gem '#{current}' (required by '#{current.required_by.last}') in any of the sources" - end - - matching_versions.reverse_each do |spec| - conflict = resolve_requirement(spec, current, reqs.dup, activated.dup) - conflicts << conflict if conflict - end - # If the current requirement is a root level gem and we have conflicts, we - # can figure out the best spot to backtrack to. - if current.required_by.empty? && !conflicts.empty? - # Check the current "catch" stack for the first one that is included in the - # conflicts set. That is where the parent of the conflicting gem was required. - # By jumping back to this spot, we can try other version of the parent of - # the conflicting gem, hopefully finding a combination that activates correctly. - @stack.reverse_each do |savepoint| - if conflicts.include?(savepoint) - throw savepoint - end - end - end - end - end - - def resolve_requirement(spec, requirement, reqs, activated) - # We are going to try activating the spec. We need to keep track of stack of - # requirements that got us to the point of activating this gem. - spec.required_by.replace requirement.required_by - spec.required_by << requirement - - activated[spec.name] = spec - - # Now, we have to loop through all child dependencies and add them to our - # array of requirements. - spec.dependencies.each do |dep| - next if dep.type == :development - dep.required_by << requirement - reqs << dep - end - - # We create a savepoint and mark it by the name of the requirement that caused - # the gem to be activated. If the activated gem ever conflicts, we are able to - # jump back to this point and try another version of the gem. - length = @stack.length - @stack << requirement.name - retval = catch(requirement.name) do - resolve(reqs, activated) - end - # Since we're doing a lot of throw / catches. A push does not necessarily match - # up to a pop. So, we simply slice the stack back to what it was before the catch - # block. - @stack.slice!(length..-1) - retval - end - - def search(dependency) - @cache[dependency.hash] ||= begin - @specs[dependency.name].values.select do |spec| - dependency =~ spec - end.sort_by {|s| s.version } - end - end - end -end
\ No newline at end of file diff --git a/railties/lib/rails/vendor/bundler/lib/bundler/runtime.rb b/railties/lib/rails/vendor/bundler/lib/bundler/runtime.rb deleted file mode 100644 index 27e0254966..0000000000 --- a/railties/lib/rails/vendor/bundler/lib/bundler/runtime.rb +++ /dev/null @@ -1,2 +0,0 @@ -require File.join(File.dirname(__FILE__), "runtime", "dsl") -require File.join(File.dirname(__FILE__), "runtime", "dependency")
\ No newline at end of file diff --git a/railties/lib/rails/vendor/bundler/lib/bundler/source.rb b/railties/lib/rails/vendor/bundler/lib/bundler/source.rb deleted file mode 100644 index 37828ca316..0000000000 --- a/railties/lib/rails/vendor/bundler/lib/bundler/source.rb +++ /dev/null @@ -1,150 +0,0 @@ -module Bundler - # Represents a source of rubygems. Initially, this is only gem repositories, but - # eventually, this will be git, svn, HTTP - class Source - attr_accessor :tmp_path - end - - class GemSource < Source - attr_reader :uri - - def initialize(options) - @uri = options[:uri] - @uri = URI.parse(@uri) unless @uri.is_a?(URI) - raise ArgumentError, "The source must be an absolute URI" unless @uri.absolute? - end - - def gems - @specs ||= fetch_specs - end - - def ==(other) - uri == other.uri - end - - def to_s - @uri.to_s - end - - class RubygemsRetardation < StandardError; end - - def download(spec, repository) - Bundler.logger.info "Downloading #{spec.full_name}.gem" - - destination = repository.download_path_for(:gem) - - unless destination.writable? - raise RubygemsRetardation - end - - Gem::RemoteFetcher.fetcher.download(spec, uri, repository.download_path_for(:gem)) - end - - private - - def fetch_specs - Bundler.logger.info "Updating source: #{to_s}" - - deflated = Gem::RemoteFetcher.fetcher.fetch_path("#{uri}/Marshal.4.8.Z") - inflated = Gem.inflate deflated - - index = Marshal.load(inflated) - index.gems - rescue Gem::RemoteFetcher::FetchError => e - raise ArgumentError, "#{to_s} is not a valid source: #{e.message}" - end - end - - class DirectorySource < Source - def initialize(options) - @name = options[:name] - @version = options[:version] - @location = options[:location] - @require_paths = options[:require_paths] || %w(lib) - end - - def gems - @gems ||= begin - specs = {} - - # Find any gemspec files in the directory and load those specs - Dir[@location.join('**', '*.gemspec')].each do |file| - path = Pathname.new(file).relative_path_from(@location).dirname - spec = eval(File.read(file)) - spec.require_paths.map! { |p| path.join(p) } - specs[spec.full_name] = spec - end - - # If a gemspec for the dependency was not found, add it to the list - if specs.keys.grep(/^#{Regexp.escape(@name)}/).empty? - case - when @version.nil? - raise ArgumentError, "If you use :at, you must specify the gem" \ - "and version you wish to stand in for" - when !Gem::Version.correct?(@version) - raise ArgumentError, "If you use :at, you must specify a gem and" \ - "version. You specified #{@version} for the version" - end - - default = Gem::Specification.new do |s| - s.name = @name - s.version = Gem::Version.new(@version) if @version - end - specs[default.full_name] = default - end - - specs - end - end - - def ==(other) - # TMP HAX - other.is_a?(DirectorySource) - end - - def to_s - "#{@name} (#{@version}) Located at: '#{@location}'" - end - - def download(spec, repository) - spec.require_paths.map! { |p| File.join(@location, p) } - repository.add_spec(:directory, spec) - end - end - - class GitSource < DirectorySource - def initialize(options) - super - @uri = options[:uri] - @ref = options[:ref] - @branch = options[:branch] - end - - def gems - FileUtils.mkdir_p(tmp_path.join("gitz")) - - # TMP HAX to get the *.gemspec reading to work - @location = tmp_path.join("gitz", @name) - - Bundler.logger.info "Cloning git repository at: #{@uri}" - `git clone #{@uri} #{@location} --no-hardlinks` - - if @ref - Dir.chdir(@location) { `git checkout #{@ref}` } - elsif @branch && @branch != "master" - Dir.chdir(@location) { `git checkout origin/#{@branch}` } - end - super - end - - def download(spec, repository) - dest = repository.download_path_for(:directory).join(@name) - spec.require_paths.map! { |p| File.join(dest, p) } - repository.add_spec(:directory, spec) - if spec.name == @name - FileUtils.mkdir_p(dest.dirname) - FileUtils.mv(tmp_path.join("gitz", spec.name), dest) - end - end - end -end
\ No newline at end of file diff --git a/railties/lib/rails/vendor/bundler/lib/bundler/templates/app_script.erb b/railties/lib/rails/vendor/bundler/lib/bundler/templates/app_script.erb deleted file mode 100644 index 3e47a53ca8..0000000000 --- a/railties/lib/rails/vendor/bundler/lib/bundler/templates/app_script.erb +++ /dev/null @@ -1,3 +0,0 @@ -<%= shebang bin_file_name %> -require File.join(File.dirname(__FILE__), "<%= path.join("environment").relative_path_from(Pathname.new(bin_dir)) %>") -load File.join(File.dirname(__FILE__), "<%= path.join("gems", @spec.full_name, @spec.bindir, bin_file_name).relative_path_from(Pathname.new(bin_dir)) %>")
\ No newline at end of file diff --git a/railties/lib/rails/vendor/bundler/lib/bundler/templates/environment.erb b/railties/lib/rails/vendor/bundler/lib/bundler/templates/environment.erb deleted file mode 100644 index 21f3de8854..0000000000 --- a/railties/lib/rails/vendor/bundler/lib/bundler/templates/environment.erb +++ /dev/null @@ -1,127 +0,0 @@ -# DO NOT MODIFY THIS FILE -module Bundler - dir = File.dirname(__FILE__) - -<% unless options[:system_gems] -%> - ENV["GEM_HOME"] = dir - ENV["GEM_PATH"] = dir -<% end -%> - ENV["PATH"] = "#{dir}/<%= bindir %>:#{ENV["PATH"]}" - ENV["RUBYOPT"] = "-r#{__FILE__} #{ENV["RUBYOPT"]}" - -<% load_paths.each do |load_path| -%> - $LOAD_PATH.unshift File.expand_path("#{dir}/<%= load_path %>") -<% end -%> - - @gemfile = "#{dir}/<%= filename %>" - -<% if options[:rubygems] -%> - require "rubygems" - - @bundled_specs = {} -<% spec_files.each do |name, path| -%> - @bundled_specs["<%= name %>"] = eval(File.read("#{dir}/<%= path %>")) - @bundled_specs["<%= name %>"].loaded_from = "#{dir}/<%= path %>" -<% end -%> - - def self.add_specs_to_loaded_specs - Gem.loaded_specs.merge! @bundled_specs - end - - def self.add_specs_to_index - @bundled_specs.each do |name, spec| - Gem.source_index.add_spec spec - end - end - - add_specs_to_loaded_specs - add_specs_to_index -<% end -%> - - def self.require_env(env = nil) - context = Class.new do - def initialize(env) @env = env && env.to_s ; end - def method_missing(*) ; end - def only(env) - old, @only = @only, _combine_onlys(env) - yield - @only = old - end - def except(env) - old, @except = @except, _combine_excepts(env) - yield - @except = old - end - def gem(name, *args) - opt = args.last || {} - only = _combine_onlys(opt[:only] || opt["only"]) - except = _combine_excepts(opt[:except] || opt["except"]) - files = opt[:require_as] || opt["require_as"] || name - - return unless !only || only.any? {|e| e == @env } - return if except && except.any? {|e| e == @env } - - files.each { |f| require f } - yield if block_given? - true - end - private - def _combine_onlys(only) - return @only unless only - only = [only].flatten.compact.uniq.map { |o| o.to_s } - only &= @only if @only - only - end - def _combine_excepts(except) - return @except unless except - except = [except].flatten.compact.uniq.map { |o| o.to_s } - except |= @except if @except - except - end - end - context.new(env && env.to_s).instance_eval(File.read(@gemfile)) - end -end - -<% if options[:rubygems] -%> -module Gem - def source_index.refresh! - super - Bundler.add_specs_to_index - end -end -<% else -%> -$" << "rubygems.rb" - -module Kernel - def gem(*) - # Silently ignore calls to gem, since, in theory, everything - # is activated correctly already. - end -end - -# Define all the Gem errors for gems that reference them. -module Gem - def self.ruby ; <%= Gem.ruby.inspect %> ; end - class LoadError < ::LoadError; end - class Exception < RuntimeError; end - class CommandLineError < Exception; end - class DependencyError < Exception; end - class DependencyRemovalException < Exception; end - class GemNotInHomeException < Exception ; end - class DocumentError < Exception; end - class EndOfYAMLException < Exception; end - class FilePermissionError < Exception; end - class FormatException < Exception; end - class GemNotFoundException < Exception; end - class InstallError < Exception; end - class InvalidSpecificationException < Exception; end - class OperationNotSupportedError < Exception; end - class RemoteError < Exception; end - class RemoteInstallationCancelled < Exception; end - class RemoteInstallationSkipped < Exception; end - class RemoteSourceException < Exception; end - class VerificationError < Exception; end - class SystemExitException < SystemExit; end -end -<% end -%>
\ No newline at end of file diff --git a/railties/test/abstract_unit.rb b/railties/test/abstract_unit.rb index 2d6983076a..77ef82856a 100644 --- a/railties/test/abstract_unit.rb +++ b/railties/test/abstract_unit.rb @@ -17,7 +17,6 @@ require 'fileutils' require 'active_support' require 'active_support/core_ext/logger' -require 'active_support/test_case' require 'action_controller' require 'rails/all' diff --git a/railties/test/application/generators_test.rb b/railties/test/application/generators_test.rb index 0c858d6394..e1e51c318c 100644 --- a/railties/test/application/generators_test.rb +++ b/railties/test/application/generators_test.rb @@ -52,8 +52,8 @@ module ApplicationTests config.generators.test_framework :rspec RUBY - require "#{app_path}/config/environment" # Initialize the application + require "#{app_path}/config/environment" require "rails/generators" Rails::Generators.configure! diff --git a/railties/test/application/initializer_test.rb b/railties/test/application/initializer_test.rb index 3fd0b0e5df..754c0f1839 100644 --- a/railties/test/application/initializer_test.rb +++ b/railties/test/application/initializer_test.rb @@ -83,6 +83,17 @@ module ApplicationTests assert_equal "congratulations", $test_after_initialize_block2 end + test "after_initialize runs after frameworks have been initialized" do + $activerecord_configurations = nil + add_to_config <<-RUBY + config.after_initialize { $activerecord_configurations = ActiveRecord::Base.configurations } + RUBY + + require "#{app_path}/config/environment" + assert $activerecord_configurations + assert $activerecord_configurations['development'] + end + # i18n test "setting another default locale" do add_to_config <<-RUBY diff --git a/railties/test/application/metal_test.rb b/railties/test/application/metal_test.rb new file mode 100644 index 0000000000..225bede117 --- /dev/null +++ b/railties/test/application/metal_test.rb @@ -0,0 +1,86 @@ +require 'isolation/abstract_unit' + +module ApplicationTests + class MetalTest < Test::Unit::TestCase + include ActiveSupport::Testing::Isolation + + def setup + build_app + boot_rails + + require 'rack/test' + extend Rack::Test::Methods + end + + def app + @app ||= begin + require "#{app_path}/config/environment" + Rails.application + end + end + + test "single metal endpoint" do + app_file 'app/metal/foo_metal.rb', <<-RUBY + class FooMetal + def self.call(env) + [200, { "Content-Type" => "text/html"}, ["FooMetal"]] + end + end + RUBY + + get "/" + assert_equal 200, last_response.status + assert_equal "FooMetal", last_response.body + end + + test "multiple metal endpoints" do + app_file 'app/metal/metal_a.rb', <<-RUBY + class MetalA + def self.call(env) + [404, { "Content-Type" => "text/html", "X-Cascade" => "pass" }, ["Metal A"]] + end + end + RUBY + + app_file 'app/metal/metal_b.rb', <<-RUBY + class MetalB + def self.call(env) + [200, { "Content-Type" => "text/html"}, ["Metal B"]] + end + end + RUBY + + get "/" + assert_equal 200, last_response.status + assert_equal "Metal B", last_response.body + end + + test "pass through to application" do + app_file 'app/metal/foo_metal.rb', <<-RUBY + class FooMetal + def self.call(env) + [404, { "Content-Type" => "text/html", "X-Cascade" => "pass" }, ["Not Found"]] + end + end + RUBY + + controller :foo, <<-RUBY + class FooController < ActionController::Base + def index + render :text => "foo" + end + end + RUBY + + app_file 'config/routes.rb', <<-RUBY + AppTemplate::Application.routes.draw do |map| + match ':controller(/:action)' + end + RUBY + + get "/foo" + assert_equal 200, last_response.status + assert_equal "foo", last_response.body + end + end +end diff --git a/railties/test/application/middleware_test.rb b/railties/test/application/middleware_test.rb new file mode 100644 index 0000000000..7b3077bb6e --- /dev/null +++ b/railties/test/application/middleware_test.rb @@ -0,0 +1,80 @@ +require 'isolation/abstract_unit' + +module ApplicationTests + class MiddlewareTest < Test::Unit::TestCase + include ActiveSupport::Testing::Isolation + + def setup + build_app + boot_rails + FileUtils.rm_rf "#{app_path}/config/environments" + end + + test "default middleware stack" do + boot! + + assert_equal [ + "ActionDispatch::Static", + "Rack::Lock", + "Rack::Runtime", + "ActionDispatch::ShowExceptions", + "ActionDispatch::Callbacks", + "ActionDispatch::Session::CookieStore", + "ActionDispatch::Flash", + "ActionDispatch::Cascade", + "ActionDispatch::ParamsParser", + "Rack::MethodOverride", + "ActionDispatch::Head", + "ActiveRecord::ConnectionAdapters::ConnectionManagement", + "ActiveRecord::QueryCache" + ], middleware + end + + test "removing activerecord omits its middleware" do + use_frameworks [] + boot! + assert !middleware.include?("ActiveRecord::ConnectionAdapters::ConnectionManagement") + assert !middleware.include?("ActiveRecord::QueryCache") + end + + test "removes lock if allow concurrency is set" do + add_to_config "config.action_controller.allow_concurrency = true" + boot! + assert !middleware.include?("Rack::Lock") + end + + test "removes static asset server if serve_static_assets is disabled" do + add_to_config "config.serve_static_assets = false" + boot! + assert !middleware.include?("ActionDispatch::Static") + end + + test "use middleware" do + use_frameworks [] + add_to_config "config.middleware.use Rack::Config" + boot! + assert_equal "Rack::Config", middleware.last + end + + test "insert middleware after" do + add_to_config "config.middleware.insert_after ActionDispatch::Static, Rack::Config" + boot! + assert_equal "Rack::Config", middleware.second + end + + test "insert middleware before" do + add_to_config "config.middleware.insert_before ActionDispatch::Static, Rack::Config" + boot! + assert_equal "Rack::Config", middleware.first + end + + private + def boot! + require "#{app_path}/config/environment" + end + + def middleware + AppTemplate::Application.instance.middleware.active.map(&:klass).map(&:name) + end + end +end diff --git a/railties/test/application/notifications_test.rb b/railties/test/application/notifications_test.rb index b57e829cca..1eb0777db8 100644 --- a/railties/test/application/notifications_test.rb +++ b/railties/test/application/notifications_test.rb @@ -12,28 +12,64 @@ module ApplicationTests end end + class MockLogger + def method_missing(*args) + @logged ||= [] + @logged << args.last + end + + def logged + @logged.compact.map { |l| l.to_s.strip } + end + end + class NotificationsTest < Test::Unit::TestCase include ActiveSupport::Testing::Isolation def setup build_app boot_rails + end + + def instrument(*args, &block) + ActiveSupport::Notifications.instrument(*args, &block) + end + + def wait + ActiveSupport::Notifications.notifier.wait + end + + test "new queue is set" do + # We don't want to load all frameworks, so remove them and clean up environments. + use_frameworks [] FileUtils.rm_rf("#{app_path}/config/environments") - require "active_support/notifications" - @events = [] add_to_config <<-RUBY config.notifications.notifier = ActiveSupport::Notifications::Notifier.new(ApplicationTests::MyQueue.new) RUBY - end - test "new queue is set" do - use_frameworks [] require "#{app_path}/config/environment" assert_raise RuntimeError do ActiveSupport::Notifications.publish('foo') end end + + test "rails subscribers are added" do + add_to_config <<-RUBY + config.colorize_logging = false + RUBY + + require "#{app_path}/config/environment" + + ActiveRecord::Base.logger = logger = MockLogger.new + + # Mimic an ActiveRecord notifications + instrument "active_record.sql", :name => "SQL", :sql => "SHOW tables" + wait + + assert_equal 1, logger.logged.size + assert_match /SHOW tables/, logger.logged.last + end end end diff --git a/railties/test/application/test_test.rb b/railties/test/application/test_test.rb new file mode 100644 index 0000000000..37175783d8 --- /dev/null +++ b/railties/test/application/test_test.rb @@ -0,0 +1,63 @@ +require 'isolation/abstract_unit' + +module ApplicationTests + class TestTest < Test::Unit::TestCase + include ActiveSupport::Testing::Isolation + + def setup + build_app + boot_rails + end + + test "truth" do + app_file 'test/unit/foo_test.rb', <<-RUBY + require 'test_helper' + + class FooTest < ActiveSupport::TestCase + def test_truth + assert true + end + end + RUBY + + run_test 'unit/foo_test.rb' + end + + test "integration test" do + controller 'posts', <<-RUBY + class PostsController < ActionController::Base + end + RUBY + + app_file 'app/views/posts/index.html.erb', <<-HTML + Posts#index + HTML + + app_file 'test/integration/posts_test.rb', <<-RUBY + require 'test_helper' + + class PostsTest < ActionController::IntegrationTest + def test_index + get '/posts' + assert_response :success + assert_template "index" + end + end + RUBY + + run_test 'integration/posts_test.rb' + end + + private + def run_test(name) + result = ruby '-Itest', "#{app_path}/test/#{name}" + assert_equal 0, $?.to_i, result + end + + def ruby(*args) + Dir.chdir(app_path) do + `RUBYLIB='#{$:.join(':')}' #{Gem.ruby} #{args.join(' ')}` + end + end + end +end diff --git a/railties/test/fixtures/metal/multiplemetals/app/metal/metal_a.rb b/railties/test/fixtures/metal/multiplemetals/app/metal/metal_a.rb deleted file mode 100644 index 4ca4ddd447..0000000000 --- a/railties/test/fixtures/metal/multiplemetals/app/metal/metal_a.rb +++ /dev/null @@ -1,5 +0,0 @@ -class MetalA - def self.call(env) - [404, { "Content-Type" => "text/html"}, ["Metal A"]] - end -end diff --git a/railties/test/fixtures/metal/multiplemetals/app/metal/metal_b.rb b/railties/test/fixtures/metal/multiplemetals/app/metal/metal_b.rb deleted file mode 100644 index 80e69fe0b0..0000000000 --- a/railties/test/fixtures/metal/multiplemetals/app/metal/metal_b.rb +++ /dev/null @@ -1,5 +0,0 @@ -class MetalB - def self.call(env) - [200, { "Content-Type" => "text/html"}, ["Metal B"]] - end -end diff --git a/railties/test/fixtures/metal/pluralmetal/app/metal/legacy_routes.rb b/railties/test/fixtures/metal/pluralmetal/app/metal/legacy_routes.rb deleted file mode 100644 index 0cd3737c32..0000000000 --- a/railties/test/fixtures/metal/pluralmetal/app/metal/legacy_routes.rb +++ /dev/null @@ -1,5 +0,0 @@ -class LegacyRoutes < Rails::Rack::Metal - def self.call(env) - [301, { "Location" => "http://example.com"}, []] - end -end diff --git a/railties/test/fixtures/metal/singlemetal/app/metal/foo_metal.rb b/railties/test/fixtures/metal/singlemetal/app/metal/foo_metal.rb deleted file mode 100644 index 5f5b087592..0000000000 --- a/railties/test/fixtures/metal/singlemetal/app/metal/foo_metal.rb +++ /dev/null @@ -1,5 +0,0 @@ -class FooMetal < Rails::Rack::Metal - def self.call(env) - [200, { "Content-Type" => "text/html"}, ["Hi"]] - end -end diff --git a/railties/test/fixtures/metal/subfolders/app/metal/Folder/metal_a.rb b/railties/test/fixtures/metal/subfolders/app/metal/Folder/metal_a.rb deleted file mode 100644 index 25b3bb0abc..0000000000 --- a/railties/test/fixtures/metal/subfolders/app/metal/Folder/metal_a.rb +++ /dev/null @@ -1,7 +0,0 @@ -module Folder - class MetalA < Rails::Rack::Metal - def self.call(env) - [200, { "Content-Type" => "text/html"}, ["Hi"]] - end - end -end diff --git a/railties/test/fixtures/metal/subfolders/app/metal/Folder/metal_b.rb b/railties/test/fixtures/metal/subfolders/app/metal/Folder/metal_b.rb deleted file mode 100644 index 7583363f71..0000000000 --- a/railties/test/fixtures/metal/subfolders/app/metal/Folder/metal_b.rb +++ /dev/null @@ -1,7 +0,0 @@ -module Folder - class MetalB < Rails::Rack::Metal - def self.call(env) - [200, { "Content-Type" => "text/html"}, ["Hi"]] - end - end -end diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb index 7dd798db75..62ea07f14e 100644 --- a/railties/test/generators/app_generator_test.rb +++ b/railties/test/generators/app_generator_test.rb @@ -55,13 +55,19 @@ class AppGeneratorTest < GeneratorsTestCase end def test_invalid_application_name_raises_an_error - content = capture(:stderr){ Rails::Generators::AppGenerator.start [File.join(destination_root, "43-things")] } + content = capture(:stderr){ run_generator [File.join(destination_root, "43-things")] } assert_equal "Invalid application name 43-things. Please give a name which does not start with numbers.\n", content end def test_invalid_application_name_is_fixed - silence(:stdout){ Rails::Generators::AppGenerator.start [File.join(destination_root, "things-43")] } - assert_file "things-43/config/environment.rb", /Things43::Application/ + run_generator [File.join(destination_root, "things-43")] + assert_file "things-43/config/environment.rb", /Things43::Application\.initialize!/ + assert_file "things-43/config/application.rb", /^module Things43$/ + end + + def test_application_names_are_not_singularized + run_generator [File.join(destination_root, "hats")] + assert_file "hats/config/environment.rb", /Hats::Application\.initialize!/ end def test_config_database_is_added_by_default @@ -138,7 +144,7 @@ class AppGeneratorTest < GeneratorsTestCase template = %{ say "It works!" } template.instance_eval "def read; self; end" # Make the string respond to read - generator([destination_root], :template => path, :database => "sqlite3").expects(:open).with(path).returns(template) + generator([destination_root], :template => path).expects(:open).with(path).returns(template) assert_match /It works!/, silence(:stdout){ generator.invoke } end @@ -162,14 +168,16 @@ class AppGeneratorTest < GeneratorsTestCase end def test_dev_option - run_generator [destination_root, "--dev"] + generator([destination_root], :dev => true).expects(:run).with("gem bundle") + silence(:stdout){ generator.invoke } rails_path = File.expand_path('../../..', Rails.root) - dev_gem = %(gem "rails", :path => #{rails_path.inspect}) + dev_gem = %(directory #{rails_path.inspect}, :glob => "{*/,}*.gemspec") assert_file 'Gemfile', /^#{Regexp.escape(dev_gem)}$/ end def test_edge_option - run_generator [destination_root, "--edge"] + generator([destination_root], :edge => true).expects(:run).with("gem bundle") + silence(:stdout){ generator.invoke } edge_gem = %(gem "rails", :git => "git://github.com/rails/rails.git") assert_file 'Gemfile', /^#{Regexp.escape(edge_gem)}$/ end diff --git a/railties/test/generators/generators_test_helper.rb b/railties/test/generators/generators_test_helper.rb index fcd0989fd7..54953b76c8 100644 --- a/railties/test/generators/generators_test_helper.rb +++ b/railties/test/generators/generators_test_helper.rb @@ -1,5 +1,3 @@ -# TODO: Fix this RAILS_ENV stuff -RAILS_ENV = 'test' unless defined?(RAILS_ENV) require 'abstract_unit' module Rails @@ -25,4 +23,8 @@ class GeneratorsTestCase < Rails::Generators::TestCase rescue # Do nothing. end + + def test_truth + # Don't cry test/unit + end end
\ No newline at end of file diff --git a/railties/test/initializer/path_test.rb b/railties/test/initializer/path_test.rb index bfb1887d11..328dda6d2c 100644 --- a/railties/test/initializer/path_test.rb +++ b/railties/test/initializer/path_test.rb @@ -63,7 +63,7 @@ module InitializerTests end test "environments has a glob equal to the current environment" do - assert_equal "#{RAILS_ENV}.rb", @paths.config.environments.glob + assert_equal "#{Rails.env}.rb", @paths.config.environments.glob end test "load path includes each of the paths in config.paths as long as the directories exist" do @@ -85,17 +85,17 @@ module InitializerTests end test "controller paths include builtin in development mode" do - RAILS_ENV.replace "development" + Rails.env.replace "development" assert Rails::Configuration.new.paths.app.controllers.paths.any? { |p| p =~ /builtin/ } end test "controller paths does not have builtin_directories in test mode" do - RAILS_ENV.replace "test" + Rails.env.replace "test" assert !Rails::Configuration.new.paths.app.controllers.paths.any? { |p| p =~ /builtin/ } end test "controller paths does not have builtin_directories in production mode" do - RAILS_ENV.replace "production" + Rails.env.replace "production" assert !Rails::Configuration.new.paths.app.controllers.paths.any? { |p| p =~ /builtin/ } end diff --git a/railties/test/metal_test.rb b/railties/test/metal_test.rb deleted file mode 100644 index 91f55c2b5e..0000000000 --- a/railties/test/metal_test.rb +++ /dev/null @@ -1,101 +0,0 @@ -require 'abstract_unit' - -class MetalTest < Test::Unit::TestCase - def test_metals_should_return_list_of_found_metal_apps - use_appdir("singlemetal") do - assert_equal(["FooMetal"], found_metals_as_string_array) - end - end - - def test_metals_should_respect_class_name_conventions - use_appdir("pluralmetal") do - assert_equal(["LegacyRoutes"], found_metals_as_string_array) - end - end - - def test_metals_should_return_alphabetical_list_of_found_metal_apps - use_appdir("multiplemetals") do - assert_equal(["MetalA", "MetalB"], found_metals_as_string_array) - end - end - - def test_metals_load_order_should_be_overriden_by_requested_metals - use_appdir("multiplemetals") do - Rails::Rack::Metal.requested_metals = ["MetalB", "MetalA"] - assert_equal(["MetalB", "MetalA"], found_metals_as_string_array) - end - end - - def test_metals_not_listed_should_not_load - use_appdir("multiplemetals") do - Rails::Rack::Metal.requested_metals = ["MetalB"] - assert_equal(["MetalB"], found_metals_as_string_array) - end - end - - def test_metal_finding_should_work_with_subfolders - use_appdir("subfolders") do - assert_equal(["Folder::MetalA", "Folder::MetalB"], found_metals_as_string_array) - end - end - - def test_metal_finding_with_requested_metals_should_work_with_subfolders - use_appdir("subfolders") do - Rails::Rack::Metal.requested_metals = ["Folder::MetalB"] - assert_equal(["Folder::MetalB"], found_metals_as_string_array) - end - end - - def test_metal_finding_should_work_with_multiple_metal_paths_in_185_and_below - use_appdir("singlemetal") do - engine_metal_path = "#{File.dirname(__FILE__)}/fixtures/plugins/engines/engine/app/metal" - Rails::Rack::Metal.metal_paths << engine_metal_path - $LOAD_PATH << engine_metal_path - assert_equal(["FooMetal", "EngineMetal"], found_metals_as_string_array) - end - end - - def test_metal_default_pass_through_on_404 - use_appdir("multiplemetals") do - result = Rails::Rack::Metal.new(app).call({}) - assert_equal 200, result.first - assert_equal ["Metal B"], result.last - end - end - - def test_metal_pass_through_on_417 - use_appdir("multiplemetals") do - Rails::Rack::Metal.pass_through_on = 417 - result = Rails::Rack::Metal.new(app).call({}) - assert_equal 404, result.first - assert_equal ["Metal A"], result.last - end - end - - def test_metal_pass_through_on_404_and_200 - use_appdir("multiplemetals") do - Rails::Rack::Metal.pass_through_on = [404, 200] - result = Rails::Rack::Metal.new(app).call({}) - assert_equal 402, result.first - assert_equal ["End of the Line"], result.last - end - end - - private - - def app - lambda{|env|[402,{},["End of the Line"]]} - end - - def use_appdir(root) - dir = "#{File.dirname(__FILE__)}/fixtures/metal/#{root}" - Rails::Rack::Metal.metal_paths = ["#{dir}/app/metal"] - Rails::Rack::Metal.requested_metals = nil - $LOAD_PATH << "#{dir}/app/metal" - yield - end - - def found_metals_as_string_array - Rails::Rack::Metal.metals.map { |m| m.to_s } - end -end diff --git a/railties/test/plugins/configuration_test.rb b/railties/test/plugins/configuration_test.rb index 25bf24eb3b..09f8943af9 100644 --- a/railties/test/plugins/configuration_test.rb +++ b/railties/test/plugins/configuration_test.rb @@ -32,5 +32,14 @@ module PluginsTest assert_equal "hello", MyApp.config.foo.greetings assert_equal "bar", MyApp.config.foo.bar end + + test "plugin can add subscribers" do + begin + class Foo < Rails::Railtie; subscriber(Rails::Subscriber.new); end + assert_kind_of Rails::Subscriber, Rails::Subscriber.subscribers[:foo] + ensure + Rails::Subscriber.subscribers.clear + end + end end end diff --git a/railties/test/plugins/vendored_test.rb b/railties/test/plugins/vendored_test.rb index 9a2d40cad8..b3b85891b2 100644 --- a/railties/test/plugins/vendored_test.rb +++ b/railties/test/plugins/vendored_test.rb @@ -191,5 +191,11 @@ module PluginsTest boot_rails assert_equal [:a, :c, :b], $arr end + + test "plugin order array is strings" do + add_to_config "config.plugins = %w( c_plugin all )" + boot_rails + assert_equal [:c, :a, :b], $arr + end end -end
\ No newline at end of file +end diff --git a/railties/test/rails_info_controller_test.rb b/railties/test/rails_info_controller_test.rb index 435bd34925..edab27465e 100644 --- a/railties/test/rails_info_controller_test.rb +++ b/railties/test/rails_info_controller_test.rb @@ -1,6 +1,5 @@ require 'abstract_unit' require 'action_controller' -require 'action_controller/test_case' require 'rails/info' require 'rails/info_controller' diff --git a/railties/test/subscriber_test.rb b/railties/test/subscriber_test.rb new file mode 100644 index 0000000000..ac34939510 --- /dev/null +++ b/railties/test/subscriber_test.rb @@ -0,0 +1,130 @@ +require 'abstract_unit' +require 'rails/subscriber/test_helper' + +class MySubscriber < Rails::Subscriber + attr_reader :event + + def some_event(event) + @event = event + info event.name + end + + def foo(event) + debug "debug" + info "info" + warn "warn" + end + + def bar(event) + info "#{color("cool", :red)}, #{color("isn't it?", :blue, true)}" + end +end + +module SubscriberTest + def setup + super + @subscriber = MySubscriber.new + Rails::Subscriber.instance_variable_set(:@log_tailer, nil) + end + + def teardown + super + Rails::Subscriber.subscribers.clear + Rails::Subscriber.instance_variable_set(:@log_tailer, nil) + end + + def instrument(*args, &block) + ActiveSupport::Notifications.instrument(*args, &block) + end + + def test_proxies_method_to_rails_logger + @subscriber.foo(nil) + assert_equal %w(debug), @logger.logged(:debug) + assert_equal %w(info), @logger.logged(:info) + assert_equal %w(warn), @logger.logged(:warn) + end + + def test_set_color_for_messages + Rails::Subscriber.colorize_logging = true + @subscriber.bar(nil) + assert_equal "\e[31mcool\e[0m, \e[1m\e[34misn't it?\e[0m", @logger.logged(:info).last + end + + def test_does_not_set_color_if_colorize_logging_is_set_to_false + @subscriber.bar(nil) + assert_equal "cool, isn't it?", @logger.logged(:info).last + end + + def test_event_is_sent_to_the_registered_class + Rails::Subscriber.add :my_subscriber, @subscriber + instrument "my_subscriber.some_event" + wait + assert_equal %w(my_subscriber.some_event), @logger.logged(:info) + end + + def test_event_is_an_active_support_notifications_event + Rails::Subscriber.add :my_subscriber, @subscriber + instrument "my_subscriber.some_event" + wait + assert_kind_of ActiveSupport::Notifications::Event, @subscriber.event + end + + def test_does_not_send_the_event_if_it_doesnt_match_the_class + Rails::Subscriber.add :my_subscriber, @subscriber + instrument "my_subscriber.unknown_event" + wait + # If we get here, it means that NoMethodError was raised. + end + + def test_does_not_send_the_event_if_logger_is_nil + Rails.logger = nil + @subscriber.expects(:some_event).never + Rails::Subscriber.add :my_subscriber, @subscriber + instrument "my_subscriber.some_event" + wait + end + + def test_flushes_loggers + Rails::Subscriber.add :my_subscriber, @subscriber + Rails::Subscriber.flush_all! + assert_equal 1, @logger.flush_count + end + + def test_flushes_loggers_when_action_dispatch_callback_is_received + Rails::Subscriber.add :my_subscriber, @subscriber + instrument "action_dispatch.callback" + wait + assert_equal 1, @logger.flush_count + end + + def test_flushes_the_same_logger_just_once + Rails::Subscriber.add :my_subscriber, @subscriber + Rails::Subscriber.add :another, @subscriber + instrument "action_dispatch.callback" + wait + assert_equal 1, @logger.flush_count + end + + def test_tails_logs_when_action_dispatch_callback_is_received + log_tailer = mock() + log_tailer.expects(:tail!) + Rails::Subscriber.log_tailer = log_tailer + + Rails::Subscriber.add :my_subscriber, @subscriber + instrument "action_dispatch.callback" + wait + ensure + Rails::Subscriber.log_tailer = nil + end + + class SyncSubscriberTest < ActiveSupport::TestCase + include Rails::Subscriber::SyncTestHelper + include SubscriberTest + end + + class AsyncSubscriberTest < ActiveSupport::TestCase + include Rails::Subscriber::AsyncTestHelper + include SubscriberTest + end + +end
\ No newline at end of file |