diff options
Diffstat (limited to 'railties/lib')
154 files changed, 2574 insertions, 2228 deletions
diff --git a/railties/lib/rails.rb b/railties/lib/rails.rb index fe789f3c2a..ee48043a50 100644 --- a/railties/lib/rails.rb +++ b/railties/lib/rails.rb @@ -1,18 +1,18 @@ -require 'rails/ruby_version_check' +require "rails/ruby_version_check" -require 'pathname' +require "pathname" -require 'active_support' -require 'active_support/dependencies/autoload' -require 'active_support/core_ext/kernel/reporting' -require 'active_support/core_ext/module/delegation' -require 'active_support/core_ext/array/extract_options' +require "active_support" +require "active_support/dependencies/autoload" +require "active_support/core_ext/kernel/reporting" +require "active_support/core_ext/module/delegation" +require "active_support/core_ext/array/extract_options" -require 'rails/application' -require 'rails/version' +require "rails/application" +require "rails/version" -require 'active_support/railtie' -require 'action_dispatch/railtie' +require "active_support/railtie" +require "action_dispatch/railtie" # UTF-8 is the default internal and external encoding. silence_warnings do @@ -46,14 +46,14 @@ module Rails def backtrace_cleaner @backtrace_cleaner ||= begin - # Relies on Active Support, so we have to lazy load to postpone definition until AS has been loaded - require 'rails/backtrace_cleaner' + # Relies on Active Support, so we have to lazy load to postpone definition until Active Support has been loaded + require "rails/backtrace_cleaner" Rails::BacktraceCleaner.new end end - # Returns a Pathname object of the current rails project, - # otherwise it returns nil if there is no project: + # Returns a Pathname object of the current Rails project, + # otherwise it returns +nil+ if there is no project: # # Rails.root # # => #<Pathname:/Users/someuser/some/path/project> @@ -77,7 +77,7 @@ module Rails @_env = ActiveSupport::StringInquirer.new(environment) end - # Returns all rails groups for loading based on: + # Returns all Rails groups for loading based on: # # * The Rails environment; # * The environment variable RAILS_GROUPS; @@ -100,7 +100,7 @@ module Rails end # Returns a Pathname object of the public folder of the current - # rails project, otherwise it returns nil if there is no project: + # Rails project, otherwise it returns +nil+ if there is no project: # # Rails.public_path # # => #<Pathname:/Users/someuser/some/path/project/public> diff --git a/railties/lib/rails/all.rb b/railties/lib/rails/all.rb index 1a7f7855f1..7606ea0e46 100644 --- a/railties/lib/rails/all.rb +++ b/railties/lib/rails/all.rb @@ -1,4 +1,4 @@ -require 'rails' +require "rails" %w( active_record/railtie diff --git a/railties/lib/rails/api/task.rb b/railties/lib/rails/api/task.rb index d478bbf9e8..bc670b1d75 100644 --- a/railties/lib/rails/api/task.rb +++ b/railties/lib/rails/api/task.rb @@ -1,33 +1,33 @@ -require 'rdoc/task' +require "rdoc/task" module Rails module API class Task < RDoc::Task RDOC_FILES = { - 'activesupport' => { - :include => %w( + "activesupport" => { + include: %w( README.rdoc lib/active_support/**/*.rb ), - :exclude => 'lib/active_support/vendor/*' + exclude: "lib/active_support/vendor/*" }, - 'activerecord' => { - :include => %w( + "activerecord" => { + include: %w( README.rdoc lib/active_record/**/*.rb ) }, - 'activemodel' => { - :include => %w( + "activemodel" => { + include: %w( README.rdoc lib/active_model/**/*.rb ) }, - 'actionpack' => { - :include => %w( + "actionpack" => { + include: %w( README.rdoc lib/abstract_controller/**/*.rb lib/action_controller/**/*.rb @@ -35,41 +35,41 @@ module Rails ) }, - 'actionview' => { - :include => %w( + "actionview" => { + include: %w( README.rdoc lib/action_view/**/*.rb ), - :exclude => 'lib/action_view/vendor/*' + exclude: "lib/action_view/vendor/*" }, - 'actionmailer' => { - :include => %w( + "actionmailer" => { + include: %w( README.rdoc lib/action_mailer/**/*.rb ) }, - 'activejob' => { - :include => %w( + "activejob" => { + include: %w( README.md lib/active_job/**/*.rb ) }, - 'actioncable' => { - :include => %w( + "actioncable" => { + include: %w( README.md lib/action_cable/**/*.rb ) }, - 'railties' => { - :include => %w( + "railties" => { + include: %w( README.rdoc lib/**/*.rb ), - :exclude => 'lib/rails/generators/rails/**/templates/**/*.rb' + exclude: "lib/rails/generators/rails/**/templates/**/*.rb" } } @@ -92,16 +92,16 @@ module Rails end def load_and_configure_sdoc - require 'sdoc' + require "sdoc" - self.title = 'Ruby on Rails API' + self.title = "Ruby on Rails API" self.rdoc_dir = api_dir - options << '-m' << api_main - options << '-e' << 'UTF-8' + options << "-m" << api_main + options << "-e" << "UTF-8" - options << '-f' << 'sdoc' - options << '-T' << 'rails' + options << "-f" << "sdoc" + options << "-T" << "rails" rescue LoadError $stderr.puts %(Unable to load SDoc, please add\n\n gem 'sdoc', require: false\n\nto the Gemfile.) exit 1 @@ -121,22 +121,35 @@ module Rails rdoc_files.exclude("#{cdr}/#{pattern}") end end + + # Only generate documentation for files that have been + # changed since the API was generated. + if Dir.exist?("doc/rdoc") && !ENV["ALL"] + last_generation = DateTime.rfc2822(File.open("doc/rdoc/created.rid", &:readline)) + + rdoc_files.keep_if do |file| + File.mtime(file).to_datetime > last_generation + end + + # Nothing to do + exit(0) if rdoc_files.empty? + end end def setup_horo_variables - ENV['HORO_PROJECT_NAME'] = 'Ruby on Rails' - ENV['HORO_PROJECT_VERSION'] = rails_version + ENV["HORO_PROJECT_NAME"] = "Ruby on Rails" + ENV["HORO_PROJECT_VERSION"] = rails_version end def api_main - component_root_dir('railties') + '/RDOC_MAIN.rdoc' + component_root_dir("railties") + "/RDOC_MAIN.rdoc" end end class RepoTask < Task def load_and_configure_sdoc super - options << '-g' # link to GitHub, SDoc flag + options << "-g" # link to GitHub, SDoc flag end def component_root_dir(component) @@ -144,7 +157,7 @@ module Rails end def api_dir - 'doc/rdoc' + "doc/rdoc" end end @@ -156,7 +169,7 @@ module Rails class StableTask < RepoTask def rails_version - File.read('RAILS_VERSION').strip + File.read("RAILS_VERSION").strip end end end diff --git a/railties/lib/rails/app_loader.rb b/railties/lib/rails/app_loader.rb index af004d85bf..525d5f0161 100644 --- a/railties/lib/rails/app_loader.rb +++ b/railties/lib/rails/app_loader.rb @@ -1,12 +1,12 @@ -require 'pathname' -require 'rails/version' +require "pathname" +require "rails/version" module Rails module AppLoader # :nodoc: extend self RUBY = Gem.ruby - EXECUTABLES = ['bin/rails', 'script/rails'] + EXECUTABLES = ["bin/rails", "script/rails"] BUNDLER_WARNING = <<EOS Looks like your app's ./bin/rails is a stub that was generated by Bundler. @@ -39,21 +39,21 @@ EOS if contents =~ /(APP|ENGINE)_PATH/ exec RUBY, exe, *ARGV break # non reachable, hack to be able to stub exec in the test suite - elsif exe.end_with?('bin/rails') && contents.include?('This file was generated by Bundler') + elsif exe.end_with?("bin/rails") && contents.include?("This file was generated by Bundler") $stderr.puts(BUNDLER_WARNING) - Object.const_set(:APP_PATH, File.expand_path('config/application', Dir.pwd)) - require File.expand_path('../boot', APP_PATH) - require 'rails/commands' + Object.const_set(:APP_PATH, File.expand_path("config/application", Dir.pwd)) + require File.expand_path("../boot", APP_PATH) + require "rails/commands" break end end # If we exhaust the search there is no executable, this could be a # call to generate a new application, so restore the original cwd. - Dir.chdir(original_cwd) and return if Pathname.new(Dir.pwd).root? + Dir.chdir(original_cwd) && return if Pathname.new(Dir.pwd).root? # Otherwise keep moving upwards in search of an executable. - Dir.chdir('..') + Dir.chdir("..") end end diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb index c383de3e06..f96432c89f 100644 --- a/railties/lib/rails/application.rb +++ b/railties/lib/rails/application.rb @@ -1,9 +1,9 @@ -require 'yaml' -require 'active_support/core_ext/hash/keys' -require 'active_support/core_ext/object/blank' -require 'active_support/key_generator' -require 'active_support/message_verifier' -require 'rails/engine' +require "yaml" +require "active_support/core_ext/hash/keys" +require "active_support/core_ext/object/blank" +require "active_support/key_generator" +require "active_support/message_verifier" +require "rails/engine" module Rails # An Engine with the responsibility of coordinating the whole boot process. @@ -75,18 +75,19 @@ module Rails # If you decide to define rake tasks, runners, or initializers in an # application other than +Rails.application+, then you must run them manually. class Application < Engine - autoload :Bootstrap, 'rails/application/bootstrap' - autoload :Configuration, 'rails/application/configuration' - autoload :DefaultMiddlewareStack, 'rails/application/default_middleware_stack' - autoload :Finisher, 'rails/application/finisher' - autoload :Railties, 'rails/engine/railties' - autoload :RoutesReloader, 'rails/application/routes_reloader' + autoload :Bootstrap, "rails/application/bootstrap" + autoload :Configuration, "rails/application/configuration" + autoload :DefaultMiddlewareStack, "rails/application/default_middleware_stack" + autoload :Finisher, "rails/application/finisher" + autoload :Railties, "rails/engine/railties" + autoload :RoutesReloader, "rails/application/routes_reloader" class << self def inherited(base) super Rails.app_class = base add_lib_to_load_path!(find_root(base.called_from)) + ActiveSupport.run_load_hooks(:before_configuration, base) end def instance @@ -146,7 +147,6 @@ module Rails def run_load_hooks! # :nodoc: return self if @ran_load_hooks @ran_load_hooks = true - ActiveSupport.run_load_hooks(:before_configuration, self) @initial_variable_values.each do |variable_name, value| if INITIAL_VARIABLES.include?(variable_name) @@ -274,7 +274,7 @@ module Rails # Sends the initializers to the +initializer+ method defined in the # Rails::Initializable module. Each Rails::Application class has its own # set of initializers, as defined by the Initializable module. - def initializer(name, opts={}, &block) + def initializer(name, opts = {}, &block) self.class.initializer(name, opts, &block) end @@ -317,7 +317,7 @@ module Rails # Rails application, you will need to add lib to $LOAD_PATH on your own in case # you need to load files in lib/ during the application configuration as well. def self.add_lib_to_load_path!(root) #:nodoc: - path = File.join root, 'lib' + path = File.join root, "lib" if File.exist?(path) && !$LOAD_PATH.include?(path) $LOAD_PATH.unshift(path) end @@ -347,7 +347,7 @@ module Rails # Initialize the application passing the given group. By default, the # group is :default - def initialize!(group=:default) #:nodoc: + def initialize!(group = :default) #:nodoc: raise "Application has been already initialized." if @initialized run_initializers(group, self) @initialized = true @@ -391,11 +391,11 @@ module Rails require "erb" all_secrets = YAML.load(ERB.new(IO.read(yaml)).result) || {} - shared_secrets = all_secrets['shared'] + shared_secrets = all_secrets["shared"] env_secrets = all_secrets[Rails.env] - secrets.merge!(shared_secrets.symbolize_keys) if shared_secrets - secrets.merge!(env_secrets.symbolize_keys) if env_secrets + secrets.merge!(shared_secrets.deep_symbolize_keys) if shared_secrets + secrets.merge!(env_secrets.deep_symbolize_keys) if env_secrets end # Fallback to config.secret_key_base if secrets.secret_key_base isn't set @@ -522,15 +522,15 @@ module Rails private - def build_request(env) - req = super - env["ORIGINAL_FULLPATH"] = req.fullpath - env["ORIGINAL_SCRIPT_NAME"] = req.script_name - req - end + def build_request(env) + req = super + env["ORIGINAL_FULLPATH"] = req.fullpath + env["ORIGINAL_SCRIPT_NAME"] = req.script_name + req + end - def build_middleware - config.app_middleware + super - end + def build_middleware + config.app_middleware + super + end end end diff --git a/railties/lib/rails/application/bootstrap.rb b/railties/lib/rails/application/bootstrap.rb index f615f22b26..11da271501 100644 --- a/railties/lib/rails/application/bootstrap.rb +++ b/railties/lib/rails/application/bootstrap.rb @@ -1,7 +1,7 @@ -require 'fileutils' -require 'active_support/notifications' -require 'active_support/dependencies' -require 'active_support/descendants_tracker' +require "fileutils" +require "active_support/notifications" +require "active_support/dependencies" +require "active_support/descendants_tracker" module Rails class Application @@ -36,7 +36,7 @@ INFO FileUtils.mkdir_p File.dirname path end - f = File.open path, 'a' + f = File.open path, "a" f.binmode f.sync = config.autoflush_log # if true make sure every write flushes diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb index f415a20833..810750ed35 100644 --- a/railties/lib/rails/application/configuration.rb +++ b/railties/lib/rails/application/configuration.rb @@ -1,10 +1,10 @@ -require 'active_support/core_ext/kernel/reporting' -require 'active_support/file_update_checker' -require 'rails/engine/configuration' -require 'rails/source_annotation_extractor' +require "active_support/core_ext/kernel/reporting" +require "active_support/file_update_checker" +require "rails/engine/configuration" +require "rails/source_annotation_extractor" -require 'active_support/deprecation' -require 'active_support/core_ext/string/strip' # for strip_heredoc +require "active_support/deprecation" +require "active_support/core_ext/string/strip" # for strip_heredoc module Rails class Application @@ -16,7 +16,7 @@ module Rails :railties_order, :relative_url_root, :secret_key_base, :secret_token, :ssl_options, :public_file_server, :session_options, :time_zone, :reload_classes_only_on_change, - :beginning_of_week, :filter_redirect, :x + :beginning_of_week, :filter_redirect, :x, :enable_dependency_loading attr_writer :log_level attr_reader :encoding, :api_only, :static_cache_control @@ -34,8 +34,7 @@ module Rails @public_file_server.index_name = "index" @force_ssl = false @ssl_options = {} - @session_store = :cookie_store - @session_options = {} + @session_store = nil @time_zone = "UTC" @beginning_of_week = :monday @log_level = nil @@ -54,6 +53,7 @@ module Rails @api_only = false @debug_exception_response_format = nil @x = Custom.new + @enable_dependency_loading = false end def static_cache_control=(value) @@ -134,7 +134,7 @@ module Rails require "yaml" require "erb" YAML.load(ERB.new(yaml.read).result) || {} - elsif ENV['DATABASE_URL'] + elsif ENV["DATABASE_URL"] # Value from ENV['DATABASE_URL'] is set to default database connection # by Active Record. {} @@ -164,29 +164,37 @@ module Rails self.generators.colorize_logging = val end - def session_store(*args) - if args.empty? - case @session_store - when :disabled - nil - when :active_record_store + def session_store(new_session_store = nil, **options) + if new_session_store + if new_session_store == :active_record_store begin ActionDispatch::Session::ActiveRecordStore rescue NameError raise "`ActiveRecord::SessionStore` is extracted out of Rails into a gem. " \ "Please add `activerecord-session_store` to your Gemfile to use it." end + end + + @session_store = new_session_store + @session_options = options || {} + else + case @session_store + when :disabled + nil + when :active_record_store + ActionDispatch::Session::ActiveRecordStore when Symbol ActionDispatch::Session.const_get(@session_store.to_s.camelize) else @session_store end - else - @session_store = args.shift - @session_options = args.shift || {} end end + def session_store? #:nodoc: + @session_store + end + def annotations SourceAnnotationExtractor::Annotation end @@ -205,6 +213,10 @@ module Rails } end end + + def respond_to_missing?(symbol, *) + true + end end end end diff --git a/railties/lib/rails/application/default_middleware_stack.rb b/railties/lib/rails/application/default_middleware_stack.rb index 381e548730..d070aca2dd 100644 --- a/railties/lib/rails/application/default_middleware_stack.rb +++ b/railties/lib/rails/application/default_middleware_stack.rb @@ -19,7 +19,7 @@ module Rails if config.public_file_server.enabled headers = config.public_file_server.headers || {} - headers['Cache-Control'.freeze] = config.static_cache_control if config.static_cache_control + headers["Cache-Control".freeze] = config.static_cache_control if config.static_cache_control middleware.use ::ActionDispatch::Static, paths["public"].first, index: config.public_file_server.index_name, headers: headers end @@ -41,12 +41,11 @@ module Rails middleware.use ::Rack::Runtime middleware.use ::Rack::MethodOverride unless config.api_only middleware.use ::ActionDispatch::RequestId + middleware.use ::ActionDispatch::RemoteIp, config.action_dispatch.ip_spoofing_check, config.action_dispatch.trusted_proxies - # Must come after Rack::MethodOverride to properly log overridden methods middleware.use ::Rails::Rack::Logger, config.log_tags middleware.use ::ActionDispatch::ShowExceptions, show_exceptions_app middleware.use ::ActionDispatch::DebugExceptions, app, config.debug_exception_response_format - middleware.use ::ActionDispatch::RemoteIp, config.action_dispatch.ip_spoofing_check, config.action_dispatch.trusted_proxies unless config.cache_classes middleware.use ::ActionDispatch::Reloader, app.reloader @@ -76,9 +75,9 @@ module Rails return unless rack_cache begin - require 'rack/cache' + require "rack/cache" rescue LoadError => error - error.message << ' Be sure to add rack-cache to your Gemfile' + error.message << " Be sure to add rack-cache to your Gemfile" raise end diff --git a/railties/lib/rails/application/finisher.rb b/railties/lib/rails/application/finisher.rb index 97dde9a3e9..a855e8fab0 100644 --- a/railties/lib/rails/application/finisher.rb +++ b/railties/lib/rails/application/finisher.rb @@ -22,17 +22,25 @@ module Rails initializer :add_builtin_route do |app| if Rails.env.development? app.routes.prepend do - get '/rails/info/properties' => "rails/info#properties", internal: true - get '/rails/info/routes' => "rails/info#routes", internal: true - get '/rails/info' => "rails/info#index", internal: true + get "/rails/info/properties" => "rails/info#properties", internal: true + get "/rails/info/routes" => "rails/info#routes", internal: true + get "/rails/info" => "rails/info#index", internal: true end app.routes.append do - get '/' => "rails/welcome#index", internal: true + get "/" => "rails/welcome#index", internal: true end end end + # Setup default session store if not already set in config/application.rb + initializer :setup_default_session_store, before: :build_middleware_stack do |app| + unless app.config.session_store? + app_name = app.class.name ? app.railtie_name.chomp("_application") : "" + app.config.session_store :cookie_store, key: "_#{app_name}_session" + end + end + initializer :build_middleware_stack do build_middleware_stack end @@ -117,7 +125,7 @@ module Rails initializer :set_routes_reloader_hook do |app| reloader = routes_reloader reloader.execute_if_updated - self.reloaders << reloader + reloaders << reloader app.reloader.to_run do # We configure #execute rather than #execute_if_updated because if # autoloaded constants are cleared we need to reload routes also in @@ -153,7 +161,7 @@ module Rails if config.reload_classes_only_on_change reloader = config.file_watcher.new(*watchable_args, &callback) - self.reloaders << reloader + reloaders << reloader # Prepend this callback to have autoloaded constants cleared before # any other possible reloading, in case they need to autoload fresh @@ -176,7 +184,7 @@ module Rails # Disable dependency loading during request cycle initializer :disable_dependency_loading do - if config.eager_load && config.cache_classes + if config.eager_load && config.cache_classes && !config.enable_dependency_loading ActiveSupport::Dependencies.unhook! end end diff --git a/railties/lib/rails/application_controller.rb b/railties/lib/rails/application_controller.rb index 618a09a5b3..a98e51fd28 100644 --- a/railties/lib/rails/application_controller.rb +++ b/railties/lib/rails/application_controller.rb @@ -1,16 +1,16 @@ class Rails::ApplicationController < ActionController::Base # :nodoc: - self.view_paths = File.expand_path('../templates', __FILE__) - layout 'application' + self.view_paths = File.expand_path("../templates", __FILE__) + layout "application" - protected + private - def require_local! - unless local_request? - render html: '<p>For security purposes, this information is only available to local requests.</p>'.html_safe, status: :forbidden + def require_local! + unless local_request? + render html: "<p>For security purposes, this information is only available to local requests.</p>".html_safe, status: :forbidden + end end - end - def local_request? - Rails.application.config.consider_all_requests_local || request.local? - end + def local_request? + Rails.application.config.consider_all_requests_local || request.local? + end end diff --git a/railties/lib/rails/backtrace_cleaner.rb b/railties/lib/rails/backtrace_cleaner.rb index 5276eb33c9..5c833e12ba 100644 --- a/railties/lib/rails/backtrace_cleaner.rb +++ b/railties/lib/rails/backtrace_cleaner.rb @@ -1,12 +1,12 @@ -require 'active_support/backtrace_cleaner' +require "active_support/backtrace_cleaner" module Rails class BacktraceCleaner < ActiveSupport::BacktraceCleaner - APP_DIRS_PATTERN = /^\/?(app|config|lib|test)/ + APP_DIRS_PATTERN = /^\/?(app|config|lib|test|\(\w*\))/ RENDER_TEMPLATE_PATTERN = /:in `_render_template_\w*'/ - EMPTY_STRING = ''.freeze - SLASH = '/'.freeze - DOT_SLASH = './'.freeze + EMPTY_STRING = "".freeze + SLASH = "/".freeze + DOT_SLASH = "./".freeze def initialize super diff --git a/railties/lib/rails/cli.rb b/railties/lib/rails/cli.rb index a8794bc0de..973b746068 100644 --- a/railties/lib/rails/cli.rb +++ b/railties/lib/rails/cli.rb @@ -1,15 +1,17 @@ -require 'rails/app_loader' +require "rails/app_loader" # If we are inside a Rails application this method performs an exec and thus # the rest of this script is not run. Rails::AppLoader.exec_app -require 'rails/ruby_version_check' +require "rails/ruby_version_check" Signal.trap("INT") { puts; exit(1) } -if ARGV.first == 'plugin' +require "rails/command" + +if ARGV.first == "plugin" ARGV.shift - require 'rails/commands/plugin' + Rails::Command.invoke :plugin, ARGV else - require 'rails/commands/application' + Rails::Command.invoke :application, ARGV end diff --git a/railties/lib/rails/code_statistics.rb b/railties/lib/rails/code_statistics.rb index 7a8f42fe94..9c4bd16aad 100644 --- a/railties/lib/rails/code_statistics.rb +++ b/railties/lib/rails/code_statistics.rb @@ -1,16 +1,15 @@ -require 'rails/code_statistics_calculator' -require 'active_support/core_ext/enumerable' +require "rails/code_statistics_calculator" +require "active_support/core_ext/enumerable" class CodeStatistics #:nodoc: + TEST_TYPES = ["Controller tests", + "Helper tests", + "Model tests", + "Mailer tests", + "Job tests", + "Integration tests"] - TEST_TYPES = ['Controller tests', - 'Helper tests', - 'Model tests', - 'Mailer tests', - 'Job tests', - 'Integration tests'] - - HEADERS = {lines: ' Lines', code_lines: ' LOC', classes: 'Classes', methods: 'Methods'} + HEADERS = { lines: " Lines", code_lines: " LOC", classes: "Classes", methods: "Methods" } def initialize(*pairs) @pairs = pairs @@ -33,7 +32,7 @@ class CodeStatistics #:nodoc: private def calculate_statistics - Hash[@pairs.map{|pair| [pair.first, calculate_directory_statistics(pair.last)]}] + Hash[@pairs.map { |pair| [pair.first, calculate_directory_statistics(pair.last)] }] end def calculate_directory_statistics(directory, pattern = /^(?!\.).*?\.(rb|js|coffee|rake)$/) @@ -71,25 +70,25 @@ class CodeStatistics #:nodoc: end def width_for(label) - [@statistics.values.sum {|s| s.send(label) }.to_s.size, HEADERS[label].length].max + [@statistics.values.sum { |s| s.send(label) }.to_s.size, HEADERS[label].length].max end def print_header print_splitter - print '| Name ' + print "| Name " HEADERS.each do |k, v| print " | #{v.rjust(width_for(k))}" end - puts ' | M/C | LOC/M |' + puts " | M/C | LOC/M |" print_splitter end def print_splitter - print '+----------------------' + print "+----------------------" HEADERS.each_key do |k| print "+#{'-' * (width_for(k) + 2)}" end - puts '+-----+-------+' + puts "+-----+-------+" end def print_line(name, statistics) @@ -107,7 +106,7 @@ class CodeStatistics #:nodoc: code = calculate_code tests = calculate_tests - puts " Code LOC: #{code} Test LOC: #{tests} Code to Test Ratio: 1:#{sprintf("%.1f", tests.to_f/code)}" + puts " Code LOC: #{code} Test LOC: #{tests} Code to Test Ratio: 1:#{sprintf("%.1f", tests.to_f / code)}" puts "" end end diff --git a/railties/lib/rails/code_statistics_calculator.rb b/railties/lib/rails/code_statistics_calculator.rb index fad13e8517..d0194af197 100644 --- a/railties/lib/rails/code_statistics_calculator.rb +++ b/railties/lib/rails/code_statistics_calculator.rb @@ -43,7 +43,7 @@ class CodeStatisticsCalculator #:nodoc: def add_by_file_path(file_path) File.open(file_path) do |f| - self.add_by_io(f, file_type(file_path)) + add_by_io(f, file_type(file_path)) end end @@ -77,10 +77,10 @@ class CodeStatisticsCalculator #:nodoc: private def file_type(file_path) - if file_path.end_with? '_test.rb' + if file_path.end_with? "_test.rb" :minitest else - File.extname(file_path).sub(/\A\./, '').downcase.to_sym + File.extname(file_path).sub(/\A\./, "").downcase.to_sym end end end diff --git a/railties/lib/rails/command.rb b/railties/lib/rails/command.rb new file mode 100644 index 0000000000..ddb953543f --- /dev/null +++ b/railties/lib/rails/command.rb @@ -0,0 +1,99 @@ +require "active_support" +require "active_support/dependencies/autoload" +require "active_support/core_ext/enumerable" +require "active_support/core_ext/object/blank" +require "active_support/core_ext/hash/transform_values" + +require "thor" + +module Rails + module Command + extend ActiveSupport::Autoload + + autoload :Behavior + autoload :Base + + include Behavior + + class << self + def hidden_commands # :nodoc: + @hidden_commands ||= [] + end + + def environment # :nodoc: + ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development" + end + + # Receives a namespace, arguments and the behavior to invoke the command. + def invoke(namespace, args = [], **config) + namespace = namespace.to_s + namespace = "help" if namespace.blank? || Thor::HELP_MAPPINGS.include?(namespace) + namespace = "version" if %w( -v --version ).include? namespace + + if command = find_by_namespace(namespace) + command.perform(namespace, args, config) + else + find_by_namespace("rake").perform(namespace, args, config) + end + end + + # Rails finds namespaces similar to thor, it only adds one rule: + # + # Command names must end with "_command.rb". This is required because Rails + # looks in load paths and loads the command just before it's going to be used. + # + # find_by_namespace :webrat, :rails, :integration + # + # Will search for the following commands: + # + # "rails:webrat", "webrat:integration", "webrat" + # + # Notice that "rails:commands:webrat" could be loaded as well, what + # Rails looks for is the first and last parts of the namespace. + def find_by_namespace(name) # :nodoc: + lookups = [ name, "rails:#{name}" ] + + lookup(lookups) + + namespaces = subclasses.index_by(&:namespace) + namespaces[(lookups & namespaces.keys).first] + end + + # Returns the root of the Rails engine or app running the command. + def root + if defined?(ENGINE_ROOT) + Pathname.new(ENGINE_ROOT) + elsif defined?(APP_PATH) + Pathname.new(File.expand_path("../..", APP_PATH)) + end + end + + def print_commands # :nodoc: + sorted_groups.each { |b, n| print_list(b, n) } + end + + def sorted_groups # :nodoc: + lookup! + + groups = (subclasses - hidden_commands).group_by { |c| c.namespace.split(":").first } + groups.transform_values! { |commands| commands.flat_map(&:printing_commands).sort } + + rails = groups.delete("rails") + [[ "rails", rails ]] + groups.sort.to_a + end + + private + def command_type # :doc: + @command_type ||= "command" + end + + def lookup_paths # :doc: + @lookup_paths ||= %w( rails/commands commands ) + end + + def file_lookup_paths # :doc: + @file_lookup_paths ||= [ "{#{lookup_paths.join(',')}}", "**", "*_command.rb" ] + end + end + end +end diff --git a/railties/lib/rails/command/actions.rb b/railties/lib/rails/command/actions.rb new file mode 100644 index 0000000000..31b656ec31 --- /dev/null +++ b/railties/lib/rails/command/actions.rb @@ -0,0 +1,42 @@ +module Rails + module Command + module Actions + # Change to the application's path if there is no config.ru file in current directory. + # This allows us to run `rails server` from other directories, but still get + # the main config.ru and properly set the tmp directory. + def set_application_directory! + Dir.chdir(File.expand_path("../../", APP_PATH)) unless File.exist?(File.expand_path("config.ru")) + end + + if defined?(ENGINE_PATH) + def require_application_and_environment! + require ENGINE_PATH + end + + def load_tasks + Rake.application.init("rails") + Rake.application.load_rakefile + end + + def load_generators + engine = ::Rails::Engine.find(ENGINE_ROOT) + Rails::Generators.namespace = engine.railtie_namespace + engine.load_generators + end + else + def require_application_and_environment! + require APP_PATH + Rails.application.require_environment! + end + + def load_tasks + Rails.application.load_tasks + end + + def load_generators + Rails.application.load_generators + end + end + end + end +end diff --git a/railties/lib/rails/command/base.rb b/railties/lib/rails/command/base.rb new file mode 100644 index 0000000000..7ae190433a --- /dev/null +++ b/railties/lib/rails/command/base.rb @@ -0,0 +1,143 @@ +require "thor" +require "erb" + +require "active_support/core_ext/string/filters" +require "active_support/core_ext/string/inflections" + +require "rails/command/actions" + +module Rails + module Command + class Base < Thor + class Error < Thor::Error # :nodoc: + end + + include Actions + + class << self + # Returns true when the app is a Rails engine. + def engine? + defined?(ENGINE_ROOT) + end + + # Tries to get the description from a USAGE file one folder above the command + # root. + def desc(usage = nil, description = nil, options = {}) + if usage + super + else + @desc ||= ERB.new(File.read(usage_path)).result(binding) if usage_path + end + end + + # Convenience method to get the namespace from the class name. It's the + # same as Thor default except that the Command at the end of the class + # is removed. + def namespace(name = nil) + if name + super + else + @namespace ||= super.chomp("_command").sub(/:command:/, ":") + end + end + + # Convenience method to hide this command from the available ones when + # running rails command. + def hide_command! + Rails::Command.hidden_commands << self + end + + def inherited(base) #:nodoc: + super + + if base.name && base.name !~ /Base$/ + Rails::Command.subclasses << base + end + end + + def perform(command, args, config) # :nodoc: + command = nil if Thor::HELP_MAPPINGS.include?(args.first) + + dispatch(command, args.dup, nil, config) + end + + def printing_commands + namespace.sub(/^rails:/, "") + end + + def executable + "bin/rails #{command_name}" + end + + # Use Rails' default banner. + def banner(*) + "#{executable} #{arguments.map(&:usage).join(' ')} [options]".squish! + end + + # Sets the base_name taking into account the current class namespace. + # + # Rails::Command::TestCommand.base_name # => 'rails' + def base_name + @base_name ||= begin + if base = name.to_s.split("::").first + base.underscore + end + end + end + + # Return command name without namespaces. + # + # Rails::Command::TestCommand.command_name # => 'test' + def command_name + @command_name ||= begin + if command = name.to_s.split("::").last + command.chomp!("Command") + command.underscore + end + end + end + + # Path to lookup a USAGE description in a file. + def usage_path + if default_command_root + path = File.join(default_command_root, "USAGE") + path if File.exist?(path) + end + end + + # Default file root to place extra files a command might need, placed + # one folder above the command file. + # + # For a `Rails::Command::TestCommand` placed in `rails/command/test_command.rb` + # would return `rails/test`. + def default_command_root + path = File.expand_path(File.join("../commands", command_name), __dir__) + path if File.exist?(path) + end + + private + # Allow the command method to be called perform. + def create_command(meth) + if meth == "perform" + alias_method command_name, meth + else + # Prevent exception about command without usage. + # Some commands define their documentation differently. + @usage ||= "" + @desc ||= "" + + super + end + end + end + + def help + if command_name = self.class.command_name + self.class.command_help(shell, command_name) + else + super + end + end + end + end +end diff --git a/railties/lib/rails/command/behavior.rb b/railties/lib/rails/command/behavior.rb new file mode 100644 index 0000000000..4a92f72f16 --- /dev/null +++ b/railties/lib/rails/command/behavior.rb @@ -0,0 +1,123 @@ +require "active_support" + +module Rails + module Command + module Behavior #:nodoc: + extend ActiveSupport::Concern + + class_methods do + # Remove the color from output. + def no_color! + Thor::Base.shell = Thor::Shell::Basic + end + + # Track all command subclasses. + def subclasses + @subclasses ||= [] + end + + private + + # This code is based directly on the Text gem implementation. + # Copyright (c) 2006-2013 Paul Battley, Michael Neumann, Tim Fletcher. + # + # Returns a value representing the "cost" of transforming str1 into str2. + def levenshtein_distance(str1, str2) # :doc: + s = str1 + t = str2 + n = s.length + m = t.length + + return m if (0 == n) + return n if (0 == m) + + d = (0..m).to_a + x = nil + + # avoid duplicating an enumerable object in the loop + str2_codepoint_enumerable = str2.each_codepoint + + str1.each_codepoint.with_index do |char1, i| + e = i + 1 + + str2_codepoint_enumerable.with_index do |char2, j| + cost = (char1 == char2) ? 0 : 1 + x = [ + d[j + 1] + 1, # insertion + e + 1, # deletion + d[j] + cost # substitution + ].min + d[j] = e + e = x + end + + d[m] = x + end + + x + end + + # Prints a list of generators. + def print_list(base, namespaces) + return if namespaces.empty? + puts "#{base.camelize}:" + + namespaces.each do |namespace| + puts(" #{namespace}") + end + + puts + end + + # Receives namespaces in an array and tries to find matching generators + # in the load path. + def lookup(namespaces) + paths = namespaces_to_paths(namespaces) + + paths.each do |raw_path| + lookup_paths.each do |base| + path = "#{base}/#{raw_path}_#{command_type}" + + begin + require path + return + rescue LoadError => e + raise unless e.message =~ /#{Regexp.escape(path)}$/ + rescue Exception => e + warn "[WARNING] Could not load #{command_type} #{path.inspect}. Error: #{e.message}.\n#{e.backtrace.join("\n")}" + end + end + end + end + + # This will try to load any command in the load path to show in help. + def lookup! + $LOAD_PATH.each do |base| + Dir[File.join(base, *file_lookup_paths)].each do |path| + begin + path = path.sub("#{base}/", "") + require path + rescue Exception + # No problem + end + end + end + end + + # Convert namespaces to paths by replacing ":" for "/" and adding + # an extra lookup. For example, "rails:model" should be searched + # in both: "rails/model/model_generator" and "rails/model_generator". + def namespaces_to_paths(namespaces) + paths = [] + namespaces.each do |namespace| + pieces = namespace.split(":") + paths << pieces.dup.push(pieces.last).join("/") + paths << pieces.join("/") + end + paths.uniq! + paths + end + end + end + end +end diff --git a/railties/lib/rails/command/environment_argument.rb b/railties/lib/rails/command/environment_argument.rb new file mode 100644 index 0000000000..05eac34155 --- /dev/null +++ b/railties/lib/rails/command/environment_argument.rb @@ -0,0 +1,34 @@ +require "active_support" + +module Rails + module Command + module EnvironmentArgument #:nodoc: + extend ActiveSupport::Concern + + included do + argument :environment, optional: true, banner: "environment" + end + + private + def extract_environment_option_from_argument + if environment + self.options = options.merge(environment: acceptable_environment(environment)) + elsif !options[:environment] + self.options = options.merge(environment: Rails::Command.environment) + end + end + + def acceptable_environment(env = nil) + if available_environments.include? env + env + else + %w( production development test ).detect { |e| e =~ /^#{env}/ } || env + end + end + + def available_environments + Dir["config/environments/*.rb"].map { |fname| File.basename(fname, ".*") } + end + end + end +end diff --git a/railties/lib/rails/commands.rb b/railties/lib/rails/commands.rb index 5a66b78a92..fff0119c65 100644 --- a/railties/lib/rails/commands.rb +++ b/railties/lib/rails/commands.rb @@ -1,4 +1,4 @@ -ARGV << '--help' if ARGV.empty? +require "rails/command" aliases = { "g" => "generate", @@ -13,6 +13,4 @@ aliases = { command = ARGV.shift command = aliases[command] || command -require 'rails/commands/commands_tasks' - -Rails::CommandsTasks.new(ARGV).run_command!(command) +Rails::Command.invoke command, ARGV diff --git a/railties/lib/rails/commands/application.rb b/railties/lib/rails/commands/application.rb deleted file mode 100644 index c998e6b6a8..0000000000 --- a/railties/lib/rails/commands/application.rb +++ /dev/null @@ -1,17 +0,0 @@ -require 'rails/generators' -require 'rails/generators/rails/app/app_generator' - -module Rails - module Generators - class AppGenerator # :nodoc: - # We want to exit on failure to be kind to other libraries - # This is only when accessing via CLI - def self.exit_on_failure? - true - end - end - end -end - -args = Rails::Generators::ARGVScrubber.new(ARGV).prepare! -Rails::Generators::AppGenerator.start args diff --git a/railties/lib/rails/commands/application/application_command.rb b/railties/lib/rails/commands/application/application_command.rb new file mode 100644 index 0000000000..7675d3b3d1 --- /dev/null +++ b/railties/lib/rails/commands/application/application_command.rb @@ -0,0 +1,29 @@ +require "rails/generators" +require "rails/generators/rails/app/app_generator" + +module Rails + module Generators + class AppGenerator # :nodoc: + # We want to exit on failure to be kind to other libraries + # This is only when accessing via CLI + def self.exit_on_failure? + true + end + end + end + + module Command + class ApplicationCommand < Base # :nodoc: + hide_command! + + def help + perform # Punt help output to the generator. + end + + def perform(*args) + Rails::Generators::AppGenerator.start \ + Rails::Generators::ARGVScrubber.new(args).prepare! + end + end + end +end diff --git a/railties/lib/rails/commands/commands_tasks.rb b/railties/lib/rails/commands/commands_tasks.rb deleted file mode 100644 index da3b9452d5..0000000000 --- a/railties/lib/rails/commands/commands_tasks.rb +++ /dev/null @@ -1,180 +0,0 @@ -require 'rails/commands/rake_proxy' - -module Rails - # This is a class which takes in a rails command and initiates the appropriate - # initiation sequence. - # - # Warning: This class mutates ARGV because some commands require manipulating - # it before they are run. - class CommandsTasks # :nodoc: - include Rails::RakeProxy - - attr_reader :argv - - HELP_MESSAGE = <<-EOT -Usage: rails COMMAND [ARGS] - -The most common rails commands are: - generate Generate new code (short-cut alias: "g") - console Start the Rails console (short-cut alias: "c") - server Start the Rails server (short-cut alias: "s") - test Run tests (short-cut alias: "t") - dbconsole Start a console for the database specified in config/database.yml - (short-cut alias: "db") - new Create a new Rails application. "rails new my_app" creates a - new application called MyApp in "./my_app" - -All commands can be run with -h (or --help) for more information. - -In addition to those commands, there are: -EOT - - ADDITIONAL_COMMANDS = [ - [ 'destroy', 'Undo code generated with "generate" (short-cut alias: "d")' ], - [ 'plugin new', 'Generates skeleton for developing a Rails plugin' ], - [ 'runner', - 'Run a piece of code in the application environment (short-cut alias: "r")' ] - ] - - COMMAND_WHITELIST = %w(plugin generate destroy console server dbconsole runner new version help test) - - def initialize(argv) - @argv = argv - end - - def run_command!(command) - command = parse_command(command) - - if COMMAND_WHITELIST.include?(command) - send(command) - else - run_rake_task(command) - end - end - - def plugin - require_command!("plugin") - end - - def generate - generate_or_destroy(:generate) - end - - def destroy - generate_or_destroy(:destroy) - end - - def console - require_command!("console") - options = Rails::Console.parse_arguments(argv) - - # RAILS_ENV needs to be set before config/application is required - ENV['RAILS_ENV'] = options[:environment] if options[:environment] - - # shift ARGV so IRB doesn't freak - shift_argv! - - require_application_and_environment! - Rails::Console.start(Rails.application, options) - end - - def server - set_application_directory! - require_command!("server") - - Rails::Server.new.tap do |server| - # We need to require application after the server sets environment, - # otherwise the --environment option given to the server won't propagate. - require APP_PATH - Dir.chdir(Rails.application.root) - server.start - end - end - - def test - require_command!("test") - end - - def dbconsole - require_command!("dbconsole") - Rails::DBConsole.start - end - - def runner - require_command!("runner") - end - - def new - if %w(-h --help).include?(argv.first) - require_command!("application") - else - exit_with_initialization_warning! - end - end - - def version - argv.unshift '--version' - require_command!("application") - end - - def help - write_help_message - write_commands ADDITIONAL_COMMANDS + formatted_rake_tasks - end - - private - - def exit_with_initialization_warning! - puts "Can't initialize a new Rails application within the directory of another, please change to a non-Rails directory first.\n" - puts "Type 'rails' for help." - exit(1) - end - - def shift_argv! - argv.shift if argv.first && argv.first[0] != '-' - end - - def require_command!(command) - require "rails/commands/#{command}" - end - - def generate_or_destroy(command) - require 'rails/generators' - require_application_and_environment! - Rails.application.load_generators - require_command!(command) - end - - # Change to the application's path if there is no config.ru file in current directory. - # This allows us to run `rails server` from other directories, but still get - # the main config.ru and properly set the tmp directory. - def set_application_directory! - Dir.chdir(File.expand_path('../../', APP_PATH)) unless File.exist?(File.expand_path("config.ru")) - end - - def require_application_and_environment! - require APP_PATH - Rails.application.require_environment! - end - - def write_help_message - puts HELP_MESSAGE - end - - def write_commands(commands) - width = commands.map { |name, _| name.size }.max || 10 - commands.each { |command| printf(" %-#{width}s %s\n", *command) } - end - - def parse_command(command) - case command - when '--version', '-v' - 'version' - when '--help', '-h' - 'help' - else - command - end - end - end -end diff --git a/railties/lib/rails/commands/console.rb b/railties/lib/rails/commands/console.rb deleted file mode 100644 index ea5d20ea24..0000000000 --- a/railties/lib/rails/commands/console.rb +++ /dev/null @@ -1,68 +0,0 @@ -require 'optparse' -require 'irb' -require 'irb/completion' -require 'rails/commands/console_helper' - -module Rails - class Console - include ConsoleHelper - - class << self - def parse_arguments(arguments) - options = {} - - OptionParser.new do |opt| - opt.banner = "Usage: rails console [environment] [options]" - opt.on('-s', '--sandbox', 'Rollback database modifications on exit.') { |v| options[:sandbox] = v } - opt.on("-e", "--environment=name", String, - "Specifies the environment to run this console under (test/development/production).", - "Default: development") { |v| options[:environment] = v.strip } - opt.parse!(arguments) - end - - set_options_env(arguments, options) - end - end - - attr_reader :options, :app, :console - - def initialize(app, options={}) - @app = app - @options = options - - app.sandbox = sandbox? - app.load_console - - @console = app.config.console || IRB - end - - def sandbox? - options[:sandbox] - end - - def environment - options[:environment] ||= super - end - alias_method :environment?, :environment - - def set_environment! - Rails.env = environment - end - - def start - set_environment! if environment? - - if sandbox? - puts "Loading #{Rails.env} environment in sandbox (Rails #{Rails.version})" - puts "Any modifications you make will be rolled back on exit" - else - puts "Loading #{Rails.env} environment (Rails #{Rails.version})" - end - - if defined?(console::ExtendCommandBundle) - console::ExtendCommandBundle.include(Rails::ConsoleMethods) - end - console.start - end - end -end diff --git a/railties/lib/rails/commands/console/console_command.rb b/railties/lib/rails/commands/console/console_command.rb new file mode 100644 index 0000000000..62e3aa19df --- /dev/null +++ b/railties/lib/rails/commands/console/console_command.rb @@ -0,0 +1,89 @@ +require "irb" +require "irb/completion" + +require "rails/command/environment_argument" + +module Rails + class Console + module BacktraceCleaner + def filter_backtrace(bt) + if result = super + Rails.backtrace_cleaner.filter([result]).first + end + end + end + + def self.start(*args) + new(*args).start + end + + attr_reader :options, :app, :console + + def initialize(app, options = {}) + @app = app + @options = options + + app.sandbox = sandbox? + app.load_console + + @console = app.config.console || IRB + + if @console == IRB + IRB::WorkSpace.prepend(BacktraceCleaner) + end + end + + def sandbox? + options[:sandbox] + end + + def environment + options[:environment] + end + alias_method :environment?, :environment + + def set_environment! + Rails.env = environment + end + + def start + set_environment! if environment? + + if sandbox? + puts "Loading #{Rails.env} environment in sandbox (Rails #{Rails.version})" + puts "Any modifications you make will be rolled back on exit" + else + puts "Loading #{Rails.env} environment (Rails #{Rails.version})" + end + + if defined?(console::ExtendCommandBundle) + console::ExtendCommandBundle.include(Rails::ConsoleMethods) + end + console.start + end + end + + module Command + class ConsoleCommand < Base # :nodoc: + include EnvironmentArgument + + class_option :sandbox, aliases: "-s", type: :boolean, default: false, + desc: "Rollback database modifications on exit." + + class_option :environment, aliases: "-e", type: :string, + desc: "Specifies the environment to run this console under (test/development/production)." + + def perform + extract_environment_option_from_argument + + # RAILS_ENV needs to be set before config/application is required. + ENV["RAILS_ENV"] = options[:environment] + + ARGV.clear # Clear ARGV so IRB doesn't freak. + + require_application_and_environment! + Rails::Console.start(Rails.application, options) + end + end + end +end diff --git a/railties/lib/rails/commands/console_helper.rb b/railties/lib/rails/commands/console_helper.rb deleted file mode 100644 index 8ee0b60012..0000000000 --- a/railties/lib/rails/commands/console_helper.rb +++ /dev/null @@ -1,34 +0,0 @@ -require 'active_support/concern' - -module Rails - module ConsoleHelper # :nodoc: - extend ActiveSupport::Concern - - module ClassMethods - def start(*args) - new(*args).start - end - - private - def set_options_env(arguments, options) - if arguments.first && arguments.first[0] != '-' - env = arguments.first - if available_environments.include? env - options[:environment] = env - else - options[:environment] = %w(production development test).detect { |e| e =~ /^#{env}/ } || env - end - end - options - end - - def available_environments - Dir['config/environments/*.rb'].map { |fname| File.basename(fname, '.*') } - end - end - - def environment - ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development" - end - end -end
\ No newline at end of file diff --git a/railties/lib/rails/commands/dbconsole.rb b/railties/lib/rails/commands/dbconsole.rb deleted file mode 100644 index 2c36edfa3f..0000000000 --- a/railties/lib/rails/commands/dbconsole.rb +++ /dev/null @@ -1,173 +0,0 @@ -require 'erb' -require 'yaml' -require 'optparse' -require 'rails/commands/console_helper' - -module Rails - class DBConsole - include ConsoleHelper - - attr_reader :arguments - - class << self - def parse_arguments(arguments) - options = {} - - OptionParser.new do |opt| - opt.banner = "Usage: rails dbconsole [environment] [options]" - opt.on("-p", "--include-password", "Automatically provide the password from database.yml") do |v| - options['include_password'] = true - end - - opt.on("--mode [MODE]", ['html', 'list', 'line', 'column'], - "Automatically put the sqlite3 database in the specified mode (html, list, line, column).") do |mode| - options['mode'] = mode - end - - opt.on("--header") do |h| - options['header'] = h - end - - opt.on("-h", "--help", "Show this help message.") do - puts opt - exit - end - - opt.on("-e", "--environment=name", String, - "Specifies the environment to run this console under (test/development/production).", - "Default: development" - ) { |v| options[:environment] = v.strip } - - opt.parse!(arguments) - abort opt.to_s unless (0..1).include?(arguments.size) - end - - set_options_env(arguments, options) - end - end - - def initialize(arguments = ARGV) - @arguments = arguments - end - - def start - options = self.class.parse_arguments(arguments) - ENV['RAILS_ENV'] = options[:environment] || environment - - case config["adapter"] - when /^(jdbc)?mysql/ - args = { - 'host' => '--host', - 'port' => '--port', - 'socket' => '--socket', - 'username' => '--user', - 'encoding' => '--default-character-set', - 'sslca' => '--ssl-ca', - 'sslcert' => '--ssl-cert', - 'sslcapath' => '--ssl-capath', - 'sslcipher' => '--ssl-cipher', - 'sslkey' => '--ssl-key' - }.map { |opt, arg| "#{arg}=#{config[opt]}" if config[opt] }.compact - - if config['password'] && options['include_password'] - args << "--password=#{config['password']}" - elsif config['password'] && !config['password'].to_s.empty? - args << "-p" - end - - args << config['database'] - - find_cmd_and_exec(['mysql', 'mysql5'], *args) - - when /^postgres|^postgis/ - ENV['PGUSER'] = config["username"] if config["username"] - ENV['PGHOST'] = config["host"] if config["host"] - ENV['PGPORT'] = config["port"].to_s if config["port"] - ENV['PGPASSWORD'] = config["password"].to_s if config["password"] && options['include_password'] - find_cmd_and_exec('psql', config["database"]) - - when "sqlite3" - args = [] - - args << "-#{options['mode']}" if options['mode'] - args << "-header" if options['header'] - args << File.expand_path(config['database'], Rails.respond_to?(:root) ? Rails.root : nil) - - find_cmd_and_exec('sqlite3', *args) - - when "oracle", "oracle_enhanced" - logon = "" - - if config['username'] - logon = config['username'] - logon << "/#{config['password']}" if config['password'] && options['include_password'] - logon << "@#{config['database']}" if config['database'] - end - - find_cmd_and_exec('sqlplus', logon) - - when "sqlserver" - args = [] - - args += ["-D", "#{config['database']}"] if config['database'] - args += ["-U", "#{config['username']}"] if config['username'] - args += ["-P", "#{config['password']}"] if config['password'] - - if config['host'] - host_arg = "#{config['host']}" - host_arg << ":#{config['port']}" if config['port'] - args += ["-S", host_arg] - end - - find_cmd_and_exec("sqsh", *args) - - else - abort "Unknown command-line client for #{config['database']}." - end - end - - def config - @config ||= begin - if configurations[environment].blank? - raise ActiveRecord::AdapterNotSpecified, "'#{environment}' database is not configured. Available configuration: #{configurations.inspect}" - else - configurations[environment] - end - end - end - - def environment - Rails.respond_to?(:env) ? Rails.env : super - end - - protected - def configurations - require APP_PATH - ActiveRecord::Base.configurations = Rails.application.config.database_configuration - ActiveRecord::Base.configurations - end - - def find_cmd_and_exec(commands, *args) - commands = Array(commands) - - dirs_on_path = ENV['PATH'].to_s.split(File::PATH_SEPARATOR) - unless (ext = RbConfig::CONFIG['EXEEXT']).empty? - commands = commands.map{|cmd| "#{cmd}#{ext}"} - end - - full_path_command = nil - found = commands.detect do |cmd| - dirs_on_path.detect do |path| - full_path_command = File.join(path, cmd) - File.file?(full_path_command) && File.executable?(full_path_command) - end - end - - if found - exec full_path_command, *args - else - abort("Couldn't find database client: #{commands.join(', ')}. Check your $PATH and try again.") - end - end - end -end diff --git a/railties/lib/rails/commands/dbconsole/dbconsole_command.rb b/railties/lib/rails/commands/dbconsole/dbconsole_command.rb new file mode 100644 index 0000000000..588fb06b15 --- /dev/null +++ b/railties/lib/rails/commands/dbconsole/dbconsole_command.rb @@ -0,0 +1,155 @@ +require "rails/command/environment_argument" + +module Rails + class DBConsole + def self.start(*args) + new(*args).start + end + + def initialize(options = {}) + @options = options + end + + def start + ENV["RAILS_ENV"] = @options[:environment] || environment + + case config["adapter"] + when /^(jdbc)?mysql/ + args = { + "host" => "--host", + "port" => "--port", + "socket" => "--socket", + "username" => "--user", + "encoding" => "--default-character-set", + "sslca" => "--ssl-ca", + "sslcert" => "--ssl-cert", + "sslcapath" => "--ssl-capath", + "sslcipher" => "--ssl-cipher", + "sslkey" => "--ssl-key" + }.map { |opt, arg| "#{arg}=#{config[opt]}" if config[opt] }.compact + + if config["password"] && @options["include_password"] + args << "--password=#{config['password']}" + elsif config["password"] && !config["password"].to_s.empty? + args << "-p" + end + + args << config["database"] + + find_cmd_and_exec(["mysql", "mysql5"], *args) + + when /^postgres|^postgis/ + ENV["PGUSER"] = config["username"] if config["username"] + ENV["PGHOST"] = config["host"] if config["host"] + ENV["PGPORT"] = config["port"].to_s if config["port"] + ENV["PGPASSWORD"] = config["password"].to_s if config["password"] && @options["include_password"] + find_cmd_and_exec("psql", config["database"]) + + when "sqlite3" + args = [] + + args << "-#{@options['mode']}" if @options["mode"] + args << "-header" if @options["header"] + args << File.expand_path(config["database"], Rails.respond_to?(:root) ? Rails.root : nil) + + find_cmd_and_exec("sqlite3", *args) + + when "oracle", "oracle_enhanced" + logon = "" + + if config["username"] + logon = config["username"] + logon << "/#{config['password']}" if config["password"] && @options["include_password"] + logon << "@#{config['database']}" if config["database"] + end + + find_cmd_and_exec("sqlplus", logon) + + when "sqlserver" + args = [] + + args += ["-D", "#{config['database']}"] if config["database"] + args += ["-U", "#{config['username']}"] if config["username"] + args += ["-P", "#{config['password']}"] if config["password"] + + if config["host"] + host_arg = "#{config['host']}" + host_arg << ":#{config['port']}" if config["port"] + args += ["-S", host_arg] + end + + find_cmd_and_exec("sqsh", *args) + + else + abort "Unknown command-line client for #{config['database']}." + end + end + + def config + @config ||= begin + if configurations[environment].blank? + raise ActiveRecord::AdapterNotSpecified, "'#{environment}' database is not configured. Available configuration: #{configurations.inspect}" + else + configurations[environment] + end + end + end + + def environment + Rails.respond_to?(:env) ? Rails.env : Rails::Command.environment + end + + private + def configurations # :doc: + require APP_PATH + ActiveRecord::Base.configurations = Rails.application.config.database_configuration + ActiveRecord::Base.configurations + end + + def find_cmd_and_exec(commands, *args) # :doc: + commands = Array(commands) + + dirs_on_path = ENV["PATH"].to_s.split(File::PATH_SEPARATOR) + unless (ext = RbConfig::CONFIG["EXEEXT"]).empty? + commands = commands.map { |cmd| "#{cmd}#{ext}" } + end + + full_path_command = nil + found = commands.detect do |cmd| + dirs_on_path.detect do |path| + full_path_command = File.join(path, cmd) + File.file?(full_path_command) && File.executable?(full_path_command) + end + end + + if found + exec full_path_command, *args + else + abort("Couldn't find database client: #{commands.join(', ')}. Check your $PATH and try again.") + end + end + end + + module Command + class DbconsoleCommand < Base # :nodoc: + include EnvironmentArgument + + class_option :include_password, aliases: "-p", type: :boolean, + desc: "Automatically provide the password from database.yml" + + class_option :mode, enum: %w( html list line column ), type: :string, + desc: "Automatically put the sqlite3 database in the specified mode (html, list, line, column)." + + class_option :header, type: :string + + class_option :environment, aliases: "-e", type: :string, + desc: "Specifies the environment to run this console under (test/development/production)." + + def perform + extract_environment_option_from_argument + + Rails::DBConsole.start(options) + end + end + end +end diff --git a/railties/lib/rails/commands/destroy.rb b/railties/lib/rails/commands/destroy.rb deleted file mode 100644 index ce26cc3fde..0000000000 --- a/railties/lib/rails/commands/destroy.rb +++ /dev/null @@ -1,11 +0,0 @@ -require 'rails/generators' - -#if no argument/-h/--help is passed to rails destroy command, then -#it generates the help associated. -if [nil, "-h", "--help"].include?(ARGV.first) - Rails::Generators.help 'destroy' - exit -end - -name = ARGV.shift -Rails::Generators.invoke name, ARGV, behavior: :revoke, destination_root: Rails.root diff --git a/railties/lib/rails/commands/destroy/destroy_command.rb b/railties/lib/rails/commands/destroy/destroy_command.rb new file mode 100644 index 0000000000..5b552b2070 --- /dev/null +++ b/railties/lib/rails/commands/destroy/destroy_command.rb @@ -0,0 +1,21 @@ +require "rails/generators" + +module Rails + module Command + class DestroyCommand < Base # :nodoc: + def help + Rails::Generators.help self.class.command_name + end + + def perform(*) + generator = args.shift + return help unless generator + + require_application_and_environment! + Rails.application.load_generators + + Rails::Generators.invoke generator, args, behavior: :revoke, destination_root: Rails.root + end + end + end +end diff --git a/railties/lib/rails/commands/generate.rb b/railties/lib/rails/commands/generate.rb deleted file mode 100644 index 926c36b967..0000000000 --- a/railties/lib/rails/commands/generate.rb +++ /dev/null @@ -1,13 +0,0 @@ -require 'rails/generators' - -#if no argument/-h/--help is passed to rails generate command, then -#it generates the help associated. -if [nil, "-h", "--help"].include?(ARGV.first) - Rails::Generators.help 'generate' - exit -end - -name = ARGV.shift - -root = defined?(ENGINE_ROOT) ? ENGINE_ROOT : Rails.root -Rails::Generators.invoke name, ARGV, behavior: :invoke, destination_root: root diff --git a/railties/lib/rails/commands/generate/generate_command.rb b/railties/lib/rails/commands/generate/generate_command.rb new file mode 100644 index 0000000000..aa8dab71b0 --- /dev/null +++ b/railties/lib/rails/commands/generate/generate_command.rb @@ -0,0 +1,23 @@ +require "rails/generators" + +module Rails + module Command + class GenerateCommand < Base # :nodoc: + def help + Rails::Generators.help self.class.command_name + end + + def perform(*) + generator = args.shift + return help unless generator + + require_application_and_environment! + load_generators + + ARGV.shift + + Rails::Generators.invoke generator, args, behavior: :invoke, destination_root: Rails::Command.root + end + end + end +end diff --git a/railties/lib/rails/commands/help/USAGE b/railties/lib/rails/commands/help/USAGE new file mode 100644 index 0000000000..348f41861f --- /dev/null +++ b/railties/lib/rails/commands/help/USAGE @@ -0,0 +1,27 @@ +Usage: bin/rails COMMAND [args] [options] +<% if engine? %> +The common Rails commands available for engines are: + generate Generate new code (short-cut alias: "g") + destroy Undo code generated with "generate" (short-cut alias: "d") + test Run tests (short-cut alias: "t") + +All commands can be run with -h for more information. + +If you want to run any commands that need to be run in context +of the application, like `bin/rails server` or `bin/rails console`, +you should do it from the application's directory (typically test/dummy). +<% else %> +The most common rails commands are: + generate Generate new code (short-cut alias: "g") + console Start the Rails console (short-cut alias: "c") + server Start the Rails server (short-cut alias: "s") + test Run tests (short-cut alias: "t") + dbconsole Start a console for the database specified in config/database.yml + (short-cut alias: "db") + new Create a new Rails application. "rails new my_app" creates a + new application called MyApp in "./my_app" + +All commands can be run with -h (or --help) for more information. +<% end %> +In addition to those commands, there are: + diff --git a/railties/lib/rails/commands/help/help_command.rb b/railties/lib/rails/commands/help/help_command.rb new file mode 100644 index 0000000000..90d37217fc --- /dev/null +++ b/railties/lib/rails/commands/help/help_command.rb @@ -0,0 +1,13 @@ +module Rails + module Command + class HelpCommand < Base # :nodoc: + hide_command! + + def help(*) + puts self.class.desc + + Rails::Command.print_commands + end + end + end +end diff --git a/railties/lib/rails/commands/new/new_command.rb b/railties/lib/rails/commands/new/new_command.rb new file mode 100644 index 0000000000..74d1fa5021 --- /dev/null +++ b/railties/lib/rails/commands/new/new_command.rb @@ -0,0 +1,15 @@ +module Rails + module Command + class NewCommand < Base # :nodoc: + def help + Rails::Command.invoke :application, [ "--help" ] + end + + def perform(*) + puts "Can't initialize a new Rails application within the directory of another, please change to a non-Rails directory first.\n" + puts "Type 'rails' for help." + exit 1 + end + end + end +end diff --git a/railties/lib/rails/commands/plugin.rb b/railties/lib/rails/commands/plugin.rb deleted file mode 100644 index 52d8966ead..0000000000 --- a/railties/lib/rails/commands/plugin.rb +++ /dev/null @@ -1,23 +0,0 @@ -if ARGV.first != "new" - ARGV[0] = "--help" -else - ARGV.shift - unless ARGV.delete("--no-rc") - customrc = ARGV.index{ |x| x.include?("--rc=") } - railsrc = if customrc - File.expand_path(ARGV.delete_at(customrc).gsub(/--rc=/, "")) - else - File.join(File.expand_path("~"), '.railsrc') - end - if File.exist?(railsrc) - extra_args_string = File.read(railsrc) - extra_args = extra_args_string.split(/\n+/).flat_map(&:split) - puts "Using #{extra_args.join(" ")} from #{railsrc}" - ARGV.insert(1, *extra_args) - end - end -end - -require 'rails/generators' -require 'rails/generators/rails/plugin/plugin_generator' -Rails::Generators::PluginGenerator.start diff --git a/railties/lib/rails/commands/plugin/plugin_command.rb b/railties/lib/rails/commands/plugin/plugin_command.rb new file mode 100644 index 0000000000..b40ab006af --- /dev/null +++ b/railties/lib/rails/commands/plugin/plugin_command.rb @@ -0,0 +1,43 @@ +module Rails + module Command + class PluginCommand < Base # :nodoc: + hide_command! + + def help + run_plugin_generator %w( --help ) + end + + def self.banner(*) # :nodoc: + "#{executable} new [options]" + end + + class_option :rc, type: :string, default: File.join("~", ".railsrc"), + desc: "Initialize the plugin command with previous defaults. Uses .railsrc in your home directory by default." + + class_option :no_rc, desc: "Skip evaluating .railsrc." + + def perform(type = nil, *plugin_args) + plugin_args << "--help" unless type == "new" + + unless options.key?("no_rc") # Thor's not so indifferent access hash. + railsrc = File.expand_path(options[:rc]) + + if File.exist?(railsrc) + extra_args = File.read(railsrc).split(/\n+/).flat_map(&:split) + puts "Using #{extra_args.join(" ")} from #{railsrc}" + plugin_args.insert(1, *extra_args) + end + end + + run_plugin_generator plugin_args + end + + private + def run_plugin_generator(plugin_args) + require "rails/generators" + require "rails/generators/rails/plugin/plugin_generator" + Rails::Generators::PluginGenerator.start plugin_args + end + end + end +end diff --git a/railties/lib/rails/commands/rake/rake_command.rb b/railties/lib/rails/commands/rake/rake_command.rb new file mode 100644 index 0000000000..075b1fd23d --- /dev/null +++ b/railties/lib/rails/commands/rake/rake_command.rb @@ -0,0 +1,49 @@ +module Rails + module Command + class RakeCommand < Base # :nodoc: + extend Rails::Command::Actions + + namespace "rake" + + class << self + def printing_commands + formatted_rake_tasks.map(&:first) + end + + def perform(task, *) + require_rake + + ARGV.unshift(task) # Prepend the task, so Rake knows how to run it. + + Rake.application.standard_exception_handling do + Rake.application.init("rails") + Rake.application.load_rakefile + Rake.application.top_level + end + end + + private + def rake_tasks + require_rake + + return @rake_tasks if defined?(@rake_tasks) + + require_application_and_environment! + + Rake::TaskManager.record_task_metadata = true + Rake.application.instance_variable_set(:@name, "rails") + load_tasks + @rake_tasks = Rake.application.tasks.select(&:comment) + end + + def formatted_rake_tasks + rake_tasks.map { |t| [ t.name_with_args, t.comment ] } + end + + def require_rake + require "rake" # Defer booting Rake until we know it's needed. + end + end + end + end +end diff --git a/railties/lib/rails/commands/rake_proxy.rb b/railties/lib/rails/commands/rake_proxy.rb deleted file mode 100644 index f7d5df6b2f..0000000000 --- a/railties/lib/rails/commands/rake_proxy.rb +++ /dev/null @@ -1,34 +0,0 @@ -require 'rake' -require 'active_support' - -module Rails - module RakeProxy #:nodoc: - private - def run_rake_task(command) - ARGV.unshift(command) # Prepend the command, so Rake knows how to run it. - - Rake.application.standard_exception_handling do - Rake.application.init('rails') - Rake.application.load_rakefile - Rake.application.top_level - end - end - - def rake_tasks - return @rake_tasks if defined?(@rake_tasks) - - ActiveSupport::Deprecation.silence do - require_application_and_environment! - end - - Rake::TaskManager.record_task_metadata = true - Rake.application.instance_variable_set(:@name, 'rails') - Rails.application.load_tasks - @rake_tasks = Rake.application.tasks.select(&:comment) - end - - def formatted_rake_tasks - rake_tasks.map { |t| [ t.name_with_args, t.comment ] } - end - end -end diff --git a/railties/lib/rails/commands/runner.rb b/railties/lib/rails/commands/runner.rb deleted file mode 100644 index f9c183ac86..0000000000 --- a/railties/lib/rails/commands/runner.rb +++ /dev/null @@ -1,69 +0,0 @@ -require 'optparse' - -options = { environment: (ENV['RAILS_ENV'] || ENV['RACK_ENV'] || "development").dup } -code_or_file = nil -command = 'bin/rails runner' - -if ARGV.first.nil? - ARGV.push "-h" -end - -ARGV.clone.options do |opts| - opts.banner = "Usage: rails runner [options] [<'Some.ruby(code)'> | <filename.rb>]" - - opts.separator "" - - opts.on("-e", "--environment=name", String, - "Specifies the environment for the runner to operate under (test/development/production).", - "Default: development") { |v| options[:environment] = v } - - opts.separator "" - - opts.on("-h", "--help", - "Show this help message.") { $stdout.puts opts; exit } - - opts.separator "" - opts.separator "Examples: " - - opts.separator " rails runner 'puts Rails.env'" - opts.separator " This runs the code `puts Rails.env` after loading the app" - opts.separator "" - opts.separator " rails runner path/to/filename.rb" - opts.separator " This runs the Ruby file located at `path/to/filename.rb` after loading the app" - - if RbConfig::CONFIG['host_os'] !~ /mswin|mingw/ - opts.separator "" - opts.separator "You can also use runner as a shebang line for your executables:" - opts.separator " -------------------------------------------------------------" - opts.separator " #!/usr/bin/env #{File.expand_path(command)}" - opts.separator "" - opts.separator " Product.all.each { |p| p.price *= 2 ; p.save! }" - opts.separator " -------------------------------------------------------------" - end - - opts.order! { |o| code_or_file ||= o } rescue retry -end - -ARGV.delete(code_or_file) - -ENV["RAILS_ENV"] = options[:environment] - -require APP_PATH -Rails.application.require_environment! -Rails.application.load_runner - -if code_or_file.nil? - $stderr.puts "Run '#{command} -h' for help." - exit 1 -elsif File.exist?(code_or_file) - $0 = code_or_file - Kernel.load code_or_file -else - begin - eval(code_or_file, binding, __FILE__, __LINE__) - rescue SyntaxError, NameError - $stderr.puts "Please specify a valid ruby command or the path of a script to run." - $stderr.puts "Run '#{command} -h' for help." - exit 1 - end -end diff --git a/railties/lib/rails/commands/runner/USAGE b/railties/lib/rails/commands/runner/USAGE new file mode 100644 index 0000000000..b2a6e8493d --- /dev/null +++ b/railties/lib/rails/commands/runner/USAGE @@ -0,0 +1,17 @@ +Examples: + +Run `puts Rails.env` after loading the app: + + <%= executable %> 'puts Rails.env' + +Run the Ruby file located at `path/to/filename.rb` after loading the app: + + <%= executable %> path/to/filename.rb + +<% unless Gem.win_platform? %> +You can also use the runner command as a shebang line for your executables: + + #!/usr/bin/env <%= File.expand_path(executable) %> + + Product.all.each { |p| p.price *= 2 ; p.save! } +<% end %> diff --git a/railties/lib/rails/commands/runner/runner_command.rb b/railties/lib/rails/commands/runner/runner_command.rb new file mode 100644 index 0000000000..4989a7837d --- /dev/null +++ b/railties/lib/rails/commands/runner/runner_command.rb @@ -0,0 +1,46 @@ +module Rails + module Command + class RunnerCommand < Base # :nodoc: + class_option :environment, aliases: "-e", type: :string, + default: Rails::Command.environment.dup, + desc: "The environment for the runner to operate under (test/development/production)" + + def help + super + puts self.class.desc + end + + def self.banner(*) + "#{super} [<'Some.ruby(code)'> | <filename.rb>]" + end + + def perform(code_or_file = nil, *file_argv) + unless code_or_file + help + exit 1 + end + + ENV["RAILS_ENV"] = options[:environment] + + require_application_and_environment! + Rails.application.load_runner + + if File.exist?(code_or_file) + $0 = code_or_file + ARGV.replace(file_argv) + Kernel.load code_or_file + else + begin + eval(code_or_file, binding, __FILE__, __LINE__) + rescue SyntaxError, NameError => error + $stderr.puts "Please specify a valid ruby command or the path of a script to run." + $stderr.puts "Run '#{self.class.executable} -h' for help." + $stderr.puts + $stderr.puts error + exit 1 + end + end + end + end + end +end diff --git a/railties/lib/rails/commands/server.rb b/railties/lib/rails/commands/server.rb deleted file mode 100644 index 7418dff18b..0000000000 --- a/railties/lib/rails/commands/server.rb +++ /dev/null @@ -1,139 +0,0 @@ -require 'fileutils' -require 'optparse' -require 'action_dispatch' -require 'rails' -require 'rails/dev_caching' - -module Rails - class Server < ::Rack::Server - class Options - DEFAULT_PID_PATH = File.expand_path("tmp/pids/server.pid").freeze - - def parse!(args) - args, options = args.dup, {} - - option_parser(options).parse! args - - options[:log_stdout] = options[:daemonize].blank? && (options[:environment] || Rails.env) == "development" - options[:server] = args.shift - options - end - - private - - def option_parser(options) - OptionParser.new do |opts| - opts.banner = "Usage: rails server [mongrel, thin etc] [options]" - opts.on("-p", "--port=port", Integer, - "Runs Rails on the specified port.", "Default: 3000") { |v| options[:Port] = v } - opts.on("-b", "--binding=IP", String, - "Binds Rails to the specified IP.", "Default: localhost") { |v| options[:Host] = v } - opts.on("-c", "--config=file", String, - "Uses a custom rackup configuration.") { |v| options[:config] = v } - opts.on("-d", "--daemon", "Runs server as a Daemon.") { options[:daemonize] = true } - opts.on("-e", "--environment=name", String, - "Specifies the environment to run this server under (test/development/production).", - "Default: development") { |v| options[:environment] = v } - opts.on("-P", "--pid=pid", String, - "Specifies the PID file.", - "Default: tmp/pids/server.pid") { |v| options[:pid] = v } - opts.on("-C", "--[no-]dev-caching", - "Specifies whether to perform caching in development.", - "true or false") { |v| options[:caching] = v } - - opts.separator "" - - opts.on("-h", "--help", "Shows this help message.") { puts opts; exit } - end - end - end - - def initialize(*) - super - set_environment - end - - # TODO: this is no longer required but we keep it for the moment to support older config.ru files. - def app - @app ||= begin - app = super - app.respond_to?(:to_app) ? app.to_app : app - end - end - - def opt_parser - Options.new - end - - def set_environment - ENV["RAILS_ENV"] ||= options[:environment] - end - - def start - print_boot_information - trap(:INT) { exit } - create_tmp_directories - setup_dev_caching - log_to_stdout if options[:log_stdout] - - super - ensure - # The '-h' option calls exit before @options is set. - # If we call 'options' with it unset, we get double help banners. - puts 'Exiting' unless @options && options[:daemonize] - end - - def middleware - Hash.new([]) - end - - def default_options - super.merge({ - Port: ENV.fetch('PORT', 3000).to_i, - DoNotReverseLookup: true, - environment: (ENV['RAILS_ENV'] || ENV['RACK_ENV'] || "development").dup, - daemonize: false, - caching: nil, - pid: Options::DEFAULT_PID_PATH, - restart_cmd: restart_command - }) - end - - private - - def setup_dev_caching - if options[:environment] == "development" - Rails::DevCaching.enable_by_argument(options[:caching]) - end - end - - def print_boot_information - url = "#{options[:SSLEnable] ? 'https' : 'http'}://#{options[:Host]}:#{options[:Port]}" - puts "=> Booting #{ActiveSupport::Inflector.demodulize(server)}" - puts "=> Rails #{Rails.version} application starting in #{Rails.env} on #{url}" - puts "=> Run `rails server -h` for more startup options" - end - - def create_tmp_directories - %w(cache pids sockets).each do |dir_to_make| - FileUtils.mkdir_p(File.join(Rails.root, 'tmp', dir_to_make)) - end - end - - def log_to_stdout - wrapped_app # touch the app so the logger is set up - - console = ActiveSupport::Logger.new(STDOUT) - console.formatter = Rails.logger.formatter - console.level = Rails.logger.level - - unless ActiveSupport::Logger.logger_outputs_to?(Rails.logger, STDOUT) - Rails.logger.extend(ActiveSupport::Logger.broadcast(console)) - end - end - - def restart_command - "bin/rails server #{ARGV.join(' ')}" - end - end -end diff --git a/railties/lib/rails/commands/server/server_command.rb b/railties/lib/rails/commands/server/server_command.rb new file mode 100644 index 0000000000..15c636103b --- /dev/null +++ b/railties/lib/rails/commands/server/server_command.rb @@ -0,0 +1,173 @@ +require "fileutils" +require "optparse" +require "action_dispatch" +require "rails" +require "rails/dev_caching" + +module Rails + class Server < ::Rack::Server + class Options + def parse!(args) + Rails::Command::ServerCommand.new([], args).server_options + end + end + + def initialize(options = nil) + @default_options = options || {} + super(@default_options) + set_environment + end + + # TODO: this is no longer required but we keep it for the moment to support older config.ru files. + def app + @app ||= begin + app = super + app.respond_to?(:to_app) ? app.to_app : app + end + end + + def opt_parser + Options.new + end + + def set_environment + ENV["RAILS_ENV"] ||= options[:environment] + end + + def start + print_boot_information + trap(:INT) { exit } + create_tmp_directories + setup_dev_caching + log_to_stdout if options[:log_stdout] + + super + ensure + # The '-h' option calls exit before @options is set. + # If we call 'options' with it unset, we get double help banners. + puts "Exiting" unless @options && options[:daemonize] + end + + def middleware + Hash.new([]) + end + + def default_options + super.merge(@default_options) + end + + private + def setup_dev_caching + if options[:environment] == "development" + Rails::DevCaching.enable_by_argument(options[:caching]) + end + end + + def print_boot_information + url = "#{options[:SSLEnable] ? 'https' : 'http'}://#{options[:Host]}:#{options[:Port]}" + puts "=> Booting #{ActiveSupport::Inflector.demodulize(server)}" + puts "=> Rails #{Rails.version} application starting in #{Rails.env} on #{url}" + puts "=> Run `rails server -h` for more startup options" + end + + def create_tmp_directories + %w(cache pids sockets).each do |dir_to_make| + FileUtils.mkdir_p(File.join(Rails.root, "tmp", dir_to_make)) + end + end + + def log_to_stdout + wrapped_app # touch the app so the logger is set up + + console = ActiveSupport::Logger.new(STDOUT) + console.formatter = Rails.logger.formatter + console.level = Rails.logger.level + + unless ActiveSupport::Logger.logger_outputs_to?(Rails.logger, STDOUT) + Rails.logger.extend(ActiveSupport::Logger.broadcast(console)) + end + end + + def restart_command + "bin/rails server #{ARGV.join(' ')}" + end + end + + module Command + class ServerCommand < Base # :nodoc: + DEFAULT_PID_PATH = File.expand_path("tmp/pids/server.pid").freeze + + class_option :port, aliases: "-p", type: :numeric, + desc: "Runs Rails on the specified port.", banner: :port, default: 3000 + class_option :binding, aliases: "-b", type: :string, default: "localhost", + desc: "Binds Rails to the specified IP.", banner: :IP + class_option :config, aliases: "-c", type: :string, default: "config.ru", + desc: "Uses a custom rackup configuration.", banner: :file + class_option :daemon, aliases: "-d", type: :boolean, default: false, + desc: "Runs server as a Daemon." + class_option :environment, aliases: "-e", type: :string, + desc: "Specifies the environment to run this server under (development/test/production).", banner: :name + class_option :pid, aliases: "-P", type: :string, default: DEFAULT_PID_PATH, + desc: "Specifies the PID file." + class_option "dev-caching", aliases: "-C", type: :boolean, default: nil, + desc: "Specifies whether to perform caching in development." + + def initialize(args = [], local_options = {}, config = {}) + @original_options = local_options + super + @server = self.args.shift + @log_stdout = options[:daemon].blank? && (options[:environment] || Rails.env) == "development" + end + + def perform + set_application_directory! + Rails::Server.new(server_options).tap do |server| + # Require application after server sets environment to propagate + # the --environment option. + require APP_PATH + Dir.chdir(Rails.application.root) + server.start + end + end + + no_commands do + def server_options + { + server: @server, + log_stdout: @log_stdout, + Port: port, + Host: host, + DoNotReverseLookup: true, + config: options[:config], + environment: environment, + daemonize: options[:daemon], + pid: options[:pid], + caching: options["dev-caching"], + restart_cmd: restart_command + } + end + end + + private + def port + ENV.fetch("PORT", options[:port]).to_i + end + + def host + ENV.fetch("HOST", options[:binding]) + end + + def environment + options[:environment] || Rails::Command.environment + end + + def restart_command + "bin/rails server #{@server} #{@original_options.join(" ")}" + end + + def self.banner(*) + "rails server [puma, thin etc] [options]" + end + end + end +end diff --git a/railties/lib/rails/commands/test.rb b/railties/lib/rails/commands/test.rb deleted file mode 100644 index dd069f081f..0000000000 --- a/railties/lib/rails/commands/test.rb +++ /dev/null @@ -1,9 +0,0 @@ -require "rails/test_unit/minitest_plugin" - -if defined?(ENGINE_ROOT) - $: << File.expand_path('test', ENGINE_ROOT) -else - $: << File.expand_path('../../test', APP_PATH) -end - -exit Minitest.run(ARGV) diff --git a/railties/lib/rails/commands/test/test_command.rb b/railties/lib/rails/commands/test/test_command.rb new file mode 100644 index 0000000000..7bf8f61137 --- /dev/null +++ b/railties/lib/rails/commands/test/test_command.rb @@ -0,0 +1,20 @@ +require "rails/command" +require "rails/test_unit/minitest_plugin" + +module Rails + module Command + class TestCommand < Base # :nodoc: + def help + perform # Hand over help printing to minitest. + end + + def perform(*) + $LOAD_PATH << Rails::Command.root.join("test") + + Minitest.run_via[:rails] = true + + require "active_support/testing/autorun" + end + end + end +end diff --git a/railties/lib/rails/commands/version/version_command.rb b/railties/lib/rails/commands/version/version_command.rb new file mode 100644 index 0000000000..ac745594ee --- /dev/null +++ b/railties/lib/rails/commands/version/version_command.rb @@ -0,0 +1,9 @@ +module Rails + module Command + class VersionCommand < Base # :nodoc: + def perform + Rails::Command.invoke :application, [ "--version" ] + end + end + end +end diff --git a/railties/lib/rails/configuration.rb b/railties/lib/rails/configuration.rb index 30eafd59f2..fc7d4909f6 100644 --- a/railties/lib/rails/configuration.rb +++ b/railties/lib/rails/configuration.rb @@ -1,7 +1,7 @@ -require 'active_support/ordered_options' -require 'active_support/core_ext/object' -require 'rails/paths' -require 'rails/rack' +require "active_support/ordered_options" +require "active_support/core_ext/object" +require "rails/paths" +require "rails/rack" module Rails module Configuration @@ -91,8 +91,8 @@ module Rails attr_reader :hidden_namespaces def initialize - @aliases = Hash.new { |h,k| h[k] = {} } - @options = Hash.new { |h,k| h[k] = {} } + @aliases = Hash.new { |h, k| h[k] = {} } + @options = Hash.new { |h, k| h[k] = {} } @fallbacks = {} @templates = [] @colorize_logging = true @@ -112,7 +112,7 @@ module Rails end def method_missing(method, *args) - method = method.to_s.sub(/=$/, '').to_sym + method = method.to_s.sub(/=$/, "").to_sym return @options[method] if args.empty? diff --git a/railties/lib/rails/console/app.rb b/railties/lib/rails/console/app.rb index 9ad77e0a80..affadc8e09 100644 --- a/railties/lib/rails/console/app.rb +++ b/railties/lib/rails/console/app.rb @@ -1,11 +1,11 @@ -require 'active_support/all' -require 'action_controller' +require "active_support/all" +require "action_controller" module Rails module ConsoleMethods # reference the global "app" instance, created on demand. To recreate the # instance, pass a non-false value as the parameter. - def app(create=false) + def app(create = false) @app_integration_instance = nil if create @app_integration_instance ||= new_session do |sess| sess.host! "www.example.com" @@ -27,7 +27,7 @@ module Rails end # reloads the environment - def reload!(print=true) + def reload!(print = true) puts "Reloading..." if print Rails.application.reloader.reload! true diff --git a/railties/lib/rails/dev_caching.rb b/railties/lib/rails/dev_caching.rb index f2a53d6417..f69275a34a 100644 --- a/railties/lib/rails/dev_caching.rb +++ b/railties/lib/rails/dev_caching.rb @@ -1,27 +1,27 @@ -require 'fileutils' +require "fileutils" module Rails module DevCaching # :nodoc: class << self - FILE = 'tmp/caching-dev.txt' + FILE = "tmp/caching-dev.txt" def enable_by_file - FileUtils.mkdir_p('tmp') + FileUtils.mkdir_p("tmp") if File.exist?(FILE) delete_cache_file - puts 'Development mode is no longer being cached.' + puts "Development mode is no longer being cached." else create_cache_file - puts 'Development mode is now being cached.' + puts "Development mode is now being cached." end - FileUtils.touch 'tmp/restart.txt' - FileUtils.rm_f('tmp/pids/server.pid') + FileUtils.touch "tmp/restart.txt" + FileUtils.rm_f("tmp/pids/server.pid") end def enable_by_argument(caching) - FileUtils.mkdir_p('tmp') + FileUtils.mkdir_p("tmp") if caching create_cache_file diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb index 9701409755..2dd1fb3273 100644 --- a/railties/lib/rails/engine.rb +++ b/railties/lib/rails/engine.rb @@ -1,8 +1,8 @@ -require 'rails/railtie' -require 'rails/engine/railties' -require 'active_support/core_ext/module/delegation' -require 'pathname' -require 'thread' +require "rails/railtie" +require "rails/engine/railties" +require "active_support/core_ext/module/delegation" +require "pathname" +require "thread" module Rails # <tt>Rails::Engine</tt> allows you to wrap a specific Rails application or subset of @@ -337,7 +337,7 @@ module Rails # == Loading priority # # In order to change engine's priority you can use +config.railties_order+ in the main application. - # It will affect the priority of loading views, helpers, assets and all the other files + # It will affect the priority of loading views, helpers, assets, and all the other files # related to engine or application. # # # load Blog::Engine with highest priority, followed by application and other railties @@ -402,7 +402,7 @@ module Rails end unless mod.respond_to?(:railtie_routes_url_helpers) - define_method(:railtie_routes_url_helpers) {|include_path_helpers = true| railtie.routes.url_helpers(include_path_helpers) } + define_method(:railtie_routes_url_helpers) { |include_path_helpers = true| railtie.routes.url_helpers(include_path_helpers) } end end end @@ -436,7 +436,7 @@ module Rails # Load console and invoke the registered hooks. # Check <tt>Rails::Railtie.console</tt> for more info. - def load_console(app=self) + def load_console(app = self) require "rails/console/app" require "rails/console/helpers" run_console_blocks(app) @@ -445,14 +445,14 @@ module Rails # Load Rails runner and invoke the registered hooks. # Check <tt>Rails::Railtie.runner</tt> for more info. - def load_runner(app=self) + def load_runner(app = self) run_runner_blocks(app) self end # Load Rake, railties tasks and invoke the registered hooks. # Check <tt>Rails::Railtie.rake_tasks</tt> for more info. - def load_tasks(app=self) + def load_tasks(app = self) require "rake" run_tasks_blocks(app) self @@ -460,7 +460,7 @@ module Rails # Load Rails generators and invoke the registered hooks. # Check <tt>Rails::Railtie.generators</tt> for more info. - def load_generators(app=self) + def load_generators(app = self) require "rails/generators" run_generators_blocks(app) Rails::Generators.configure!(app.config.generators) @@ -590,8 +590,8 @@ module Rails initializer :add_view_paths do views = paths["app/views"].existent unless views.empty? - ActiveSupport.on_load(:action_controller){ prepend_view_path(views) if respond_to?(:prepend_view_path) } - ActiveSupport.on_load(:action_mailer){ prepend_view_path(views) } + ActiveSupport.on_load(:action_controller) { prepend_view_path(views) if respond_to?(:prepend_view_path) } + ActiveSupport.on_load(:action_mailer) { prepend_view_path(views) } end end @@ -619,7 +619,7 @@ module Rails end rake_tasks do - next if self.is_a?(Rails::Application) + next if is_a?(Rails::Application) next unless has_migrations? namespace railtie_name do @@ -643,62 +643,62 @@ module Rails protected - def load_config_initializer(initializer) - ActiveSupport::Notifications.instrument('load_config_initializer.railties', initializer: initializer) do - load(initializer) + def run_tasks_blocks(*) #:nodoc: + super + paths["lib/tasks"].existent.sort.each { |ext| load(ext) } end - end - def run_tasks_blocks(*) #:nodoc: - super - paths["lib/tasks"].existent.sort.each { |ext| load(ext) } - end - - def has_migrations? #:nodoc: - paths["db/migrate"].existent.any? - end + private - def self.find_root_with_flag(flag, root_path, default=nil) #:nodoc: + def load_config_initializer(initializer) # :doc: + ActiveSupport::Notifications.instrument("load_config_initializer.railties", initializer: initializer) do + load(initializer) + end + end - while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}") - parent = File.dirname(root_path) - root_path = parent != root_path && parent + def has_migrations? + paths["db/migrate"].existent.any? end - root = File.exist?("#{root_path}/#{flag}") ? root_path : default - raise "Could not find root path for #{self}" unless root + def self.find_root_with_flag(flag, root_path, default = nil) #:nodoc: - Pathname.new File.realpath root - end + while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}") + parent = File.dirname(root_path) + root_path = parent != root_path && parent + end - def default_middleware_stack #:nodoc: - ActionDispatch::MiddlewareStack.new - end + root = File.exist?("#{root_path}/#{flag}") ? root_path : default + raise "Could not find root path for #{self}" unless root - def _all_autoload_once_paths #:nodoc: - config.autoload_once_paths - end + Pathname.new File.realpath root + end - def _all_autoload_paths #:nodoc: - @_all_autoload_paths ||= (config.autoload_paths + config.eager_load_paths + config.autoload_once_paths).uniq - end + def default_middleware_stack + ActionDispatch::MiddlewareStack.new + end - def _all_load_paths #:nodoc: - @_all_load_paths ||= (config.paths.load_paths + _all_autoload_paths).uniq - end + def _all_autoload_once_paths + config.autoload_once_paths + end - private + def _all_autoload_paths + @_all_autoload_paths ||= (config.autoload_paths + config.eager_load_paths + config.autoload_once_paths).uniq + end - def build_request(env) - env.merge!(env_config) - req = ActionDispatch::Request.new env - req.routes = routes - req.engine_script_name = req.script_name - req - end + def _all_load_paths + @_all_load_paths ||= (config.paths.load_paths + _all_autoload_paths).uniq + end - def build_middleware - config.middleware - end + def build_request(env) + env.merge!(env_config) + req = ActionDispatch::Request.new env + req.routes = routes + req.engine_script_name = req.script_name + req + end + + def build_middleware + config.middleware + end end end diff --git a/railties/lib/rails/engine/commands.rb b/railties/lib/rails/engine/commands.rb index 7bbd9ef744..a23ae44b0b 100644 --- a/railties/lib/rails/engine/commands.rb +++ b/railties/lib/rails/engine/commands.rb @@ -1,6 +1,4 @@ -require 'rails/engine/commands_tasks' - -ARGV << '--help' if ARGV.empty? +require "rails/command" aliases = { "g" => "generate", @@ -11,4 +9,4 @@ aliases = { command = ARGV.shift command = aliases[command] || command -Rails::Engine::CommandsTasks.new(ARGV).run_command!(command) +Rails::Command.invoke command, ARGV diff --git a/railties/lib/rails/engine/commands_tasks.rb b/railties/lib/rails/engine/commands_tasks.rb deleted file mode 100644 index fa3ee59b7d..0000000000 --- a/railties/lib/rails/engine/commands_tasks.rb +++ /dev/null @@ -1,116 +0,0 @@ -require 'rails/commands/rake_proxy' - -module Rails - class Engine - class CommandsTasks # :nodoc: - include Rails::RakeProxy - - attr_reader :argv - - HELP_MESSAGE = <<-EOT -Usage: rails COMMAND [ARGS] - -The common Rails commands available for engines are: - generate Generate new code (short-cut alias: "g") - destroy Undo code generated with "generate" (short-cut alias: "d") - test Run tests (short-cut alias: "t") - -All commands can be run with -h for more information. - -If you want to run any commands that need to be run in context -of the application, like `rails server` or `rails console`, -you should do it from application's directory (typically test/dummy). - -In addition to those commands, there are: - EOT - - COMMAND_WHITELIST = %w(generate destroy version help test) - - def initialize(argv) - @argv = argv - end - - def run_command!(command) - command = parse_command(command) - - if COMMAND_WHITELIST.include?(command) - send(command) - else - run_rake_task(command) - end - end - - def generate - generate_or_destroy(:generate) - end - - def destroy - generate_or_destroy(:destroy) - end - - def test - require_command!("test") - end - - def version - argv.unshift '--version' - require_command!("application") - end - - def help - write_help_message - write_commands(formatted_rake_tasks) - end - - private - - def require_command!(command) - require "rails/commands/#{command}" - end - - def generate_or_destroy(command) - load_generators - require_command!(command) - end - - def load_generators - require 'rails/generators' - require ENGINE_PATH - - engine = ::Rails::Engine.find(ENGINE_ROOT) - Rails::Generators.namespace = engine.railtie_namespace - engine.load_generators - end - - def write_help_message - puts HELP_MESSAGE - end - - def write_commands(commands) - width = commands.map { |name, _| name.size }.max || 10 - commands.each { |command| printf(" %-#{width}s %s\n", *command) } - end - - def parse_command(command) - case command - when '--version', '-v' - 'version' - when '--help', '-h' - 'help' - else - command - end - end - - def rake_tasks - return @rake_tasks if defined?(@rake_tasks) - - load_generators - Rake::TaskManager.record_task_metadata = true - Rake.application.init('rails') - Rake.application.load_rakefile - @rake_tasks = Rake.application.tasks.select(&:comment) - end - end - end -end diff --git a/railties/lib/rails/engine/configuration.rb b/railties/lib/rails/engine/configuration.rb index 294d07446f..0c40173c38 100644 --- a/railties/lib/rails/engine/configuration.rb +++ b/railties/lib/rails/engine/configuration.rb @@ -1,4 +1,4 @@ -require 'rails/railtie/configuration' +require "rails/railtie/configuration" module Rails class Engine @@ -7,7 +7,7 @@ module Rails attr_accessor :middleware attr_writer :eager_load_paths, :autoload_once_paths, :autoload_paths - def initialize(root=nil) + def initialize(root = nil) super() @root = root @generators = app_generators.dup diff --git a/railties/lib/rails/generators.rb b/railties/lib/rails/generators.rb index 330bd7ec5d..e1980a42ad 100644 --- a/railties/lib/rails/generators.rb +++ b/railties/lib/rails/generators.rb @@ -1,45 +1,48 @@ -activesupport_path = File.expand_path('../../../../activesupport/lib', __FILE__) +activesupport_path = File.expand_path("../../../../activesupport/lib", __FILE__) $:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path) -require 'thor/group' +require "thor/group" +require "rails/command" -require 'active_support' -require 'active_support/core_ext/object/blank' -require 'active_support/core_ext/kernel/singleton_class' -require 'active_support/core_ext/array/extract_options' -require 'active_support/core_ext/hash/deep_merge' -require 'active_support/core_ext/module/attribute_accessors' -require 'active_support/core_ext/string/inflections' +require "active_support" +require "active_support/core_ext/object/blank" +require "active_support/core_ext/kernel/singleton_class" +require "active_support/core_ext/array/extract_options" +require "active_support/core_ext/hash/deep_merge" +require "active_support/core_ext/module/attribute_accessors" +require "active_support/core_ext/string/inflections" module Rails module Generators - autoload :Actions, 'rails/generators/actions' - autoload :ActiveModel, 'rails/generators/active_model' - autoload :Base, 'rails/generators/base' - autoload :Migration, 'rails/generators/migration' - autoload :NamedBase, 'rails/generators/named_base' - autoload :ResourceHelpers, 'rails/generators/resource_helpers' - autoload :TestCase, 'rails/generators/test_case' + include Rails::Command::Behavior + + autoload :Actions, "rails/generators/actions" + autoload :ActiveModel, "rails/generators/active_model" + autoload :Base, "rails/generators/base" + autoload :Migration, "rails/generators/migration" + autoload :NamedBase, "rails/generators/named_base" + autoload :ResourceHelpers, "rails/generators/resource_helpers" + autoload :TestCase, "rails/generators/test_case" mattr_accessor :namespace DEFAULT_ALIASES = { rails: { - actions: '-a', - orm: '-o', - javascripts: '-j', - javascript_engine: '-je', - resource_controller: '-c', - scaffold_controller: '-c', - stylesheets: '-y', - stylesheet_engine: '-se', - scaffold_stylesheet: '-ss', - template_engine: '-e', - test_framework: '-t' + actions: "-a", + orm: "-o", + javascripts: "-j", + javascript_engine: "-je", + resource_controller: "-c", + scaffold_controller: "-c", + stylesheets: "-y", + stylesheet_engine: "-se", + scaffold_stylesheet: "-ss", + template_engine: "-e", + test_framework: "-t" }, test_unit: { - fixture_replacement: '-r', + fixture_replacement: "-r", } } @@ -64,335 +67,247 @@ module Rails } } - def self.configure!(config) #:nodoc: - api_only! if config.api_only - no_color! unless config.colorize_logging - aliases.deep_merge! config.aliases - options.deep_merge! config.options - fallbacks.merge! config.fallbacks - templates_path.concat config.templates - templates_path.uniq! - hide_namespaces(*config.hidden_namespaces) - end - - def self.templates_path #:nodoc: - @templates_path ||= [] - end - - def self.aliases #:nodoc: - @aliases ||= DEFAULT_ALIASES.dup - end - - def self.options #:nodoc: - @options ||= DEFAULT_OPTIONS.dup - end - - # Hold configured generators fallbacks. If a plugin developer wants a - # generator group to fallback to another group in case of missing generators, - # they can add a fallback. - # - # For example, shoulda is considered a test_framework and is an extension - # of test_unit. However, most part of shoulda generators are similar to - # test_unit ones. - # - # Shoulda then can tell generators to search for test_unit generators when - # some of them are not available by adding a fallback: - # - # Rails::Generators.fallbacks[:shoulda] = :test_unit - def self.fallbacks - @fallbacks ||= {} - end - - # Configure generators for API only applications. It basically hides - # everything that is usually browser related, such as assets and session - # migration generators, and completely disable helpers and assets - # so generators such as scaffold won't create them. - def self.api_only! - hide_namespaces "assets", "helper", "css", "js" - - options[:rails].merge!( - api: true, - assets: false, - helper: false, - template_engine: nil - ) - - if ARGV.first == 'mailer' - options[:rails].merge!(template_engine: :erb) + class << self + def configure!(config) #:nodoc: + api_only! if config.api_only + no_color! unless config.colorize_logging + aliases.deep_merge! config.aliases + options.deep_merge! config.options + fallbacks.merge! config.fallbacks + templates_path.concat config.templates + templates_path.uniq! + hide_namespaces(*config.hidden_namespaces) end - end - - # Remove the color from output. - def self.no_color! - Thor::Base.shell = Thor::Shell::Basic - end - # Track all generators subclasses. - def self.subclasses - @subclasses ||= [] - end - - # Rails finds namespaces similar to thor, it only adds one rule: - # - # Generators names must end with "_generator.rb". This is required because Rails - # looks in load paths and loads the generator just before it's going to be used. - # - # find_by_namespace :webrat, :rails, :integration - # - # Will search for the following generators: - # - # "rails:webrat", "webrat:integration", "webrat" - # - # Notice that "rails:generators:webrat" could be loaded as well, what - # Rails looks for is the first and last parts of the namespace. - def self.find_by_namespace(name, base=nil, context=nil) #:nodoc: - lookups = [] - lookups << "#{base}:#{name}" if base - lookups << "#{name}:#{context}" if context - - unless base || context - unless name.to_s.include?(?:) - lookups << "#{name}:#{name}" - lookups << "rails:#{name}" - end - lookups << "#{name}" + def templates_path #:nodoc: + @templates_path ||= [] end - lookup(lookups) + def aliases #:nodoc: + @aliases ||= DEFAULT_ALIASES.dup + end - namespaces = Hash[subclasses.map { |klass| [klass.namespace, klass] }] + def options #:nodoc: + @options ||= DEFAULT_OPTIONS.dup + end - lookups.each do |namespace| - klass = namespaces[namespace] - return klass if klass + # Hold configured generators fallbacks. If a plugin developer wants a + # generator group to fallback to another group in case of missing generators, + # they can add a fallback. + # + # For example, shoulda is considered a test_framework and is an extension + # of test_unit. However, most part of shoulda generators are similar to + # test_unit ones. + # + # Shoulda then can tell generators to search for test_unit generators when + # some of them are not available by adding a fallback: + # + # Rails::Generators.fallbacks[:shoulda] = :test_unit + def fallbacks + @fallbacks ||= {} end - invoke_fallbacks_for(name, base) || invoke_fallbacks_for(context, name) - end + # Configure generators for API only applications. It basically hides + # everything that is usually browser related, such as assets and session + # migration generators, and completely disable helpers and assets + # so generators such as scaffold won't create them. + def api_only! + hide_namespaces "assets", "helper", "css", "js" + + options[:rails].merge!( + api: true, + assets: false, + helper: false, + template_engine: nil + ) + + if ARGV.first == "mailer" + options[:rails].merge!(template_engine: :erb) + end + end - # Receives a namespace, arguments and the behavior to invoke the generator. - # It's used as the default entry point for generate, destroy and update - # commands. - def self.invoke(namespace, args=ARGV, config={}) - names = namespace.to_s.split(':') - if klass = find_by_namespace(names.pop, names.any? && names.join(':')) - args << "--help" if args.empty? && klass.arguments.any?(&:required?) - klass.start(args, config) - else - options = sorted_groups.flat_map(&:last) - suggestions = options.sort_by {|suggested| levenshtein_distance(namespace.to_s, suggested) }.first(3) - msg = "Could not find generator '#{namespace}'. " - msg << "Maybe you meant #{ suggestions.map {|s| "'#{s}'"}.to_sentence(last_word_connector: " or ", locale: :en) }\n" - msg << "Run `rails generate --help` for more options." - puts msg + # Remove the color from output. + def no_color! + Thor::Base.shell = Thor::Shell::Basic end - end - # Returns an array of generator namespaces that are hidden. - # Generator namespaces may be hidden for a variety of reasons. - # Some are aliased such as "rails:migration" and can be - # invoked with the shorter "migration", others are private to other generators - # such as "css:scaffold". - def self.hidden_namespaces - @hidden_namespaces ||= begin - orm = options[:rails][:orm] - test = options[:rails][:test_framework] - template = options[:rails][:template_engine] - css = options[:rails][:stylesheet_engine] - - [ - "rails", - "resource_route", - "#{orm}:migration", - "#{orm}:model", - "#{test}:controller", - "#{test}:helper", - "#{test}:integration", - "#{test}:mailer", - "#{test}:model", - "#{test}:scaffold", - "#{test}:view", - "#{test}:job", - "#{template}:controller", - "#{template}:scaffold", - "#{template}:mailer", - "#{css}:scaffold", - "#{css}:assets", - "css:assets", - "css:scaffold" - ] + # Returns an array of generator namespaces that are hidden. + # Generator namespaces may be hidden for a variety of reasons. + # Some are aliased such as "rails:migration" and can be + # invoked with the shorter "migration", others are private to other generators + # such as "css:scaffold". + def hidden_namespaces + @hidden_namespaces ||= begin + orm = options[:rails][:orm] + test = options[:rails][:test_framework] + template = options[:rails][:template_engine] + css = options[:rails][:stylesheet_engine] + + [ + "rails", + "resource_route", + "#{orm}:migration", + "#{orm}:model", + "#{test}:controller", + "#{test}:helper", + "#{test}:integration", + "#{test}:mailer", + "#{test}:model", + "#{test}:scaffold", + "#{test}:view", + "#{test}:job", + "#{template}:controller", + "#{template}:scaffold", + "#{template}:mailer", + "#{css}:scaffold", + "#{css}:assets", + "css:assets", + "css:scaffold" + ] + end end - end - class << self def hide_namespaces(*namespaces) hidden_namespaces.concat(namespaces) end alias hide_namespace hide_namespaces - end - # Show help message with available generators. - def self.help(command = 'generate') - puts "Usage: rails #{command} GENERATOR [args] [options]" - puts - puts "General options:" - puts " -h, [--help] # Print generator's options and usage" - puts " -p, [--pretend] # Run but do not make any changes" - puts " -f, [--force] # Overwrite files that already exist" - puts " -s, [--skip] # Skip files that already exist" - puts " -q, [--quiet] # Suppress status output" - puts - puts "Please choose a generator below." - puts - - print_generators - end + # Show help message with available generators. + def help(command = "generate") + puts "Usage: rails #{command} GENERATOR [args] [options]" + puts + puts "General options:" + puts " -h, [--help] # Print generator's options and usage" + puts " -p, [--pretend] # Run but do not make any changes" + puts " -f, [--force] # Overwrite files that already exist" + puts " -s, [--skip] # Skip files that already exist" + puts " -q, [--quiet] # Suppress status output" + puts + puts "Please choose a generator below." + puts - def self.public_namespaces - lookup! - subclasses.map(&:namespace) - end + print_generators + end - def self.print_generators - sorted_groups.each { |b, n| print_list(b, n) } - end + def public_namespaces + lookup! + subclasses.map(&:namespace) + end - def self.sorted_groups - namespaces = public_namespaces - namespaces.sort! - groups = Hash.new { |h,k| h[k] = [] } - namespaces.each do |namespace| - base = namespace.split(':').first - groups[base] << namespace + def print_generators + sorted_groups.each { |b, n| print_list(b, n) } end - rails = groups.delete("rails") - rails.map! { |n| n.sub(/^rails:/, '') } - rails.delete("app") - rails.delete("plugin") - hidden_namespaces.each { |n| groups.delete(n.to_s) } + def sorted_groups + namespaces = public_namespaces + namespaces.sort! - [["rails", rails]] + groups.sort.to_a - end + groups = Hash.new { |h, k| h[k] = [] } + namespaces.each do |namespace| + base = namespace.split(":").first + groups[base] << namespace + end - protected - - # This code is based directly on the Text gem implementation - # Returns a value representing the "cost" of transforming str1 into str2 - def self.levenshtein_distance str1, str2 - s = str1 - t = str2 - n = s.length - m = t.length - - return m if (0 == n) - return n if (0 == m) - - d = (0..m).to_a - x = nil - - # avoid duplicating an enumerable object in the loop - str2_codepoint_enumerable = str2.each_codepoint - - str1.each_codepoint.with_index do |char1, i| - e = i+1 - - str2_codepoint_enumerable.with_index do |char2, j| - cost = (char1 == char2) ? 0 : 1 - x = [ - d[j+1] + 1, # insertion - e + 1, # deletion - d[j] + cost # substitution - ].min - d[j] = e - e = x - end + rails = groups.delete("rails") + rails.map! { |n| n.sub(/^rails:/, "") } + rails.delete("app") + rails.delete("plugin") - d[m] = x - end + hidden_namespaces.each { |n| groups.delete(n.to_s) } - x + [[ "rails", rails ]] + groups.sort.to_a end - # Prints a list of generators. - def self.print_list(base, namespaces) #:nodoc: - namespaces = namespaces.reject do |n| - hidden_namespaces.include?(n) + # Rails finds namespaces similar to thor, it only adds one rule: + # + # Generators names must end with "_generator.rb". This is required because Rails + # looks in load paths and loads the generator just before it's going to be used. + # + # find_by_namespace :webrat, :rails, :integration + # + # Will search for the following generators: + # + # "rails:webrat", "webrat:integration", "webrat" + # + # Notice that "rails:generators:webrat" could be loaded as well, what + # Rails looks for is the first and last parts of the namespace. + def find_by_namespace(name, base = nil, context = nil) #:nodoc: + lookups = [] + lookups << "#{base}:#{name}" if base + lookups << "#{name}:#{context}" if context + + unless base || context + unless name.to_s.include?(?:) + lookups << "#{name}:#{name}" + lookups << "rails:#{name}" + end + lookups << "#{name}" end - return if namespaces.empty? - puts "#{base.camelize}:" + lookup(lookups) - namespaces.each do |namespace| - puts(" #{namespace}") + namespaces = Hash[subclasses.map { |klass| [klass.namespace, klass] }] + lookups.each do |namespace| + + klass = namespaces[namespace] + return klass if klass end - puts + invoke_fallbacks_for(name, base) || invoke_fallbacks_for(context, name) end - # Try fallbacks for the given base. - def self.invoke_fallbacks_for(name, base) #:nodoc: - return nil unless base && fallbacks[base.to_sym] - invoked_fallbacks = [] + # Receives a namespace, arguments and the behavior to invoke the generator. + # It's used as the default entry point for generate, destroy and update + # commands. + def invoke(namespace, args = ARGV, config = {}) + names = namespace.to_s.split(":") + if klass = find_by_namespace(names.pop, names.any? && names.join(":")) + args << "--help" if args.empty? && klass.arguments.any?(&:required?) + klass.start(args, config) + else + options = sorted_groups.flat_map(&:last) + suggestions = options.sort_by { |suggested| levenshtein_distance(namespace.to_s, suggested) }.first(3) + msg = "Could not find generator '#{namespace}'. " + msg << "Maybe you meant #{ suggestions.map { |s| "'#{s}'" }.to_sentence(last_word_connector: " or ", locale: :en) }\n" + msg << "Run `rails generate --help` for more options." + puts msg + end + end - Array(fallbacks[base.to_sym]).each do |fallback| - next if invoked_fallbacks.include?(fallback) - invoked_fallbacks << fallback + private - klass = find_by_namespace(name, fallback) - return klass if klass + def print_list(base, namespaces) # :doc: + namespaces = namespaces.reject { |n| hidden_namespaces.include?(n) } + super end - nil - end + # Try fallbacks for the given base. + def invoke_fallbacks_for(name, base) + return nil unless base && fallbacks[base.to_sym] + invoked_fallbacks = [] + + Array(fallbacks[base.to_sym]).each do |fallback| + next if invoked_fallbacks.include?(fallback) + invoked_fallbacks << fallback - # Receives namespaces in an array and tries to find matching generators - # in the load path. - def self.lookup(namespaces) #:nodoc: - paths = namespaces_to_paths(namespaces) - - paths.each do |raw_path| - ["rails/generators", "generators"].each do |base| - path = "#{base}/#{raw_path}_generator" - - begin - require path - return - rescue LoadError => e - raise unless e.message =~ /#{Regexp.escape(path)}$/ - rescue Exception => e - warn "[WARNING] Could not load generator #{path.inspect}. Error: #{e.message}.\n#{e.backtrace.join("\n")}" - end + klass = find_by_namespace(name, fallback) + return klass if klass end + + nil end - end - # This will try to load any generator in the load path to show in help. - def self.lookup! #:nodoc: - $LOAD_PATH.each do |base| - Dir[File.join(base, "{rails/generators,generators}", "**", "*_generator.rb")].each do |path| - begin - path = path.sub("#{base}/", "") - require path - rescue Exception - # No problem - end - end + def command_type # :doc: + @command_type ||= "generator" end - end - # Convert namespaces to paths by replacing ":" for "/" and adding - # an extra lookup. For example, "rails:model" should be searched - # in both: "rails/model/model_generator" and "rails/model_generator". - def self.namespaces_to_paths(namespaces) #:nodoc: - paths = [] - namespaces.each do |namespace| - pieces = namespace.split(":") - paths << pieces.dup.push(pieces.last).join("/") - paths << pieces.join("/") + def lookup_paths # :doc: + @lookup_paths ||= %w( rails/generators generators ) end - paths.uniq! - paths - end + + def file_lookup_paths # :doc: + @file_lookup_paths ||= [ "{#{lookup_paths.join(',')}}", "**", "*_generator.rb" ] + end + end end end diff --git a/railties/lib/rails/generators/actions.rb b/railties/lib/rails/generators/actions.rb index c947c062fa..d058d82cea 100644 --- a/railties/lib/rails/generators/actions.rb +++ b/railties/lib/rails/generators/actions.rb @@ -68,7 +68,7 @@ module Rails # add_source "http://gems.github.com/" do # gem "rspec-rails" # end - def add_source(source, options={}, &block) + def add_source(source, options = {}, &block) log :source, source in_root do @@ -96,14 +96,14 @@ module Rails # environment(nil, env: "development") do # "config.action_controller.asset_host = 'localhost:3000'" # end - def environment(data=nil, options={}) + def environment(data = nil, options = {}) sentinel = /class [a-z_:]+ < Rails::Application/i env_file_sentinel = /Rails\.application\.configure do/ data = yield if !data && block_given? in_root do if options[:env].nil? - inject_into_file 'config/application.rb', "\n #{data}", after: sentinel, verbose: false + inject_into_file "config/application.rb", "\n #{data}", after: sentinel, verbose: false else Array(options[:env]).each do |env| inject_into_file "config/environments/#{env}.rb", "\n #{data}", after: env_file_sentinel, verbose: false @@ -118,7 +118,7 @@ module Rails # git :init # git add: "this.file that.rb" # git add: "onefile.rb", rm: "badfile.cxx" - def git(commands={}) + def git(commands = {}) if commands.is_a?(Symbol) run "git #{commands}" else @@ -137,7 +137,7 @@ module Rails # end # # vendor("foreign.rb", "# Foreign code is fun") - def vendor(filename, data=nil, &block) + def vendor(filename, data = nil, &block) log :vendor, filename create_file("vendor/#{filename}", data, verbose: false, &block) end @@ -150,7 +150,7 @@ module Rails # end # # lib("foreign.rb", "# Foreign code is fun") - def lib(filename, data=nil, &block) + def lib(filename, data = nil, &block) log :lib, filename create_file("lib/#{filename}", data, verbose: false, &block) end @@ -170,7 +170,7 @@ module Rails # end # # rakefile('seed.rake', 'puts "Planting seeds"') - def rakefile(filename, data=nil, &block) + def rakefile(filename, data = nil, &block) log :rakefile, filename create_file("lib/tasks/#{filename}", data, verbose: false, &block) end @@ -188,7 +188,7 @@ module Rails # end # # initializer("api.rb", "API_KEY = '123456'") - def initializer(filename, data=nil, &block) + def initializer(filename, data = nil, &block) log :initializer, filename create_file("config/initializers/#{filename}", data, verbose: false, &block) end @@ -210,7 +210,7 @@ module Rails # rake("db:migrate") # rake("db:migrate", env: "production") # rake("gems:install", sudo: true) - def rake(command, options={}) + def rake(command, options = {}) execute_command :rake, command, options end @@ -219,7 +219,7 @@ module Rails # rails("db:migrate") # rails("db:migrate", env: "production") # rails("gems:install", sudo: true) - def rails_command(command, options={}) + def rails_command(command, options = {}) execute_command :rails, command, options end @@ -239,7 +239,7 @@ module Rails sentinel = /\.routes\.draw do\s*\n/m in_root do - inject_into_file 'config/routes.rb', " #{routing_code}\n", { after: sentinel, verbose: false, force: false } + inject_into_file "config/routes.rb", " #{routing_code}\n", after: sentinel, verbose: false, force: false end end @@ -260,12 +260,12 @@ module Rails @after_bundle_callbacks << block end - protected + private # Define log for backwards compatibility. If just one argument is sent, # invoke say, otherwise invoke say_status. Differently from say and # similarly to say_status, this method respects the quiet? option given. - def log(*args) + def log(*args) # :doc: if args.size == 1 say args.first.to_s unless options.quiet? else @@ -274,19 +274,18 @@ module Rails end end - # Runs the supplied command using either "rake ..." or "rails ..." # based on the executor parameter provided. - def execute_command(executor, command, options={}) + def execute_command(executor, command, options = {}) # :doc: log executor, command - env = options[:env] || ENV["RAILS_ENV"] || 'development' - sudo = options[:sudo] && RbConfig::CONFIG['host_os'] !~ /mswin|mingw/ ? 'sudo ' : '' + env = options[:env] || ENV["RAILS_ENV"] || "development" + sudo = options[:sudo] && !Gem.win_platform? ? "sudo " : "" in_root { run("#{sudo}#{extify(executor)} #{command} RAILS_ENV=#{env}", verbose: false) } end # Add an extension to the given name based on the platform. - def extify(name) - if RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ + def extify(name) # :doc: + if Gem.win_platform? "#{name}.bat" else name @@ -295,7 +294,7 @@ module Rails # Surround string with single quotes if there is no quotes. # Otherwise fall back to double quotes - def quote(value) + def quote(value) # :doc: return value.inspect unless value.is_a? String if value.include?("'") diff --git a/railties/lib/rails/generators/actions/create_migration.rb b/railties/lib/rails/generators/actions/create_migration.rb index 6c5b55466d..f677e545e5 100644 --- a/railties/lib/rails/generators/actions/create_migration.rb +++ b/railties/lib/rails/generators/actions/create_migration.rb @@ -1,11 +1,10 @@ -require 'fileutils' -require 'thor/actions' +require "fileutils" +require "thor/actions" module Rails module Generators module Actions class CreateMigration < Thor::Actions::CreateFile #:nodoc: - def migration_dir File.dirname(@destination) end @@ -38,32 +37,32 @@ module Rails end alias :exists? :existing_migration - protected + private - def on_conflict_behavior - options = base.options.merge(config) - if identical? - say_status :identical, :blue, relative_existing_migration - elsif options[:force] - say_status :remove, :green, relative_existing_migration - say_status :create, :green - unless pretend? - ::FileUtils.rm_rf(existing_migration) - yield + def on_conflict_behavior # :doc: + options = base.options.merge(config) + if identical? + say_status :identical, :blue, relative_existing_migration + elsif options[:force] + say_status :remove, :green, relative_existing_migration + say_status :create, :green + unless pretend? + ::FileUtils.rm_rf(existing_migration) + yield + end + elsif options[:skip] + say_status :skip, :yellow + else + say_status :conflict, :red + raise Error, "Another migration is already named #{migration_file_name}: " + + "#{existing_migration}. Use --force to replace this migration " + + "or --skip to ignore conflicted file." end - elsif options[:skip] - say_status :skip, :yellow - else - say_status :conflict, :red - raise Error, "Another migration is already named #{migration_file_name}: " + - "#{existing_migration}. Use --force to replace this migration " + - "or --skip to ignore conflicted file." end - end - def say_status(status, color, message = relative_destination) - base.shell.say_status(status, message, color) if config[:verbose] - end + def say_status(status, color, message = relative_destination) # :doc: + base.shell.say_status(status, message, color) if config[:verbose] + end end end end diff --git a/railties/lib/rails/generators/active_model.rb b/railties/lib/rails/generators/active_model.rb index 6183944bb0..2679d06fe4 100644 --- a/railties/lib/rails/generators/active_model.rb +++ b/railties/lib/rails/generators/active_model.rb @@ -39,13 +39,13 @@ module Rails # GET edit # PATCH/PUT update # DELETE destroy - def self.find(klass, params=nil) + def self.find(klass, params = nil) "#{klass}.find(#{params})" end # GET new # POST create - def self.build(klass, params=nil) + def self.build(klass, params = nil) if params "#{klass}.new(#{params})" else @@ -59,7 +59,7 @@ module Rails end # PATCH/PUT update - def update(params=nil) + def update(params = nil) "#{name}.update(#{params})" end diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb index f0a3289563..ea88afe9f4 100644 --- a/railties/lib/rails/generators/app_base.rb +++ b/railties/lib/rails/generators/app_base.rb @@ -1,16 +1,16 @@ -require 'fileutils' -require 'digest/md5' -require 'active_support/core_ext/string/strip' -require 'rails/version' unless defined?(Rails::VERSION) -require 'open-uri' -require 'uri' -require 'rails/generators' -require 'active_support/core_ext/array/extract_options' +require "fileutils" +require "digest/md5" +require "active_support/core_ext/string/strip" +require "rails/version" unless defined?(Rails::VERSION) +require "open-uri" +require "uri" +require "rails/generators" +require "active_support/core_ext/array/extract_options" module Rails module Generators class AppBase < Base # :nodoc: - DATABASES = %w( mysql oracle postgresql sqlite3 frontbase ibm_db sqlserver ) + DATABASES = %w( mysql postgresql sqlite3 oracle frontbase ibm_db sqlserver ) JDBC_DATABASES = %w( jdbcmysql jdbcsqlite3 jdbcpostgresql jdbc ) DATABASES.concat(JDBC_DATABASES) @@ -24,42 +24,45 @@ module Rails end def self.add_shared_options_for(name) - class_option :template, type: :string, aliases: '-m', + class_option :template, type: :string, aliases: "-m", desc: "Path to some #{name} template (can be a filesystem path or URL)" - class_option :database, type: :string, aliases: '-d', default: 'sqlite3', + class_option :database, type: :string, aliases: "-d", default: "sqlite3", desc: "Preconfigure for selected database (options: #{DATABASES.join('/')})" - class_option :javascript, type: :string, aliases: '-j', default: 'jquery', - desc: 'Preconfigure for selected JavaScript library' + class_option :javascript, type: :string, aliases: "-j", + desc: "Preconfigure for selected JavaScript library" + + class_option :webpack, type: :string, default: nil, + desc: "Preconfigure for app-like JavaScript with Webpack" + + class_option :skip_yarn, type: :boolean, default: false, + desc: "Don't use Yarn for managing JavaScript dependencies" class_option :skip_gemfile, type: :boolean, default: false, desc: "Don't create a Gemfile" - class_option :skip_bundle, type: :boolean, aliases: '-B', default: false, - desc: "Don't run bundle install" - - class_option :skip_git, type: :boolean, aliases: '-G', default: false, - desc: 'Skip .gitignore file' + class_option :skip_git, type: :boolean, aliases: "-G", default: false, + desc: "Skip .gitignore file" class_option :skip_keeps, type: :boolean, default: false, - desc: 'Skip source control .keep files' + desc: "Skip source control .keep files" class_option :skip_action_mailer, type: :boolean, aliases: "-M", default: false, desc: "Skip Action Mailer files" - class_option :skip_active_record, type: :boolean, aliases: '-O', default: false, - desc: 'Skip Active Record files' + class_option :skip_active_record, type: :boolean, aliases: "-O", default: false, + desc: "Skip Active Record files" - class_option :skip_puma, type: :boolean, aliases: '-P', default: false, - desc: 'Skip Puma related files' + class_option :skip_puma, type: :boolean, aliases: "-P", default: false, + desc: "Skip Puma related files" - class_option :skip_action_cable, type: :boolean, aliases: '-C', default: false, - desc: 'Skip Action Cable files' + class_option :skip_action_cable, type: :boolean, aliases: "-C", default: false, + desc: "Skip Action Cable files" - class_option :skip_sprockets, type: :boolean, aliases: '-S', default: false, - desc: 'Skip Sprockets files' + class_option :skip_sprockets, type: :boolean, aliases: "-S", default: false, + desc: "Skip Sprockets files" class_option :skip_spring, type: :boolean, default: false, desc: "Don't install Spring application preloader" @@ -67,14 +70,17 @@ module Rails class_option :skip_listen, type: :boolean, default: false, desc: "Don't generate configuration that depends on the listen gem" - class_option :skip_javascript, type: :boolean, aliases: '-J', default: false, - desc: 'Skip JavaScript files' + class_option :skip_coffee, type: :boolean, default: false, + desc: "Don't use CoffeeScript" + + class_option :skip_javascript, type: :boolean, aliases: "-J", default: false, + desc: "Skip JavaScript files" class_option :skip_turbolinks, type: :boolean, default: false, - desc: 'Skip turbolinks gem' + desc: "Skip turbolinks gem" - class_option :skip_test, type: :boolean, aliases: '-T', default: false, - desc: 'Skip test files' + class_option :skip_test, type: :boolean, aliases: "-T", default: false, + desc: "Skip test files" class_option :dev, type: :boolean, default: false, desc: "Setup the #{name} with Gemfile pointing to your Rails checkout" @@ -86,10 +92,10 @@ module Rails desc: "Path to file containing extra configuration options for rails command" class_option :no_rc, type: :boolean, default: false, - desc: 'Skip loading of extra configuration options from .railsrc file' + desc: "Skip loading of extra configuration options from .railsrc file" - class_option :help, type: :boolean, aliases: '-h', group: :rails, - desc: 'Show this help message and quit' + class_option :help, type: :boolean, aliases: "-h", group: :rails, + desc: "Show this help message and quit" end def initialize(*args) @@ -99,9 +105,9 @@ module Rails convert_database_option_for_jruby end - protected + private - def gemfile_entry(name, *args) + def gemfile_entry(name, *args) # :doc: options = args.extract_options! version = args.first github = options[:github] @@ -117,11 +123,12 @@ module Rails self end - def gemfile_entries + def gemfile_entries # :doc: [rails_gemfile_entry, database_gemfile_entry, webserver_gemfile_entry, assets_gemfile_entry, + webpacker_gemfile_entry, javascript_gemfile_entry, jbuilder_gemfile_entry, psych_gemfile_entry, @@ -129,13 +136,13 @@ module Rails @extra_entries].flatten.find_all(&@gem_filter) end - def add_gem_entry_filter + def add_gem_entry_filter # :doc: @gem_filter = lambda { |next_filter, entry| yield(entry) && next_filter.call(entry) }.curry[@gem_filter] end - def builder + def builder # :doc: @builder ||= begin builder_class = get_builder_class builder_class.include(ActionMethods) @@ -143,62 +150,63 @@ module Rails end end - def build(meth, *args) + def build(meth, *args) # :doc: builder.send(meth, *args) if builder.respond_to?(meth) end - def create_root + def create_root # :doc: valid_const? - empty_directory '.' + empty_directory "." FileUtils.cd(destination_root) unless options[:pretend] end - def apply_rails_template + def apply_rails_template # :doc: apply rails_template if rails_template rescue Thor::Error, LoadError, Errno::ENOENT => e raise Error, "The template [#{rails_template}] could not be loaded. Error: #{e}" end - def set_default_accessors! + def set_default_accessors! # :doc: self.destination_root = File.expand_path(app_path, destination_root) - self.rails_template = case options[:template] + self.rails_template = \ + case options[:template] when /^https?:\/\// options[:template] when String File.expand_path(options[:template], Dir.pwd) else options[:template] - end + end end - def database_gemfile_entry + def database_gemfile_entry # :doc: return [] if options[:skip_active_record] gem_name, gem_version = gem_for_database GemfileEntry.version gem_name, gem_version, "Use #{options[:database]} as the database for Active Record" end - def webserver_gemfile_entry + def webserver_gemfile_entry # :doc: return [] if options[:skip_puma] - comment = 'Use Puma as the app server' - GemfileEntry.new('puma', '~> 3.0', comment) + comment = "Use Puma as the app server" + GemfileEntry.new("puma", "~> 3.0", comment) end - def include_all_railties? + def include_all_railties? # :doc: options.values_at(:skip_active_record, :skip_action_mailer, :skip_test, :skip_sprockets, :skip_action_cable).none? end - def comment_if(value) - options[value] ? '# ' : '' + def comment_if(value) # :doc: + options[value] ? "# " : "" end - def keeps? + def keeps? # :doc: !options[:skip_keeps] end - def sqlite3? - !options[:skip_active_record] && options[:database] == 'sqlite3' + def sqlite3? # :doc: + !options[:skip_active_record] && options[:database] == "sqlite3" end class GemfileEntry < Struct.new(:name, :version, :comment, :options, :commented_out) @@ -235,17 +243,18 @@ module Rails def rails_gemfile_entry dev_edge_common = [ + GemfileEntry.github("arel", "rails/arel") ] if options.dev? [ - GemfileEntry.path('rails', Rails::Generators::RAILS_DEV_PATH) + GemfileEntry.path("rails", Rails::Generators::RAILS_DEV_PATH) ] + dev_edge_common elsif options.edge? [ - GemfileEntry.github('rails', 'rails/rails') + GemfileEntry.github("rails", "rails/rails") ] + dev_edge_common else - [GemfileEntry.version('rails', + [GemfileEntry.version("rails", rails_version_specifier, "Bundle edge Rails instead: gem 'rails', github: 'rails/rails'")] end @@ -266,12 +275,12 @@ module Rails end def gem_for_database - # %w( mysql oracle postgresql sqlite3 frontbase ibm_db sqlserver jdbcmysql jdbcsqlite3 jdbcpostgresql ) + # %w( mysql postgresql sqlite3 oracle frontbase ibm_db sqlserver jdbcmysql jdbcsqlite3 jdbcpostgresql ) case options[:database] - when "oracle" then ["ruby-oci8", nil] + when "mysql" then ["mysql2", [">= 0.3.18", "< 0.5"]] when "postgresql" then ["pg", ["~> 0.18"]] + when "oracle" then ["ruby-oci8", nil] when "frontbase" then ["ruby-frontbase", nil] - when "mysql" then ["mysql2", [">= 0.3.18", "< 0.5"]] when "sqlserver" then ["activerecord-sqlserver-adapter", nil] when "jdbcmysql" then ["activerecord-jdbcmysql-adapter", nil] when "jdbcsqlite3" then ["activerecord-jdbcsqlite3-adapter", nil] @@ -284,9 +293,9 @@ module Rails def convert_database_option_for_jruby if defined?(JRUBY_VERSION) case options[:database] - when "oracle" then options[:database].replace "jdbc" when "postgresql" then options[:database].replace "jdbcpostgresql" when "mysql" then options[:database].replace "jdbcmysql" + when "oracle" then options[:database].replace "jdbc" when "sqlite3" then options[:database].replace "jdbcsqlite3" end end @@ -296,35 +305,48 @@ module Rails return [] if options[:skip_sprockets] gems = [] - gems << GemfileEntry.github('sass-rails', 'rails/sass-rails', nil, - 'Use SCSS for stylesheets') + gems << GemfileEntry.github("sass-rails", "rails/sass-rails", nil, + "Use SCSS for stylesheets") - gems << GemfileEntry.version('uglifier', - '>= 1.3.0', - 'Use Uglifier as compressor for JavaScript assets') + if !options[:skip_javascript] + gems << GemfileEntry.version("uglifier", + ">= 1.3.0", + "Use Uglifier as compressor for JavaScript assets") + end gems end + def webpacker_gemfile_entry + return [] unless options[:webpack] + + comment = "Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker" + GemfileEntry.github "webpacker", "rails/webpacker", nil, comment + end + def jbuilder_gemfile_entry - comment = 'Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder' - GemfileEntry.new 'jbuilder', '~> 2.5', comment, {}, options[:api] + comment = "Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder" + GemfileEntry.new "jbuilder", "~> 2.5", comment, {}, options[:api] end def coffee_gemfile_entry - GemfileEntry.github 'coffee-rails', 'rails/coffee-rails', nil, 'Use CoffeeScript for .coffee assets and views' + GemfileEntry.version "coffee-rails", "~> 4.2", "Use CoffeeScript for .coffee assets and views" end def javascript_gemfile_entry if options[:skip_javascript] || options[:skip_sprockets] [] else - gems = [coffee_gemfile_entry, javascript_runtime_gemfile_entry] - gems << GemfileEntry.version("#{options[:javascript]}-rails", nil, - "Use #{options[:javascript]} as the JavaScript library") + gems = [javascript_runtime_gemfile_entry] + gems << coffee_gemfile_entry unless options[:skip_coffee] + + if options[:javascript] + gems << GemfileEntry.version("#{options[:javascript]}-rails", nil, + "Use #{options[:javascript]} as the JavaScript library") + end unless options[:skip_turbolinks] - gems << GemfileEntry.version("turbolinks", "~> 5.x", + gems << GemfileEntry.version("turbolinks", "~> 5", "Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks") end @@ -333,27 +355,27 @@ module Rails end def javascript_runtime_gemfile_entry - comment = 'See https://github.com/rails/execjs#readme for more supported runtimes' + comment = "See https://github.com/rails/execjs#readme for more supported runtimes" if defined?(JRUBY_VERSION) - GemfileEntry.version 'therubyrhino', nil, comment + GemfileEntry.version "therubyrhino", nil, comment else - GemfileEntry.new 'therubyracer', nil, comment, { platforms: :ruby }, true + GemfileEntry.new "therubyracer", nil, comment, { platforms: :ruby }, true end end def psych_gemfile_entry return [] unless defined?(Rubinius) - comment = 'Use Psych as the YAML engine, instead of Syck, so serialized ' \ - 'data can be read safely from different rubies (see http://git.io/uuLVag)' - GemfileEntry.new('psych', '~> 2.0', comment, platforms: :rbx) + comment = "Use Psych as the YAML engine, instead of Syck, so serialized " \ + "data can be read safely from different rubies (see http://git.io/uuLVag)" + GemfileEntry.new("psych", "~> 2.0", comment, platforms: :rbx) end def cable_gemfile_entry return [] if options[:skip_action_cable] - comment = 'Use Redis adapter to run Action Cable in production' + comment = "Use Redis adapter to run Action Cable in production" gems = [] - gems << GemfileEntry.new("redis", '~> 3.0', comment, {}, true) + gems << GemfileEntry.new("redis", "~> 3.0", comment, {}, true) gems end @@ -368,9 +390,9 @@ module Rails # We unset temporary bundler variables to load proper bundler and Gemfile. # # Thanks to James Tucker for the Gem tricks involved in this call. - _bundle_command = Gem.bin_path('bundler', 'bundle') + _bundle_command = Gem.bin_path("bundler", "bundle") - require 'bundler' + require "bundler" Bundler.with_clean_env do full_command = %Q["#{Gem.ruby}" "#{_bundle_command}" #{command}] if options[:quiet] @@ -394,11 +416,18 @@ module Rails end def os_supports_listen_out_of_the_box? - RbConfig::CONFIG['host_os'] =~ /darwin|linux/ + RbConfig::CONFIG["host_os"] =~ /darwin|linux/ end def run_bundle - bundle_command('install') if bundle_install? + bundle_command("install") if bundle_install? + end + + def run_webpack + if !(webpack = options[:webpack]).nil? + rails_command "webpacker:install" + rails_command "webpacker:install:#{webpack}" unless webpack == "webpack" + end end def generate_spring_binstubs diff --git a/railties/lib/rails/generators/base.rb b/railties/lib/rails/generators/base.rb index c72ec400a0..cc6ae3860f 100644 --- a/railties/lib/rails/generators/base.rb +++ b/railties/lib/rails/generators/base.rb @@ -1,5 +1,5 @@ begin - require 'thor/group' + require "thor/group" rescue LoadError puts "Thor is not available.\nIf you ran this command from a git checkout " \ "of Rails, please make sure thor is installed,\nand run this command " \ @@ -20,14 +20,14 @@ module Rails strict_args_position! # Returns the source root for this generator using default_source_root as default. - def self.source_root(path=nil) + def self.source_root(path = nil) @_source_root = path if path @_source_root ||= default_source_root end # Tries to get the description from a USAGE file one folder above the source # root otherwise uses a default description. - def self.desc(description=nil) + def self.desc(description = nil) return super if description @desc ||= if usage_path @@ -40,15 +40,15 @@ module Rails # Convenience method to get the namespace from the class name. It's the # same as Thor default except that the Generator at the end of the class # is removed. - def self.namespace(name=nil) + def self.namespace(name = nil) return super if name - @namespace ||= super.sub(/_generator$/, '').sub(/:generators:/, ':') + @namespace ||= super.sub(/_generator$/, "").sub(/:generators:/, ":") end # Convenience method to hide this generator from the available ones when # running rails generator command. def self.hide! - Rails::Generators.hide_namespace self.namespace + Rails::Generators.hide_namespace(namespace) end # Invoke a generator based on the value supplied by the user to the @@ -168,7 +168,7 @@ module Rails names.each do |name| unless class_options.key?(name) defaults = if options[:type] == :boolean - { } + {} elsif [true, false].include?(default_value_for_option(name, options)) { banner: "" } else @@ -195,7 +195,7 @@ module Rails end # Make class option aware of Rails::Generators.options and Rails::Generators.aliases. - def self.class_option(name, options={}) #:nodoc: + def self.class_option(name, options = {}) #:nodoc: options[:desc] = "Indicates when to generate #{name.to_s.humanize.downcase}" unless options.key?(:desc) options[:aliases] = default_aliases_for_option(name, options) options[:default] = default_value_for_option(name, options) @@ -208,7 +208,7 @@ module Rails def self.default_source_root return unless base_name && generator_name return unless default_generator_root - path = File.join(default_generator_root, 'templates') + path = File.join(default_generator_root, "templates") path if File.exist?(path) end @@ -230,7 +230,7 @@ module Rails Rails::Generators.subclasses << base Rails::Generators.templates_path.each do |path| - if base.name.include?('::') + if base.name.include?("::") base.source_paths << File.join(path, base.base_name, base.generator_name) else base.source_paths << File.join(path, base.generator_name) @@ -239,11 +239,11 @@ module Rails end end - protected + private # Check whether the given class names are already taken by user # application or Ruby on Rails. - def class_collisions(*class_names) #:nodoc: + def class_collisions(*class_names) return unless behavior == :invoke class_names.flatten.each do |class_name| @@ -251,7 +251,7 @@ module Rails next if class_name.strip.empty? # Split the class from its module nesting - nesting = class_name.split('::') + nesting = class_name.split("::") last_name = nesting.pop last = extract_last_module(nesting) @@ -264,7 +264,7 @@ module Rails end # Takes in an array of nested modules and extracts the last module - def extract_last_module(nesting) + def extract_last_module(nesting) # :doc: nesting.inject(Object) do |last_module, nest| break unless last_module.const_defined?(nest, false) last_module.const_get(nest) @@ -272,14 +272,14 @@ module Rails end # Use Rails default banner. - def self.banner - "rails generate #{namespace.sub(/^rails:/,'')} #{self.arguments.map(&:usage).join(' ')} [options]".gsub(/\s+/, ' ') + def self.banner # :doc: + "rails generate #{namespace.sub(/^rails:/, '')} #{arguments.map(&:usage).join(' ')} [options]".gsub(/\s+/, " ") end # Sets the base_name taking into account the current class namespace. - def self.base_name + def self.base_name # :doc: @base_name ||= begin - if base = name.to_s.split('::').first + if base = name.to_s.split("::").first base.underscore end end @@ -287,10 +287,10 @@ module Rails # Removes the namespaces and get the generator name. For example, # Rails::Generators::ModelGenerator will return "model" as generator name. - def self.generator_name + def self.generator_name # :doc: @generator_name ||= begin - if generator = name.to_s.split('::').last - generator.sub!(/Generator$/, '') + if generator = name.to_s.split("::").last + generator.sub!(/Generator$/, "") generator.underscore end end @@ -298,21 +298,21 @@ module Rails # Returns the default value for the option name given doing a lookup in # Rails::Generators.options. - def self.default_value_for_option(name, options) + def self.default_value_for_option(name, options) # :doc: default_for_option(Rails::Generators.options, name, options, options[:default]) end # Returns default aliases for the option name given doing a lookup in # Rails::Generators.aliases. - def self.default_aliases_for_option(name, options) + def self.default_aliases_for_option(name, options) # :doc: default_for_option(Rails::Generators.aliases, name, options, options[:aliases]) end # Returns default for the option name given doing a lookup in config. - def self.default_for_option(config, name, options, default) - if generator_name and c = config[generator_name.to_sym] and c.key?(name) + def self.default_for_option(config, name, options, default) # :doc: + if generator_name && (c = config[generator_name.to_sym]) && c.key?(name) c[name] - elsif base_name and c = config[base_name.to_sym] and c.key?(name) + elsif base_name && (c = config[base_name.to_sym]) && c.key?(name) c[name] elsif config[:rails].key?(name) config[:rails][name] @@ -343,7 +343,7 @@ module Rails # Small macro to add ruby as an option to the generator with proper # default value plus an instance helper method called shebang. - def self.add_shebang_option! + def self.add_shebang_option! # :doc: class_option :ruby, type: :string, aliases: "-r", default: Thor::Util.ruby_command, desc: "Path to the Ruby binary of your choice", banner: "PATH" @@ -361,7 +361,7 @@ module Rails } end - def self.usage_path + def self.usage_path # :doc: paths = [ source_root && File.expand_path("../USAGE", source_root), default_generator_root && File.join(default_generator_root, "USAGE") @@ -369,11 +369,10 @@ module Rails paths.compact.detect { |path| File.exist? path } end - def self.default_generator_root + def self.default_generator_root # :doc: path = File.expand_path(File.join(base_name, generator_name), base_root) path if File.exist?(path) end - end end end diff --git a/railties/lib/rails/generators/css/assets/assets_generator.rb b/railties/lib/rails/generators/css/assets/assets_generator.rb index e4a305f4b3..20baf31a34 100644 --- a/railties/lib/rails/generators/css/assets/assets_generator.rb +++ b/railties/lib/rails/generators/css/assets/assets_generator.rb @@ -6,7 +6,7 @@ module Css # :nodoc: source_root File.expand_path("../templates", __FILE__) def copy_stylesheet - copy_file "stylesheet.css", File.join('app/assets/stylesheets', class_path, "#{file_name}.css") + copy_file "stylesheet.css", File.join("app/assets/stylesheets", class_path, "#{file_name}.css") end end end diff --git a/railties/lib/rails/generators/erb.rb b/railties/lib/rails/generators/erb.rb index 0755ac335c..d5e326d6ee 100644 --- a/railties/lib/rails/generators/erb.rb +++ b/railties/lib/rails/generators/erb.rb @@ -1,25 +1,25 @@ -require 'rails/generators/named_base' +require "rails/generators/named_base" module Erb # :nodoc: module Generators # :nodoc: class Base < Rails::Generators::NamedBase #:nodoc: - protected + private - def formats - [format] - end + def formats + [format] + end - def format - :html - end + def format + :html + end - def handler - :erb - end + def handler + :erb + end - def filename_with_extensions(name, format = self.format) - [name, format, handler].compact.join(".") - end + def filename_with_extensions(name, format = self.format) + [name, format, handler].compact.join(".") + end end end end diff --git a/railties/lib/rails/generators/erb/controller/controller_generator.rb b/railties/lib/rails/generators/erb/controller/controller_generator.rb index 94c1b835d1..36ecfea09b 100644 --- a/railties/lib/rails/generators/erb/controller/controller_generator.rb +++ b/railties/lib/rails/generators/erb/controller/controller_generator.rb @@ -1,4 +1,4 @@ -require 'rails/generators/erb' +require "rails/generators/erb" module Erb # :nodoc: module Generators # :nodoc: diff --git a/railties/lib/rails/generators/erb/mailer/mailer_generator.rb b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb index 97f3657070..677f8041ae 100644 --- a/railties/lib/rails/generators/erb/mailer/mailer_generator.rb +++ b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb @@ -1,4 +1,4 @@ -require 'rails/generators/erb' +require "rails/generators/erb" module Erb # :nodoc: module Generators # :nodoc: @@ -6,12 +6,12 @@ module Erb # :nodoc: argument :actions, type: :array, default: [], banner: "method method" def copy_view_files - view_base_path = File.join("app/views", class_path, file_name + '_mailer') + view_base_path = File.join("app/views", class_path, file_name + "_mailer") empty_directory view_base_path if self.behavior == :invoke formats.each do |format| - layout_path = File.join('app/views/layouts', class_path, filename_with_extensions('mailer', format)) + layout_path = File.join("app/views/layouts", class_path, filename_with_extensions("mailer", format)) template filename_with_extensions(:layout, format), layout_path end end @@ -26,15 +26,15 @@ module Erb # :nodoc: end end - protected + private - def formats - [:text, :html] - end + def formats + [:text, :html] + end - def file_name - @_file_name ||= super.gsub(/_mailer/i, '') - end + def file_name + @_file_name ||= super.gsub(/_mailer/i, "") + end end end end diff --git a/railties/lib/rails/generators/erb/scaffold/scaffold_generator.rb b/railties/lib/rails/generators/erb/scaffold/scaffold_generator.rb index c94829a0ae..0d77ef21da 100644 --- a/railties/lib/rails/generators/erb/scaffold/scaffold_generator.rb +++ b/railties/lib/rails/generators/erb/scaffold/scaffold_generator.rb @@ -1,5 +1,5 @@ -require 'rails/generators/erb' -require 'rails/generators/resource_helpers' +require "rails/generators/erb" +require "rails/generators/resource_helpers" module Erb # :nodoc: module Generators # :nodoc: @@ -21,7 +21,7 @@ module Erb # :nodoc: end end - protected + private def available_views %w(index edit show new _form) diff --git a/railties/lib/rails/generators/generated_attribute.rb b/railties/lib/rails/generators/generated_attribute.rb index 7e437e7344..baed7bf1e3 100644 --- a/railties/lib/rails/generators/generated_attribute.rb +++ b/railties/lib/rails/generators/generated_attribute.rb @@ -1,4 +1,4 @@ -require 'active_support/time' +require "active_support/time" module Rails module Generators @@ -12,7 +12,7 @@ module Rails class << self def parse(column_definition) - name, type, has_index = column_definition.split(':') + name, type, has_index = column_definition.split(":") # if user provided "name:index" instead of "name:string:index" # type should be set blank so GeneratedAttribute's constructor @@ -56,7 +56,7 @@ module Rails end end - def initialize(name, type=nil, index_type=false, attr_options={}) + def initialize(name, type = nil, index_type = false, attr_options = {}) @name = name @type = type || :string @has_index = INDEX_OPTIONS.include?(index_type) @@ -66,40 +66,40 @@ module Rails def field_type @field_type ||= case type - when :integer then :number_field - when :float, :decimal then :text_field - when :time then :time_select - when :datetime, :timestamp then :datetime_select - when :date then :date_select - when :text then :text_area - when :boolean then :check_box + when :integer then :number_field + when :float, :decimal then :text_field + when :time then :time_select + when :datetime, :timestamp then :datetime_select + when :date then :date_select + when :text then :text_area + when :boolean then :check_box else - :text_field + :text_field end end def default @default ||= case type - when :integer then 1 - when :float then 1.5 - when :decimal then "9.99" - when :datetime, :timestamp, :time then Time.now.to_s(:db) - when :date then Date.today.to_s(:db) - when :string then name == "type" ? "" : "MyString" - when :text then "MyText" - when :boolean then false - when :references, :belongs_to then nil + when :integer then 1 + when :float then 1.5 + when :decimal then "9.99" + when :datetime, :timestamp, :time then Time.now.to_s(:db) + when :date then Date.today.to_s(:db) + when :string then name == "type" ? "" : "MyString" + when :text then "MyText" + when :boolean then false + when :references, :belongs_to then nil else - "" + "" end end def plural_name - name.sub(/_id$/, '').pluralize + name.sub(/_id$/, "").pluralize end def singular_name - name.sub(/_id$/, '').singularize + name.sub(/_id$/, "").singularize end def human_name @@ -127,11 +127,11 @@ module Rails end def polymorphic? - self.attr_options[:polymorphic] + attr_options[:polymorphic] end def required? - self.attr_options[:required] + attr_options[:required] end def has_index? @@ -143,7 +143,7 @@ module Rails end def password_digest? - name == 'password' && type == :digest + name == "password" && type == :digest end def token? @@ -151,7 +151,7 @@ module Rails end def inject_options - "".tap { |s| options_for_migration.each { |k,v| s << ", #{k}: #{v.inspect}" } } + "".tap { |s| options_for_migration.each { |k, v| s << ", #{k}: #{v.inspect}" } } end def inject_index_options diff --git a/railties/lib/rails/generators/js/assets/assets_generator.rb b/railties/lib/rails/generators/js/assets/assets_generator.rb index 1e925b2cd2..64d706ec91 100644 --- a/railties/lib/rails/generators/js/assets/assets_generator.rb +++ b/railties/lib/rails/generators/js/assets/assets_generator.rb @@ -6,7 +6,7 @@ module Js # :nodoc: source_root File.expand_path("../templates", __FILE__) def copy_javascript - copy_file "javascript.js", File.join('app/assets/javascripts', class_path, "#{file_name}.js") + copy_file "javascript.js", File.join("app/assets/javascripts", class_path, "#{file_name}.js") end end end diff --git a/railties/lib/rails/generators/migration.rb b/railties/lib/rails/generators/migration.rb index 87f2e1d42b..0d63b9a5c9 100644 --- a/railties/lib/rails/generators/migration.rb +++ b/railties/lib/rails/generators/migration.rb @@ -1,5 +1,5 @@ -require 'active_support/concern' -require 'rails/generators/actions/create_migration' +require "active_support/concern" +require "rails/generators/actions/create_migration" module Rails module Generators @@ -39,7 +39,7 @@ module Rails migration_dir = File.dirname(destination) @migration_number = self.class.next_migration_number(migration_dir) - @migration_file_name = File.basename(destination, '.rb') + @migration_file_name = File.basename(destination, ".rb") @migration_class_name = @migration_file_name.camelize end @@ -52,16 +52,16 @@ module Rails # # migration_template "migration.rb", "db/migrate/add_foo_to_bar.rb" def migration_template(source, destination, config = {}) - source = File.expand_path(find_in_source_paths(source.to_s)) + source = File.expand_path(find_in_source_paths(source.to_s)) set_migration_assigns!(destination) - context = instance_eval('binding') + context = instance_eval("binding") dir, base = File.split(destination) - numbered_destination = File.join(dir, ["%migration_number%", base].join('_')) + numbered_destination = File.join(dir, ["%migration_number%", base].join("_")) create_migration numbered_destination, nil, config do - ERB.new(::File.binread(source), nil, '-', '@output_buffer').result(context) + ERB.new(::File.binread(source), nil, "-", "@output_buffer").result(context) end end end diff --git a/railties/lib/rails/generators/model_helpers.rb b/railties/lib/rails/generators/model_helpers.rb index 42c646543e..6f87a18660 100644 --- a/railties/lib/rails/generators/model_helpers.rb +++ b/railties/lib/rails/generators/model_helpers.rb @@ -1,4 +1,4 @@ -require 'rails/generators/active_model' +require "rails/generators/active_model" module Rails module Generators @@ -8,7 +8,7 @@ module Rails mattr_accessor :skip_warn def self.included(base) #:nodoc: - base.class_option :force_plural, type: :boolean, default: false, desc: 'Forces the use of the given model name' + base.class_option :force_plural, type: :boolean, default: false, desc: "Forces the use of the given model name" end def initialize(args, *_options) diff --git a/railties/lib/rails/generators/named_base.rb b/railties/lib/rails/generators/named_base.rb index ee076eb711..e3660b012a 100644 --- a/railties/lib/rails/generators/named_base.rb +++ b/railties/lib/rails/generators/named_base.rb @@ -1,6 +1,6 @@ -require 'active_support/core_ext/module/introspection' -require 'rails/generators/base' -require 'rails/generators/generated_attribute' +require "active_support/core_ext/module/introspection" +require "rails/generators/base" +require "rails/generators/generated_attribute" module Rails module Generators @@ -14,7 +14,7 @@ module Rails # Unfreeze name in case it's given as a frozen string args[0] = args[0].dup if args[0].is_a?(String) && args[0].frozen? super - assign_names!(self.name) + assign_names!(name) parse_attributes! if respond_to?(:attributes) end @@ -28,182 +28,182 @@ module Rails end def js_template(source, destination) - template(source + '.js', destination + '.js') + template(source + ".js", destination + ".js") end end + # TODO Change this to private once we've dropped Ruby 2.2 support. + # Workaround for Ruby 2.2 "private attribute?" warning. protected attr_reader :file_name + private + # FIXME: We are avoiding to use alias because a bug on thor that make # this method public and add it to the task list. - def singular_name + def singular_name # :doc: file_name end # Wrap block with namespace of current application # if namespace exists and is not skipped - def module_namespacing(&block) + def module_namespacing(&block) # :doc: content = capture(&block) content = wrap_with_namespace(content) if namespaced? concat(content) end - def indent(content, multiplier = 2) + def indent(content, multiplier = 2) # :doc: spaces = " " * multiplier - content.each_line.map {|line| line.blank? ? line : "#{spaces}#{line}" }.join + content.each_line.map { |line| line.blank? ? line : "#{spaces}#{line}" }.join end - def wrap_with_namespace(content) + def wrap_with_namespace(content) # :doc: content = indent(content).chomp "module #{namespace.name}\n#{content}\nend\n" end - def inside_template + def inside_template # :doc: @inside_template = true yield ensure @inside_template = false end - def inside_template? + def inside_template? # :doc: @inside_template end - def namespace + def namespace # :doc: Rails::Generators.namespace end - def namespaced? + def namespaced? # :doc: !options[:skip_namespace] && namespace end - def file_path - @file_path ||= (class_path + [file_name]).join('/') + def file_path # :doc: + @file_path ||= (class_path + [file_name]).join("/") end - def class_path + def class_path # :doc: inside_template? || !namespaced? ? regular_class_path : namespaced_class_path end - def regular_class_path + def regular_class_path # :doc: @class_path end - def namespaced_file_path - @namespaced_file_path ||= namespaced_class_path.join("/") - end - - def namespaced_class_path + def namespaced_class_path # :doc: @namespaced_class_path ||= [namespaced_path] + @class_path end - def namespaced_path + def namespaced_path # :doc: @namespaced_path ||= namespace.name.split("::").first.underscore end - def class_name - (class_path + [file_name]).map!(&:camelize).join('::') + def class_name # :doc: + (class_path + [file_name]).map!(&:camelize).join("::") end - def human_name + def human_name # :doc: @human_name ||= singular_name.humanize end - def plural_name + def plural_name # :doc: @plural_name ||= singular_name.pluralize end - def i18n_scope - @i18n_scope ||= file_path.tr('/', '.') + def i18n_scope # :doc: + @i18n_scope ||= file_path.tr("/", ".") end - def table_name + def table_name # :doc: @table_name ||= begin base = pluralize_table_names? ? plural_name : singular_name - (class_path + [base]).join('_') + (class_path + [base]).join("_") end end - def uncountable? + def uncountable? # :doc: singular_name == plural_name end - def index_helper + def index_helper # :doc: uncountable? ? "#{plural_table_name}_index" : plural_table_name end - def show_helper + def show_helper # :doc: "#{singular_table_name}_url(@#{singular_table_name})" end - def edit_helper + def edit_helper # :doc: "edit_#{show_helper}" end - def new_helper + def new_helper # :doc: "new_#{singular_table_name}_url" end - def singular_table_name + def singular_table_name # :doc: @singular_table_name ||= (pluralize_table_names? ? table_name.singularize : table_name) end - def plural_table_name + def plural_table_name # :doc: @plural_table_name ||= (pluralize_table_names? ? table_name : table_name.pluralize) end - def plural_file_name + def plural_file_name # :doc: @plural_file_name ||= file_name.pluralize end - def fixture_file_name + def fixture_file_name # :doc: @fixture_file_name ||= (pluralize_table_names? ? plural_file_name : file_name) end - def route_url - @route_url ||= class_path.collect {|dname| "/" + dname }.join + "/" + plural_file_name + def route_url # :doc: + @route_url ||= class_path.collect { |dname| "/" + dname }.join + "/" + plural_file_name end - def url_helper_prefix - @url_helper_prefix ||= (class_path + [file_name]).join('_') + def url_helper_prefix # :doc: + @url_helper_prefix ||= (class_path + [file_name]).join("_") end # Tries to retrieve the application name or simply return application. - def application_name + def application_name # :doc: if defined?(Rails) && Rails.application - Rails.application.class.name.split('::').first.underscore + Rails.application.class.name.split("::").first.underscore else "application" end end - def assign_names!(name) #:nodoc: - @class_path = name.include?('/') ? name.split('/') : name.split('::') + def assign_names!(name) + @class_path = name.include?("/") ? name.split("/") : name.split("::") @class_path.map!(&:underscore) @file_name = @class_path.pop end # Convert attributes array into GeneratedAttribute objects. - def parse_attributes! #:nodoc: + def parse_attributes! self.attributes = (attributes || []).map do |attr| Rails::Generators::GeneratedAttribute.parse(attr) end end - def attributes_names + def attributes_names # :doc: @attributes_names ||= attributes.each_with_object([]) do |a, names| names << a.column_name - names << 'password_confirmation' if a.password_digest? + names << "password_confirmation" if a.password_digest? names << "#{a.name}_type" if a.polymorphic? end end - def pluralize_table_names? + def pluralize_table_names? # :doc: !defined?(ActiveRecord::Base) || ActiveRecord::Base.pluralize_table_names end - def mountable_engine? + def mountable_engine? # :doc: defined?(ENGINE_ROOT) && namespaced? end @@ -217,7 +217,7 @@ module Rails # If the generator is invoked with class name Admin, it will check for # the presence of "AdminDecorator". # - def self.check_class_collision(options={}) + def self.check_class_collision(options = {}) # :doc: define_method :check_class_collision do name = if self.respond_to?(:controller_class_name) # for ScaffoldBase controller_class_name diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb index 448dce06af..8efdfdcb44 100644 --- a/railties/lib/rails/generators/rails/app/app_generator.rb +++ b/railties/lib/rails/generators/rails/app/app_generator.rb @@ -1,4 +1,4 @@ -require 'rails/generators/app_base' +require "rails/generators/app_base" module Rails module ActionMethods # :nodoc: @@ -54,13 +54,13 @@ module Rails end def app - directory 'app' + directory "app" - keep_file 'app/assets/images' - empty_directory_with_keep_file 'app/assets/javascripts/channels' unless options[:skip_action_cable] + keep_file "app/assets/images" + empty_directory_with_keep_file "app/assets/javascripts/channels" unless options[:skip_action_cable] - keep_file 'app/controllers/concerns' - keep_file 'app/models/concerns' + keep_file "app/controllers/concerns" + keep_file "app/models/concerns" end def bin @@ -89,24 +89,24 @@ module Rails end def config_when_updating - cookie_serializer_config_exist = File.exist?('config/initializers/cookies_serializer.rb') - action_cable_config_exist = File.exist?('config/cable.yml') - rack_cors_config_exist = File.exist?('config/initializers/cors.rb') + cookie_serializer_config_exist = File.exist?("config/initializers/cookies_serializer.rb") + action_cable_config_exist = File.exist?("config/cable.yml") + rack_cors_config_exist = File.exist?("config/initializers/cors.rb") config - gsub_file 'config/environments/development.rb', /^(\s+)config\.file_watcher/, '\1# config.file_watcher' + gsub_file "config/environments/development.rb", /^(\s+)config\.file_watcher/, '\1# config.file_watcher' unless cookie_serializer_config_exist - gsub_file 'config/initializers/cookies_serializer.rb', /json(?!,)/, 'marshal' + gsub_file "config/initializers/cookies_serializer.rb", /json(?!,)/, "marshal" end unless action_cable_config_exist - template 'config/cable.yml' + template "config/cable.yml" end unless rack_cors_config_exist - remove_file 'config/initializers/cors.rb' + remove_file "config/initializers/cors.rb" end end @@ -119,13 +119,13 @@ module Rails end def lib - empty_directory 'lib' - empty_directory_with_keep_file 'lib/tasks' - empty_directory_with_keep_file 'lib/assets' + empty_directory "lib" + empty_directory_with_keep_file "lib/tasks" + empty_directory_with_keep_file "lib/assets" end def log - empty_directory_with_keep_file 'log' + empty_directory_with_keep_file "log" end def public_directory @@ -133,15 +133,15 @@ module Rails end def test - empty_directory_with_keep_file 'test/fixtures' - empty_directory_with_keep_file 'test/fixtures/files' - empty_directory_with_keep_file 'test/controllers' - empty_directory_with_keep_file 'test/mailers' - empty_directory_with_keep_file 'test/models' - empty_directory_with_keep_file 'test/helpers' - empty_directory_with_keep_file 'test/integration' - - template 'test/test_helper.rb' + empty_directory_with_keep_file "test/fixtures" + empty_directory_with_keep_file "test/fixtures/files" + empty_directory_with_keep_file "test/controllers" + empty_directory_with_keep_file "test/mailers" + empty_directory_with_keep_file "test/models" + empty_directory_with_keep_file "test/helpers" + empty_directory_with_keep_file "test/integration" + + template "test/test_helper.rb" end def tmp @@ -151,19 +151,12 @@ module Rails end def vendor - vendor_javascripts - vendor_stylesheets - end + empty_directory_with_keep_file "vendor" - def vendor_javascripts - unless options[:skip_javascript] - empty_directory_with_keep_file 'vendor/assets/javascripts' + unless options[:skip_yarn] + template "package.json", "vendor/package.json" end end - - def vendor_stylesheets - empty_directory_with_keep_file 'vendor/assets/stylesheets' - end end module Generators @@ -182,6 +175,9 @@ module Rails class_option :api, type: :boolean, desc: "Preconfigure smaller stack for API only apps" + class_option :skip_bundle, type: :boolean, aliases: "-B", default: false, + desc: "Don't run bundle install" + def initialize(*args) super @@ -193,9 +189,11 @@ module Rails raise Error, "Invalid value for --database option. Supported for preconfiguration are: #{DATABASES.join(", ")}." end - # Force sprockets to be skipped when generating API only apps. + # Force sprockets and yarn to be skipped when generating API only apps. # Can't modify options hash as it's frozen by default. - self.options = options.merge(skip_sprockets: true, skip_javascript: true).freeze if options[:api] + if options[:api] + self.options = options.merge(skip_sprockets: true, skip_javascript: true, skip_yarn: true).freeze + end end public_task :set_default_accessors! @@ -205,8 +203,8 @@ module Rails build(:readme) build(:rakefile) build(:configru) - build(:gitignore) unless options[:skip_git] - build(:gemfile) unless options[:skip_gemfile] + build(:gitignore) unless options[:skip_git] + build(:gemfile) unless options[:skip_gemfile] end def create_app_files @@ -226,6 +224,11 @@ module Rails end remove_task :update_config_files + def display_upgrade_guide_info + say "\nAfter this, check Rails upgrade guide at http://guides.rubyonrails.org/upgrading_ruby_on_rails.html for more details about upgrading your app." + end + remove_task :display_upgrade_guide_info + def create_boot_file template "config/boot.rb" end @@ -236,6 +239,7 @@ module Rails end def create_db_files + return if options[:skip_active_record] build(:db) end @@ -261,112 +265,119 @@ module Rails def create_vendor_files build(:vendor) + + if options[:skip_yarn] + remove_file "vendor/package.json" + end end def delete_app_assets_if_api_option if options[:api] - remove_dir 'app/assets' - remove_dir 'lib/assets' - remove_dir 'tmp/cache/assets' - remove_dir 'vendor/assets' + remove_dir "app/assets" + remove_dir "lib/assets" + remove_dir "tmp/cache/assets" end end def delete_app_helpers_if_api_option if options[:api] - remove_dir 'app/helpers' - remove_dir 'test/helpers' + remove_dir "app/helpers" + remove_dir "test/helpers" end end def delete_application_layout_file_if_api_option if options[:api] - remove_file 'app/views/layouts/application.html.erb' + remove_file "app/views/layouts/application.html.erb" end end def delete_public_files_if_api_option if options[:api] - remove_file 'public/404.html' - remove_file 'public/422.html' - remove_file 'public/500.html' - remove_file 'public/apple-touch-icon-precomposed.png' - remove_file 'public/apple-touch-icon.png' - remove_file 'public/favicon.ico' + remove_file "public/404.html" + remove_file "public/422.html" + remove_file "public/500.html" + remove_file "public/apple-touch-icon-precomposed.png" + remove_file "public/apple-touch-icon.png" + remove_file "public/favicon.ico" end end def delete_js_folder_skipping_javascript if options[:skip_javascript] - remove_dir 'app/assets/javascripts' + remove_dir "app/assets/javascripts" end end def delete_assets_initializer_skipping_sprockets if options[:skip_sprockets] - remove_file 'config/initializers/assets.rb' + remove_file "config/initializers/assets.rb" end end def delete_application_record_skipping_active_record if options[:skip_active_record] - remove_file 'app/models/application_record.rb' + remove_file "app/models/application_record.rb" end end def delete_action_mailer_files_skipping_action_mailer if options[:skip_action_mailer] - remove_file 'app/mailers/application_mailer.rb' - remove_file 'app/views/layouts/mailer.html.erb' - remove_file 'app/views/layouts/mailer.text.erb' + remove_file "app/views/layouts/mailer.html.erb" + remove_file "app/views/layouts/mailer.text.erb" + remove_dir "app/mailers" + remove_dir "test/mailers" end end def delete_action_cable_files_skipping_action_cable if options[:skip_action_cable] - remove_file 'config/cable.yml' - remove_file 'app/assets/javascripts/cable.js' - remove_dir 'app/channels' + remove_file "config/cable.yml" + remove_file "app/assets/javascripts/cable.js" + remove_dir "app/channels" end end def delete_non_api_initializers_if_api_option if options[:api] - remove_file 'config/initializers/session_store.rb' - remove_file 'config/initializers/cookies_serializer.rb' + remove_file "config/initializers/cookies_serializer.rb" end end def delete_api_initializers unless options[:api] - remove_file 'config/initializers/cors.rb' + remove_file "config/initializers/cors.rb" end end + def delete_bin_yarn_if_skip_yarn_option + remove_file "bin/yarn" if options[:skip_yarn] + end + def finish_template build(:leftovers) end public_task :apply_rails_template, :run_bundle - public_task :generate_spring_binstubs + public_task :run_webpack, :generate_spring_binstubs def run_after_bundle_callbacks @after_bundle_callbacks.each(&:call) end - protected - def self.banner - "rails new #{self.arguments.map(&:usage).join(' ')} [options]" + "rails new #{arguments.map(&:usage).join(' ')} [options]" end + private + # Define file as an alias to create_file for backwards compatibility. def file(*args, &block) create_file(*args, &block) end def app_name - @app_name ||= (defined_app_const_base? ? defined_app_name : File.basename(destination_root)).tr('\\', '').tr(". ", "_") + @app_name ||= (defined_app_const_base? ? defined_app_name : File.basename(destination_root)).tr('\\', "").tr(". ", "_") end def defined_app_name @@ -381,7 +392,7 @@ module Rails alias :defined_app_const_base? :defined_app_const_base def app_const_base - @app_const_base ||= defined_app_const_base || app_name.gsub(/\W/, '_').squeeze('_').camelize + @app_const_base ||= defined_app_const_base || app_name.gsub(/\W/, "_").squeeze("_").camelize end alias :camelized :app_const_base @@ -416,7 +427,7 @@ module Rails "/opt/local/var/run/mysql4/mysqld.sock", # mac + darwinports + mysql4 "/opt/local/var/run/mysql5/mysqld.sock", # mac + darwinports + mysql5 "/opt/lampp/var/mysql/mysql.sock" # xampp for linux - ].find { |f| File.exist?(f) } unless RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ + ].find { |f| File.exist?(f) } unless Gem.win_platform? end def get_builder_class @@ -444,14 +455,14 @@ module Rails end def self.default_rc_file - File.expand_path('~/.railsrc') + File.expand_path("~/.railsrc") end private def handle_version_request!(argument) - if ['--version', '-v'].include?(argument) - require 'rails/version' + if ["--version", "-v"].include?(argument) + require "rails/version" puts "Rails #{Rails::VERSION::STRING}" exit(0) end @@ -461,20 +472,20 @@ module Rails if argument == "new" yield else - ['--help'] + argv.drop(1) + ["--help"] + argv.drop(1) end end def handle_rails_rc!(argv) - if argv.find { |arg| arg == '--no-rc' } - argv.reject { |arg| arg == '--no-rc' } + if argv.find { |arg| arg == "--no-rc" } + argv.reject { |arg| arg == "--no-rc" } else railsrc(argv) { |rc_argv, rc| insert_railsrc_into_argv!(rc_argv, rc) } end end def railsrc(argv) - if (customrc = argv.index{ |x| x.include?("--rc=") }) + if (customrc = argv.index { |x| x.include?("--rc=") }) fname = File.expand_path(argv[customrc].gsub(/--rc=/, "")) yield(argv.take(customrc) + argv.drop(customrc + 1), fname) else diff --git a/railties/lib/rails/generators/rails/app/templates/Gemfile b/railties/lib/rails/generators/rails/app/templates/Gemfile index 86143ca1f1..f1015b16d5 100644 --- a/railties/lib/rails/generators/rails/app/templates/Gemfile +++ b/railties/lib/rails/generators/rails/app/templates/Gemfile @@ -1,5 +1,10 @@ source 'https://rubygems.org' +git_source(:github) do |repo_name| + repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/") + "https://github.com/#{repo_name}.git" +end + <% gemfile_entries.each do |gem| -%> <% if gem.comment -%> @@ -35,11 +40,11 @@ group :development do <%- if options.dev? || options.edge? -%> gem 'web-console', github: 'rails/web-console' <%- else -%> - gem 'web-console' + gem 'web-console', '>= 3.3.0' <%- end -%> <%- end -%> <% if depend_on_listen? -%> - gem 'listen', '~> 3.0.5' + gem 'listen', '>= 3.0.5', '< 3.2' <% end -%> <% if spring_install? -%> # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring diff --git a/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt b/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt index c88426ec06..25870f19c8 100644 --- a/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt +++ b/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt @@ -1,8 +1,8 @@ // This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // -// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, -// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. +// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's +// vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. JavaScript code in this file should be added after the last require_* statement. @@ -11,9 +11,11 @@ // about supported directives. // <% unless options[:skip_javascript] -%> +<% if options[:javascript] -%> //= require <%= options[:javascript] %> -//= require <%= options[:javascript] %>_ujs -<% if gemfile_entries.any? { |m| m.name == "turbolinks" } -%> +<% end -%> +//= require rails-ujs +<% unless options[:skip_turbolinks] -%> //= require turbolinks <% end -%> <% end -%> diff --git a/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/cable.js b/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/cable.js index 71ee1e66de..739aa5f022 100644 --- a/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/cable.js +++ b/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/cable.js @@ -1,5 +1,5 @@ // Action Cable provides the framework to deal with WebSockets in Rails. -// You can generate new channels where WebSocket features live using the rails generate channel command. +// You can generate new channels where WebSocket features live using the `rails generate channel` command. // //= require action_cable //= require_self diff --git a/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css b/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css index 0ebd7fe829..865300bef9 100644 --- a/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css +++ b/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css @@ -2,8 +2,8 @@ * This is a manifest file that'll be compiled into application.css, which will include all the files * listed below. * - * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, - * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path. + * Any CSS and SCSS file within this directory, lib/assets/stylesheets, or any plugin's + * vendor/assets/stylesheets directory can be referenced here using a relative path. * * You're free to add application-wide styles to this file and they'll appear at the bottom of the * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS diff --git a/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt b/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt index d51f79bd49..5460155b3e 100644 --- a/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt +++ b/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt @@ -7,7 +7,7 @@ <%- if options[:skip_javascript] -%> <%%= stylesheet_link_tag 'application', media: 'all' %> <%- else -%> - <%- if gemfile_entries.any? { |m| m.name == 'turbolinks' } -%> + <%- unless options[:skip_turbolinks] -%> <%%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> <%%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %> <%- else -%> diff --git a/railties/lib/rails/generators/rails/app/templates/bin/setup b/railties/lib/rails/generators/rails/app/templates/bin/setup.tt index acae810c1a..c6607dbb2b 100644 --- a/railties/lib/rails/generators/rails/app/templates/bin/setup +++ b/railties/lib/rails/generators/rails/app/templates/bin/setup.tt @@ -16,7 +16,12 @@ chdir APP_ROOT do puts '== Installing dependencies ==' system! 'gem install bundler --conservative' system('bundle check') || system!('bundle install') +<% unless options[:skip_yarn] %> + # Install JavaScript dependencies if using Yarn + # system('bin/yarn') +<% end %> +<% unless options.skip_active_record -%> # puts "\n== Copying sample files ==" # unless File.exist?('config/database.yml') # cp 'config/database.yml.sample', 'config/database.yml' @@ -24,6 +29,7 @@ chdir APP_ROOT do puts "\n== Preparing database ==" system! 'bin/rails db:setup' +<% end -%> puts "\n== Removing old logs and tempfiles ==" system! 'bin/rails log:clear tmp:clear' diff --git a/railties/lib/rails/generators/rails/app/templates/bin/update b/railties/lib/rails/generators/rails/app/templates/bin/update.tt index 770a605fed..d23af018c7 100644 --- a/railties/lib/rails/generators/rails/app/templates/bin/update +++ b/railties/lib/rails/generators/rails/app/templates/bin/update.tt @@ -16,9 +16,10 @@ chdir APP_ROOT do puts '== Installing dependencies ==' system! 'gem install bundler --conservative' system('bundle check') || system!('bundle install') - +<% unless options.skip_active_record -%> puts "\n== Updating database ==" system! 'bin/rails db:migrate' +<% end -%> puts "\n== Removing old logs and tempfiles ==" system! 'bin/rails log:clear tmp:clear' diff --git a/railties/lib/rails/generators/rails/app/templates/bin/yarn b/railties/lib/rails/generators/rails/app/templates/bin/yarn new file mode 100644 index 0000000000..872438cecb --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/bin/yarn @@ -0,0 +1,9 @@ +VENDOR_PATH = File.expand_path('../vendor', __dir__) +Dir.chdir(VENDOR_PATH) do + begin + exec "yarnpkg #{ARGV.join(" ")}" + rescue Errno::ENOENT + puts "Yarn executable was not detected in the system." + puts "Download Yarn at https://yarnpkg.com/en/docs/install" + end +end diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcmysql.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcmysql.yml index a2b2a64ba6..8bc8735a8e 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcmysql.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcmysql.yml @@ -1,4 +1,4 @@ -# MySQL. Versions 5.0 and up are supported. +# MySQL. Versions 5.1.10 and up are supported. # # Install the MySQL driver: # gem install activerecord-jdbcmysql-adapter diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml index d987cf303b..269af1470d 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml @@ -1,4 +1,4 @@ -# MySQL. Versions 5.0 and up are supported. +# MySQL. Versions 5.1.10 and up are supported. # # Install the MySQL driver # gem install mysql2 diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml index bd5c0b10f6..145cfb7f74 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml @@ -17,7 +17,7 @@ default: &default adapter: postgresql encoding: unicode - # For details on connection pooling, see rails configuration guide + # For details on connection pooling, see Rails configuration guide # http://guides.rubyonrails.org/configuring.html#database-pooling pool: <%%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt index f3ccf95045..511b4a82eb 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt +++ b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt @@ -18,7 +18,7 @@ Rails.application.configure do config.cache_store = :memory_store config.public_file_server.headers = { - 'Cache-Control' => 'public, max-age=172800' + 'Cache-Control' => "public, max-age=#{2.days.seconds.to_i}" } else config.action_controller.perform_caching = false diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt index 363af05459..7deab5dbb1 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt +++ b/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt @@ -19,8 +19,12 @@ Rails.application.configure do config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? <%- unless options.skip_sprockets? -%> + <%- if options.skip_javascript? -%> + # Compress CSS. + <%- else -%> # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier + <%- end -%> # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt index 42fee3b036..56416b3075 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt +++ b/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt @@ -15,7 +15,7 @@ Rails.application.configure do # Configure public file server for tests with Cache-Control for performance. config.public_file_server.enabled = true config.public_file_server.headers = { - 'Cache-Control' => 'public, max-age=3600' + 'Cache-Control' => "public, max-age=#{1.hour.seconds.to_i}" } # Show full error reports and disable caching. diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/assets.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/initializers/assets.rb.tt index 01ef3e6630..f5d03fb117 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/initializers/assets.rb.tt +++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/assets.rb.tt @@ -3,9 +3,14 @@ # Version of your assets, change this if you want to expire all your assets. Rails.application.config.assets.version = '1.0' -# Add additional assets to the asset load path +# Add additional assets to the asset load path. # Rails.application.config.assets.paths << Emoji.images_path +<%- unless options[:skip_yarn] -%> +# Add Yarn node_modules folder to the asset load path. +Rails.application.config.assets.paths << Rails.root.join('vendor/node_modules') +<%- end -%> # Precompile additional assets. -# application.js, application.css, and all non-JS/CSS in app/assets folder are already added. -# Rails.application.config.assets.precompile += %w( search.js ) +# application.js, application.css, and all non-JS/CSS in the app/assets +# folder are already added. +# Rails.application.config.assets.precompile += %w( admin.js admin.css ) diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/new_framework_defaults.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/initializers/new_framework_defaults.rb.tt index 991963b65e..3ad3eba98a 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/initializers/new_framework_defaults.rb.tt +++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/new_framework_defaults.rb.tt @@ -6,7 +6,7 @@ # Once upgraded flip defaults one by one to migrate to the new default. # <%- end -%> -# Read the Rails 5.0 release notes for more info on each option. +# Read the Guide for Upgrading Ruby on Rails for more info on each option. <%- unless options[:api] -%> # Enable per-form CSRF tokens. Previous versions had false. @@ -32,3 +32,9 @@ ActiveSupport.halt_callback_chains_on_return_false = <%= options[:update] ? true # Configure SSL options to enable HSTS with subdomains. Previous versions had false. Rails.application.config.ssl_options = { hsts: { subdomains: true } } <%- end -%> +<%- unless options[:skip_sprockets] -%> + +# Unknown asset fallback will return the path passed in when the given +# asset is not present in the asset pipeline. +Rails.application.config.assets.unknown_asset_fallback = <%= options[:update] ? true : false %> +<%- end -%> 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 deleted file mode 100644 index 2bb9b82c61..0000000000 --- a/railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt +++ /dev/null @@ -1,3 +0,0 @@ -# Be sure to restart your server when you modify this file. - -Rails.application.config.session_store :cookie_store, key: <%= "'_#{app_name}_session'" %> diff --git a/railties/lib/rails/generators/rails/app/templates/config/puma.rb b/railties/lib/rails/generators/rails/app/templates/config/puma.rb index c7f311f811..1e19380dcb 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/puma.rb +++ b/railties/lib/rails/generators/rails/app/templates/config/puma.rb @@ -1,13 +1,13 @@ # Puma can serve each request in a thread from an internal thread pool. -# The `threads` method setting takes two numbers a minimum and maximum. +# The `threads` method setting takes two numbers: a minimum and maximum. # Any libraries that use thread pools should be configured to match # the maximum value specified for Puma. Default is set to 5 threads for minimum -# and maximum, this matches the default thread size of Active Record. +# and maximum; this matches the default thread size of Active Record. # -threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }.to_i +threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } threads threads_count, threads_count -# Specifies the `port` that Puma will listen on to receive requests, default is 3000. +# Specifies the `port` that Puma will listen on to receive requests; default is 3000. # port ENV.fetch("PORT") { 3000 } @@ -32,16 +32,25 @@ environment ENV.fetch("RAILS_ENV") { "development" } # # preload_app! +# If you are preloading your application and using Active Record, it's +# recommended that you close any connections to the database before workers +# are forked to prevent connection leakage. +# +# before_fork do +# ActiveRecord::Base.connection_pool.disconnect! if defined?(ActiveRecord) +# end + # The code in the `on_worker_boot` will be called if you are using # clustered mode by specifying a number of `workers`. After each worker -# process is booted this block will be run, if you are using `preload_app!` -# option you will want to use this block to reconnect to any threads -# or connections that may have been created at application boot, Ruby +# process is booted, this block will be run. If you are using the `preload_app!` +# option, you will want to use this block to reconnect to any threads +# or connections that may have been created at application boot, as Ruby # cannot share connections between processes. # # on_worker_boot do # ActiveRecord::Base.establish_connection if defined?(ActiveRecord) # end +# # Allow puma to be restarted by `rails restart` command. plugin :tmp_restart diff --git a/railties/lib/rails/generators/rails/app/templates/gitignore b/railties/lib/rails/generators/rails/app/templates/gitignore index 0e66cc4237..709b341387 100644 --- a/railties/lib/rails/generators/rails/app/templates/gitignore +++ b/railties/lib/rails/generators/rails/app/templates/gitignore @@ -21,5 +21,8 @@ !/tmp/.keep <% end -%> -# Ignore Byebug command history file. +<% unless options[:skip_yarn] -%> +/vendor/node_modules + +<% end -%> .byebug_history diff --git a/railties/lib/rails/generators/rails/app/templates/package.json b/railties/lib/rails/generators/rails/app/templates/package.json new file mode 100644 index 0000000000..46db57dcbe --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/package.json @@ -0,0 +1,5 @@ +{ + "name": "<%= app_name %>", + "private": true, + "dependencies": {} +} diff --git a/railties/lib/rails/generators/rails/app/templates/public/robots.txt b/railties/lib/rails/generators/rails/app/templates/public/robots.txt index 3c9c7c01f3..37b576a4a0 100644 --- a/railties/lib/rails/generators/rails/app/templates/public/robots.txt +++ b/railties/lib/rails/generators/rails/app/templates/public/robots.txt @@ -1,5 +1 @@ # See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file -# -# To ban all spiders from the entire site uncomment the next two lines: -# User-agent: * -# Disallow: / 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 87b8fe3516..2f92168eef 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 @@ -1,4 +1,3 @@ -ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' diff --git a/railties/lib/rails/generators/rails/assets/assets_generator.rb b/railties/lib/rails/generators/rails/assets/assets_generator.rb index 6f4b86e708..95d00c2d39 100644 --- a/railties/lib/rails/generators/rails/assets/assets_generator.rb +++ b/railties/lib/rails/generators/rails/assets/assets_generator.rb @@ -7,19 +7,19 @@ module Rails class_option :javascript_engine, desc: "Engine for JavaScripts" class_option :stylesheet_engine, desc: "Engine for Stylesheets" - protected + private - def asset_name - file_name - end + def asset_name + file_name + end - hook_for :javascript_engine do |javascript_engine| - invoke javascript_engine, [name] if options[:javascripts] - end + hook_for :javascript_engine do |javascript_engine| + invoke javascript_engine, [name] if options[:javascripts] + end - hook_for :stylesheet_engine do |stylesheet_engine| - invoke stylesheet_engine, [name] if options[:stylesheets] - end + hook_for :stylesheet_engine do |stylesheet_engine| + invoke stylesheet_engine, [name] if options[:stylesheets] + end end end end diff --git a/railties/lib/rails/generators/rails/controller/controller_generator.rb b/railties/lib/rails/generators/rails/controller/controller_generator.rb index 6c583e5811..06bdb8b5ce 100644 --- a/railties/lib/rails/generators/rails/controller/controller_generator.rb +++ b/railties/lib/rails/generators/rails/controller/controller_generator.rb @@ -3,18 +3,20 @@ module Rails class ControllerGenerator < NamedBase # :nodoc: argument :actions, type: :array, default: [], banner: "action action" class_option :skip_routes, type: :boolean, desc: "Don't add routes to config/routes.rb." + class_option :helper, type: :boolean + class_option :assets, type: :boolean check_class_collision suffix: "Controller" def create_controller_files - template 'controller.rb', File.join('app/controllers', class_path, "#{file_name}_controller.rb") + template "controller.rb", File.join("app/controllers", class_path, "#{file_name}_controller.rb") end def add_routes unless options[:skip_routes] actions.reverse_each do |action| # route prepends two spaces onto the front of the string that is passed, this corrects that. - route generate_routing_code(action)[2..-1] + route indent(generate_routing_code(action), 2)[2..-1] end end end @@ -32,27 +34,30 @@ module Rails # end # end def generate_routing_code(action) - depth = regular_class_path.length + depth = 0 + lines = [] + # Create 'namespace' ladder # namespace :foo do # namespace :bar do - namespace_ladder = regular_class_path.each_with_index.map do |ns, i| - indent(" namespace :#{ns} do\n", i * 2) - end.join + regular_class_path.each do |ns| + lines << indent("namespace :#{ns} do\n", depth * 2) + depth += 1 + end # Create route # get 'baz/index' - route = indent(%{ get '#{file_name}/#{action}'\n}, depth * 2) + lines << indent(%{get '#{file_name}/#{action}'\n}, depth * 2) # Create `end` ladder # end # end - end_ladder = (1..depth).reverse_each.map do |i| - indent("end\n", i * 2) - end.join + until depth.zero? + depth -= 1 + lines << indent("end\n", depth * 2) + end - # Combine the 3 parts to generate complete route entry - namespace_ladder + route + end_ladder + lines.join end end end diff --git a/railties/lib/rails/generators/rails/generator/generator_generator.rb b/railties/lib/rails/generators/rails/generator/generator_generator.rb index 15d88f06ac..299a7da5f1 100644 --- a/railties/lib/rails/generators/rails/generator/generator_generator.rb +++ b/railties/lib/rails/generators/rails/generator/generator_generator.rb @@ -7,12 +7,12 @@ module Rails desc: "Namespace generator under lib/generators/name" def create_generator_files - directory '.', generator_dir + directory ".", generator_dir end hook_for :test_framework - protected + private def generator_dir if options[:namespace] @@ -21,7 +21,6 @@ module Rails File.join("lib", "generators", regular_class_path) end end - end end end diff --git a/railties/lib/rails/generators/rails/helper/helper_generator.rb b/railties/lib/rails/generators/rails/helper/helper_generator.rb index 5ff38e4111..e48b1b6fb3 100644 --- a/railties/lib/rails/generators/rails/helper/helper_generator.rb +++ b/railties/lib/rails/generators/rails/helper/helper_generator.rb @@ -4,7 +4,7 @@ module Rails check_class_collision suffix: "Helper" def create_helper_files - template 'helper.rb', File.join('app/helpers', class_path, "#{file_name}_helper.rb") + template "helper.rb", File.join("app/helpers", class_path, "#{file_name}_helper.rb") end hook_for :test_framework diff --git a/railties/lib/rails/generators/rails/model/model_generator.rb b/railties/lib/rails/generators/rails/model/model_generator.rb index ec78fd855d..c32a8a079a 100644 --- a/railties/lib/rails/generators/rails/model/model_generator.rb +++ b/railties/lib/rails/generators/rails/model/model_generator.rb @@ -1,4 +1,4 @@ -require 'rails/generators/model_helpers' +require "rails/generators/model_helpers" module Rails module Generators diff --git a/railties/lib/rails/generators/rails/plugin/plugin_generator.rb b/railties/lib/rails/generators/rails/plugin/plugin_generator.rb index 56efd35a95..4cf4f8cd9a 100644 --- a/railties/lib/rails/generators/rails/plugin/plugin_generator.rb +++ b/railties/lib/rails/generators/rails/plugin/plugin_generator.rb @@ -1,6 +1,6 @@ -require 'active_support/core_ext/hash/slice' +require "active_support/core_ext/hash/slice" require "rails/generators/rails/app/app_generator" -require 'date' +require "date" module Rails # The plugin builder allows you to override elements of the plugin @@ -18,20 +18,20 @@ module Rails def app if mountable? if api? - directory 'app', exclude_pattern: %r{app/(views|helpers)} + directory "app", exclude_pattern: %r{app/(views|helpers)} else - directory 'app' + directory "app" empty_directory_with_keep_file "app/assets/images/#{namespaced_name}" end elsif full? - empty_directory_with_keep_file 'app/models' - empty_directory_with_keep_file 'app/controllers' - empty_directory_with_keep_file 'app/mailers' + empty_directory_with_keep_file "app/models" + empty_directory_with_keep_file "app/controllers" + empty_directory_with_keep_file "app/mailers" unless api? empty_directory_with_keep_file "app/assets/images/#{namespaced_name}" - empty_directory_with_keep_file 'app/helpers' - empty_directory_with_keep_file 'app/views' + empty_directory_with_keep_file "app/helpers" + empty_directory_with_keep_file "app/views" end end end @@ -81,7 +81,7 @@ task default: :test end PASSTHROUGH_OPTIONS = [ - :skip_active_record, :skip_action_mailer, :skip_javascript, :database, + :skip_active_record, :skip_action_mailer, :skip_javascript, :skip_sprockets, :database, :javascript, :quiet, :pretend, :force, :skip ] @@ -149,7 +149,7 @@ task default: :test end def bin(force = false) - bin_file = engine? ? 'bin/rails.tt' : 'bin/test.tt' + bin_file = engine? ? "bin/rails.tt" : "bin/test.tt" template bin_file, force: force do |content| "#{shebang}\n" + content end @@ -258,7 +258,7 @@ task default: :test build(:leftovers) end - public_task :apply_rails_template, :run_bundle + public_task :apply_rails_template def run_after_bundle_callbacks @after_bundle_callbacks.each do |callback| @@ -270,8 +270,8 @@ task default: :test @name ||= begin # same as ActiveSupport::Inflector#underscore except not replacing '-' underscored = original_name.dup - underscored.gsub!(/([A-Z]+)([A-Z][a-z])/,'\1_\2') - underscored.gsub!(/([a-z\d])([A-Z])/,'\1_\2') + underscored.gsub!(/([A-Z]+)([A-Z][a-z])/, '\1_\2') + underscored.gsub!(/([a-z\d])([A-Z])/, '\1_\2') underscored.downcase! underscored @@ -283,10 +283,10 @@ task default: :test end def namespaced_name - @namespaced_name ||= name.gsub('-', '/') + @namespaced_name ||= name.tr("-", "/") end - protected + private def create_dummy_app(path = nil) dummy_path(path) if path @@ -320,7 +320,7 @@ task default: :test end def with_dummy_app? - options[:skip_test].blank? || options[:dummy_path] != 'test/dummy' + options[:skip_test].blank? || options[:dummy_path] != "test/dummy" end def api? @@ -328,7 +328,7 @@ task default: :test end def self.banner - "rails plugin new #{self.arguments.map(&:usage).join(' ')} [options]" + "rails plugin new #{arguments.map(&:usage).join(' ')} [options]" end def original_name @@ -340,7 +340,7 @@ task default: :test end def wrap_in_modules(unwrapped_code) - unwrapped_code = "#{unwrapped_code}".strip.gsub(/\s$\n/, '') + unwrapped_code = "#{unwrapped_code}".strip.gsub(/\s$\n/, "") modules.reverse.inject(unwrapped_code) do |content, mod| str = "module #{mod}\n" str += content.lines.map { |line| " #{line}" }.join @@ -357,7 +357,7 @@ task default: :test end def camelized - @camelized ||= name.gsub(/\W/, '_').squeeze('_').camelize + @camelized ||= name.gsub(/\W/, "_").squeeze("_").camelize end def author @@ -442,7 +442,7 @@ end def relative_path return unless inside_application? - app_path.sub(/^#{rails_app_path}\//, '') + app_path.sub(/^#{rails_app_path}\//, "") end end end diff --git a/railties/lib/rails/generators/rails/plugin/templates/bin/test.tt b/railties/lib/rails/generators/rails/plugin/templates/bin/test.tt index 62b94618fd..c0fbb84a93 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/bin/test.tt +++ b/railties/lib/rails/generators/rails/plugin/templates/bin/test.tt @@ -5,4 +5,6 @@ require 'rails/test_unit/minitest_plugin' Rails::TestUnitReporter.executable = 'bin/test' -exit Minitest.run(ARGV) +Minitest.run_via[:rails] = true + +require "active_support/testing/autorun" diff --git a/railties/lib/rails/generators/rails/plugin/templates/test/test_helper.rb b/railties/lib/rails/generators/rails/plugin/templates/test/test_helper.rb index a5eebcb19f..e84e403018 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/test/test_helper.rb +++ b/railties/lib/rails/generators/rails/plugin/templates/test/test_helper.rb @@ -1,6 +1,3 @@ -# Configure Rails Environment -ENV["RAILS_ENV"] = "test" - require File.expand_path("../../<%= options[:dummy_path] -%>/config/environment.rb", __FILE__) <% unless options[:skip_active_record] -%> ActiveRecord::Migrator.migrations_paths = [File.expand_path("../../<%= options[:dummy_path] -%>/db/migrate", __FILE__)] diff --git a/railties/lib/rails/generators/rails/resource/resource_generator.rb b/railties/lib/rails/generators/rails/resource/resource_generator.rb index 3acf21df13..5ac5164af0 100644 --- a/railties/lib/rails/generators/rails/resource/resource_generator.rb +++ b/railties/lib/rails/generators/rails/resource/resource_generator.rb @@ -1,5 +1,5 @@ -require 'rails/generators/resource_helpers' -require 'rails/generators/rails/model/model_generator' +require "rails/generators/resource_helpers" +require "rails/generators/rails/model/model_generator" module Rails module Generators diff --git a/railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb b/railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb index 17c32bfdb3..ed6bf7f7d7 100644 --- a/railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb +++ b/railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb @@ -1,4 +1,4 @@ -require 'rails/generators/rails/resource/resource_generator' +require "rails/generators/rails/resource/resource_generator" module Rails module Generators diff --git a/railties/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb b/railties/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb index d0b8cad896..e4f3161ffd 100644 --- a/railties/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb +++ b/railties/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb @@ -1,4 +1,4 @@ -require 'rails/generators/resource_helpers' +require "rails/generators/resource_helpers" module Rails module Generators @@ -17,7 +17,7 @@ module Rails def create_controller_files template_file = options.api? ? "api_controller.rb" : "controller.rb" - template template_file, File.join('app/controllers', controller_class_path, "#{controller_file_name}_controller.rb") + template template_file, File.join("app/controllers", controller_class_path, "#{controller_file_name}_controller.rb") end hook_for :template_engine, :test_framework, as: :scaffold diff --git a/railties/lib/rails/generators/rails/task/task_generator.rb b/railties/lib/rails/generators/rails/task/task_generator.rb index 754824ca0c..bb96bdf0dd 100644 --- a/railties/lib/rails/generators/rails/task/task_generator.rb +++ b/railties/lib/rails/generators/rails/task/task_generator.rb @@ -4,9 +4,8 @@ module Rails argument :actions, type: :array, default: [], banner: "action action" def create_task_files - template 'task.rb', File.join('lib/tasks', "#{file_name}.rake") + template "task.rb", File.join("lib/tasks", "#{file_name}.rake") end - end end end diff --git a/railties/lib/rails/generators/resource_helpers.rb b/railties/lib/rails/generators/resource_helpers.rb index 9c2037783e..978b053308 100644 --- a/railties/lib/rails/generators/resource_helpers.rb +++ b/railties/lib/rails/generators/resource_helpers.rb @@ -1,12 +1,11 @@ -require 'rails/generators/active_model' -require 'rails/generators/model_helpers' +require "rails/generators/active_model" +require "rails/generators/model_helpers" module Rails module Generators # Deal with controller names on scaffold and add some helpers to deal with # ActiveModel. module ResourceHelpers # :nodoc: - def self.included(base) #:nodoc: base.include(Rails::Generators::ModelHelpers) base.class_option :model_name, type: :string, desc: "ModelName to be used" @@ -18,16 +17,20 @@ module Rails controller_name = name if options[:model_name] self.name = options[:model_name] - assign_names!(self.name) + assign_names!(name) end assign_controller_names!(controller_name.pluralize) end + # TODO Change this to private once we've dropped Ruby 2.2 support. + # Workaround for Ruby 2.2 "private attribute?" warning. protected attr_reader :controller_name, :controller_file_name + private + def controller_class_path if options[:model_name] @controller_class_path @@ -38,21 +41,21 @@ module Rails def assign_controller_names!(name) @controller_name = name - @controller_class_path = name.include?('/') ? name.split('/') : name.split('::') + @controller_class_path = name.include?("/") ? name.split("/") : name.split("::") @controller_class_path.map!(&:underscore) @controller_file_name = @controller_class_path.pop end def controller_file_path - @controller_file_path ||= (controller_class_path + [controller_file_name]).join('/') + @controller_file_path ||= (controller_class_path + [controller_file_name]).join("/") end def controller_class_name - (controller_class_path + [controller_file_name]).map!(&:camelize).join('::') + (controller_class_path + [controller_file_name]).map!(&:camelize).join("::") end def controller_i18n_scope - @controller_i18n_scope ||= controller_file_path.tr('/', '.') + @controller_i18n_scope ||= controller_file_path.tr("/", ".") end # Loads the ORM::Generators::ActiveModel class. This class is responsible @@ -74,7 +77,7 @@ module Rails end # Initialize ORM::Generators::ActiveModel to access instance methods. - def orm_instance(name=singular_table_name) + def orm_instance(name = singular_table_name) @orm_instance ||= orm_class.new(name) end end diff --git a/railties/lib/rails/generators/test_case.rb b/railties/lib/rails/generators/test_case.rb index 58592b4f8e..3eec929aeb 100644 --- a/railties/lib/rails/generators/test_case.rb +++ b/railties/lib/rails/generators/test_case.rb @@ -1,8 +1,8 @@ -require 'rails/generators' -require 'rails/generators/testing/behaviour' -require 'rails/generators/testing/setup_and_teardown' -require 'rails/generators/testing/assertions' -require 'fileutils' +require "rails/generators" +require "rails/generators/testing/behaviour" +require "rails/generators/testing/setup_and_teardown" +require "rails/generators/testing/assertions" +require "fileutils" module Rails module Generators @@ -30,7 +30,6 @@ module Rails include Rails::Generators::Testing::SetupAndTeardown include Rails::Generators::Testing::Assertions include FileUtils - end end end diff --git a/railties/lib/rails/generators/test_unit.rb b/railties/lib/rails/generators/test_unit.rb index fe45c9e15d..722efcf492 100644 --- a/railties/lib/rails/generators/test_unit.rb +++ b/railties/lib/rails/generators/test_unit.rb @@ -1,4 +1,4 @@ -require 'rails/generators/named_base' +require "rails/generators/named_base" module TestUnit # :nodoc: module Generators # :nodoc: diff --git a/railties/lib/rails/generators/test_unit/controller/controller_generator.rb b/railties/lib/rails/generators/test_unit/controller/controller_generator.rb index b5aa581769..ac528d94f1 100644 --- a/railties/lib/rails/generators/test_unit/controller/controller_generator.rb +++ b/railties/lib/rails/generators/test_unit/controller/controller_generator.rb @@ -1,4 +1,4 @@ -require 'rails/generators/test_unit' +require "rails/generators/test_unit" module TestUnit # :nodoc: module Generators # :nodoc: @@ -7,8 +7,8 @@ module TestUnit # :nodoc: check_class_collision suffix: "ControllerTest" def create_test_files - template 'functional_test.rb', - File.join('test/controllers', class_path, "#{file_name}_controller_test.rb") + template "functional_test.rb", + File.join("test/controllers", class_path, "#{file_name}_controller_test.rb") end end end diff --git a/railties/lib/rails/generators/test_unit/generator/generator_generator.rb b/railties/lib/rails/generators/test_unit/generator/generator_generator.rb index d7307398ce..6b6e094453 100644 --- a/railties/lib/rails/generators/test_unit/generator/generator_generator.rb +++ b/railties/lib/rails/generators/test_unit/generator/generator_generator.rb @@ -1,4 +1,4 @@ -require 'rails/generators/test_unit' +require "rails/generators/test_unit" module TestUnit # :nodoc: module Generators # :nodoc: @@ -9,10 +9,10 @@ module TestUnit # :nodoc: desc: "Namespace generator under lib/generators/name" def create_generator_files - template 'generator_test.rb', File.join('test/lib/generators', class_path, "#{file_name}_generator_test.rb") + template "generator_test.rb", File.join("test/lib/generators", class_path, "#{file_name}_generator_test.rb") end - protected + private def generator_path if options[:namespace] diff --git a/railties/lib/rails/generators/test_unit/helper/helper_generator.rb b/railties/lib/rails/generators/test_unit/helper/helper_generator.rb index bde4e88915..6674a15fa3 100644 --- a/railties/lib/rails/generators/test_unit/helper/helper_generator.rb +++ b/railties/lib/rails/generators/test_unit/helper/helper_generator.rb @@ -1,4 +1,4 @@ -require 'rails/generators/test_unit' +require "rails/generators/test_unit" module TestUnit # :nodoc: module Generators # :nodoc: diff --git a/railties/lib/rails/generators/test_unit/integration/integration_generator.rb b/railties/lib/rails/generators/test_unit/integration/integration_generator.rb index e004835bd5..9d065c1297 100644 --- a/railties/lib/rails/generators/test_unit/integration/integration_generator.rb +++ b/railties/lib/rails/generators/test_unit/integration/integration_generator.rb @@ -1,4 +1,4 @@ -require 'rails/generators/test_unit' +require "rails/generators/test_unit" module TestUnit # :nodoc: module Generators # :nodoc: @@ -6,7 +6,7 @@ module TestUnit # :nodoc: check_class_collision suffix: "Test" def create_test_files - template 'integration_test.rb', File.join('test/integration', class_path, "#{file_name}_test.rb") + template "integration_test.rb", File.join("test/integration", class_path, "#{file_name}_test.rb") end end end diff --git a/railties/lib/rails/generators/test_unit/job/job_generator.rb b/railties/lib/rails/generators/test_unit/job/job_generator.rb index 566b61ca66..6975252b99 100644 --- a/railties/lib/rails/generators/test_unit/job/job_generator.rb +++ b/railties/lib/rails/generators/test_unit/job/job_generator.rb @@ -1,12 +1,12 @@ -require 'rails/generators/test_unit' +require "rails/generators/test_unit" module TestUnit # :nodoc: module Generators # :nodoc: class JobGenerator < Base # :nodoc: - check_class_collision suffix: 'JobTest' + check_class_collision suffix: "JobTest" def create_test_file - template 'unit_test.rb.erb', File.join('test/jobs', class_path, "#{file_name}_job_test.rb") + template "unit_test.rb.erb", File.join("test/jobs", class_path, "#{file_name}_job_test.rb") end end end diff --git a/railties/lib/rails/generators/test_unit/mailer/mailer_generator.rb b/railties/lib/rails/generators/test_unit/mailer/mailer_generator.rb index 76a0b79654..67bff8e4f9 100644 --- a/railties/lib/rails/generators/test_unit/mailer/mailer_generator.rb +++ b/railties/lib/rails/generators/test_unit/mailer/mailer_generator.rb @@ -1,4 +1,4 @@ -require 'rails/generators/test_unit' +require "rails/generators/test_unit" module TestUnit # :nodoc: module Generators # :nodoc: @@ -10,16 +10,16 @@ module TestUnit # :nodoc: end def create_test_files - template "functional_test.rb", File.join('test/mailers', class_path, "#{file_name}_mailer_test.rb") + template "functional_test.rb", File.join("test/mailers", class_path, "#{file_name}_mailer_test.rb") end def create_preview_files - template "preview.rb", File.join('test/mailers/previews', class_path, "#{file_name}_mailer_preview.rb") + template "preview.rb", File.join("test/mailers/previews", class_path, "#{file_name}_mailer_preview.rb") end - protected + private def file_name - @_file_name ||= super.gsub(/_mailer/i, '') + @_file_name ||= super.gsub(/_mailer/i, "") end end end diff --git a/railties/lib/rails/generators/test_unit/model/model_generator.rb b/railties/lib/rails/generators/test_unit/model/model_generator.rb index 086588750e..99495d5247 100644 --- a/railties/lib/rails/generators/test_unit/model/model_generator.rb +++ b/railties/lib/rails/generators/test_unit/model/model_generator.rb @@ -1,9 +1,8 @@ -require 'rails/generators/test_unit' +require "rails/generators/test_unit" module TestUnit # :nodoc: module Generators # :nodoc: class ModelGenerator < Base # :nodoc: - RESERVED_YAML_KEYWORDS = %w(y yes n no true false on off null) argument :attributes, type: :array, default: [], banner: "field:type field:type" @@ -12,14 +11,14 @@ module TestUnit # :nodoc: check_class_collision suffix: "Test" def create_test_file - template 'unit_test.rb', File.join('test/models', class_path, "#{file_name}_test.rb") + template "unit_test.rb", File.join("test/models", class_path, "#{file_name}_test.rb") end hook_for :fixture_replacement def create_fixture_file if options[:fixture] && options[:fixture_replacement].nil? - template 'fixtures.yml', File.join('test/fixtures', class_path, "#{fixture_file_name}.yml") + template "fixtures.yml", File.join("test/fixtures", class_path, "#{fixture_file_name}.yml") end end diff --git a/railties/lib/rails/generators/test_unit/plugin/plugin_generator.rb b/railties/lib/rails/generators/test_unit/plugin/plugin_generator.rb index b5d4f38444..f1c9b6da5b 100644 --- a/railties/lib/rails/generators/test_unit/plugin/plugin_generator.rb +++ b/railties/lib/rails/generators/test_unit/plugin/plugin_generator.rb @@ -1,4 +1,4 @@ -require 'rails/generators/test_unit' +require "rails/generators/test_unit" module TestUnit # :nodoc: module Generators # :nodoc: @@ -6,7 +6,7 @@ module TestUnit # :nodoc: check_class_collision suffix: "Test" def create_test_files - directory '.', 'test' + directory ".", "test" end end end diff --git a/railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb b/railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb index 0171da7cc7..8840a86d0d 100644 --- a/railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb +++ b/railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb @@ -1,5 +1,5 @@ -require 'rails/generators/test_unit' -require 'rails/generators/resource_helpers' +require "rails/generators/test_unit" +require "rails/generators/resource_helpers" module TestUnit # :nodoc: module Generators # :nodoc: @@ -39,7 +39,7 @@ module TestUnit # :nodoc: else "#{name}: @#{singular_table_name}.#{name}" end - end.sort.join(', ') + end.sort.join(", ") end end end diff --git a/railties/lib/rails/generators/testing/assertions.rb b/railties/lib/rails/generators/testing/assertions.rb index 76758df86d..1cabf4e28c 100644 --- a/railties/lib/rails/generators/testing/assertions.rb +++ b/railties/lib/rails/generators/testing/assertions.rb @@ -29,10 +29,10 @@ module Rails contents.each do |content| case content - when String - assert_equal content, read - when Regexp - assert_match content, read + when String + assert_equal content, read + when Regexp + assert_match content, read end end end diff --git a/railties/lib/rails/generators/testing/behaviour.rb b/railties/lib/rails/generators/testing/behaviour.rb index 94b5e52224..64d641d096 100644 --- a/railties/lib/rails/generators/testing/behaviour.rb +++ b/railties/lib/rails/generators/testing/behaviour.rb @@ -1,10 +1,10 @@ -require 'active_support/core_ext/class/attribute' -require 'active_support/core_ext/module/delegation' -require 'active_support/core_ext/hash/reverse_merge' -require 'active_support/core_ext/kernel/reporting' -require 'active_support/testing/stream' -require 'active_support/concern' -require 'rails/generators' +require "active_support/core_ext/class/attribute" +require "active_support/core_ext/module/delegation" +require "active_support/core_ext/hash/reverse_merge" +require "active_support/core_ext/kernel/reporting" +require "active_support/testing/stream" +require "active_support/concern" +require "rails/generators" module Rails module Generators @@ -62,48 +62,47 @@ module Rails # # You can provide a configuration hash as second argument. This method returns the output # printed by the generator. - def run_generator(args=self.default_arguments, config={}) + def run_generator(args = default_arguments, config = {}) capture(:stdout) do - args += ['--skip-bundle'] unless args.include? '--dev' - self.generator_class.start(args, config.reverse_merge(destination_root: destination_root)) + args += ["--skip-bundle"] unless args.include? "--dev" + generator_class.start(args, config.reverse_merge(destination_root: destination_root)) end end # Instantiate the generator. - def generator(args=self.default_arguments, options={}, config={}) - @generator ||= self.generator_class.new(args, options, config.reverse_merge(destination_root: destination_root)) + def generator(args = default_arguments, options = {}, config = {}) + @generator ||= generator_class.new(args, options, config.reverse_merge(destination_root: destination_root)) end # Create a Rails::Generators::GeneratedAttribute by supplying the # attribute type and, optionally, the attribute name: # # create_generated_attribute(:string, 'name') - def create_generated_attribute(attribute_type, name = 'test', index = nil) - Rails::Generators::GeneratedAttribute.parse([name, attribute_type, index].compact.join(':')) + def create_generated_attribute(attribute_type, name = "test", index = nil) + Rails::Generators::GeneratedAttribute.parse([name, attribute_type, index].compact.join(":")) end - protected + private - def destination_root_is_set? # :nodoc: + def destination_root_is_set? raise "You need to configure your Rails::Generators::TestCase destination root." unless destination_root end - def ensure_current_path # :nodoc: + def ensure_current_path cd current_path end # Clears all files and directories in destination. - def prepare_destination + def prepare_destination # :doc: rm_rf(destination_root) mkdir_p(destination_root) end - def migration_file_name(relative) # :nodoc: + def migration_file_name(relative) absolute = File.expand_path(relative, destination_root) - dirname, file_name = File.dirname(absolute), File.basename(absolute).sub(/\.rb$/, '') + dirname, file_name = File.dirname(absolute), File.basename(absolute).sub(/\.rb$/, "") Dir.glob("#{dirname}/[0-9]*_*.rb").grep(/\d+_#{file_name}.rb$/).first end - end end end diff --git a/railties/lib/rails/info.rb b/railties/lib/rails/info.rb index 5909446b66..5d4acd6f6b 100644 --- a/railties/lib/rails/info.rb +++ b/railties/lib/rails/info.rb @@ -38,64 +38,64 @@ module Rails alias inspect to_s def to_html - '<table>'.tap do |table| + "<table>".tap do |table| properties.each do |(name, value)| table << %(<tr><td class="name">#{CGI.escapeHTML(name.to_s)}</td>) formatted_value = if value.kind_of?(Array) - "<ul>" + value.map { |v| "<li>#{CGI.escapeHTML(v.to_s)}</li>" }.join + "</ul>" - else - CGI.escapeHTML(value.to_s) - end + "<ul>" + value.map { |v| "<li>#{CGI.escapeHTML(v.to_s)}</li>" }.join + "</ul>" + else + CGI.escapeHTML(value.to_s) + end table << %(<td class="value">#{formatted_value}</td></tr>) end - table << '</table>' + table << "</table>" end end end # The Rails version. - property 'Rails version' do + property "Rails version" do Rails.version.to_s end # The Ruby version and platform, e.g. "2.0.0-p247 (x86_64-darwin12.4.0)". - property 'Ruby version' do + property "Ruby version" do "#{RUBY_VERSION}-p#{RUBY_PATCHLEVEL} (#{RUBY_PLATFORM})" end # The RubyGems version, if it's installed. - property 'RubyGems version' do + property "RubyGems version" do Gem::RubyGemsVersion end - property 'Rack version' do + property "Rack version" do ::Rack.release end - property 'JavaScript Runtime' do + property "JavaScript Runtime" do ExecJS.runtime.name end - property 'Middleware' do + property "Middleware" do Rails.configuration.middleware.map(&:inspect) end # The application's location on the filesystem. - property 'Application root' do + property "Application root" do File.expand_path(Rails.root) end # The current Rails environment (development, test, or production). - property 'Environment' do + property "Environment" do Rails.env end # The name of the database adapter for the current environment. - property 'Database adapter' do - ActiveRecord::Base.configurations[Rails.env]['adapter'] + property "Database adapter" do + ActiveRecord::Base.configurations[Rails.env]["adapter"] end - property 'Database schema version' do + property "Database schema version" do ActiveRecord::Migrator.current_version rescue nil end end diff --git a/railties/lib/rails/info_controller.rb b/railties/lib/rails/info_controller.rb index 778105c5f7..8b553aea79 100644 --- a/railties/lib/rails/info_controller.rb +++ b/railties/lib/rails/info_controller.rb @@ -1,9 +1,9 @@ -require 'rails/application_controller' -require 'action_dispatch/routing/inspector' +require "rails/application_controller" +require "action_dispatch/routing/inspector" class Rails::InfoController < Rails::ApplicationController # :nodoc: prepend_view_path ActionDispatch::DebugExceptions::RESCUES_TEMPLATE_PATH - layout -> { request.xhr? ? false : 'application' } + layout -> { request.xhr? ? false : "application" } before_action :require_local! @@ -13,7 +13,7 @@ class Rails::InfoController < Rails::ApplicationController # :nodoc: def properties @info = Rails::Info.to_html - @page_title = 'Properties' + @page_title = "Properties" end def routes @@ -21,24 +21,24 @@ class Rails::InfoController < Rails::ApplicationController # :nodoc: path = URI.parser.escape path normalized_path = with_leading_slash path render json: { - exact: match_route {|it| it.match normalized_path }, - fuzzy: match_route {|it| it.spec.to_s.match path } + exact: match_route { |it| it.match normalized_path }, + fuzzy: match_route { |it| it.spec.to_s.match path } } else @routes_inspector = ActionDispatch::Routing::RoutesInspector.new(_routes.routes) - @page_title = 'Routes' + @page_title = "Routes" end end private - def match_route - _routes.routes.select {|route| - yield route.path - }.map {|route| route.path.spec.to_s } - end + def match_route + _routes.routes.select { |route| + yield route.path + }.map { |route| route.path.spec.to_s } + end - def with_leading_slash(path) - ('/' + path).squeeze('/') - end + def with_leading_slash(path) + ("/" + path).squeeze("/") + end end diff --git a/railties/lib/rails/initializable.rb b/railties/lib/rails/initializable.rb index 1a0b6d1e1a..a2615d5efd 100644 --- a/railties/lib/rails/initializable.rb +++ b/railties/lib/rails/initializable.rb @@ -1,4 +1,4 @@ -require 'tsort' +require "tsort" module Rails module Initializable @@ -34,6 +34,10 @@ module Rails return self if @context Initializer.new(@name, context, @options, &block) end + + def context_class + @context.class + end end class Collection < Array @@ -49,7 +53,7 @@ module Rails end end - def run_initializers(group=:default, *args) + def run_initializers(group = :default, *args) return if instance_variable_defined?(:@ran) initializers.tsort_each do |initializer| initializer.run(*args) if initializer.belongs_to?(group) diff --git a/railties/lib/rails/mailers_controller.rb b/railties/lib/rails/mailers_controller.rb index 6143cf2dd9..000ce40fbc 100644 --- a/railties/lib/rails/mailers_controller.rb +++ b/railties/lib/rails/mailers_controller.rb @@ -1,4 +1,4 @@ -require 'rails/application_controller' +require "rails/application_controller" class Rails::MailersController < Rails::ApplicationController # :nodoc: prepend_view_path ActionDispatch::DebugExceptions::RESCUES_TEMPLATE_PATH @@ -14,7 +14,7 @@ class Rails::MailersController < Rails::ApplicationController # :nodoc: def preview if params[:path] == @preview.preview_name @page_title = "Mailer Previews for #{@preview.preview_name}" - render action: 'mailer' + render action: "mailer" else @email_action = File.basename(params[:path]) @@ -32,7 +32,7 @@ class Rails::MailersController < Rails::ApplicationController # :nodoc: end else @part = find_preferred_part(request.format, Mime[:html], Mime[:text]) - render action: 'email', layout: false, formats: %w[html] + render action: "email", layout: false, formats: %w[html] end else raise AbstractController::ActionNotFound, "Email '#{@email_action}' not found in #{@preview.name}" @@ -40,15 +40,15 @@ class Rails::MailersController < Rails::ApplicationController # :nodoc: end end - protected - def show_previews? + private + def show_previews? # :doc: ActionMailer::Base.show_previews end - def find_preview + def find_preview # :doc: candidates = [] - params[:path].to_s.scan(%r{/|$}){ candidates << $` } - preview = candidates.detect{ |candidate| ActionMailer::Preview.exists?(candidate) } + params[:path].to_s.scan(%r{/|$}) { candidates << $` } + preview = candidates.detect { |candidate| ActionMailer::Preview.exists?(candidate) } if preview @preview = ActionMailer::Preview.find(preview) @@ -57,19 +57,19 @@ class Rails::MailersController < Rails::ApplicationController # :nodoc: end end - def find_preferred_part(*formats) + def find_preferred_part(*formats) # :doc: formats.each do |format| if part = @email.find_first_mime_type(format) return part end end - if formats.any?{ |f| @email.mime_type == f } + if formats.any? { |f| @email.mime_type == f } @email end end - def find_part(format) + def find_part(format) # :doc: if part = @email.find_first_mime_type(format) part elsif @email.mime_type == format diff --git a/railties/lib/rails/paths.rb b/railties/lib/rails/paths.rb index e47616a87f..10925de8b2 100644 --- a/railties/lib/rails/paths.rb +++ b/railties/lib/rails/paths.rb @@ -30,7 +30,7 @@ module Rails # root["config/routes"].inspect # => ["config/routes.rb"] # # The +add+ method accepts the following options as arguments: - # eager_load, autoload, autoload_once and glob. + # eager_load, autoload, autoload_once, and glob. # # Finally, the +Path+ object also provides a few helpers: # @@ -45,7 +45,6 @@ module Rails attr_accessor :path def initialize(path) - @current = nil @path = path @root = {} end @@ -180,7 +179,7 @@ module Rails end def extensions # :nodoc: - $1.split(',') if @glob =~ /\{([\S]+)\}/ + $1.split(",") if @glob =~ /\{([\S]+)\}/ end # Expands all paths against the root and return all unique values. diff --git a/railties/lib/rails/rack/debugger.rb b/railties/lib/rails/rack/debugger.rb index 1fde3db070..dccfa3e9bb 100644 --- a/railties/lib/rails/rack/debugger.rb +++ b/railties/lib/rails/rack/debugger.rb @@ -1,3 +1,3 @@ -require 'active_support/deprecation' +require "active_support/deprecation" ActiveSupport::Deprecation.warn("This file is deprecated and will be removed in Rails 5.1 with no replacement.") diff --git a/railties/lib/rails/rack/logger.rb b/railties/lib/rails/rack/logger.rb index b63d3a58d2..853fc26051 100644 --- a/railties/lib/rails/rack/logger.rb +++ b/railties/lib/rails/rack/logger.rb @@ -1,8 +1,8 @@ -require 'active_support/core_ext/time/conversions' -require 'active_support/core_ext/object/blank' -require 'active_support/log_subscriber' -require 'action_dispatch/http/request' -require 'rack/body_proxy' +require "active_support/core_ext/time/conversions" +require "active_support/core_ext/object/blank" +require "active_support/log_subscriber" +require "action_dispatch/http/request" +require "rack/body_proxy" module Rails module Rack @@ -27,54 +27,52 @@ module Rails end end - protected + private - def call_app(request, env) - instrumenter = ActiveSupport::Notifications.instrumenter - instrumenter.start 'request.action_dispatch', request: request - logger.info { started_request_message(request) } - resp = @app.call(env) - resp[2] = ::Rack::BodyProxy.new(resp[2]) { finish(request) } - resp - rescue Exception - finish(request) - raise - ensure - ActiveSupport::LogSubscriber.flush_all! - end + def call_app(request, env) # :doc: + instrumenter = ActiveSupport::Notifications.instrumenter + instrumenter.start "request.action_dispatch", request: request + logger.info { started_request_message(request) } + resp = @app.call(env) + resp[2] = ::Rack::BodyProxy.new(resp[2]) { finish(request) } + resp + rescue Exception + finish(request) + raise + ensure + ActiveSupport::LogSubscriber.flush_all! + end - # Started GET "/session/new" for 127.0.0.1 at 2012-09-26 14:51:42 -0700 - def started_request_message(request) - 'Started %s "%s" for %s at %s' % [ - request.request_method, - request.filtered_path, - request.ip, - Time.now.to_default_s ] - end + # Started GET "/session/new" for 127.0.0.1 at 2012-09-26 14:51:42 -0700 + def started_request_message(request) # :doc: + 'Started %s "%s" for %s at %s' % [ + request.request_method, + request.filtered_path, + request.ip, + Time.now.to_default_s ] + end - def compute_tags(request) - @taggers.collect do |tag| - case tag - when Proc - tag.call(request) - when Symbol - request.send(tag) - else - tag + def compute_tags(request) # :doc: + @taggers.collect do |tag| + case tag + when Proc + tag.call(request) + when Symbol + request.send(tag) + else + tag + end end end - end - private - - def finish(request) - instrumenter = ActiveSupport::Notifications.instrumenter - instrumenter.finish 'request.action_dispatch', request: request - end + def finish(request) + instrumenter = ActiveSupport::Notifications.instrumenter + instrumenter.finish "request.action_dispatch", request: request + end - def logger - Rails.logger - end + def logger + Rails.logger + end end end end diff --git a/railties/lib/rails/railtie.rb b/railties/lib/rails/railtie.rb index 492c519222..474118c0a9 100644 --- a/railties/lib/rails/railtie.rb +++ b/railties/lib/rails/railtie.rb @@ -1,7 +1,7 @@ -require 'rails/initializable' -require 'active_support/inflector' -require 'active_support/core_ext/module/introspection' -require 'active_support/core_ext/module/delegation' +require "rails/initializable" +require "active_support/inflector" +require "active_support/core_ext/module/introspection" +require "active_support/core_ext/module/delegation" module Rails # <tt>Rails::Railtie</tt> is the core of the Rails framework and provides @@ -111,7 +111,7 @@ module Rails # # Be sure to look at the documentation of those specific classes for more information. class Railtie - autoload :Configuration, 'rails/railtie/configuration' + autoload :Configuration, "rails/railtie/configuration" include Initializable @@ -132,27 +132,19 @@ module Rails end def rake_tasks(&blk) - @rake_tasks ||= [] - @rake_tasks << blk if blk - @rake_tasks + register_block_for(:rake_tasks, &blk) end def console(&blk) - @load_console ||= [] - @load_console << blk if blk - @load_console + register_block_for(:load_console, &blk) end def runner(&blk) - @load_runner ||= [] - @load_runner << blk if blk - @load_runner + register_block_for(:runner, &blk) end def generators(&blk) - @generators ||= [] - @generators << blk if blk - @generators + register_block_for(:generators, &blk) end def abstract_railtie? @@ -181,8 +173,8 @@ module Rails instance.configure(&block) end - protected - def generate_railtie_name(string) #:nodoc: + private + def generate_railtie_name(string) ActiveSupport::Inflector.underscore(string).tr("/", "_") end @@ -195,6 +187,16 @@ module Rails super end end + + # receives an instance variable identifier, set the variable value if is + # blank and append given block to value, which will be used later in + # `#each_registered_block(type, &block)` + def register_block_for(type, &blk) + var_name = "@#{type}" + blocks = instance_variable_defined?(var_name) ? instance_variable_get(var_name) : instance_variable_set(var_name, []) + blocks << blk if blk + blocks + end end delegate :railtie_name, to: :class @@ -222,31 +224,32 @@ module Rails protected - def run_console_blocks(app) #:nodoc: - each_registered_block(:console) { |block| block.call(app) } - end + def run_console_blocks(app) #:nodoc: + each_registered_block(:console) { |block| block.call(app) } + end - def run_generators_blocks(app) #:nodoc: - each_registered_block(:generators) { |block| block.call(app) } - end + def run_generators_blocks(app) #:nodoc: + each_registered_block(:generators) { |block| block.call(app) } + end - def run_runner_blocks(app) #:nodoc: - each_registered_block(:runner) { |block| block.call(app) } - end + def run_runner_blocks(app) #:nodoc: + each_registered_block(:runner) { |block| block.call(app) } + end - def run_tasks_blocks(app) #:nodoc: - extend Rake::DSL - each_registered_block(:rake_tasks) { |block| instance_exec(app, &block) } - end + def run_tasks_blocks(app) #:nodoc: + extend Rake::DSL + each_registered_block(:rake_tasks) { |block| instance_exec(app, &block) } + end private - def each_registered_block(type, &block) - klass = self.class - while klass.respond_to?(type) - klass.public_send(type).each(&block) - klass = klass.superclass + # run `&block` in every registered block in `#register_block_for` + def each_registered_block(type, &block) + klass = self.class + while klass.respond_to?(type) + klass.public_send(type).each(&block) + klass = klass.superclass + end end - end end end diff --git a/railties/lib/rails/railtie/configurable.rb b/railties/lib/rails/railtie/configurable.rb index 1572af0b2a..2a8295426e 100644 --- a/railties/lib/rails/railtie/configurable.rb +++ b/railties/lib/rails/railtie/configurable.rb @@ -1,4 +1,4 @@ -require 'active_support/concern' +require "active_support/concern" module Rails class Railtie @@ -9,7 +9,7 @@ module Rails delegate :config, to: :instance def inherited(base) - raise "You cannot inherit from a #{self.superclass.name} child" + raise "You cannot inherit from a #{superclass.name} child" end def instance @@ -24,11 +24,11 @@ module Rails class_eval(&block) end - protected + private - def method_missing(*args, &block) - instance.send(*args, &block) - end + def method_missing(*args, &block) + instance.send(*args, &block) + end end end end diff --git a/railties/lib/rails/railtie/configuration.rb b/railties/lib/rails/railtie/configuration.rb index eb3b2d8ef4..aecc81c491 100644 --- a/railties/lib/rails/railtie/configuration.rb +++ b/railties/lib/rails/railtie/configuration.rb @@ -1,4 +1,4 @@ -require 'rails/configuration' +require "rails/configuration" module Rails class Railtie diff --git a/railties/lib/rails/ruby_version_check.rb b/railties/lib/rails/ruby_version_check.rb index 67a19d8a94..b212835df7 100644 --- a/railties/lib/rails/ruby_version_check.rb +++ b/railties/lib/rails/ruby_version_check.rb @@ -1,4 +1,4 @@ -if RUBY_VERSION < '2.2.2' && RUBY_ENGINE == 'ruby' +if RUBY_VERSION < "2.2.2" && RUBY_ENGINE == "ruby" desc = defined?(RUBY_DESCRIPTION) ? RUBY_DESCRIPTION : "ruby #{RUBY_VERSION} (#{RUBY_RELEASE_DATE})" abort <<-end_message diff --git a/railties/lib/rails/source_annotation_extractor.rb b/railties/lib/rails/source_annotation_extractor.rb index 8dd87b6cc5..3a48c4c496 100644 --- a/railties/lib/rails/source_annotation_extractor.rb +++ b/railties/lib/rails/source_annotation_extractor.rb @@ -1,9 +1,9 @@ # Implements the logic behind the rake tasks for annotations like # -# rake notes -# rake notes:optimize +# rails notes +# rails notes:optimize # -# and friends. See <tt>rake -T notes</tt> and <tt>railties/lib/rails/tasks/annotations.rake</tt>. +# and friends. See <tt>rails -T notes</tt> and <tt>railties/lib/rails/tasks/annotations.rake</tt>. # # Annotation objects are triplets <tt>:line</tt>, <tt>:tag</tt>, <tt>:text</tt> that # represent the line where the annotation lives, its tag, and its text. Note @@ -15,7 +15,13 @@ class SourceAnnotationExtractor class Annotation < Struct.new(:line, :tag, :text) def self.directories - @@directories ||= %w(app config db lib test) + (ENV['SOURCE_ANNOTATION_DIRECTORIES'] || '').split(',') + @@directories ||= %w(app config db lib test) + (ENV["SOURCE_ANNOTATION_DIRECTORIES"] || "").split(",") + end + + # Registers additional directories to be included + # SourceAnnotationExtractor::Annotation.register_directories("spec","another") + def self.register_directories(*dirs) + directories.push(*dirs) end def self.extensions @@ -38,7 +44,7 @@ class SourceAnnotationExtractor # # If +options+ has a flag <tt>:tag</tt> the tag is shown as in the example above. # Otherwise the string contains just line and text. - def to_s(options={}) + def to_s(options = {}) s = "[#{line.to_s.rjust(options[:indent])}] " s << "[#{tag}] " if options[:tag] s << text @@ -60,7 +66,7 @@ class SourceAnnotationExtractor # See <tt>#find_in</tt> for a list of file extensions that will be taken into account. # # This class method is the single entry point for the rake tasks. - def self.enumerate(tag, options={}) + def self.enumerate(tag, options = {}) extractor = new(tag) dirs = options.delete(:dirs) || Annotation.directories extractor.display(extractor.find(dirs), options) @@ -110,7 +116,7 @@ class SourceAnnotationExtractor # Otherwise it returns an empty hash. def extract_annotations_from(file, pattern) lineno = 0 - result = File.readlines(file).inject([]) do |list, line| + result = File.readlines(file, encoding: Encoding::BINARY).inject([]) do |list, line| lineno += 1 next list unless line =~ pattern list << Annotation.new(lineno, $1, $2) @@ -120,7 +126,7 @@ class SourceAnnotationExtractor # Prints the mapping from filenames to annotations in +results+ ordered by filename. # The +options+ hash is passed to each annotation's +to_s+. - def display(results, options={}) + def display(results, options = {}) options[:indent] = results.flat_map { |f, a| a.map(&:line) }.max.to_s.size results.keys.sort.each do |file| puts "#{file}:" diff --git a/railties/lib/rails/tasks.rb b/railties/lib/rails/tasks.rb index d3e33584d7..48675b3845 100644 --- a/railties/lib/rails/tasks.rb +++ b/railties/lib/rails/tasks.rb @@ -1,4 +1,4 @@ -require 'rake' +require "rake" # Load Rails Rakefile extensions %w( @@ -13,7 +13,7 @@ require 'rake' routes tmp ).tap { |arr| - arr << 'statistics' if Rake.application.current_scope.empty? + arr << "statistics" if Rake.application.current_scope.empty? }.each do |task| load "rails/tasks/#{task}.rake" end diff --git a/railties/lib/rails/tasks/annotations.rake b/railties/lib/rails/tasks/annotations.rake index 386ecf44be..9a69eb9934 100644 --- a/railties/lib/rails/tasks/annotations.rake +++ b/railties/lib/rails/tasks/annotations.rake @@ -1,4 +1,4 @@ -require 'rails/source_annotation_extractor' +require "rails/source_annotation_extractor" desc "Enumerate all annotations (use notes:optimize, :fixme, :todo for focus)" task :notes do @@ -15,6 +15,6 @@ namespace :notes do desc "Enumerate a custom annotation, specify with ANNOTATION=CUSTOM" task :custom do - SourceAnnotationExtractor.enumerate ENV['ANNOTATION'] + SourceAnnotationExtractor.enumerate ENV["ANNOTATION"] end -end
\ No newline at end of file +end diff --git a/railties/lib/rails/tasks/dev.rake b/railties/lib/rails/tasks/dev.rake index d2ceaacc0c..334e968123 100644 --- a/railties/lib/rails/tasks/dev.rake +++ b/railties/lib/rails/tasks/dev.rake @@ -1,7 +1,7 @@ -require 'rails/dev_caching' +require "rails/dev_caching" namespace :dev do - desc 'Toggle development mode caching on/off' + desc "Toggle development mode caching on/off" task :cache do Rails::DevCaching.enable_by_file end diff --git a/railties/lib/rails/tasks/engine.rake b/railties/lib/rails/tasks/engine.rake index e678103f63..c92b42f6c1 100644 --- a/railties/lib/rails/tasks/engine.rake +++ b/railties/lib/rails/tasks/engine.rake @@ -2,7 +2,7 @@ task "load_app" do namespace :app do load APP_RAKEFILE end - task :environment => "app:environment" + task environment: "app:environment" if !defined?(ENGINE_ROOT) || !ENGINE_ROOT ENGINE_ROOT = find_engine_path(APP_RAKEFILE) @@ -26,11 +26,11 @@ namespace :db do desc "Display status of migrations" app_task "migrate:status" - desc 'Create the database from config/database.yml for the current Rails.env (use db:create:all to create all databases in the config)' + desc "Create the database from config/database.yml for the current Rails.env (use db:create:all to create all databases in the config)" app_task "create" app_task "create:all" - desc 'Drops the database for the current Rails.env (use db:drop:all to drop all databases)' + desc "Drops the database for the current Rails.env (use db:drop:all to drop all databases)" app_task "drop" app_task "drop:all" @@ -65,7 +65,7 @@ def find_engine_path(path) if Rails::Engine.find(path) path else - find_engine_path(File.expand_path('..', path)) + find_engine_path(File.expand_path("..", path)) end end diff --git a/railties/lib/rails/tasks/framework.rake b/railties/lib/rails/tasks/framework.rake index 51d9daaaa9..a2167796eb 100644 --- a/railties/lib/rails/tasks/framework.rake +++ b/railties/lib/rails/tasks/framework.rake @@ -1,16 +1,16 @@ -require 'active_support/deprecation' +require "active_support/deprecation" namespace :app do desc "Update configs and some other initially generated files (or use just update:configs or update:bin)" - task update: [ "update:configs", "update:bin" ] + task update: [ "update:configs", "update:bin", "update:upgrade_guide_info" ] desc "Applies the template supplied by LOCATION=(/path/to/template) or URL" task template: :environment do template = ENV["LOCATION"] raise "No LOCATION value given. Please set LOCATION either as path to a file or a URL" if template.blank? template = File.expand_path(template) if template !~ %r{\A[A-Za-z][A-Za-z0-9+\-\.]*://} - require 'rails/generators' - require 'rails/generators/rails/app/app_generator' + require "rails/generators" + require "rails/generators/rails/app/app_generator" generator = Rails::Generators::AppGenerator.new [Rails.root], {}, destination_root: Rails.root generator.apply template, verbose: false end @@ -45,8 +45,8 @@ namespace :app do def self.app_generator @app_generator ||= begin - require 'rails/generators' - require 'rails/generators/rails/app/app_generator' + require "rails/generators" + require "rails/generators/rails/app/app_generator" gen = Rails::Generators::AppGenerator.new ["rails"], { api: !!Rails.application.config.api_only, update: true }, destination_root: Rails.root @@ -67,6 +67,10 @@ namespace :app do task :bin do RailsUpdate.invoke_from_app_generator :create_bin_files end + + task :upgrade_guide_info do + RailsUpdate.invoke_from_app_generator :display_upgrade_guide_info + end end end diff --git a/railties/lib/rails/tasks/initializers.rake b/railties/lib/rails/tasks/initializers.rake index 2968b5cb53..6522f2ae5a 100644 --- a/railties/lib/rails/tasks/initializers.rake +++ b/railties/lib/rails/tasks/initializers.rake @@ -1,6 +1,6 @@ desc "Print out all defined initializers in the order they are invoked by Rails." task initializers: :environment do Rails.application.initializers.tsort_each do |initializer| - puts initializer.name + puts "#{initializer.context_class}.#{initializer.name}" end end diff --git a/railties/lib/rails/tasks/log.rake b/railties/lib/rails/tasks/log.rake index 073f235ec5..ba796845d7 100644 --- a/railties/lib/rails/tasks/log.rake +++ b/railties/lib/rails/tasks/log.rake @@ -1,9 +1,9 @@ namespace :log do - - ## + + ## # Truncates all/specified log files - # ENV['LOGS'] - # - defaults to standard environment log files i.e. 'development,test,production' + # ENV['LOGS'] + # - defaults to all environments log files i.e. 'development,test,production' # - ENV['LOGS']=all truncates all files i.e. log/*.log # - ENV['LOGS']='test,development' truncates only specified files desc "Truncates all/specified *.log files in log/ to zero bytes (specify which logs with LOGS=test,development)" @@ -14,23 +14,27 @@ namespace :log do end def log_files - if ENV['LOGS'] == 'all' + if ENV["LOGS"] == "all" FileList["log/*.log"] - elsif ENV['LOGS'] - log_files_to_truncate(ENV['LOGS']) + elsif ENV["LOGS"] + log_files_to_truncate(ENV["LOGS"]) else - log_files_to_truncate("development,test,production") + log_files_to_truncate(all_environments.join(",")) end end def log_files_to_truncate(envs) - envs.split(',') + envs.split(",") .map { |file| "log/#{file.strip}.log" } .select { |file| File.exist?(file) } end - + def clear_log_file(file) f = File.open(file, "w") f.close end + + def all_environments + Dir["config/environments/*.rb"].map { |fname| File.basename(fname, ".*") } + end end diff --git a/railties/lib/rails/tasks/middleware.rake b/railties/lib/rails/tasks/middleware.rake index 31e961b483..fd98be1ea9 100644 --- a/railties/lib/rails/tasks/middleware.rake +++ b/railties/lib/rails/tasks/middleware.rake @@ -1,4 +1,4 @@ -desc 'Prints out your Rack middleware stack' +desc "Prints out your Rack middleware stack" task middleware: :environment do Rails.configuration.middleware.each do |middleware| puts "use #{middleware.inspect}" diff --git a/railties/lib/rails/tasks/misc.rake b/railties/lib/rails/tasks/misc.rake index e6b13cc077..29ea0ff804 100644 --- a/railties/lib/rails/tasks/misc.rake +++ b/railties/lib/rails/tasks/misc.rake @@ -1,16 +1,16 @@ -desc 'Generate a cryptographically secure secret key (this is typically used to generate a secret for cookie sessions).' +desc "Generate a cryptographically secure secret key (this is typically used to generate a secret for cookie sessions)." task :secret do - require 'securerandom' + require "securerandom" puts SecureRandom.hex(64) end -desc 'List versions of all Rails frameworks and the environment' +desc "List versions of all Rails frameworks and the environment" task about: :environment do puts Rails::Info end namespace :time do - desc 'List all time zones, list by two-letter country code (`rails time:zones[US]`), or list by UTC offset (`rails time:zones[-8]`)' + desc "List all time zones, list by two-letter country code (`rails time:zones[US]`), or list by UTC offset (`rails time:zones[-8]`)" task :zones, :country_or_offset do |t, args| zones, offset = ActiveSupport::TimeZone.all, nil @@ -38,8 +38,8 @@ namespace :time do # desc 'Displays names of time zones recognized by the Rails TimeZone class with the same offset as the system local time' task :local do - require 'active_support' - require 'active_support/time' + require "active_support" + require "active_support/time" jan_offset = Time.now.beginning_of_year.utc_offset jul_offset = Time.now.beginning_of_year.change(month: 7).utc_offset @@ -49,12 +49,12 @@ namespace :time do end # to find UTC -06:00 zones, OFFSET can be set to either -6, -6:00 or 21600 - def build_time_zone_list(zones, offset = ENV['OFFSET']) - require 'active_support' - require 'active_support/time' + def build_time_zone_list(zones, offset = ENV["OFFSET"]) + require "active_support" + require "active_support/time" if offset offset = if offset.to_s.match(/(\+|-)?(\d+):(\d+)/) - sign = $1 == '-' ? -1 : 1 + sign = $1 == "-" ? -1 : 1 hours, minutes = $2.to_f, $3.to_f ((hours * 3600) + (minutes.to_f * 60)) * sign elsif offset.to_f.abs <= 13 diff --git a/railties/lib/rails/tasks/restart.rake b/railties/lib/rails/tasks/restart.rake index 3f98cbe51f..03177d9954 100644 --- a/railties/lib/rails/tasks/restart.rake +++ b/railties/lib/rails/tasks/restart.rake @@ -1,8 +1,8 @@ -desc 'Restart app by touching tmp/restart.txt' +desc "Restart app by touching tmp/restart.txt" task :restart do verbose(false) do - mkdir_p 'tmp' - touch 'tmp/restart.txt' - rm_f 'tmp/pids/server.pid' + mkdir_p "tmp" + touch "tmp/restart.txt" + rm_f "tmp/pids/server.pid" end end diff --git a/railties/lib/rails/tasks/routes.rake b/railties/lib/rails/tasks/routes.rake index ff7233cae9..f5e5b9ae87 100644 --- a/railties/lib/rails/tasks/routes.rake +++ b/railties/lib/rails/tasks/routes.rake @@ -1,13 +1,13 @@ -require 'active_support/deprecation' -require 'active_support/core_ext/string/strip' # for strip_heredoc -require 'optparse' +require "active_support/deprecation" +require "active_support/core_ext/string/strip" # for strip_heredoc +require "optparse" -desc 'Print out all defined routes in match order, with names. Target specific controller with -c option, or grep routes using -g option' +desc "Print out all defined routes in match order, with names. Target specific controller with -c option, or grep routes using -g option" task routes: :environment do all_routes = Rails.application.routes.routes - require 'action_dispatch/routing/inspector' + require "action_dispatch/routing/inspector" inspector = ActionDispatch::Routing::RoutesInspector.new(all_routes) - if ARGV.any?{ |argv| argv.start_with? 'CONTROLLER' } + if ARGV.any? { |argv| argv.start_with? "CONTROLLER" } puts <<-eow.strip_heredoc Passing `CONTROLLER` to `bin/rails routes` is deprecated and will be removed in Rails 5.1. Please use `bin/rails routes -c controller_name` instead. @@ -15,7 +15,7 @@ task routes: :environment do end routes_filter = nil - routes_filter = { controller: ENV['CONTROLLER'] } if ENV['CONTROLLER'] + routes_filter = { controller: ENV["CONTROLLER"] } if ENV["CONTROLLER"] OptionParser.new do |opts| opts.banner = "Usage: rails routes [options]" diff --git a/railties/lib/rails/tasks/statistics.rake b/railties/lib/rails/tasks/statistics.rake index 3e40d3b037..ba1697186e 100644 --- a/railties/lib/rails/tasks/statistics.rake +++ b/railties/lib/rails/tasks/statistics.rake @@ -8,9 +8,8 @@ STATS_DIRECTORIES = [ %w(Models app/models), %w(Mailers app/mailers), %w(Channels app/channels), - %w(Javascripts app/assets/javascripts), + %w(JavaScripts app/assets/javascripts), %w(Libraries lib/), - %w(Tasks lib/tasks), %w(APIs app/apis), %w(Controller\ tests test/controllers), %w(Helper\ tests test/helpers), @@ -24,6 +23,6 @@ end.select { |name, dir| File.directory?(dir) } desc "Report code statistics (KLOCs, etc) from the application or engine" task :stats do - require 'rails/code_statistics' + require "rails/code_statistics" CodeStatistics.new(*STATS_DIRECTORIES).to_s end diff --git a/railties/lib/rails/tasks/tmp.rake b/railties/lib/rails/tasks/tmp.rake index c74a17a0ca..d42a890cb6 100644 --- a/railties/lib/rails/tasks/tmp.rake +++ b/railties/lib/rails/tasks/tmp.rake @@ -2,10 +2,10 @@ namespace :tmp do desc "Clear cache and socket files from tmp/ (narrow w/ tmp:cache:clear, tmp:sockets:clear)" task clear: ["tmp:cache:clear", "tmp:sockets:clear"] - tmp_dirs = [ 'tmp/cache', - 'tmp/sockets', - 'tmp/pids', - 'tmp/cache/assets' ] + tmp_dirs = [ "tmp/cache", + "tmp/sockets", + "tmp/pids", + "tmp/cache/assets" ] tmp_dirs.each { |d| directory d } @@ -15,21 +15,21 @@ namespace :tmp do namespace :cache do # desc "Clears all files and directories in tmp/cache" task :clear do - rm_rf Dir['tmp/cache/[^.]*'], verbose: false + rm_rf Dir["tmp/cache/[^.]*"], verbose: false end end namespace :sockets do # desc "Clears all files in tmp/sockets" task :clear do - rm Dir['tmp/sockets/[^.]*'], verbose: false + rm Dir["tmp/sockets/[^.]*"], verbose: false end end namespace :pids do # desc "Clears all files in tmp/pids" task :clear do - rm Dir['tmp/pids/[^.]*'], verbose: false + rm Dir["tmp/pids/[^.]*"], verbose: false end end end diff --git a/railties/lib/rails/templates/rails/mailers/email.html.erb b/railties/lib/rails/templates/rails/mailers/email.html.erb index fed96fbc85..c63781ed0c 100644 --- a/railties/lib/rails/templates/rails/mailers/email.html.erb +++ b/railties/lib/rails/templates/rails/mailers/email.html.erb @@ -88,7 +88,10 @@ <% unless @email.attachments.nil? || @email.attachments.empty? %> <dt>Attachments:</dt> <dd> - <%= @email.attachments.map { |a| a.respond_to?(:original_filename) ? a.original_filename : a.filename }.join(', ') %> + <% @email.attachments.each do |a| %> + <% filename = a.respond_to?(:original_filename) ? a.original_filename : a.filename %> + <%= link_to filename, "data:application/octet-stream;charset=utf-8;base64,#{Base64.encode64(a.body.to_s)}", download: filename %> + <% end %> </dd> <% end %> diff --git a/railties/lib/rails/test_help.rb b/railties/lib/rails/test_help.rb index 5cc1b5b219..db341dd847 100644 --- a/railties/lib/rails/test_help.rb +++ b/railties/lib/rails/test_help.rb @@ -3,13 +3,13 @@ abort("Abort testing: Your Rails environment is running in production mode!") if Rails.env.production? require "rails/test_unit/minitest_plugin" -require 'active_support/test_case' -require 'action_controller' -require 'action_controller/test_case' -require 'action_dispatch/testing/integration' -require 'rails/generators/test_case' +require "active_support/test_case" +require "action_controller" +require "action_controller/test_case" +require "action_dispatch/testing/integration" +require "rails/generators/test_case" -require 'active_support/testing/autorun' +require "active_support/testing/autorun" if defined?(ActiveRecord::Base) ActiveRecord::Migration.maintain_test_schema! diff --git a/railties/lib/rails/test_unit/line_filtering.rb b/railties/lib/rails/test_unit/line_filtering.rb index dd9732bb12..32ba744701 100644 --- a/railties/lib/rails/test_unit/line_filtering.rb +++ b/railties/lib/rails/test_unit/line_filtering.rb @@ -1,4 +1,4 @@ -require 'method_source' +require "method_source" module Rails module LineFiltering # :nodoc: @@ -39,7 +39,7 @@ module Rails def derive_line_filters(patterns) patterns.flat_map do |file_and_line| - file, *lines = file_and_line.split(':') + file, *lines = file_and_line.split(":") if lines.empty? Filter.new(@runnable, file, nil) if file diff --git a/railties/lib/rails/test_unit/minitest_plugin.rb b/railties/lib/rails/test_unit/minitest_plugin.rb index 076ab536be..6e196a32ab 100644 --- a/railties/lib/rails/test_unit/minitest_plugin.rb +++ b/railties/lib/rails/test_unit/minitest_plugin.rb @@ -1,7 +1,7 @@ require "active_support/core_ext/module/attribute_accessors" require "rails/test_unit/reporter" require "rails/test_unit/test_requirer" -require 'shellwords' +require "shellwords" module Minitest class SuppressedSummaryReporter < SummaryReporter @@ -61,19 +61,30 @@ module Minitest # as the patterns would also contain the other Rake tasks. def self.rake_run(patterns) # :nodoc: @rake_patterns = patterns - passed = run(Shellwords.split(ENV['TESTOPTS'] || '')) - exit passed unless passed - passed + autorun end + module RunRespectingRakeTestopts + def run(args = []) + if defined?(@rake_patterns) + args = Shellwords.split(ENV["TESTOPTS"] || "") + end + + super + end + end + + singleton_class.prepend RunRespectingRakeTestopts + # Owes great inspiration to test runner trailblazers like RSpec, # minitest-reporters, maxitest and others. def self.plugin_rails_init(options) - self.run_with_rails_extension = true - ENV["RAILS_ENV"] = options[:environment] || "test" - ::Rails::TestRequirer.require_files(options[:patterns]) unless run_with_autorun + # If run via `ruby` we've been passed the files to run directly. + unless run_via[:ruby] + ::Rails::TestRequirer.require_files(options[:patterns]) + end unless options[:full_backtrace] || ENV["BACKTRACE"] # Plugin can run without Rails loaded, check before filtering. @@ -86,8 +97,7 @@ module Minitest reporter << ::Rails::TestUnitReporter.new(options[:io], options) end - mattr_accessor(:run_with_autorun) { false } - mattr_accessor(:run_with_rails_extension) { false } + mattr_accessor(:run_via) { Hash.new } end # Put Rails as the first plugin minitest initializes so other plugins @@ -95,4 +105,4 @@ end # Since minitest only loads plugins if its extensions are empty we have # to call `load_plugins` first. Minitest.load_plugins -Minitest.extensions.unshift 'rails' +Minitest.extensions.unshift "rails" diff --git a/railties/lib/rails/test_unit/railtie.rb b/railties/lib/rails/test_unit/railtie.rb index 511cee33bd..746120e6a1 100644 --- a/railties/lib/rails/test_unit/railtie.rb +++ b/railties/lib/rails/test_unit/railtie.rb @@ -1,7 +1,7 @@ -require 'rails/test_unit/line_filtering' +require "rails/test_unit/line_filtering" if defined?(Rake.application) && Rake.application.top_level_tasks.grep(/^(default$|test(:|$))/).any? - ENV['RAILS_ENV'] ||= 'test' + ENV["RAILS_ENV"] ||= "test" end module Rails @@ -14,7 +14,9 @@ module Rails end initializer "test_unit.line_filtering" do - ActiveSupport::TestCase.extend Rails::LineFiltering + ActiveSupport.on_load(:active_support_test_case) { + ActiveSupport::TestCase.extend Rails::LineFiltering + } end rake_tasks do diff --git a/railties/lib/rails/test_unit/reporter.rb b/railties/lib/rails/test_unit/reporter.rb index 4086d5b731..fe11664d5e 100644 --- a/railties/lib/rails/test_unit/reporter.rb +++ b/railties/lib/rails/test_unit/reporter.rb @@ -50,7 +50,7 @@ module Rails end def relative_path_for(file) - file.sub(/^#{app_root}\/?/, '') + file.sub(/^#{app_root}\/?/, "") end private @@ -68,7 +68,7 @@ module Rails def format_rerun_snippet(result) location, line = result.method(result.name).source_location - "#{self.executable} #{relative_path_for(location)}:#{line}" + "#{executable} #{relative_path_for(location)}:#{line}" end def app_root diff --git a/railties/lib/rails/test_unit/test_requirer.rb b/railties/lib/rails/test_unit/test_requirer.rb index 8b211ce130..fe35934abc 100644 --- a/railties/lib/rails/test_unit/test_requirer.rb +++ b/railties/lib/rails/test_unit/test_requirer.rb @@ -1,5 +1,5 @@ -require 'active_support/core_ext/object/blank' -require 'rake/file_list' +require "active_support/core_ext/object/blank" +require "rake/file_list" module Rails class TestRequirer # :nodoc: @@ -7,7 +7,7 @@ module Rails def require_files(patterns) patterns = expand_patterns(patterns) - Rake::FileList[patterns.compact.presence || 'test/**/*_test.rb'].to_a.each do |file| + Rake::FileList[patterns.compact.presence || "test/**/*_test.rb"].to_a.each do |file| require File.expand_path(file) end end @@ -15,7 +15,7 @@ module Rails private def expand_patterns(patterns) patterns.map do |arg| - arg = arg.gsub(/(:\d+)+?$/, '') + arg = arg.gsub(/(:\d+)+?$/, "") if Dir.exist?(arg) "#{arg}/**/*_test.rb" else diff --git a/railties/lib/rails/test_unit/testing.rake b/railties/lib/rails/test_unit/testing.rake index 41921e43f3..4c157c1262 100644 --- a/railties/lib/rails/test_unit/testing.rake +++ b/railties/lib/rails/test_unit/testing.rake @@ -1,17 +1,17 @@ -gem 'minitest' -require 'minitest' -require 'rails/test_unit/minitest_plugin' +gem "minitest" +require "minitest" +require "rails/test_unit/minitest_plugin" task default: :test desc "Runs all tests in test folder" task :test do $: << "test" - pattern = if ENV.key?('TEST') - ENV['TEST'] - else - "test" - end + pattern = if ENV.key?("TEST") + ENV["TEST"] + else + "test" + end Minitest.rake_run([pattern]) end @@ -21,10 +21,10 @@ namespace :test do # If used with Active Record, this task runs before the database schema is synchronized. end - task :run => %w[test] + task run: %w[test] desc "Run tests quickly, but also reset db" - task :db => %w[db:test:prepare test] + task db: %w[db:test:prepare test] ["models", "helpers", "controllers", "mailers", "integration", "jobs"].each do |name| task name => "test:prepare" do @@ -33,17 +33,17 @@ namespace :test do end end - task :generators => "test:prepare" do + task generators: "test:prepare" do $: << "test" Minitest.rake_run(["test/lib/generators"]) end - task :units => "test:prepare" do + task units: "test:prepare" do $: << "test" Minitest.rake_run(["test/models", "test/helpers", "test/unit"]) end - task :functionals => "test:prepare" do + task functionals: "test:prepare" do $: << "test" Minitest.rake_run(["test/controllers", "test/mailers", "test/functional"]) end diff --git a/railties/lib/rails/version.rb b/railties/lib/rails/version.rb index df351c4238..3d8e8291d1 100644 --- a/railties/lib/rails/version.rb +++ b/railties/lib/rails/version.rb @@ -1,4 +1,4 @@ -require_relative 'gem_version' +require_relative "gem_version" module Rails # Returns the version of the currently loaded Rails as a string. diff --git a/railties/lib/rails/welcome_controller.rb b/railties/lib/rails/welcome_controller.rb index de9cd18b01..b757dc72ef 100644 --- a/railties/lib/rails/welcome_controller.rb +++ b/railties/lib/rails/welcome_controller.rb @@ -1,4 +1,4 @@ -require 'rails/application_controller' +require "rails/application_controller" class Rails::WelcomeController < Rails::ApplicationController # :nodoc: layout false |