diff options
Diffstat (limited to 'railties/lib/rails')
137 files changed, 1581 insertions, 944 deletions
diff --git a/railties/lib/rails/all.rb b/railties/lib/rails/all.rb index 45361fca83..11f4d5c4bc 100644 --- a/railties/lib/rails/all.rb +++ b/railties/lib/rails/all.rb @@ -1,16 +1,17 @@ require "rails" %w( - active_record - action_controller - action_view - action_mailer - active_job - rails/test_unit - sprockets -).each do |framework| + active_record/railtie + action_controller/railtie + action_view/railtie + action_mailer/railtie + active_job/railtie + action_cable/engine + rails/test_unit/railtie + sprockets/railtie +).each do |railtie| begin - require "#{framework}/railtie" + require "#{railtie}" rescue LoadError end end diff --git a/railties/lib/rails/api/task.rb b/railties/lib/rails/api/task.rb index a082932632..d478bbf9e8 100644 --- a/railties/lib/rails/api/task.rb +++ b/railties/lib/rails/api/task.rb @@ -57,6 +57,13 @@ module Rails ) }, + 'actioncable' => { + :include => %w( + README.md + lib/action_cable/**/*.rb + ) + }, + 'railties' => { :include => %w( README.rdoc diff --git a/railties/lib/rails/app_rails_loader.rb b/railties/lib/rails/app_loader.rb index 39d8007333..a9fe21824e 100644 --- a/railties/lib/rails/app_rails_loader.rb +++ b/railties/lib/rails/app_loader.rb @@ -1,7 +1,8 @@ require 'pathname' +require 'rails/version' module Rails - module AppRailsLoader + module AppLoader # :nodoc: extend self RUBY = Gem.ruby @@ -9,7 +10,7 @@ module Rails BUNDLER_WARNING = <<EOS Looks like your app's ./bin/rails is a stub that was generated by Bundler. -In Rails 4, your app's bin/ directory contains executables that are versioned +In Rails #{Rails::VERSION::MAJOR}, your app's bin/ directory contains executables that are versioned like any other source code, rather than stubs that are generated on demand. Here's how to upgrade: @@ -28,7 +29,7 @@ generate it and add it to source control: EOS - def exec_app_rails + def exec_app original_cwd = Dir.pwd loop do diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb index ff6c905f3e..cac31e1eed 100644 --- a/railties/lib/rails/application.rb +++ b/railties/lib/rails/application.rb @@ -1,4 +1,5 @@ require 'fileutils' +require 'yaml' require 'active_support/core_ext/hash/keys' require 'active_support/core_ext/object/blank' require 'active_support/key_generator' @@ -6,8 +7,7 @@ require 'active_support/message_verifier' require 'rails/engine' module Rails - # In Rails 3.0, a Rails::Application object was introduced which is nothing more than - # an Engine but with the responsibility of coordinating the whole boot process. + # An Engine with the responsibility of coordinating the whole boot process. # # == Initialization # @@ -156,25 +156,20 @@ module Rails self end - # Implements call according to the Rack API. It simply - # dispatches the request to the underlying middleware stack. - def call(env) - env["ORIGINAL_FULLPATH"] = build_original_fullpath(env) - env["ORIGINAL_SCRIPT_NAME"] = env["SCRIPT_NAME"] - super(env) - end - # Reload application routes regardless if they changed or not. def reload_routes! routes_reloader.reload! end - # Return the application's KeyGenerator + # Returns the application's KeyGenerator def key_generator # number of iterations selected based on consultation with the google security # team. Details at https://github.com/rails/rails/pull/6952#issuecomment-7661220 @caching_key_generator ||= if secrets.secret_key_base + unless secrets.secret_key_base.kind_of?(String) + raise ArgumentError, "`secret_key_base` for #{Rails.env} environment must be a type of String, change this value in `config/secrets.yml`" + end key_generator = ActiveSupport::KeyGenerator.new(secrets.secret_key_base, iterations: 1000) ActiveSupport::CachingKeyGenerator.new(key_generator) else @@ -223,13 +218,16 @@ module Rails # Rails.application.configure do # config.middleware.use ExceptionNotifier, config_for(:exception_notification) # end - def config_for(name) - yaml = Pathname.new("#{paths["config"].existent.first}/#{name}.yml") + def config_for(name, env: Rails.env) + if name.is_a?(Pathname) + yaml = name + else + yaml = Pathname.new("#{paths["config"].existent.first}/#{name}.yml") + end if yaml.exist? - require "yaml" require "erb" - (YAML.load(ERB.new(yaml.read).result) || {})[Rails.env] || {} + (YAML.load(ERB.new(yaml.read).result) || {})[env] || {} else raise "Could not load configuration. No such file - #{yaml}" end @@ -504,27 +502,28 @@ module Rails default_stack.build_stack end - def build_original_fullpath(env) #:nodoc: - path_info = env["PATH_INFO"] - query_string = env["QUERY_STRING"] - script_name = env["SCRIPT_NAME"] - - if query_string.present? - "#{script_name}#{path_info}?#{query_string}" - else - "#{script_name}#{path_info}" - end - end - def validate_secret_key_config! #:nodoc: if secrets.secret_key_base.blank? ActiveSupport::Deprecation.warn "You didn't set `secret_key_base`. " + "Read the upgrade documentation to learn more about this new config option." if secrets.secret_token.blank? - raise "Missing `secret_token` and `secret_key_base` for '#{Rails.env}' environment, set these values in `config/secrets.yml`" + raise "Missing `secret_key_base` for '#{Rails.env}' environment, set this value in `config/secrets.yml`" end end end + + private + + 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 end end diff --git a/railties/lib/rails/application/bootstrap.rb b/railties/lib/rails/application/bootstrap.rb index 0f4d932749..9baf8aa742 100644 --- a/railties/lib/rails/application/bootstrap.rb +++ b/railties/lib/rails/application/bootstrap.rb @@ -63,7 +63,7 @@ INFO Rails.cache = ActiveSupport::Cache.lookup_store(config.cache_store) if Rails.cache.respond_to?(:middleware) - config.middleware.insert_before("Rack::Runtime", Rails.cache.middleware) + config.middleware.insert_before(::Rack::Runtime, Rails.cache.middleware) end end end diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb index dc3ec4274b..65cff1561a 100644 --- a/railties/lib/rails/application/configuration.rb +++ b/railties/lib/rails/application/configuration.rb @@ -3,6 +3,9 @@ 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 + module Rails class Application class Configuration < ::Rails::Engine::Configuration @@ -11,44 +14,75 @@ module Rails :eager_load, :exceptions_app, :file_watcher, :filter_parameters, :force_ssl, :helpers_paths, :logger, :log_formatter, :log_tags, :railties_order, :relative_url_root, :secret_key_base, :secret_token, - :serve_static_files, :ssl_options, :static_cache_control, :session_options, - :time_zone, :reload_classes_only_on_change, + :ssl_options, :public_file_server, + :session_options, :time_zone, :reload_classes_only_on_change, :beginning_of_week, :filter_redirect, :x attr_writer :log_level - attr_reader :encoding + attr_reader :encoding, :api_only, :static_cache_control def initialize(*) super self.encoding = "utf-8" - @allow_concurrency = nil - @consider_all_requests_local = false - @filter_parameters = [] - @filter_redirect = [] - @helpers_paths = [] - @serve_static_files = true - @static_cache_control = nil - @force_ssl = false - @ssl_options = {} - @session_store = :cookie_store - @session_options = {} - @time_zone = "UTC" - @beginning_of_week = :monday - @log_level = nil - @middleware = app_middleware - @generators = app_generators - @cache_store = [ :file_store, "#{root}/tmp/cache/" ] - @railties_order = [:all] - @relative_url_root = ENV["RAILS_RELATIVE_URL_ROOT"] - @reload_classes_only_on_change = true - @file_watcher = ActiveSupport::FileUpdateChecker - @exceptions_app = nil - @autoflush_log = true - @log_formatter = ActiveSupport::Logger::SimpleFormatter.new - @eager_load = nil - @secret_token = nil - @secret_key_base = nil - @x = Custom.new + @allow_concurrency = nil + @consider_all_requests_local = false + @filter_parameters = [] + @filter_redirect = [] + @helpers_paths = [] + @public_file_server = ActiveSupport::OrderedOptions.new + @public_file_server.enabled = true + @public_file_server.index_name = "index" + @force_ssl = false + @ssl_options = {} + @session_store = :cookie_store + @session_options = {} + @time_zone = "UTC" + @beginning_of_week = :monday + @log_level = nil + @generators = app_generators + @cache_store = [ :file_store, "#{root}/tmp/cache/" ] + @railties_order = [:all] + @relative_url_root = ENV["RAILS_RELATIVE_URL_ROOT"] + @reload_classes_only_on_change = true + @file_watcher = ActiveSupport::FileUpdateChecker + @exceptions_app = nil + @autoflush_log = true + @log_formatter = ActiveSupport::Logger::SimpleFormatter.new + @eager_load = nil + @secret_token = nil + @secret_key_base = nil + @api_only = false + @debug_exception_response_format = nil + @x = Custom.new + end + + def static_cache_control=(value) + ActiveSupport::Deprecation.warn <<-eow.strip_heredoc + `static_cache_control` is deprecated and will be removed in Rails 5.1. + Please use + `config.public_file_server.headers = { 'Cache-Control' => '#{value}' }` + instead. + eow + + @static_cache_control = value + end + + def serve_static_files + ActiveSupport::Deprecation.warn <<-eow.strip_heredoc + `serve_static_files` is deprecated and will be removed in Rails 5.1. + Please use `public_file_server.enabled` instead. + eow + + @public_file_server.enabled + end + + def serve_static_files=(value) + ActiveSupport::Deprecation.warn <<-eow.strip_heredoc + `serve_static_files` is deprecated and will be removed in Rails 5.1. + Please use `public_file_server.enabled = #{value}` instead. + eow + + @public_file_server.enabled = value end def encoding=(value) @@ -59,6 +93,21 @@ module Rails end end + def api_only=(value) + @api_only = value + generators.api_only = value + + @debug_exception_response_format ||= :api + end + + def debug_exception_response_format + @debug_exception_response_format || :default + end + + def debug_exception_response_format=(value) + @debug_exception_response_format = value + end + def paths @paths ||= begin paths = super @@ -142,22 +191,21 @@ module Rails SourceAnnotationExtractor::Annotation end - private - class Custom #:nodoc: - def initialize - @configurations = Hash.new - end + class Custom #:nodoc: + def initialize + @configurations = Hash.new + end - def method_missing(method, *args) - if method =~ /=$/ - @configurations[$`.to_sym] = args.first - else - @configurations.fetch(method) { - @configurations[method] = ActiveSupport::OrderedOptions.new - } - end + def method_missing(method, *args) + if method =~ /=$/ + @configurations[$`.to_sym] = args.first + else + @configurations.fetch(method) { + @configurations[method] = ActiveSupport::OrderedOptions.new + } end end + 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 02eea82b0c..ed6a1f82d3 100644 --- a/railties/lib/rails/application/default_middleware_stack.rb +++ b/railties/lib/rails/application/default_middleware_stack.rb @@ -17,8 +17,11 @@ module Rails middleware.use ::Rack::Sendfile, config.action_dispatch.x_sendfile_header - if config.serve_static_files - middleware.use ::ActionDispatch::Static, paths["public"].first, config.static_cache_control + 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 + + middleware.use ::ActionDispatch::Static, paths["public"].first, index: config.public_file_server.index_name, headers: headers end if rack_cache = load_rack_cache @@ -26,15 +29,35 @@ module Rails middleware.use ::Rack::Cache, rack_cache end - middleware.use ::Rack::Lock unless allow_concurrency? + if config.allow_concurrency == false + # User has explicitly opted out of concurrent request + # handling: presumably their code is not threadsafe + + middleware.use ::Rack::Lock + + elsif config.allow_concurrency == :unsafe + # Do nothing, even if we know this is dangerous. This is the + # historical behaviour for true. + + else + # Default concurrency setting: enabled, but safe + + unless config.cache_classes && config.eager_load + # Without cache_classes + eager_load, the load interlock + # is required for proper operation + + middleware.use ::ActionDispatch::LoadInterlock + end + end + middleware.use ::Rack::Runtime - middleware.use ::Rack::MethodOverride + middleware.use ::Rack::MethodOverride unless config.api_only middleware.use ::ActionDispatch::RequestId # 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 + 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 @@ -42,9 +65,9 @@ module Rails end middleware.use ::ActionDispatch::Callbacks - middleware.use ::ActionDispatch::Cookies + middleware.use ::ActionDispatch::Cookies unless config.api_only - if config.session_store + if !config.api_only && config.session_store if config.force_ssl && !config.session_options.key?(:secure) config.session_options[:secure] = true end @@ -52,7 +75,6 @@ module Rails middleware.use ::ActionDispatch::Flash end - middleware.use ::ActionDispatch::ParamsParser middleware.use ::Rack::Head middleware.use ::Rack::ConditionalGet middleware.use ::Rack::ETag, "no-cache" @@ -65,14 +87,6 @@ module Rails config.reload_classes_only_on_change != true || app.reloaders.map(&:updated?).any? end - def allow_concurrency? - if config.allow_concurrency.nil? - config.cache_classes && config.eager_load - else - config.allow_concurrency - end - end - def load_rack_cache rack_cache = config.action_dispatch.rack_cache return unless rack_cache diff --git a/railties/lib/rails/application/finisher.rb b/railties/lib/rails/application/finisher.rb index 0599e988d9..404e3c3e23 100644 --- a/railties/lib/rails/application/finisher.rb +++ b/railties/lib/rails/application/finisher.rb @@ -86,8 +86,10 @@ module Rails # added in the hook are taken into account. initializer :set_clear_dependencies_hook, group: :all do callback = lambda do - ActiveSupport::DescendantsTracker.clear - ActiveSupport::Dependencies.clear + ActiveSupport::Dependencies.interlock.attempt_unloading do + ActiveSupport::DescendantsTracker.clear + ActiveSupport::Dependencies.clear + end end if config.reload_classes_only_on_change diff --git a/railties/lib/rails/application_controller.rb b/railties/lib/rails/application_controller.rb index 9a29ec21cf..618a09a5b3 100644 --- a/railties/lib/rails/application_controller.rb +++ b/railties/lib/rails/application_controller.rb @@ -6,7 +6,7 @@ class Rails::ApplicationController < ActionController::Base # :nodoc: def require_local! unless local_request? - render text: '<p>For security purposes, this information is only available to local requests.</p>', status: :forbidden + render html: '<p>For security purposes, this information is only available to local requests.</p>'.html_safe, status: :forbidden end end diff --git a/railties/lib/rails/cli.rb b/railties/lib/rails/cli.rb index dd70c272c6..a8794bc0de 100644 --- a/railties/lib/rails/cli.rb +++ b/railties/lib/rails/cli.rb @@ -1,8 +1,8 @@ -require 'rails/app_rails_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::AppRailsLoader.exec_app_rails +Rails::AppLoader.exec_app require 'rails/ruby_version_check' Signal.trap("INT") { puts; exit(1) } diff --git a/railties/lib/rails/code_statistics.rb b/railties/lib/rails/code_statistics.rb index 583d005d46..8e9097e1ef 100644 --- a/railties/lib/rails/code_statistics.rb +++ b/railties/lib/rails/code_statistics.rb @@ -33,7 +33,7 @@ class CodeStatistics #:nodoc: Hash[@pairs.map{|pair| [pair.first, calculate_directory_statistics(pair.last)]}] end - def calculate_directory_statistics(directory, pattern = /.*\.(rb|js|coffee)$/) + def calculate_directory_statistics(directory, pattern = /.*\.(rb|js|coffee|rake)$/) stats = CodeStatisticsCalculator.new Dir.foreach(directory) do |file_name| @@ -41,11 +41,9 @@ class CodeStatistics #:nodoc: if File.directory?(path) && (/^\./ !~ file_name) stats.add(calculate_directory_statistics(path, pattern)) + elsif file_name =~ pattern + stats.add_by_file_path(path) end - - next unless file_name =~ pattern - - stats.add_by_file_path(path) end stats diff --git a/railties/lib/rails/code_statistics_calculator.rb b/railties/lib/rails/code_statistics_calculator.rb index a142236dbe..fad13e8517 100644 --- a/railties/lib/rails/code_statistics_calculator.rb +++ b/railties/lib/rails/code_statistics_calculator.rb @@ -25,6 +25,7 @@ class CodeStatisticsCalculator #:nodoc: } PATTERNS[:minitest] = PATTERNS[:rb].merge method: /^\s*(def|test)\s+['"_a-z]/ + PATTERNS[:rake] = PATTERNS[:rb] def initialize(lines = 0, code_lines = 0, classes = 0, methods = 0) @lines = lines diff --git a/railties/lib/rails/command.rb b/railties/lib/rails/command.rb new file mode 100644 index 0000000000..f7753cbb83 --- /dev/null +++ b/railties/lib/rails/command.rb @@ -0,0 +1,70 @@ +require 'rails/commands/commands_tasks' + +module Rails + class Command #:nodoc: + attr_reader :argv + + def initialize(argv = []) + @argv = argv + + @option_parser = build_option_parser + @options = {} + end + + def self.run(task_name, argv) + command_name = command_name_for(task_name) + + if command = command_for(command_name) + command.new(argv).run(command_name) + else + Rails::CommandsTasks.new(argv).run_command!(task_name) + end + end + + def run(command_name) + parse_options_for(command_name) + @option_parser.parse! @argv + + public_send(command_name) + end + + def self.options_for(command_name, &options_to_parse) + @@command_options[command_name] = options_to_parse + end + + def self.set_banner(command_name, banner) + options_for(command_name) { |opts, _| opts.banner = banner } + end + + private + @@commands = [] + @@command_options = {} + + def parse_options_for(command_name) + @@command_options.fetch(command_name, proc {}).call(@option_parser, @options) + end + + def build_option_parser + OptionParser.new do |opts| + opts.on('-h', '--help', 'Show this help.') do + puts opts + exit + end + end + end + + def self.inherited(command) + @@commands << command + end + + def self.command_name_for(task_name) + task_name.gsub(':', '_').to_sym + end + + def self.command_for(command_name) + @@commands.find do |command| + command.public_instance_methods.include?(command_name) + end + end + end +end diff --git a/railties/lib/rails/commands.rb b/railties/lib/rails/commands.rb index 12bd73db24..7627fcf5a0 100644 --- a/railties/lib/rails/commands.rb +++ b/railties/lib/rails/commands.rb @@ -7,12 +7,13 @@ aliases = { "s" => "server", "db" => "dbconsole", "r" => "runner", - "t" => "test", + "t" => "test" } command = ARGV.shift command = aliases[command] || command -require 'rails/commands/commands_tasks' +require 'rails/command' +require 'rails/commands/dev_cache' -Rails::CommandsTasks.new(ARGV).run_command!(command) +Rails::Command.run(command, ARGV) diff --git a/railties/lib/rails/commands/commands_tasks.rb b/railties/lib/rails/commands/commands_tasks.rb index d8d4080c3e..da3b9452d5 100644 --- a/railties/lib/rails/commands/commands_tasks.rb +++ b/railties/lib/rails/commands/commands_tasks.rb @@ -1,3 +1,5 @@ +require 'rails/commands/rake_proxy' + module Rails # This is a class which takes in a rails command and initiates the appropriate # initiation sequence. @@ -5,6 +7,8 @@ module Rails # 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 @@ -20,14 +24,18 @@ The most common rails commands are: new Create a new Rails application. "rails new my_app" creates a new application called MyApp in "./my_app" -In addition to those, there are: - 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") - 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) @@ -36,10 +44,11 @@ EOT def run_command!(command) command = parse_command(command) + if COMMAND_WHITELIST.include?(command) send(command) else - write_error_message(command) + run_rake_task(command) end end @@ -110,6 +119,7 @@ EOT def help write_help_message + write_commands ADDITIONAL_COMMANDS + formatted_rake_tasks end private @@ -151,13 +161,9 @@ EOT puts HELP_MESSAGE end - def write_error_message(command) - puts "Error: Command '#{command}' not recognized" - if %x{rake #{command} --dry-run 2>&1 } && $?.success? - puts "Did you mean: `$ rake #{command}` ?\n\n" - end - write_help_message - exit(1) + 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) diff --git a/railties/lib/rails/commands/console.rb b/railties/lib/rails/commands/console.rb index 48b1ad884b..ea5d20ea24 100644 --- a/railties/lib/rails/commands/console.rb +++ b/railties/lib/rails/commands/console.rb @@ -1,14 +1,13 @@ require 'optparse' require 'irb' require 'irb/completion' +require 'rails/commands/console_helper' module Rails class Console - class << self - def start(*args) - new(*args).start - end + include ConsoleHelper + class << self def parse_arguments(arguments) options = {} @@ -21,23 +20,8 @@ module Rails opt.parse!(arguments) end - 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 + set_options_env(arguments, options) end - - private - - def available_environments - Dir['config/environments/*.rb'].map { |fname| File.basename(fname, '.*') } - end end attr_reader :options, :app, :console @@ -57,12 +41,9 @@ module Rails end def environment - options[:environment] ||= ENV['RAILS_ENV'] || 'development' - end - - def environment? - environment + options[:environment] ||= super end + alias_method :environment?, :environment def set_environment! Rails.env = environment diff --git a/railties/lib/rails/commands/console_helper.rb b/railties/lib/rails/commands/console_helper.rb new file mode 100644 index 0000000000..8ee0b60012 --- /dev/null +++ b/railties/lib/rails/commands/console_helper.rb @@ -0,0 +1,34 @@ +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 index be0c0fc659..2c36edfa3f 100644 --- a/railties/lib/rails/commands/dbconsole.rb +++ b/railties/lib/rails/commands/dbconsole.rb @@ -1,13 +1,49 @@ require 'erb' require 'yaml' require 'optparse' +require 'rails/commands/console_helper' module Rails class DBConsole + include ConsoleHelper + attr_reader :arguments - def self.start - new.start + 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) @@ -15,7 +51,7 @@ module Rails end def start - options = parse_arguments(arguments) + options = self.class.parse_arguments(arguments) ENV['RAILS_ENV'] = options[:environment] || environment case config["adapter"] @@ -29,7 +65,7 @@ module Rails 'sslca' => '--ssl-ca', 'sslcert' => '--ssl-cert', 'sslcapath' => '--ssl-capath', - 'sslcipher' => '--ssh-cipher', + 'sslcipher' => '--ssl-cipher', 'sslkey' => '--ssl-key' }.map { |opt, arg| "#{arg}=#{config[opt]}" if config[opt] }.compact @@ -50,9 +86,6 @@ module Rails ENV['PGPASSWORD'] = config["password"].to_s if config["password"] && options['include_password'] find_cmd_and_exec('psql', config["database"]) - when "sqlite" - find_cmd_and_exec('sqlite', config["database"]) - when "sqlite3" args = [] @@ -89,7 +122,7 @@ module Rails find_cmd_and_exec("sqsh", *args) else - abort "Unknown command-line client for #{config['database']}. Submit a Rails patch to add support!" + abort "Unknown command-line client for #{config['database']}." end end @@ -104,90 +137,37 @@ module Rails end def environment - if Rails.respond_to?(:env) - Rails.env - else - ENV["RAILS_ENV"] || "development" - end + 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 configurations - require APP_PATH - ActiveRecord::Base.configurations = Rails.application.config.database_configuration - ActiveRecord::Base.configurations - end - - 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 + def find_cmd_and_exec(commands, *args) + commands = Array(commands) - opt.on("--header") do |h| - options['header'] = h + dirs_on_path = ENV['PATH'].to_s.split(File::PATH_SEPARATOR) + unless (ext = RbConfig::CONFIG['EXEEXT']).empty? + commands = commands.map{|cmd| "#{cmd}#{ext}"} end - opt.on("-h", "--help", "Show this help message.") do - puts opt - exit + 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 - 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 - - if arguments.first && arguments.first[0] != '-' - env = arguments.first - if available_environments.include? env - options[:environment] = env + if found + exec full_path_command, *args else - options[:environment] = %w(production development test).detect {|e| e =~ /^#{env}/} || env + abort("Couldn't find database client: #{commands.join(', ')}. Check your $PATH and try again.") end end - - options - end - - def available_environments - Dir['config/environments/*.rb'].map { |fname| File.basename(fname, '.*') } - 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/dev_cache.rb b/railties/lib/rails/commands/dev_cache.rb new file mode 100644 index 0000000000..ec96e8f630 --- /dev/null +++ b/railties/lib/rails/commands/dev_cache.rb @@ -0,0 +1,21 @@ +require 'rails/command' + +module Rails + module Commands + # This is a wrapper around the Rails dev:cache command + class DevCache < Command + set_banner :dev_cache, 'Toggle development mode caching on/off' + def dev_cache + if File.exist? 'tmp/caching-dev.txt' + File.delete 'tmp/caching-dev.txt' + puts 'Development mode is no longer being cached.' + else + FileUtils.touch 'tmp/caching-dev.txt' + puts 'Development mode is now being cached.' + end + + FileUtils.touch 'tmp/restart.txt' + end + end + end +end diff --git a/railties/lib/rails/commands/rake_proxy.rb b/railties/lib/rails/commands/rake_proxy.rb new file mode 100644 index 0000000000..f7d5df6b2f --- /dev/null +++ b/railties/lib/rails/commands/rake_proxy.rb @@ -0,0 +1,34 @@ +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 index 66a9ebf38c..86bce9b2fe 100644 --- a/railties/lib/rails/commands/runner.rb +++ b/railties/lib/rails/commands/runner.rb @@ -1,6 +1,6 @@ require 'optparse' -options = { environment: (ENV['RAILS_ENV'] || "development").dup } +options = { environment: (ENV['RAILS_ENV'] || ENV['RACK_ENV'] || "development").dup } code_or_file = nil if ARGV.first.nil? diff --git a/railties/lib/rails/commands/server.rb b/railties/lib/rails/commands/server.rb index 397a9cf406..d3ea441f8e 100644 --- a/railties/lib/rails/commands/server.rb +++ b/railties/lib/rails/commands/server.rb @@ -34,6 +34,9 @@ module Rails 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 "" @@ -67,6 +70,7 @@ module Rails print_boot_information trap(:INT) { exit } create_tmp_directories + setup_dev_caching log_to_stdout if options[:log_stdout] super @@ -77,33 +81,32 @@ module Rails end def middleware - middlewares = [] - middlewares << [::Rack::ContentLength] - - # FIXME: add Rack::Lock in the case people are using webrick. - # This is to remain backwards compatible for those who are - # running webrick in production. We should consider removing this - # in development. - if server.name == 'Rack::Handler::WEBrick' - middlewares << [::Rack::Lock] - end - - Hash.new(middlewares) + Hash.new([]) end def default_options super.merge({ - Port: 3000, + Port: ENV.fetch('PORT', 3000).to_i, DoNotReverseLookup: true, - environment: (ENV['RAILS_ENV'] || "development").dup, + environment: (ENV['RAILS_ENV'] || ENV['RACK_ENV'] || "development").dup, daemonize: false, - pid: File.expand_path("tmp/pids/server.pid"), - config: File.expand_path("config.ru") + caching: false, + pid: File.expand_path("tmp/pids/server.pid") }) end private + def setup_dev_caching + return unless options[:environment] == "development" + + if options[:caching] == false + delete_cache_file + elsif options[:caching] + create_cache_file + end + end + def print_boot_information url = "#{options[:SSLEnable] ? 'https' : 'http'}://#{options[:Host]}:#{options[:Port]}" puts "=> Booting #{ActiveSupport::Inflector.demodulize(server)}" @@ -113,6 +116,14 @@ module Rails puts "=> Ctrl-C to shutdown server" unless options[:daemonize] end + def create_cache_file + FileUtils.touch("tmp/caching-dev.txt") + end + + def delete_cache_file + FileUtils.rm("tmp/caching-dev.txt") if File.exist?("tmp/caching-dev.txt") + 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)) diff --git a/railties/lib/rails/commands/test.rb b/railties/lib/rails/commands/test.rb index 598e224a6f..dd069f081f 100644 --- a/railties/lib/rails/commands/test.rb +++ b/railties/lib/rails/commands/test.rb @@ -1,5 +1,9 @@ -require "rails/test_unit/runner" +require "rails/test_unit/minitest_plugin" -$: << File.expand_path("../../test", APP_PATH) +if defined?(ENGINE_ROOT) + $: << File.expand_path('test', ENGINE_ROOT) +else + $: << File.expand_path('../../test', APP_PATH) +end -Rails::TestRunner.run(ARGV) +exit Minitest.run(ARGV) diff --git a/railties/lib/rails/configuration.rb b/railties/lib/rails/configuration.rb index 76364cea8f..30eafd59f2 100644 --- a/railties/lib/rails/configuration.rb +++ b/railties/lib/rails/configuration.rb @@ -33,9 +33,9 @@ module Rails # config.middleware.delete ActionDispatch::Flash # class MiddlewareStackProxy - def initialize - @operations = [] - @delete_operations = [] + def initialize(operations = [], delete_operations = []) + @operations = operations + @delete_operations = delete_operations end def insert_before(*args, &block) @@ -71,10 +71,23 @@ module Rails other end + + def +(other) # :nodoc: + MiddlewareStackProxy.new(@operations + other.operations, @delete_operations + other.delete_operations) + end + + protected + def operations + @operations + end + + def delete_operations + @delete_operations + end end class Generators #:nodoc: - attr_accessor :aliases, :options, :templates, :fallbacks, :colorize_logging + attr_accessor :aliases, :options, :templates, :fallbacks, :colorize_logging, :api_only attr_reader :hidden_namespaces def initialize @@ -83,6 +96,7 @@ module Rails @fallbacks = {} @templates = [] @colorize_logging = true + @api_only = false @hidden_namespaces = [] end diff --git a/railties/lib/rails/console/app.rb b/railties/lib/rails/console/app.rb index 2a69c26deb..ac5836a588 100644 --- a/railties/lib/rails/console/app.rb +++ b/railties/lib/rails/console/app.rb @@ -18,6 +18,11 @@ module Rails app = Rails.application session = ActionDispatch::Integration::Session.new(app) yield session if block_given? + + # This makes app.url_for and app.foo_path available in the console + session.extend(app.routes.url_helpers) + session.extend(app.routes.mounted_helpers) + session end diff --git a/railties/lib/rails/console/helpers.rb b/railties/lib/rails/console/helpers.rb index b775f1ff8d..a33f71dc5b 100644 --- a/railties/lib/rails/console/helpers.rb +++ b/railties/lib/rails/console/helpers.rb @@ -4,7 +4,7 @@ module Rails # # This method assumes an +ApplicationController+ exists, and it extends +ActionController::Base+ def helper - @helper ||= ApplicationController.helpers + ApplicationController.helpers end # Gets a new instance of a controller object. diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb index 83cee28fa3..5757d235d2 100644 --- a/railties/lib/rails/engine.rb +++ b/railties/lib/rails/engine.rb @@ -2,11 +2,12 @@ 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 # functionality and share it with other applications or within a larger packaged application. - # Since Rails 3.0, every <tt>Rails::Application</tt> is just an engine, which allows for simple + # Every <tt>Rails::Application</tt> is just an engine, which allows for simple # feature and application sharing. # # Any <tt>Rails::Engine</tt> is also a <tt>Rails::Railtie</tt>, so the same @@ -15,10 +16,9 @@ module Rails # # == Creating an Engine # - # In Rails versions prior to 3.0, your gems automatically behaved as engines, however, - # this coupled Rails to Rubygems. Since Rails 3.0, if you want a gem to automatically - # behave as an engine, you have to specify an +Engine+ for it somewhere inside - # your plugin's +lib+ folder (similar to how we specify a +Railtie+): + # If you want a gem to behave as an engine, you have to specify an +Engine+ + # for it somewhere inside your plugin's +lib+ folder (similar to how we + # specify a +Railtie+): # # # lib/my_engine.rb # module MyEngine @@ -69,10 +69,9 @@ module Rails # # == Paths # - # Since Rails 3.0, applications and engines have more flexible path configuration (as - # opposed to the previous hardcoded path configuration). This means that you are not - # required to place your controllers at <tt>app/controllers</tt>, but in any place - # which you find convenient. + # Applications and engines have flexible path configuration, meaning that you + # are not required to place your controllers at <tt>app/controllers</tt>, but + # in any place which you find convenient. # # For example, let's suppose you want to place your controllers in <tt>lib/controllers</tt>. # You can set that as an option: @@ -206,42 +205,51 @@ module Rails # With such an engine, everything that is inside the +MyEngine+ module will be isolated from # the application. # - # Consider such controller: + # Consider this controller: # # module MyEngine # class FooController < ActionController::Base # end # end # - # If an engine is marked as isolated, +FooController+ has access only to helpers from +Engine+ and - # <tt>url_helpers</tt> from <tt>MyEngine::Engine.routes</tt>. + # If the +MyEngine+ engine is marked as isolated, +FooController+ only has + # access to helpers from +MyEngine+, and <tt>url_helpers</tt> from + # <tt>MyEngine::Engine.routes</tt>. # - # The next thing that changes in isolated engines is the behavior of routes. Normally, when you namespace - # your controllers, you also need to namespace all your routes. With an isolated engine, - # the namespace is applied by default, so you can ignore it in routes: + # The next thing that changes in isolated engines is the behavior of routes. + # Normally, when you namespace your controllers, you also need to namespace + # the related routes. With an isolated engine, the engine's namespace is + # automatically applied, so you don't need to specify it explicity in your + # routes: # # MyEngine::Engine.routes.draw do # resources :articles # end # - # The routes above will automatically point to <tt>MyEngine::ArticlesController</tt>. Furthermore, you don't - # need to use longer url helpers like <tt>my_engine_articles_path</tt>. Instead, you should simply use - # <tt>articles_path</tt> as you would do with your application. + # If +MyEngine+ is isolated, The routes above will point to + # <tt>MyEngine::ArticlesController</tt>. You also don't need to use longer + # url helpers like +my_engine_articles_path+. Instead, you should simply use + # +articles_path+, like you would do with your main application. # - # To make that behavior consistent with other parts of the framework, an isolated engine also has influence on - # <tt>ActiveModel::Naming</tt>. When you use a namespaced model, like <tt>MyEngine::Article</tt>, it will normally - # use the prefix "my_engine". In an isolated engine, the prefix will be omitted in url helpers and - # form fields for convenience. + # To make this behavior consistent with other parts of the framework, + # isolated engines also have an effect on <tt>ActiveModel::Naming</tt>. In a + # normal Rails app, when you use a namespaced model such as + # <tt>Namespace::Article</tt>, <tt>ActiveModel::Naming</tt> will generate + # names with the prefix "namespace". In an isolated engine, the prefix will + # be omitted in url helpers and form fields, for convenience. # - # polymorphic_url(MyEngine::Article.new) # => "articles_path" + # polymorphic_url(MyEngine::Article.new) + # # => "articles_path" # not "my_engine_articles_path" # # form_for(MyEngine::Article.new) do # text_field :title # => <input type="text" name="article[title]" id="article_title" /> # end # - # Additionally, an isolated engine will set its name according to namespace, so - # MyEngine::Engine.engine_name will be "my_engine". It will also set MyEngine.table_name_prefix - # to "my_engine_", changing the MyEngine::Article model to use the my_engine_articles table. + # Additionally, an isolated engine will set its own name according to its + # namespace, so <tt>MyEngine::Engine.engine_name</tt> will return + # "my_engine". It will also set +MyEngine.table_name_prefix+ to "my_engine_", + # meaning for example that <tt>MyEngine::Article</tt> will use the + # +my_engine_articles+ database table by default. # # == Using Engine's routes outside Engine # @@ -350,12 +358,7 @@ module Rails Rails::Railtie::Configuration.eager_load_namespaces << base base.called_from = begin - call_stack = if Kernel.respond_to?(:caller_locations) - caller_locations.map { |l| l.absolute_path || l.path } - else - # Remove the line number from backtraces making sure we don't leave anything behind - caller.map { |p| p.sub(/:\d+.*/, '') } - end + call_stack = caller_locations.map { |l| l.absolute_path || l.path } File.dirname(call_stack.detect { |p| p !~ %r[railties[\w.-]*/lib/rails|rack[\w.-]*/lib/rack] }) end @@ -405,7 +408,7 @@ module Rails end end - # Finds engine with given path + # Finds engine with given path. def find(path) expanded_path = File.expand_path path Rails::Engine.subclasses.each do |klass| @@ -427,6 +430,7 @@ module Rails @env_config = nil @helpers = nil @routes = nil + @app_build_lock = Mutex.new super end @@ -497,10 +501,13 @@ module Rails # Returns the underlying rack application for this engine. def app - @app ||= begin - config.middleware = config.middleware.merge_into(default_middleware_stack) - config.middleware.build(endpoint) - end + @app || @app_build_lock.synchronize { + @app ||= begin + stack = default_middleware_stack + config.middleware = build_middleware.merge_into(stack) + config.middleware.build(endpoint) + end + } end # Returns the endpoint for this engine. If none is registered, @@ -511,18 +518,13 @@ module Rails # Define the Rack API for this engine. def call(env) - env.merge!(env_config) - if env['SCRIPT_NAME'] - env[routes.env_key] = env['SCRIPT_NAME'].dup - end - app.call(env) + req = build_request env + app.call req.env end # Defines additional Rack env configuration that is added on each call. def env_config - @env_config ||= { - 'action_dispatch.routes' => routes - } + @env_config ||= {} end # Defines the routes for this engine. If a block is given to @@ -559,7 +561,7 @@ module Rails # and the load_once paths. # # This needs to be an initializer, since it needs to run once - # per engine and get the engine as a block parameter + # per engine and get the engine as a block parameter. initializer :set_autoload_paths, before: :bootstrap_hook do ActiveSupport::Dependencies.autoload_paths.unshift(*_all_autoload_paths) ActiveSupport::Dependencies.autoload_once_paths.unshift(*_all_autoload_once_paths) @@ -582,7 +584,7 @@ module Rails # I18n load paths are a special case since the ones added # later have higher priority. initializer :add_locales do - config.i18n.railties_load_path.concat(paths["config/locales"].existent) + config.i18n.railties_load_path << paths["config/locales"] end initializer :add_view_paths do @@ -684,5 +686,19 @@ module Rails def _all_load_paths #:nodoc: @_all_load_paths ||= (config.paths.load_paths + _all_autoload_paths).uniq end + + private + + 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 f39f926109..a6d87b78e4 100644 --- a/railties/lib/rails/engine/commands.rb +++ b/railties/lib/rails/engine/commands.rb @@ -2,7 +2,8 @@ ARGV << '--help' if ARGV.empty? aliases = { "g" => "generate", - "d" => "destroy" + "d" => "destroy", + "t" => "test" } command = ARGV.shift @@ -12,7 +13,7 @@ require ENGINE_PATH engine = ::Rails::Engine.find(ENGINE_ROOT) case command -when 'generate', 'destroy' +when 'generate', 'destroy', 'test' require 'rails/generators' Rails::Generators.namespace = engine.railtie_namespace engine.load_generators @@ -30,6 +31,7 @@ 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. diff --git a/railties/lib/rails/engine/configuration.rb b/railties/lib/rails/engine/configuration.rb index 62a4139d07..8cadbc3ddd 100644 --- a/railties/lib/rails/engine/configuration.rb +++ b/railties/lib/rails/engine/configuration.rb @@ -4,17 +4,14 @@ module Rails class Engine class Configuration < ::Rails::Railtie::Configuration attr_reader :root - attr_writer :middleware, :eager_load_paths, :autoload_once_paths, :autoload_paths + attr_accessor :middleware + attr_writer :eager_load_paths, :autoload_once_paths, :autoload_paths def initialize(root=nil) super() @root = root @generators = app_generators.dup - end - - # Returns the middleware stack for the engine. - def middleware - @middleware ||= Rails::Configuration::MiddlewareStackProxy.new + @middleware = Rails::Configuration::MiddlewareStackProxy.new end # Holds generators configuration: @@ -29,7 +26,7 @@ module Rails # # config.generators.colorize_logging = false # - def generators #:nodoc: + def generators @generators ||= Rails::Configuration::Generators.new yield(@generators) if block_given? @generators diff --git a/railties/lib/rails/gem_version.rb b/railties/lib/rails/gem_version.rb index 7d74b1bfe5..92230a74e4 100644 --- a/railties/lib/rails/gem_version.rb +++ b/railties/lib/rails/gem_version.rb @@ -8,7 +8,7 @@ module Rails MAJOR = 5 MINOR = 0 TINY = 0 - PRE = "alpha" + PRE = "beta1" STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") end diff --git a/railties/lib/rails/generators.rb b/railties/lib/rails/generators.rb index 341291f08b..e3d79521e7 100644 --- a/railties/lib/rails/generators.rb +++ b/railties/lib/rails/generators.rb @@ -33,6 +33,7 @@ module Rails scaffold_controller: '-c', stylesheets: '-y', stylesheet_engine: '-se', + scaffold_stylesheet: '-ss', template_engine: '-e', test_framework: '-t' }, @@ -44,6 +45,7 @@ module Rails DEFAULT_OPTIONS = { rails: { + api: false, assets: true, force_plural: false, helper: true, @@ -56,12 +58,14 @@ module Rails scaffold_controller: :scaffold_controller, stylesheets: true, stylesheet_engine: :css, + scaffold_stylesheet: true, test_framework: false, template_engine: :erb } } 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 @@ -99,6 +103,21 @@ module Rails @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 views, 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 + ) + end + # Remove the color from output. def self.no_color! Thor::Base.shell = Thor::Shell::Basic @@ -159,7 +178,7 @@ module Rails 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 ") }\n" + 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 @@ -189,6 +208,7 @@ module Rails "#{test}:model", "#{test}:scaffold", "#{test}:view", + "#{test}:job", "#{template}:controller", "#{template}:scaffold", "#{template}:mailer", @@ -267,10 +287,13 @@ module Rails d = (0..m).to_a x = nil - str1.each_char.each_with_index do |char1,i| + # 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.each_char.each_with_index do |char2,j| + str2_codepoint_enumerable.with_index do |char2, j| cost = (char1 == char2) ? 0 : 1 x = [ d[j+1] + 1, # insertion diff --git a/railties/lib/rails/generators/actions.rb b/railties/lib/rails/generators/actions.rb index 70a20801a0..5bbd2f1aed 100644 --- a/railties/lib/rails/generators/actions.rb +++ b/railties/lib/rails/generators/actions.rb @@ -63,12 +63,26 @@ module Rails # Add the given source to +Gemfile+ # + # If block is given, gem entries in block are wrapped into the source group. + # # add_source "http://gems.github.com/" - def add_source(source, options={}) + # + # add_source "http://gems.github.com/" do + # gem "rspec-rails" + # end + def add_source(source, options={}, &block) log :source, source in_root do - prepend_file "Gemfile", "source #{quote(source)}\n", verbose: false + if block + append_file "Gemfile", "source #{quote(source)} do", force: true + @in_group = true + instance_eval(&block) + @in_group = false + append_file "Gemfile", "\nend\n", force: true + else + prepend_file "Gemfile", "source #{quote(source)}\n", verbose: false + end end end @@ -78,11 +92,11 @@ module Rails # file in <tt>config/environments</tt>. # # environment do - # "config.autoload_paths += %W(#{config.root}/extras)" + # "config.action_controller.asset_host = 'cdn.provider.com'" # end # # environment(nil, env: "development") do - # "config.autoload_paths += %W(#{config.root}/extras)" + # "config.action_controller.asset_host = 'localhost:3000'" # end def environment(data=nil, options={}) sentinel = /class [a-z_:]+ < Rails::Application/i @@ -221,7 +235,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: true } + inject_into_file 'config/routes.rb', " #{routing_code}\n", { after: sentinel, verbose: false, force: false } end end diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb index 813f8b21fd..2f18619e30 100644 --- a/railties/lib/rails/generators/app_base.rb +++ b/railties/lib/rails/generators/app_base.rb @@ -26,6 +26,12 @@ module Rails 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', + 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 :skip_gemfile, type: :boolean, default: false, desc: "Don't create a Gemfile" @@ -45,33 +51,30 @@ module Rails class_option :skip_active_record, type: :boolean, aliases: '-O', default: false, desc: 'Skip Active Record 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_spring, type: :boolean, default: false, desc: "Don't install Spring application preloader" - 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 :skip_javascript, type: :boolean, aliases: '-J', default: false, desc: 'Skip JavaScript files' - class_option :dev, type: :boolean, default: false, - desc: "Setup the #{name} with Gemfile pointing to your Rails checkout" - - class_option :edge, type: :boolean, default: false, - desc: "Setup the #{name} with Gemfile pointing to Rails repository" - class_option :skip_turbolinks, type: :boolean, default: false, desc: 'Skip turbolinks gem' 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" + + class_option :edge, type: :boolean, default: false, + desc: "Setup the #{name} with Gemfile pointing to Rails repository" + class_option :rc, type: :string, default: false, desc: "Path to file containing extra configuration options for rails command" @@ -162,18 +165,23 @@ module Rails def database_gemfile_entry return [] if options[:skip_active_record] - GemfileEntry.version gem_for_database, nil, + gem_name, gem_version = gem_for_database + GemfileEntry.version gem_name, gem_version, "Use #{options[:database]} as the database for Active Record" end def include_all_railties? - options.values_at(:skip_active_record, :skip_action_mailer, :skip_test, :skip_sprockets).none? + options.values_at(:skip_active_record, :skip_action_mailer, :skip_test, :skip_sprockets, :skip_action_cable).none? end def comment_if(value) options[value] ? '# ' : '' end + def keeps? + !options[:skip_keeps] + end + def sqlite3? !options[:skip_active_record] && options[:database] == 'sqlite3' end @@ -198,39 +206,63 @@ module Rails def self.path(name, path, comment = nil) new(name, nil, comment, path: path) end + + def version + version = super + + if version.is_a?(Array) + version.join("', '") + else + version + end + end end def rails_gemfile_entry + dev_edge_common = [ + ] if options.dev? [ - GemfileEntry.path('rails', Rails::Generators::RAILS_DEV_PATH), - GemfileEntry.github('arel', 'rails/arel') - ] + GemfileEntry.path('rails', Rails::Generators::RAILS_DEV_PATH) + ] + dev_edge_common elsif options.edge? [ - GemfileEntry.github('rails', 'rails/rails'), - GemfileEntry.github('arel', 'rails/arel') - ] + GemfileEntry.github('rails', 'rails/rails') + ] + dev_edge_common else [GemfileEntry.version('rails', - Rails::VERSION::STRING, + rails_version_specifier, "Bundle edge Rails instead: gem 'rails', github: 'rails/rails'")] end end + def rails_version_specifier(gem_version = Rails.gem_version) + if gem_version.prerelease? + next_series = gem_version + next_series = next_series.bump while next_series.segments.size > 2 + + [">= #{gem_version}", "< #{next_series}"] + elsif gem_version.segments.size == 3 + "~> #{gem_version}" + else + patch = gem_version.segments[0, 3].join(".") + ["~> #{patch}", ">= #{gem_version}"] + end + end + def gem_for_database # %w( mysql oracle postgresql sqlite3 frontbase ibm_db sqlserver jdbcmysql jdbcsqlite3 jdbcpostgresql ) case options[:database] - when "oracle" then "ruby-oci8" - when "postgresql" then "pg" - when "frontbase" then "ruby-frontbase" - when "mysql" then "mysql2" - when "sqlserver" then "activerecord-sqlserver-adapter" - when "jdbcmysql" then "activerecord-jdbcmysql-adapter" - when "jdbcsqlite3" then "activerecord-jdbcsqlite3-adapter" - when "jdbcpostgresql" then "activerecord-jdbcpostgresql-adapter" - when "jdbc" then "activerecord-jdbc-adapter" - else options[:database] + when "oracle" then ["ruby-oci8", nil] + when "postgresql" then ["pg", ["~> 0.18"]] + 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] + when "jdbcpostgresql" then ["activerecord-jdbcpostgresql-adapter", nil] + when "jdbc" then ["activerecord-jdbc-adapter", nil] + else [options[:database], nil] end end @@ -249,8 +281,6 @@ module Rails return [] if options[:skip_sprockets] gems = [] - gems << GemfileEntry.version('sass-rails', '~> 5.0', - 'Use SCSS for stylesheets') gems << GemfileEntry.version('uglifier', '>= 1.3.0', @@ -261,7 +291,7 @@ module Rails def jbuilder_gemfile_entry comment = 'Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder' - GemfileEntry.version('jbuilder', '~> 2.0', comment) + GemfileEntry.new 'jbuilder', '~> 2.0', comment, {}, options[:api] end def coffee_gemfile_entry @@ -315,10 +345,6 @@ module Rails # its own vendored Thor, which could be a different version. Running both # things in the same process is a recipe for a night with paracetamol. # - # We use backticks and #print here instead of vanilla #system because it - # is easier to silence stdout in the existing test suite this way. The - # end-user gets the bundler commands called anyway, so no big deal. - # # We unset temporary bundler variables to load proper bundler and Gemfile. # # Thanks to James Tucker for the Gem tricks involved in this call. @@ -326,8 +352,12 @@ module Rails require 'bundler' Bundler.with_clean_env do - output = `"#{Gem.ruby}" "#{_bundle_command}" #{command}` - print output unless options[:quiet] + full_command = %Q["#{Gem.ruby}" "#{_bundle_command}" #{command}] + if options[:quiet] + system(full_command, out: File::NULL) + else + system(full_command) + end end end @@ -336,7 +366,7 @@ module Rails end def spring_install? - !options[:skip_spring] && Process.respond_to?(:fork) && !RUBY_PLATFORM.include?("cygwin") + !options[:skip_spring] && !options.dev? && Process.respond_to?(:fork) && !RUBY_PLATFORM.include?("cygwin") end def run_bundle @@ -355,7 +385,7 @@ module Rails end def keep_file(destination) - create_file("#{destination}/.keep") unless options[:skip_keeps] + create_file("#{destination}/.keep") if keeps? end end end diff --git a/railties/lib/rails/generators/base.rb b/railties/lib/rails/generators/base.rb index 813b8b629e..c72ec400a0 100644 --- a/railties/lib/rails/generators/base.rb +++ b/railties/lib/rails/generators/base.rb @@ -103,12 +103,12 @@ module Rails # hook_for :test_framework, as: :controller # end # - # And now it will lookup at: + # And now it will look up at: # # "test_unit:controller", "test_unit" # - # Similarly, if you want it to also lookup in the rails namespace, you just - # need to provide the :in value: + # Similarly, if you want it to also look up in the rails namespace, you + # just need to provide the :in value: # # class AwesomeGenerator < Rails::Generators::Base # hook_for :test_framework, in: :rails, as: :controller @@ -302,13 +302,13 @@ module Rails default_for_option(Rails::Generators.options, name, options, options[:default]) end - # Return default aliases for the option name given doing a lookup in + # Returns default aliases for the option name given doing a lookup in # Rails::Generators.aliases. def self.default_aliases_for_option(name, options) default_for_option(Rails::Generators.aliases, name, options, options[:aliases]) end - # Return default for the option name given doing a lookup in config. + # 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) c[name] diff --git a/railties/lib/rails/generators/erb/mailer/mailer_generator.rb b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb index 65563aa6db..bc249aa5e5 100644 --- a/railties/lib/rails/generators/erb/mailer/mailer_generator.rb +++ b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb @@ -9,13 +9,6 @@ module Erb # :nodoc: 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", filename_with_extensions("mailer", format)) - template filename_with_extensions(:layout, format), layout_path - end - end - actions.each do |action| @action = action diff --git a/railties/lib/rails/generators/erb/mailer/templates/layout.html.erb b/railties/lib/rails/generators/erb/mailer/templates/layout.html.erb deleted file mode 100644 index 93110e74ad..0000000000 --- a/railties/lib/rails/generators/erb/mailer/templates/layout.html.erb +++ /dev/null @@ -1,5 +0,0 @@ -<html> - <body> - <%%= yield %> - </body> -</html> diff --git a/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb b/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb index d9713b0238..519b6c8603 100644 --- a/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb +++ b/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb @@ -14,17 +14,19 @@ <% attributes.each do |attribute| -%> <div class="field"> <% if attribute.password_digest? -%> - <%%= f.label :password %><br> + <%%= f.label :password %> <%%= f.password_field :password %> </div> + <div class="field"> - <%%= f.label :password_confirmation %><br> + <%%= f.label :password_confirmation %> <%%= f.password_field :password_confirmation %> <% else -%> - <%%= f.label :<%= attribute.column_name %> %><br> + <%%= f.label :<%= attribute.column_name %> %> <%%= f.<%= attribute.field_type %> :<%= attribute.column_name %> %> <% end -%> </div> + <% end -%> <div class="actions"> <%%= f.submit %> diff --git a/railties/lib/rails/generators/erb/scaffold/templates/index.html.erb b/railties/lib/rails/generators/erb/scaffold/templates/index.html.erb index c3b8ef1181..5f4904fee1 100644 --- a/railties/lib/rails/generators/erb/scaffold/templates/index.html.erb +++ b/railties/lib/rails/generators/erb/scaffold/templates/index.html.erb @@ -28,4 +28,4 @@ <br> -<%%= link_to 'New <%= human_name %>', new_<%= singular_table_name %>_path %> +<%%= link_to 'New <%= singular_table_name.titleize %>', new_<%= singular_table_name %>_path %> diff --git a/railties/lib/rails/generators/migration.rb b/railties/lib/rails/generators/migration.rb index 51e6d68bf0..87f2e1d42b 100644 --- a/railties/lib/rails/generators/migration.rb +++ b/railties/lib/rails/generators/migration.rb @@ -10,22 +10,22 @@ module Rails extend ActiveSupport::Concern attr_reader :migration_number, :migration_file_name, :migration_class_name - module ClassMethods - def migration_lookup_at(dirname) #:nodoc: + module ClassMethods #:nodoc: + def migration_lookup_at(dirname) Dir.glob("#{dirname}/[0-9]*_*.rb") end - def migration_exists?(dirname, file_name) #:nodoc: + def migration_exists?(dirname, file_name) migration_lookup_at(dirname).grep(/\d+_#{file_name}.rb$/).first end - def current_migration_number(dirname) #:nodoc: + def current_migration_number(dirname) migration_lookup_at(dirname).collect do |file| File.basename(file).split("_").first.to_i end.max.to_i end - def next_migration_number(dirname) #:nodoc: + def next_migration_number(dirname) raise NotImplementedError end end diff --git a/railties/lib/rails/generators/named_base.rb b/railties/lib/rails/generators/named_base.rb index 36456e64f5..658d883883 100644 --- a/railties/lib/rails/generators/named_base.rb +++ b/railties/lib/rails/generators/named_base.rb @@ -18,8 +18,8 @@ module Rails parse_attributes! if respond_to?(:attributes) end - # Defines the template that would be used for the migration file. - # The arguments include the source template file, the migration filename etc. + # Overrides <tt>Thor::Actions#template</tt> so it can tell if + # a template is currently being created. no_tasks do def template(source, *args, &block) inside_template do @@ -129,6 +129,18 @@ module Rails uncountable? ? "#{plural_table_name}_index" : plural_table_name end + def show_helper + "#{singular_table_name}_url(@#{singular_table_name})" + end + + def edit_helper + "edit_#{show_helper}" + end + + def new_helper + "new_#{singular_table_name}_url" + end + def singular_table_name @singular_table_name ||= (pluralize_table_names? ? table_name.singularize : table_name) end @@ -141,6 +153,10 @@ module Rails @plural_file_name ||= file_name.pluralize end + def fixture_file_name + @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 end @@ -179,6 +195,10 @@ module Rails !defined?(ActiveRecord::Base) || ActiveRecord::Base.pluralize_table_names end + def mountable_engine? + defined?(ENGINE_ROOT) && namespaced? + end + # Add a class collisions name to be checked on class initialization. You # can supply a hash with a :prefix or :suffix to be tested. # diff --git a/railties/lib/rails/generators/rails/app/USAGE b/railties/lib/rails/generators/rails/app/USAGE index 691095f33f..28df6ebf44 100644 --- a/railties/lib/rails/generators/rails/app/USAGE +++ b/railties/lib/rails/generators/rails/app/USAGE @@ -12,4 +12,3 @@ Example: rails new ~/Code/Ruby/weblog This generates a skeletal Rails installation in ~/Code/Ruby/weblog. - See the README in the newly created application to get going. diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb index 899b33e529..44bbc478d0 100644 --- a/railties/lib/rails/generators/rails/app/app_generator.rb +++ b/railties/lib/rails/generators/rails/app/app_generator.rb @@ -57,8 +57,7 @@ module Rails directory 'app' keep_file 'app/assets/images' - keep_file 'app/mailers' - keep_file 'app/models' + keep_file 'app/assets/javascripts/channels' unless options[:skip_action_cable] keep_file 'app/controllers/concerns' keep_file 'app/models/concerns' @@ -83,6 +82,7 @@ module Rails directory "environments" directory "initializers" directory "locales" + directory "redis" unless options[:skip_action_cable] end end @@ -141,6 +141,7 @@ module Rails end def tmp + empty_directory_with_keep_file "tmp" empty_directory "tmp/cache" empty_directory "tmp/cache/assets" end @@ -174,6 +175,9 @@ module Rails class_option :version, type: :boolean, aliases: "-v", group: :rails, desc: "Show Rails version number and quit" + class_option :api, type: :boolean, + desc: "Preconfigure smaller stack for API only apps" + def initialize(*args) super @@ -184,6 +188,10 @@ module Rails if !options[:skip_active_record] && !DATABASES.include?(options[:database]) raise Error, "Invalid value for --database option. Supported for preconfiguration are: #{DATABASES.join(", ")}." end + + # Force sprockets 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] end public_task :set_default_accessors! @@ -251,6 +259,28 @@ module Rails build(:vendor) 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' + end + end + + def delete_app_helpers_if_api_option + if options[:api] + remove_dir 'app/helpers' + remove_dir 'test/helpers' + end + end + + def delete_app_views_if_api_option + if options[:api] + remove_dir 'app/views' + end + end + def delete_js_folder_skipping_javascript if options[:skip_javascript] remove_dir 'app/assets/javascripts' @@ -263,12 +293,34 @@ module Rails end end + def delete_application_record_skipping_active_record + if options[:skip_active_record] + 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' + end + end + def delete_active_record_initializers_skipping_active_record if options[:skip_active_record] remove_file 'config/initializers/active_record_belongs_to_required_by_default.rb' 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/request_forgery_protection.rb' + end + end + def finish_template build(:leftovers) end @@ -319,7 +371,9 @@ module Rails if app_const =~ /^\d/ raise Error, "Invalid application name #{app_name}. Please give a name which does not start with numbers." elsif RESERVED_NAMES.include?(app_name) - raise Error, "Invalid application name #{app_name}. Please give a name which does not match one of the reserved rails words." + raise Error, "Invalid application name #{app_name}. Please give a " \ + "name which does not match one of the reserved rails " \ + "words: #{RESERVED_NAMES.join(", ")}" elsif Object.const_defined?(app_const_base) raise Error, "Invalid application name #{app_name}, constant #{app_const_base} is already in use. Please choose another application name." end diff --git a/railties/lib/rails/generators/rails/app/templates/Gemfile b/railties/lib/rails/generators/rails/app/templates/Gemfile index c11bb58bfa..da5af4eefc 100644 --- a/railties/lib/rails/generators/rails/app/templates/Gemfile +++ b/railties/lib/rails/generators/rails/app/templates/Gemfile @@ -12,34 +12,41 @@ source 'https://rubygems.org' <% end -%> <% end -%> +# Use Puma as the app server +gem 'puma' + # Use ActiveModel has_secure_password # gem 'bcrypt', '~> 3.1.7' -# Use Unicorn as the app server -# gem 'unicorn' - # Use Capistrano for deployment # gem 'capistrano-rails', group: :development -group :development, :test do +<%- if options.api? -%> +# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible +# gem 'rack-cors' + +<%- end -%> <% if RUBY_ENGINE == 'ruby' -%> +group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'byebug' +end +group :development do +<%- unless options.api? -%> # Access an IRB console on exception pages or by using <%%= console %> in views <%- if options.dev? || options.edge? -%> - gem 'web-console', github: "rails/web-console" + gem 'web-console', github: 'rails/web-console' <%- else -%> - gem 'web-console', '~> 2.0' + gem 'web-console', '~> 3.0' <%- end -%> -<%- if spring_install? %> +<%- end -%> +<% if spring_install? -%> # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring' <% end -%> -<% end -%> end -<% if RUBY_PLATFORM.match(/bccwin|cygwin|emx|mingw|mswin|wince|java/) -%> +<% end -%> # Windows does not include zoneinfo files, so bundle the tzinfo-data gem gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] -<% end -%> diff --git a/railties/lib/rails/generators/rails/app/templates/app/assets/config/manifest.js.tt b/railties/lib/rails/generators/rails/app/templates/app/assets/config/manifest.js.tt new file mode 100644 index 0000000000..f4ee1409af --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/app/assets/config/manifest.js.tt @@ -0,0 +1,7 @@ +<% unless options.api? -%> +//= link_tree ../images +<% end -%> +<% unless options.skip_javascript -%> +//= link_directory ../javascripts .js +<% end -%> +//= link_directory ../stylesheets .css 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 cb86978d4c..c88426ec06 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 @@ -5,7 +5,7 @@ // 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. +// compiled file. JavaScript code in this file should be added after the last require_* statement. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. diff --git a/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/cable.coffee b/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/cable.coffee new file mode 100644 index 0000000000..49a7cfa69b --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/cable.coffee @@ -0,0 +1,11 @@ +# 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. +# +# Turn on the cable connection by removing the comments after the require statements (and ensure it's also on in config/routes.rb). +# +#= require action_cable +#= require_self +#= require_tree ./channels +# +# @App ||= {} +# App.cable = ActionCable.createConsumer() 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 0cdd2788d0..0ebd7fe829 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 @@ -7,7 +7,8 @@ * * 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 - * files in this directory. It is generally better to create a new file per style scope. + * files in this directory. Styles in this file should be added after the last require_* statement. + * It is generally better to create a new file per style scope. * *= require_tree . *= require_self diff --git a/railties/lib/rails/generators/rails/app/templates/app/channels/application_cable/channel.rb b/railties/lib/rails/generators/rails/app/templates/app/channels/application_cable/channel.rb new file mode 100644 index 0000000000..438c84154d --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/app/channels/application_cable/channel.rb @@ -0,0 +1,5 @@ +# Be sure to restart your server when you modify this file. Action Cable runs in an EventMachine loop that does not support auto reloading. +module ApplicationCable + class Channel < ActionCable::Channel::Base + end +end diff --git a/railties/lib/rails/generators/rails/app/templates/app/channels/application_cable/connection.rb b/railties/lib/rails/generators/rails/app/templates/app/channels/application_cable/connection.rb new file mode 100644 index 0000000000..965046f3c7 --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/app/channels/application_cable/connection.rb @@ -0,0 +1,5 @@ +# Be sure to restart your server when you modify this file. Action Cable runs in an EventMachine loop that does not support auto reloading. +module ApplicationCable + class Connection < ActionCable::Connection::Base + end +end diff --git a/railties/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb.tt b/railties/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb.tt index d83690e1b9..f726fd6305 100644 --- a/railties/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb.tt +++ b/railties/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb.tt @@ -1,5 +1,7 @@ -class ApplicationController < ActionController::Base +class ApplicationController < ActionController::<%= options[:api] ? "API" : "Base" %> +<%- unless options[:api] -%> # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception +<%- end -%> end diff --git a/railties/lib/rails/generators/rails/app/templates/app/jobs/application_job.rb b/railties/lib/rails/generators/rails/app/templates/app/jobs/application_job.rb new file mode 100644 index 0000000000..a009ace51c --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/app/jobs/application_job.rb @@ -0,0 +1,2 @@ +class ApplicationJob < ActiveJob::Base +end diff --git a/railties/lib/rails/generators/rails/app/templates/app/mailers/application_mailer.rb b/railties/lib/rails/generators/rails/app/templates/app/mailers/application_mailer.rb new file mode 100644 index 0000000000..286b2239d1 --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/app/mailers/application_mailer.rb @@ -0,0 +1,4 @@ +class ApplicationMailer < ActionMailer::Base + default from: 'from@example.com' + layout 'mailer' +end diff --git a/railties/lib/rails/generators/rails/app/templates/app/models/application_record.rb b/railties/lib/rails/generators/rails/app/templates/app/models/application_record.rb new file mode 100644 index 0000000000..10a4cba84d --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/app/models/application_record.rb @@ -0,0 +1,3 @@ +class ApplicationRecord < ActiveRecord::Base + self.abstract_class = true +end 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 75ea52828e..68b5c051b2 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 @@ -1,23 +1,26 @@ <!DOCTYPE html> <html> -<head> - <title><%= camelized %></title> - <%- if options[:skip_javascript] -%> - <%%= stylesheet_link_tag 'application', media: 'all' %> - <%- else -%> - <%- if gemfile_entries.any? { |m| m.name == 'turbolinks' } -%> - <%%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %> - <%%= javascript_include_tag 'application', 'data-turbolinks-track' => true %> - <%- else -%> - <%%= stylesheet_link_tag 'application', media: 'all' %> - <%%= javascript_include_tag 'application' %> + <head> + <title><%= camelized %></title> + <%%= csrf_meta_tags %> + <%- unless options[:skip_action_cable] -%> + <%%= action_cable_meta_tag %> <%- end -%> - <%- end -%> - <%%= csrf_meta_tags %> -</head> -<body> -<%%= yield %> + <%- if options[:skip_javascript] -%> + <%%= stylesheet_link_tag 'application', media: 'all' %> + <%- else -%> + <%- if gemfile_entries.any? { |m| m.name == 'turbolinks' } -%> + <%%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %> + <%%= javascript_include_tag 'application', 'data-turbolinks-track' => true %> + <%- else -%> + <%%= stylesheet_link_tag 'application', media: 'all' %> + <%%= javascript_include_tag 'application' %> + <%- end -%> + <%- end -%> + </head> -</body> + <body> + <%%= yield %> + </body> </html> diff --git a/railties/lib/rails/generators/rails/app/templates/app/views/layouts/mailer.html.erb.tt b/railties/lib/rails/generators/rails/app/templates/app/views/layouts/mailer.html.erb.tt new file mode 100644 index 0000000000..55f3675d49 --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/app/views/layouts/mailer.html.erb.tt @@ -0,0 +1,13 @@ +<!DOCTYPE html> +<html> + <head> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> + <style> + /* Email styles need to be inline */ + </style> + </head> + + <body> + <%%= yield %> + </body> +</html> diff --git a/railties/lib/rails/generators/erb/mailer/templates/layout.text.erb b/railties/lib/rails/generators/rails/app/templates/app/views/layouts/mailer.text.erb.tt index 6363733e6e..6363733e6e 100644 --- a/railties/lib/rails/generators/erb/mailer/templates/layout.text.erb +++ b/railties/lib/rails/generators/rails/app/templates/app/views/layouts/mailer.text.erb.tt diff --git a/railties/lib/rails/generators/rails/app/templates/bin/setup b/railties/lib/rails/generators/rails/app/templates/bin/setup index eee810be30..df88bfd3bc 100644 --- a/railties/lib/rails/generators/rails/app/templates/bin/setup +++ b/railties/lib/rails/generators/rails/app/templates/bin/setup @@ -5,13 +5,17 @@ include FileUtils # path to your application root. APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +end + chdir APP_ROOT do # This script is a starting point to setup your application. # Add necessary setup steps to this file. puts '== Installing dependencies ==' - system 'gem install bundler --conservative' - system('bundle check') or system('bundle install') + system! 'gem install bundler --conservative' + system('bundle check') or system!('bundle install') # puts "\n== Copying sample files ==" # unless File.exist?('config/database.yml') @@ -19,12 +23,11 @@ chdir APP_ROOT do # end puts "\n== Preparing database ==" - system 'ruby bin/rake db:setup' + system! 'bin/rails db:setup' puts "\n== Removing old logs and tempfiles ==" - rm_f Dir.glob('log/*') - rm_rf 'tmp/cache' + system! 'bin/rails log:clear tmp:clear' puts "\n== Restarting application server ==" - touch 'tmp/restart.txt' + system! 'bin/rails restart' end diff --git a/railties/lib/rails/generators/rails/app/templates/bin/update b/railties/lib/rails/generators/rails/app/templates/bin/update new file mode 100644 index 0000000000..c6ed3ae64b --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/bin/update @@ -0,0 +1,28 @@ +require 'pathname' +require 'fileutils' +include FileUtils + +# path to your application root. +APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) + +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +end + +chdir APP_ROOT do + # This script is a way to update your development environment automatically. + # Add necessary update steps to this file. + + puts '== Installing dependencies ==' + system! 'gem install bundler --conservative' + system 'bundle check' or system! 'bundle install' + + puts "\n== Updating database ==" + system! 'bin/rails db:migrate' + + puts "\n== Removing old logs and tempfiles ==" + system! 'bin/rails log:clear tmp:clear' + + puts "\n== Restarting application server ==" + system! 'bin/rails restart' +end diff --git a/railties/lib/rails/generators/rails/app/templates/config.ru b/railties/lib/rails/generators/rails/app/templates/config.ru deleted file mode 100644 index bd83b25412..0000000000 --- a/railties/lib/rails/generators/rails/app/templates/config.ru +++ /dev/null @@ -1,4 +0,0 @@ -# This file is used by Rack-based servers to start the application. - -require ::File.expand_path('../config/environment', __FILE__) -run Rails.application diff --git a/railties/lib/rails/generators/rails/app/templates/config.ru.tt b/railties/lib/rails/generators/rails/app/templates/config.ru.tt new file mode 100644 index 0000000000..3a279ffcc0 --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/config.ru.tt @@ -0,0 +1,11 @@ +# This file is used by Rack-based servers to start the application. + +require ::File.expand_path('../config/environment', __FILE__) + +<%- unless options[:skip_action_cable] -%> +# Action Cable uses EventMachine which requires that all classes are loaded in advance +Rails.application.eager_load! +require 'action_cable/process/logging' +<%- end -%> + +run Rails.application diff --git a/railties/lib/rails/generators/rails/app/templates/config/application.rb b/railties/lib/rails/generators/rails/app/templates/config/application.rb index a2661bfb51..cb83364360 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/application.rb +++ b/railties/lib/rails/generators/rails/app/templates/config/application.rb @@ -11,6 +11,7 @@ require "active_job/railtie" require "action_controller/railtie" <%= comment_if :skip_action_mailer %>require "action_mailer/railtie" require "action_view/railtie" +<%= comment_if :skip_action_cable %>require "action_cable/engine" <%= comment_if :skip_sprockets %>require "sprockets/railtie" <%= comment_if :skip_test %>require "rails/test_unit/railtie" <% end -%> @@ -24,13 +25,12 @@ module <%= app_const_base %> # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. +<%- if options[:api] -%> - # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. - # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. - # config.time_zone = 'Central Time (US & Canada)' - - # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. - # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] - # config.i18n.default_locale = :de + # Only loads a smaller set of middleware suitable for API only apps. + # Middleware like session, flash, cookies can be added back manually. + # Skip views, helpers and assets when generating a new resource. + config.api_only = true +<%- end -%> 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 f5b62e8fb3..5ca549a8c8 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 @@ -7,7 +7,7 @@ # gem 'activerecord-jdbcmysql-adapter' # # And be sure to use new-style password hashing: -# http://dev.mysql.com/doc/refman/5.6/en/old-client.html +# http://dev.mysql.com/doc/refman/5.7/en/old-client.html # default: &default adapter: mysql 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 b0767bd93a..119c2fe2c3 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 @@ -7,7 +7,7 @@ # gem 'mysql2' # # And be sure to use new-style password hashing: -# http://dev.mysql.com/doc/refman/5.6/en/old-client.html +# http://dev.mysql.com/doc/refman/5.7/en/old-client.html # default: &default adapter: mysql2 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 ecb5d4170f..fd41372d9c 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 @@ -9,9 +9,20 @@ Rails.application.configure do # Do not eager load code on boot. config.eager_load = false - # Show full error reports and disable caching. - config.consider_all_requests_local = true - config.action_controller.perform_caching = false + # Show full error reports. + config.consider_all_requests_local = true + + # Enable/disable caching. By default caching is disabled. + if Rails.root.join('tmp/caching-dev.txt').exist? + config.action_controller.perform_caching = true + config.cache_store = :memory_store + config.public_file_server.headers = { + 'Cache-Control' => 'public, max-age=172800' + } + else + config.action_controller.perform_caching = false + config.cache_store = :null_store + end <%- unless options.skip_action_mailer? -%> # Don't care if the mailer can't send. @@ -44,4 +55,8 @@ Rails.application.configure do # Raises error for missing translations # config.action_view.raise_on_missing_translations = true + + # Use an evented file watcher to asynchronously detect changes in source code, + # routes, locales, etc. This feature depends on the listen gem. + # config.file_watcher = ActiveSupport::EventedFileUpdateChecker end 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 8c09396fc1..8d59a6fcf3 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 @@ -16,7 +16,7 @@ Rails.application.configure do # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. - config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present? + config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? <%- unless options.skip_sprockets? -%> # Compress JavaScripts and CSS. @@ -40,6 +40,12 @@ Rails.application.configure do # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX + <%- unless options[:skip_action_cable] -%> + # Action Cable endpoint configuration + # config.action_cable.url = 'wss://example.com/cable' + # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] + <%- end -%> + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true @@ -51,7 +57,8 @@ Rails.application.configure do # config.log_tags = [ :subdomain, :request_id ] # Use a different logger for distributed setups. - # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) + # require 'syslog/logger' + # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') # Use a different cache store in production. # config.cache_store = :mem_cache_store 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 0306deb18c..8133917591 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 @@ -12,9 +12,11 @@ Rails.application.configure do # preloads Rails for running tests, you may have to set it to true. config.eager_load = false - # Configure static file server for tests with Cache-Control for performance. - config.serve_static_files = true - config.static_cache_control = 'public, max-age=3600' + # 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' + } # Show full error reports and disable caching. config.consider_all_requests_local = true diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/active_record_belongs_to_required_by_default.rb b/railties/lib/rails/generators/rails/app/templates/config/initializers/active_record_belongs_to_required_by_default.rb index 30c4f89792..40c831ec58 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/initializers/active_record_belongs_to_required_by_default.rb +++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/active_record_belongs_to_required_by_default.rb @@ -1,4 +1,5 @@ # Be sure to restart your server when you modify this file. -# Require `belongs_to` associations by default. +# Require `belongs_to` associations by default. This is a new Rails 5.0 default, +# so introduced as a config to ensure apps made with earlier versions of Rails aren't affected when upgrading. Rails.application.config.active_record.belongs_to_required_by_default = true diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/application_controller_renderer.rb b/railties/lib/rails/generators/rails/app/templates/config/initializers/application_controller_renderer.rb index ea930f54da..51639b67a0 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/initializers/application_controller_renderer.rb +++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/application_controller_renderer.rb @@ -1,5 +1,5 @@ -## Change renderer defaults here. -# +# Be sure to restart your server when you modify this file. + # ApplicationController.renderer.defaults.merge!( # http_host: 'example.org', # https: false diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/callback_terminator.rb b/railties/lib/rails/generators/rails/app/templates/config/initializers/callback_terminator.rb index e63022da91..43510c244b 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/initializers/callback_terminator.rb +++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/callback_terminator.rb @@ -1,4 +1,5 @@ # Be sure to restart your server when you modify this file. -# Do not halt callback chains when a callback returns false. -Rails.application.config.active_support.halt_callback_chains_on_return_false = false +# Do not halt callback chains when a callback returns false. This is a new Rails 5.0 default, +# so introduced as a config to ensure apps made with earlier versions of Rails aren't affected when upgrading. +ActiveSupport.halt_callback_chains_on_return_false = false diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/cookies_serializer.rb b/railties/lib/rails/generators/rails/app/templates/config/initializers/cookies_serializer.rb index 7f70458dee..93329258f7 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/initializers/cookies_serializer.rb +++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/cookies_serializer.rb @@ -1,3 +1,4 @@ # Be sure to restart your server when you modify this file. +# This is a new Rails 5.0 default, so introduced as a config to ensure apps made with earlier versions of Rails aren't affected when upgrading. Rails.application.config.action_dispatch.cookies_serializer = :json diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/cors.rb b/railties/lib/rails/generators/rails/app/templates/config/initializers/cors.rb new file mode 100644 index 0000000000..3b1c1b5ed1 --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/cors.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Avoid CORS issues when API is called from the frontend app. +# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests. + +# Read more: https://github.com/cyu/rack-cors + +# Rails.application.config.middleware.insert_before 0, Rack::Cors do +# allow do +# origins 'example.com' +# +# resource '*', +# headers: :any, +# methods: [:get, :post, :put, :patch, :delete, :options, :head] +# end +# end diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/request_forgery_protection.rb b/railties/lib/rails/generators/rails/app/templates/config/initializers/request_forgery_protection.rb new file mode 100644 index 0000000000..3eab78a885 --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/request_forgery_protection.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Enable origin-checking CSRF mitigation. +Rails.application.config.action_controller.forgery_protection_origin_check = true diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt index 94f612c3dd..cadc85cfac 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt +++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt @@ -5,7 +5,7 @@ # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. ActiveSupport.on_load(:action_controller) do - wrap_parameters format: [:json] if respond_to?(:wrap_parameters) + wrap_parameters format: [:json] end <%- unless options.skip_active_record? -%> diff --git a/railties/lib/rails/generators/rails/app/templates/config/redis/cable.yml b/railties/lib/rails/generators/rails/app/templates/config/redis/cable.yml new file mode 100644 index 0000000000..0176be24f9 --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/config/redis/cable.yml @@ -0,0 +1,9 @@ +# Action Cable uses Redis to administer connections, channels, and sending/receiving messages over the WebSocket. +production: + url: redis://localhost:6379/1 + +development: + url: redis://localhost:6379/2 + +test: + url: redis://localhost:6379/3 diff --git a/railties/lib/rails/generators/rails/app/templates/config/routes.rb b/railties/lib/rails/generators/rails/app/templates/config/routes.rb index 3f66539d54..8293c8a483 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/routes.rb +++ b/railties/lib/rails/generators/rails/app/templates/config/routes.rb @@ -1,56 +1,6 @@ Rails.application.routes.draw do - # The priority is based upon order of creation: first created -> highest priority. - # See how all your routes lay out with "rake routes". + # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html - # You can have the root of your site routed with "root" - # root 'welcome#index' - - # Example of regular route: - # get 'products/:id' => 'catalog#view' - - # Example of named route that can be invoked with purchase_url(id: product.id) - # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase - - # Example resource route (maps HTTP verbs to controller actions automatically): - # resources :products - - # Example resource route with options: - # resources :products do - # member do - # get 'short' - # post 'toggle' - # end - # - # collection do - # get 'sold' - # end - # end - - # Example resource route with sub-resources: - # resources :products do - # resources :comments, :sales - # resource :seller - # end - - # Example resource route with more complex sub-resources: - # resources :products do - # resources :comments - # resources :sales do - # get 'recent', on: :collection - # end - # end - - # Example resource route with concerns: - # concern :toggleable do - # post 'toggle' - # end - # resources :posts, concerns: :toggleable - # resources :photos, concerns: :toggleable - - # Example resource route within a namespace: - # namespace :admin do - # # Directs /admin/products/* to Admin::ProductsController - # # (app/controllers/admin/products_controller.rb) - # resources :products - # end + # Serve websocket cable requests in-process + # mount ActionCable.server => '/cable' end diff --git a/railties/lib/rails/generators/rails/app/templates/db/seeds.rb.tt b/railties/lib/rails/generators/rails/app/templates/db/seeds.rb.tt index 4edb1e857e..cfadd24017 100644 --- a/railties/lib/rails/generators/rails/app/templates/db/seeds.rb.tt +++ b/railties/lib/rails/generators/rails/app/templates/db/seeds.rb.tt @@ -1,7 +1,7 @@ # This file should contain all the record creation needed to seed the database with its default values. -# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). +# The data can then be loaded with the rails db:seed (or created alongside the db with db:setup). # # Examples: # -# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) -# Mayor.create(name: 'Emanuel', city: cities.first) +# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) +# Character.create(name: 'Luke', movie: movies.first) diff --git a/railties/lib/rails/generators/rails/app/templates/gitignore b/railties/lib/rails/generators/rails/app/templates/gitignore index 7c6f2098b8..0e66cc4237 100644 --- a/railties/lib/rails/generators/rails/app/templates/gitignore +++ b/railties/lib/rails/generators/rails/app/templates/gitignore @@ -15,5 +15,11 @@ <% end -%> # Ignore all logfiles and tempfiles. /log/* +/tmp/* +<% if keeps? -%> !/log/.keep -/tmp +!/tmp/.keep +<% end -%> + +# Ignore Byebug command history file. +.byebug_history diff --git a/railties/lib/rails/generators/rails/controller/controller_generator.rb b/railties/lib/rails/generators/rails/controller/controller_generator.rb index df615c88b5..0a4c509a31 100644 --- a/railties/lib/rails/generators/rails/controller/controller_generator.rb +++ b/railties/lib/rails/generators/rails/controller/controller_generator.rb @@ -13,12 +13,14 @@ module Rails def add_routes unless options[:skip_routes] actions.reverse_each do |action| - route generate_routing_code(action) + # route prepends two spaces onto the front of the string that is passed, this corrects that. + route generate_routing_code(action)[2..-1] end end end - hook_for :template_engine, :test_framework, :helper, :assets + hook_for :template_engine, :test_framework + hook_for :helper, :assets, hide: true private @@ -36,12 +38,12 @@ module Rails # 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) + indent(" namespace :#{ns} do\n", i * 2) end.join # Create route # get 'baz/index' - route = indent(%{get '#{file_name}/#{action}'\n}, depth * 2) + route = indent(%{ get '#{file_name}/#{action}'\n}, depth * 2) # Create `end` ladder # end diff --git a/railties/lib/rails/generators/rails/plugin/plugin_generator.rb b/railties/lib/rails/generators/rails/plugin/plugin_generator.rb index 68c3829515..7d7477de75 100644 --- a/railties/lib/rails/generators/rails/plugin/plugin_generator.rb +++ b/railties/lib/rails/generators/rails/plugin/plugin_generator.rb @@ -8,7 +8,7 @@ module Rails # generator. # # This allows you to override entire operations, like the creation of the - # Gemfile, README, or JavaScript files, without needing to know exactly + # Gemfile, \README, or JavaScript files, without needing to know exactly # what those operations do so you can create another template action. class PluginBuilder def rakefile @@ -17,20 +17,27 @@ module Rails def app if mountable? - directory 'app' - empty_directory_with_keep_file "app/assets/images/#{namespaced_name}" + if api? + directory 'app', exclude_pattern: %r{app/(views|helpers)} + else + 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/views' - empty_directory_with_keep_file 'app/helpers' empty_directory_with_keep_file 'app/mailers' - empty_directory_with_keep_file "app/assets/images/#{namespaced_name}" + + 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' + end end end def readme - template "README.rdoc" + template "README.md" end def gemfile @@ -82,6 +89,7 @@ task default: :test opts = (options || {}).slice(*PASSTHROUGH_OPTIONS) opts[:force] = force opts[:skip_bundle] = true + opts[:api] = options.api? invoke Rails::Generators::AppGenerator, [ File.expand_path(dummy_path, destination_root) ], opts @@ -96,8 +104,9 @@ task default: :test end def test_dummy_assets - template "rails/javascripts.js", "#{dummy_path}/app/assets/javascripts/application.js", force: true - template "rails/stylesheets.css", "#{dummy_path}/app/assets/stylesheets/application.css", force: true + template "rails/javascripts.js", "#{dummy_path}/app/assets/javascripts/application.js", force: true + template "rails/stylesheets.css", "#{dummy_path}/app/assets/stylesheets/application.css", force: true + template "rails/dummy_manifest.js", "#{dummy_path}/app/assets/config/manifest.js", force: true end def test_dummy_clean @@ -108,12 +117,16 @@ task default: :test remove_file "Gemfile" remove_file "lib/tasks" remove_file "public/robots.txt" - remove_file "README" + remove_file "README.md" remove_file "test" remove_file "vendor" end end + def assets_manifest + template "rails/engine_manifest.js", "app/assets/config/#{underscored_name}_manifest.js" + end + def stylesheets if mountable? copy_file "rails/stylesheets.css", @@ -135,9 +148,8 @@ task default: :test end def bin(force = false) - return unless engine? - - directory "bin", force: force do |content| + bin_file = engine? ? 'bin/rails.tt' : 'bin/test.tt' + template bin_file, force: force do |content| "#{shebang}\n" + content end chmod "bin", 0755, verbose: false @@ -176,6 +188,9 @@ task default: :test desc: "If creating plugin in application's directory " + "skip adding entry to Gemfile" + class_option :api, type: :boolean, default: false, + desc: "Generate a smaller stack for API application plugins" + def initialize(*args) @dummy_path = nil super @@ -209,16 +224,16 @@ task default: :test build(:lib) end - def create_public_stylesheets_files - build(:stylesheets) + def create_assets_manifest_file + build(:assets_manifest) if !api? && engine? end - def create_javascript_files - build(:javascripts) + def create_public_stylesheets_files + build(:stylesheets) unless api? end - def create_images_directory - build(:images) + def create_javascript_files + build(:javascripts) unless api? end def create_bin_files @@ -305,6 +320,10 @@ task default: :test options[:skip_test].blank? || options[:dummy_path] != 'test/dummy' end + def api? + options[:api] + end + def self.banner "rails plugin new #{self.arguments.map(&:usage).join(' ')} [options]" end @@ -364,7 +383,9 @@ task default: :test elsif camelized =~ /^\d/ raise Error, "Invalid plugin name #{original_name}. Please give a name which does not start with numbers." elsif RESERVED_NAMES.include?(name) - raise Error, "Invalid plugin name #{original_name}. Please give a name which does not match one of the reserved rails words." + raise Error, "Invalid plugin name #{original_name}. Please give a " \ + "name which does not match one of the reserved rails " \ + "words: #{RESERVED_NAMES.join(", ")}" elsif Object.const_defined?(camelized) raise Error, "Invalid plugin name #{original_name}, constant #{camelized} is already in use. Please choose another plugin name." end diff --git a/railties/lib/rails/generators/rails/plugin/templates/%name%.gemspec b/railties/lib/rails/generators/rails/plugin/templates/%name%.gemspec index f8ece4fe73..d84d1aabdb 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/%name%.gemspec +++ b/railties/lib/rails/generators/rails/plugin/templates/%name%.gemspec @@ -14,14 +14,11 @@ Gem::Specification.new do |s| s.description = "TODO: Description of <%= camelized_modules %>." s.license = "MIT" - s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"] -<% unless options.skip_test? -%> - s.test_files = Dir["test/**/*"] -<% end -%> + s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md"] - <%= '# ' if options.dev? || options.edge? -%>s.add_dependency "rails", "~> <%= Rails::VERSION::STRING %>" + <%= '# ' if options.dev? || options.edge? -%>s.add_dependency "rails", "<%= Array(rails_version_specifier).join('", "') %>" <% unless options[:skip_active_record] -%> - s.add_development_dependency "<%= gem_for_database %>" + s.add_development_dependency "<%= gem_for_database[0] %>" <% end -%> end diff --git a/railties/lib/rails/generators/rails/plugin/templates/Gemfile b/railties/lib/rails/generators/rails/plugin/templates/Gemfile index 2c91c6a0ea..22a4548ff2 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/Gemfile +++ b/railties/lib/rails/generators/rails/plugin/templates/Gemfile @@ -1,7 +1,7 @@ source 'https://rubygems.org' <% if options[:skip_gemspec] -%> -<%= '# ' if options.dev? || options.edge? -%>gem 'rails', '~> <%= Rails::VERSION::STRING %>' +<%= '# ' if options.dev? || options.edge? -%>gem 'rails', '<%= Array(rails_version_specifier).join("', '") %>' <% else -%> # Declare your gem's dependencies in <%= name %>.gemspec. # Bundler will treat runtime dependencies like base dependencies, and @@ -11,7 +11,7 @@ gemspec <% if options[:skip_gemspec] -%> group :development do - gem '<%= gem_for_database %>' + gem '<%= gem_for_database[0] %>' end <% else -%> # Declare any dependencies that are still in development here instead of in diff --git a/railties/lib/rails/generators/rails/plugin/templates/README.md b/railties/lib/rails/generators/rails/plugin/templates/README.md new file mode 100644 index 0000000000..61ad1ed36a --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin/templates/README.md @@ -0,0 +1,3 @@ +# <%= camelized_modules %> + +This project rocks and uses MIT-LICENSE. diff --git a/railties/lib/rails/generators/rails/plugin/templates/README.rdoc b/railties/lib/rails/generators/rails/plugin/templates/README.rdoc deleted file mode 100644 index 25983ca5da..0000000000 --- a/railties/lib/rails/generators/rails/plugin/templates/README.rdoc +++ /dev/null @@ -1,3 +0,0 @@ -= <%= camelized_modules %> - -This project rocks and uses MIT-LICENSE.
\ No newline at end of file diff --git a/railties/lib/rails/generators/rails/plugin/templates/Rakefile b/railties/lib/rails/generators/rails/plugin/templates/Rakefile index bda55bae29..f1943644e4 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/Rakefile +++ b/railties/lib/rails/generators/rails/plugin/templates/Rakefile @@ -10,7 +10,7 @@ RDoc::Task.new(:rdoc) do |rdoc| rdoc.rdoc_dir = 'rdoc' rdoc.title = '<%= camelized_modules %>' rdoc.options << '--line-numbers' - rdoc.rdoc_files.include('README.rdoc') + rdoc.rdoc_files.include('README.md') rdoc.rdoc_files.include('lib/**/*.rb') end diff --git a/railties/lib/rails/generators/rails/plugin/templates/app/controllers/%namespaced_name%/application_controller.rb.tt b/railties/lib/rails/generators/rails/plugin/templates/app/controllers/%namespaced_name%/application_controller.rb.tt index 7157e48c42..7fe4e5034d 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/app/controllers/%namespaced_name%/application_controller.rb.tt +++ b/railties/lib/rails/generators/rails/plugin/templates/app/controllers/%namespaced_name%/application_controller.rb.tt @@ -1,5 +1,5 @@ <%= wrap_in_modules <<-rb.strip_heredoc - class ApplicationController < ActionController::Base + class ApplicationController < ActionController::#{api? ? "API" : "Base"} end rb %> diff --git a/railties/lib/rails/generators/rails/plugin/templates/app/jobs/%namespaced_name%/application_job.rb.tt b/railties/lib/rails/generators/rails/plugin/templates/app/jobs/%namespaced_name%/application_job.rb.tt new file mode 100644 index 0000000000..bad1ff2d16 --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin/templates/app/jobs/%namespaced_name%/application_job.rb.tt @@ -0,0 +1,5 @@ +<%= wrap_in_modules <<-rb.strip_heredoc + class ApplicationJob < ActiveJob::Base + end +rb +%> diff --git a/railties/lib/rails/generators/rails/plugin/templates/app/models/application_record.rb.tt b/railties/lib/rails/generators/rails/plugin/templates/app/models/application_record.rb.tt new file mode 100644 index 0000000000..8aa3de78f1 --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin/templates/app/models/application_record.rb.tt @@ -0,0 +1,6 @@ +<%= wrap_in_modules <<-rb.strip_heredoc + class ApplicationRecord < ActiveRecord::Base + self.abstract_class = true + end +rb +%> diff --git a/railties/lib/rails/generators/rails/plugin/templates/bin/test.tt b/railties/lib/rails/generators/rails/plugin/templates/bin/test.tt new file mode 100644 index 0000000000..62b94618fd --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin/templates/bin/test.tt @@ -0,0 +1,8 @@ +$: << File.expand_path(File.expand_path('../../test', __FILE__)) + +require 'bundler/setup' +require 'rails/test_unit/minitest_plugin' + +Rails::TestUnitReporter.executable = 'bin/test' + +exit Minitest.run(ARGV) diff --git a/railties/lib/rails/generators/rails/plugin/templates/gitignore b/railties/lib/rails/generators/rails/plugin/templates/gitignore index d524fcbc4e..54c78d7927 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/gitignore +++ b/railties/lib/rails/generators/rails/plugin/templates/gitignore @@ -6,5 +6,4 @@ pkg/ <%= dummy_path %>/db/*.sqlite3-journal <%= dummy_path %>/log/*.log <%= dummy_path %>/tmp/ -<%= dummy_path %>/.sass-cache <% end -%> diff --git a/railties/lib/rails/generators/rails/plugin/templates/lib/%namespaced_name%/engine.rb b/railties/lib/rails/generators/rails/plugin/templates/lib/%namespaced_name%/engine.rb index 17afd52177..8938770fc4 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/lib/%namespaced_name%/engine.rb +++ b/railties/lib/rails/generators/rails/plugin/templates/lib/%namespaced_name%/engine.rb @@ -1,6 +1,7 @@ <%= wrap_in_modules <<-rb.strip_heredoc class Engine < ::Rails::Engine #{mountable? ? ' isolate_namespace ' + camelized_modules : ' '} + #{api? ? " config.generators.api_only = true" : ' '} end rb %> diff --git a/railties/lib/rails/generators/rails/plugin/templates/lib/%namespaced_name%/version.rb b/railties/lib/rails/generators/rails/plugin/templates/lib/%namespaced_name%/version.rb index d257295988..b08f4ef9ae 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/lib/%namespaced_name%/version.rb +++ b/railties/lib/rails/generators/rails/plugin/templates/lib/%namespaced_name%/version.rb @@ -1 +1 @@ -<%= wrap_in_modules 'VERSION = "0.0.1"' %> +<%= wrap_in_modules "VERSION = '0.1.0'" %> diff --git a/railties/lib/rails/generators/rails/plugin/templates/rails/dummy_manifest.js b/railties/lib/rails/generators/rails/plugin/templates/rails/dummy_manifest.js new file mode 100644 index 0000000000..8d21b2b6fb --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin/templates/rails/dummy_manifest.js @@ -0,0 +1,11 @@ + +<% unless api? -%> +//= link_tree ../images +<% end -%> +<% unless options.skip_javascript -%> +//= link_directory ../javascripts .js +<% end -%> +//= link_directory ../stylesheets .css +<% if mountable? && !api? -%> +//= link <%= underscored_name %>_manifest.js +<% end -%> diff --git a/railties/lib/rails/generators/rails/plugin/templates/rails/engine_manifest.js b/railties/lib/rails/generators/rails/plugin/templates/rails/engine_manifest.js new file mode 100644 index 0000000000..2f23844f5e --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin/templates/rails/engine_manifest.js @@ -0,0 +1,6 @@ +<% if mountable? -%> +<% if !options.skip_javascript -%> +//= link_directory ../javascripts/<%= namespaced_name %> .js +<% end -%> +//= link_directory ../stylesheets/<%= namespaced_name %> .css +<% end -%> diff --git a/railties/lib/rails/generators/rails/plugin/templates/rails/javascripts.js b/railties/lib/rails/generators/rails/plugin/templates/rails/javascripts.js index 8913b40f69..e54c6461cc 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/rails/javascripts.js +++ b/railties/lib/rails/generators/rails/plugin/templates/rails/javascripts.js @@ -5,7 +5,7 @@ // 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. +// compiled file. JavaScript code in this file should be added after the last require_* statement. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. diff --git a/railties/lib/rails/generators/rails/plugin/templates/rails/routes.rb b/railties/lib/rails/generators/rails/plugin/templates/rails/routes.rb index 673de44108..694510edc0 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/rails/routes.rb +++ b/railties/lib/rails/generators/rails/plugin/templates/rails/routes.rb @@ -1,4 +1,3 @@ Rails.application.routes.draw do - mount <%= camelized_modules %>::Engine => "/<%= name %>" end diff --git a/railties/lib/rails/generators/rails/plugin/templates/rails/stylesheets.css b/railties/lib/rails/generators/rails/plugin/templates/rails/stylesheets.css index 0cdd2788d0..0ebd7fe829 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/rails/stylesheets.css +++ b/railties/lib/rails/generators/rails/plugin/templates/rails/stylesheets.css @@ -7,7 +7,8 @@ * * 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 - * files in this directory. It is generally better to create a new file per style scope. + * files in this directory. Styles in this file should be added after the last require_* statement. + * It is generally better to create a new file per style scope. * *= require_tree . *= require_self diff --git a/railties/lib/rails/generators/rails/plugin/templates/test/integration/navigation_test.rb b/railties/lib/rails/generators/rails/plugin/templates/test/integration/navigation_test.rb index 824caecb24..f5d1ec2046 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/test/integration/navigation_test.rb +++ b/railties/lib/rails/generators/rails/plugin/templates/test/integration/navigation_test.rb @@ -1,10 +1,6 @@ require 'test_helper' class NavigationTest < ActionDispatch::IntegrationTest -<% unless options[:skip_active_record] -%> - fixtures :all -<% end -%> - # test "the truth" do # assert true # end 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 0852ffce9a..a0b00fc5c5 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 @@ -14,12 +14,14 @@ require "rails/test_help" # to be shown. Minitest.backtrace_filter = Minitest::BacktraceFilter.new -# Load support files -Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f } +<% unless engine? -%> +Rails::TestUnitReporter.executable = 'bin/test' +<% end -%> # Load fixtures from the engine if ActiveSupport::TestCase.respond_to?(:fixture_path=) ActiveSupport::TestCase.fixture_path = File.expand_path("../fixtures", __FILE__) - ActiveSupport::TestCase.file_fixture_path = ActiveSupport::TestCase.fixture_path + "files" + ActionDispatch::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path + ActiveSupport::TestCase.file_fixture_path = ActiveSupport::TestCase.fixture_path + "/files" ActiveSupport::TestCase.fixtures :all end diff --git a/railties/lib/rails/generators/rails/resource/resource_generator.rb b/railties/lib/rails/generators/rails/resource/resource_generator.rb index 8014feb75f..3acf21df13 100644 --- a/railties/lib/rails/generators/rails/resource/resource_generator.rb +++ b/railties/lib/rails/generators/rails/resource/resource_generator.rb @@ -1,6 +1,5 @@ require 'rails/generators/resource_helpers' require 'rails/generators/rails/model/model_generator' -require 'active_support/core_ext/object/blank' module Rails module Generators diff --git a/railties/lib/rails/generators/rails/resource_route/resource_route_generator.rb b/railties/lib/rails/generators/rails/resource_route/resource_route_generator.rb index c986f95e67..42705107ae 100644 --- a/railties/lib/rails/generators/rails/resource_route/resource_route_generator.rb +++ b/railties/lib/rails/generators/rails/resource_route/resource_route_generator.rb @@ -1,7 +1,6 @@ module Rails module Generators class ResourceRouteGenerator < NamedBase # :nodoc: - # Properly nests namespaces passed into a generator # # $ rails generate resource admin/users/products diff --git a/railties/lib/rails/generators/rails/scaffold/USAGE b/railties/lib/rails/generators/rails/scaffold/USAGE index 1b2a944103..d2e495758d 100644 --- a/railties/lib/rails/generators/rails/scaffold/USAGE +++ b/railties/lib/rails/generators/rails/scaffold/USAGE @@ -36,6 +36,6 @@ Description: Examples: `rails generate scaffold post` - `rails generate scaffold post title body:text published:boolean` + `rails generate scaffold post title:string body:text published:boolean` `rails generate scaffold purchase amount:decimal tracking_id:integer:uniq` `rails generate scaffold user email:uniq password:digest` diff --git a/railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb b/railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb index e89789e72b..17c32bfdb3 100644 --- a/railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb +++ b/railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb @@ -10,10 +10,11 @@ module Rails class_option :stylesheet_engine, desc: "Engine for Stylesheets" class_option :assets, type: :boolean class_option :resource_route, type: :boolean + class_option :scaffold_stylesheet, type: :boolean def handle_skip @options = @options.merge(stylesheets: false) unless options[:assets] - @options = @options.merge(stylesheet_engine: false) unless options[:stylesheets] + @options = @options.merge(stylesheet_engine: false) unless options[:stylesheets] && options[:scaffold_stylesheet] end hook_for :scaffold_controller, required: true diff --git a/railties/lib/rails/generators/rails/scaffold/templates/scaffold.css b/railties/lib/rails/generators/rails/scaffold/templates/scaffold.css index 69af1e8307..79f8b7f96f 100644 --- a/railties/lib/rails/generators/rails/scaffold/templates/scaffold.css +++ b/railties/lib/rails/generators/rails/scaffold/templates/scaffold.css @@ -1,8 +1,11 @@ -body { background-color: #fff; color: #333; } +body { + background-color: #fff; + color: #333; +} body, p, ol, ul, td { font-family: verdana, arial, helvetica, sans-serif; - font-size: 13px; + font-size: 13px; line-height: 18px; margin: 33px; } @@ -13,9 +16,18 @@ pre { font-size: 11px; } -a { color: #000; } -a:visited { color: #666; } -a:hover { color: #fff; background-color:#000; } +a { + color: #000; +} + +a:visited { + color: #666; +} + +a:hover { + color: #fff; + background-color: #000; +} th { padding-bottom: 5px; @@ -27,7 +39,8 @@ td { padding-right: 5px; } -div.field, div.actions { +div.field, +div.actions { margin-bottom: 10px; } @@ -56,7 +69,7 @@ div.field, div.actions { padding: 5px 5px 5px 15px; font-size: 12px; margin: -7px; - margin-bottom: 0px; + margin-bottom: 0; background-color: #c00; color: #fff; } @@ -65,3 +78,7 @@ div.field, div.actions { font-size: 12px; list-style: square; } + +label { + display: block; +} 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 c01b82884d..d0b8cad896 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 @@ -10,11 +10,14 @@ module Rails class_option :helper, type: :boolean class_option :orm, banner: "NAME", type: :string, required: true, desc: "ORM to generate the controller for" + class_option :api, type: :boolean, + desc: "Generates API controller" argument :attributes, type: :array, default: [], banner: "field:type field:type" def create_controller_files - template "controller.rb", File.join('app/controllers', controller_class_path, "#{controller_file_name}_controller.rb") + template_file = options.api? ? "api_controller.rb" : "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/scaffold_controller/templates/api_controller.rb b/railties/lib/rails/generators/rails/scaffold_controller/templates/api_controller.rb new file mode 100644 index 0000000000..400afec6dc --- /dev/null +++ b/railties/lib/rails/generators/rails/scaffold_controller/templates/api_controller.rb @@ -0,0 +1,61 @@ +<% if namespaced? -%> +require_dependency "<%= namespaced_path %>/application_controller" + +<% end -%> +<% module_namespacing do -%> +class <%= controller_class_name %>Controller < ApplicationController + before_action :set_<%= singular_table_name %>, only: [:show, :update, :destroy] + + # GET <%= route_url %> + def index + @<%= plural_table_name %> = <%= orm_class.all(class_name) %> + + render json: <%= "@#{plural_table_name}" %> + end + + # GET <%= route_url %>/1 + def show + render json: <%= "@#{singular_table_name}" %> + end + + # POST <%= route_url %> + def create + @<%= singular_table_name %> = <%= orm_class.build(class_name, "#{singular_table_name}_params") %> + + if @<%= orm_instance.save %> + render json: <%= "@#{singular_table_name}" %>, status: :created, location: <%= "@#{singular_table_name}" %> + else + render json: <%= "@#{orm_instance.errors}" %>, status: :unprocessable_entity + end + end + + # PATCH/PUT <%= route_url %>/1 + def update + if @<%= orm_instance.update("#{singular_table_name}_params") %> + render json: <%= "@#{singular_table_name}" %> + else + render json: <%= "@#{orm_instance.errors}" %>, status: :unprocessable_entity + end + end + + # DELETE <%= route_url %>/1 + def destroy + @<%= orm_instance.destroy %> + end + + private + # Use callbacks to share common setup or constraints between actions. + def set_<%= singular_table_name %> + @<%= singular_table_name %> = <%= orm_class.find(class_name, "params[:id]") %> + end + + # Only allow a trusted parameter "white list" through. + def <%= "#{singular_table_name}_params" %> + <%- if attributes_names.empty? -%> + params.fetch(:<%= singular_table_name %>, {}) + <%- else -%> + params.require(:<%= singular_table_name %>).permit(<%= attributes_names.map { |name| ":#{name}" }.join(', ') %>) + <%- end -%> + end +end +<% end -%> diff --git a/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb b/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb index 2c3b04043f..42b9e34274 100644 --- a/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb +++ b/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb @@ -1,5 +1,5 @@ <% if namespaced? -%> -require_dependency "<%= namespaced_file_path %>/application_controller" +require_dependency "<%= namespaced_path %>/application_controller" <% end -%> <% module_namespacing do -%> @@ -59,7 +59,7 @@ class <%= controller_class_name %>Controller < ApplicationController # Only allow a trusted parameter "white list" through. def <%= "#{singular_table_name}_params" %> <%- if attributes_names.empty? -%> - params[:<%= singular_table_name %>] + params.fetch(:<%= singular_table_name %>, {}) <%- else -%> params.require(:<%= singular_table_name %>).permit(<%= attributes_names.map { |name| ":#{name}" }.join(', ') %>) <%- end -%> diff --git a/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb b/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb index 509bd60564..4f2ceb8589 100644 --- a/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb +++ b/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb @@ -1,7 +1,11 @@ require 'test_helper' <% module_namespacing do -%> -class <%= class_name %>ControllerTest < ActionController::TestCase +class <%= class_name %>ControllerTest < ActionDispatch::IntegrationTest +<% if mountable_engine? -%> + include Engine.routes.url_helpers + +<% end -%> <% if actions.empty? -%> # test "the truth" do # assert true @@ -9,7 +13,7 @@ class <%= class_name %>ControllerTest < ActionController::TestCase <% else -%> <% actions.each do |action| -%> test "should get <%= action %>" do - get :<%= action %> + get <%= file_name %>_<%= action %>_url assert_response :success 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 2826a3ffa1..086588750e 100644 --- a/railties/lib/rails/generators/test_unit/model/model_generator.rb +++ b/railties/lib/rails/generators/test_unit/model/model_generator.rb @@ -19,7 +19,7 @@ module TestUnit # :nodoc: def create_fixture_file if options[:fixture] && options[:fixture_replacement].nil? - template 'fixtures.yml', File.join('test/fixtures', class_path, "#{plural_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/scaffold/scaffold_generator.rb b/railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb index 2e1f55f2a6..0171da7cc7 100644 --- a/railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb +++ b/railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb @@ -8,13 +8,26 @@ module TestUnit # :nodoc: check_class_collision suffix: "ControllerTest" + class_option :api, type: :boolean, + desc: "Generates API functional tests" + argument :attributes, type: :array, default: [], banner: "field:type field:type" def create_test_files - template "functional_test.rb", + template_file = options.api? ? "api_functional_test.rb" : "functional_test.rb" + template template_file, File.join("test/controllers", controller_class_path, "#{controller_file_name}_controller_test.rb") end + def fixture_name + @fixture_name ||= + if mountable_engine? + "%s_%s" % [namespaced_path, table_name] + else + table_name + end + end + private def attributes_hash diff --git a/railties/lib/rails/generators/test_unit/scaffold/templates/api_functional_test.rb b/railties/lib/rails/generators/test_unit/scaffold/templates/api_functional_test.rb new file mode 100644 index 0000000000..0d18478043 --- /dev/null +++ b/railties/lib/rails/generators/test_unit/scaffold/templates/api_functional_test.rb @@ -0,0 +1,44 @@ +require 'test_helper' + +<% module_namespacing do -%> +class <%= controller_class_name %>ControllerTest < ActionDispatch::IntegrationTest + <%- if mountable_engine? -%> + include Engine.routes.url_helpers + + <%- end -%> + setup do + @<%= singular_table_name %> = <%= fixture_name %>(:one) + end + + test "should get index" do + get <%= index_helper %>_url + assert_response :success + end + + test "should create <%= singular_table_name %>" do + assert_difference('<%= class_name %>.count') do + post <%= index_helper %>_url, params: { <%= "#{singular_table_name}: { #{attributes_hash} }" %> } + end + + assert_response 201 + end + + test "should show <%= singular_table_name %>" do + get <%= show_helper %> + assert_response :success + end + + test "should update <%= singular_table_name %>" do + patch <%= show_helper %>, params: { <%= "#{singular_table_name}: { #{attributes_hash} }" %> } + assert_response 200 + end + + test "should destroy <%= singular_table_name %>" do + assert_difference('<%= class_name %>.count', -1) do + delete <%= show_helper %> + end + + assert_response 204 + end +end +<% end -%> diff --git a/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb b/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb index 8d825ae7b0..0e6bef12fc 100644 --- a/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb +++ b/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb @@ -1,48 +1,51 @@ require 'test_helper' <% module_namespacing do -%> -class <%= controller_class_name %>ControllerTest < ActionController::TestCase +class <%= controller_class_name %>ControllerTest < ActionDispatch::IntegrationTest + <%- if mountable_engine? -%> + include Engine.routes.url_helpers + + <%- end -%> setup do - @<%= singular_table_name %> = <%= table_name %>(:one) + @<%= singular_table_name %> = <%= fixture_name %>(:one) end test "should get index" do - get :index + get <%= index_helper %>_url assert_response :success - assert_not_nil assigns(:<%= table_name %>) end test "should get new" do - get :new + get <%= new_helper %> assert_response :success end test "should create <%= singular_table_name %>" do assert_difference('<%= class_name %>.count') do - post :create, params: { <%= "#{singular_table_name}: { #{attributes_hash} }" %> } + post <%= index_helper %>_url, params: { <%= "#{singular_table_name}: { #{attributes_hash} }" %> } end - assert_redirected_to <%= singular_table_name %>_path(assigns(:<%= singular_table_name %>)) + assert_redirected_to <%= singular_table_name %>_path(<%= class_name %>.last) end test "should show <%= singular_table_name %>" do - get :show, params: { id: <%= "@#{singular_table_name}" %> } + get <%= show_helper %> assert_response :success end test "should get edit" do - get :edit, params: { id: <%= "@#{singular_table_name}" %> } + get <%= edit_helper %> assert_response :success end test "should update <%= singular_table_name %>" do - patch :update, params: { id: <%= "@#{singular_table_name}" %>, <%= "#{singular_table_name}: { #{attributes_hash} }" %> } - assert_redirected_to <%= singular_table_name %>_path(assigns(:<%= singular_table_name %>)) + patch <%= show_helper %>, params: { <%= "#{singular_table_name}: { #{attributes_hash} }" %> } + assert_redirected_to <%= singular_table_name %>_path(<%= "@#{singular_table_name}" %>) end test "should destroy <%= singular_table_name %>" do assert_difference('<%= class_name %>.count', -1) do - delete :destroy, params: { id: <%= "@#{singular_table_name}" %> } + delete <%= show_helper %> end assert_redirected_to <%= index_helper %>_path diff --git a/railties/lib/rails/generators/testing/assertions.rb b/railties/lib/rails/generators/testing/assertions.rb index bd069e4bd0..76758df86d 100644 --- a/railties/lib/rails/generators/testing/assertions.rb +++ b/railties/lib/rails/generators/testing/assertions.rb @@ -1,5 +1,3 @@ -require 'shellwords' - module Rails module Generators module Testing @@ -23,7 +21,7 @@ module Rails # end # end def assert_file(relative, *contents) - absolute = File.expand_path(relative, destination_root).shellescape + absolute = File.expand_path(relative, destination_root) assert File.exist?(absolute), "Expected file #{relative.inspect} to exist, but does not" read = File.read(absolute) if block_given? || !contents.empty? diff --git a/railties/lib/rails/generators/testing/behaviour.rb b/railties/lib/rails/generators/testing/behaviour.rb index c9700e1cd7..94b5e52224 100644 --- a/railties/lib/rails/generators/testing/behaviour.rb +++ b/railties/lib/rails/generators/testing/behaviour.rb @@ -92,7 +92,8 @@ module Rails cd current_path end - def prepare_destination # :nodoc: + # Clears all files and directories in destination. + def prepare_destination rm_rf(destination_root) mkdir_p(destination_root) end diff --git a/railties/lib/rails/info_controller.rb b/railties/lib/rails/info_controller.rb index 6e61cc3cb5..778105c5f7 100644 --- a/railties/lib/rails/info_controller.rb +++ b/railties/lib/rails/info_controller.rb @@ -18,7 +18,7 @@ class Rails::InfoController < Rails::ApplicationController # :nodoc: def routes if path = params[:path] - path = URI.escape path + path = URI.parser.escape path normalized_path = with_leading_slash path render json: { exact: match_route {|it| it.match normalized_path }, diff --git a/railties/lib/rails/mailers_controller.rb b/railties/lib/rails/mailers_controller.rb index 32740d66da..6143cf2dd9 100644 --- a/railties/lib/rails/mailers_controller.rb +++ b/railties/lib/rails/mailers_controller.rb @@ -3,7 +3,7 @@ require 'rails/application_controller' class Rails::MailersController < Rails::ApplicationController # :nodoc: prepend_view_path ActionDispatch::DebugExceptions::RESCUES_TEMPLATE_PATH - before_action :require_local! + before_action :require_local!, unless: :show_previews? before_action :find_preview, only: :preview def index @@ -16,31 +16,35 @@ class Rails::MailersController < Rails::ApplicationController # :nodoc: @page_title = "Mailer Previews for #{@preview.preview_name}" render action: 'mailer' else - email = File.basename(params[:path]) + @email_action = File.basename(params[:path]) - if @preview.email_exists?(email) - @email = @preview.call(email) + if @preview.email_exists?(@email_action) + @email = @preview.call(@email_action) if params[:part] part_type = Mime::Type.lookup(params[:part]) if part = find_part(part_type) response.content_type = part_type - render text: part.respond_to?(:decoded) ? part.decoded : part + render plain: part.respond_to?(:decoded) ? part.decoded : part else - raise AbstractController::ActionNotFound, "Email part '#{part_type}' not found in #{@preview.name}##{email}" + raise AbstractController::ActionNotFound, "Email part '#{part_type}' not found in #{@preview.name}##{@email_action}" end else - @part = find_preferred_part(request.format, Mime::HTML, Mime::TEXT) + @part = find_preferred_part(request.format, Mime[:html], Mime[:text]) render action: 'email', layout: false, formats: %w[html] end else - raise AbstractController::ActionNotFound, "Email '#{email}' not found in #{@preview.name}" + raise AbstractController::ActionNotFound, "Email '#{@email_action}' not found in #{@preview.name}" end end end protected + def show_previews? + ActionMailer::Base.show_previews + end + def find_preview candidates = [] params[:path].to_s.scan(%r{/|$}){ candidates << $` } @@ -54,18 +58,20 @@ class Rails::MailersController < Rails::ApplicationController # :nodoc: end def find_preferred_part(*formats) - if @email.multipart? - formats.each do |format| - return find_part(format) if @email.parts.any?{ |p| p.mime_type == format } + formats.each do |format| + if part = @email.find_first_mime_type(format) + return part end - else + end + + if formats.any?{ |f| @email.mime_type == f } @email end end def find_part(format) - if @email.multipart? - @email.parts.find{ |p| p.mime_type == format } + if part = @email.find_first_mime_type(format) + part elsif @email.mime_type == format @email end diff --git a/railties/lib/rails/paths.rb b/railties/lib/rails/paths.rb index ebcaaaba46..e47616a87f 100644 --- a/railties/lib/rails/paths.rb +++ b/railties/lib/rails/paths.rb @@ -123,6 +123,10 @@ module Rails options[:load_path] ? load_path! : skip_load_path! end + def absolute_current # :nodoc: + File.expand_path(@current, @root.path) + end + def children keys = @root.keys.find_all { |k| k.start_with?(@current) && k != @current @@ -175,6 +179,10 @@ module Rails @paths end + def extensions # :nodoc: + $1.split(',') if @glob =~ /\{([\S]+)\}/ + end + # Expands all paths against the root and return all unique values. def expanded raise "You need to set a path root" unless @root.path diff --git a/railties/lib/rails/rack/logger.rb b/railties/lib/rails/rack/logger.rb index 9962e6d943..12676b18bc 100644 --- a/railties/lib/rails/rack/logger.rb +++ b/railties/lib/rails/rack/logger.rb @@ -7,6 +7,10 @@ require 'rack/body_proxy' module Rails module Rack # Sets log tags, logs the request, calls the app, and flushes the logs. + # + # Log tags (+taggers+) can be an Array containing: methods that the +request+ + # object responds to, objects that respond to +to_s+ or Proc objects that accept + # an instance of the +request+ object. class Logger < ActiveSupport::LogSubscriber def initialize(app, taggers = nil) @app = app diff --git a/railties/lib/rails/ruby_version_check.rb b/railties/lib/rails/ruby_version_check.rb index 9131c51e91..67a19d8a94 100644 --- a/railties/lib/rails/ruby_version_check.rb +++ b/railties/lib/rails/ruby_version_check.rb @@ -1,13 +1,13 @@ -if RUBY_VERSION < '2.2.1' && 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 - Rails 5 requires to run on Ruby 2.2.1 or newer. + Rails 5 requires Ruby 2.2.2 or newer. You're running #{desc} - Please upgrade to Ruby 2.2.1 or newer to continue. + Please upgrade to Ruby 2.2.2 or newer to continue. end_message end diff --git a/railties/lib/rails/source_annotation_extractor.rb b/railties/lib/rails/source_annotation_extractor.rb index 9b058a1848..8dd87b6cc5 100644 --- a/railties/lib/rails/source_annotation_extractor.rb +++ b/railties/lib/rails/source_annotation_extractor.rb @@ -3,7 +3,7 @@ # rake notes # rake notes:optimize # -# and friends. See <tt>rake -T notes</tt> and <tt>railties/lib/tasks/annotations.rake</tt>. +# and friends. See <tt>rake -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 diff --git a/railties/lib/rails/tasks.rb b/railties/lib/rails/tasks.rb index 5dfc96894c..d60eaf6f4f 100644 --- a/railties/lib/rails/tasks.rb +++ b/railties/lib/rails/tasks.rb @@ -4,14 +4,15 @@ require 'rake' %w( annotations framework - initializer + initializers log middleware misc restart routes - statistics tmp -).each do |task| +).tap { |arr| + arr << 'statistics' if Rake.application.current_scope.empty? +}.each do |task| load "rails/tasks/#{task}.rake" end diff --git a/railties/lib/rails/tasks/engine.rake b/railties/lib/rails/tasks/engine.rake index 16ad1bfc84..c51524f8f6 100644 --- a/railties/lib/rails/tasks/engine.rake +++ b/railties/lib/rails/tasks/engine.rake @@ -40,7 +40,7 @@ namespace :db do desc "Rolls the schema back to the previous version (specify steps w/ STEP=n)." app_task "rollback" - desc "Create a db/schema.rb file that can be portably used against any DB supported by AR" + desc "Create a db/schema.rb file that can be portably used against any DB supported by Active Record" app_task "schema:dump" desc "Load a schema.rb file into the database" diff --git a/railties/lib/rails/tasks/framework.rake b/railties/lib/rails/tasks/framework.rake index a1c805f8aa..904b9d9ad6 100644 --- a/railties/lib/rails/tasks/framework.rake +++ b/railties/lib/rails/tasks/framework.rake @@ -32,35 +32,37 @@ namespace :rails do FileUtils.cp_r src_name, dst_name end end - end + end end namespace :update do - def invoke_from_app_generator(method) - app_generator.send(method) - end + class RailsUpdate + def self.invoke_from_app_generator(method) + app_generator.send(method) + end - def app_generator - @app_generator ||= begin - require 'rails/generators' - require 'rails/generators/rails/app/app_generator' - gen = Rails::Generators::AppGenerator.new ["rails"], { with_dispatchers: true }, - destination_root: Rails.root - File.exist?(Rails.root.join("config", "application.rb")) ? - gen.send(:app_const) : gen.send(:valid_const?) - gen + def self.app_generator + @app_generator ||= begin + require 'rails/generators' + require 'rails/generators/rails/app/app_generator' + gen = Rails::Generators::AppGenerator.new ["rails"], { with_dispatchers: true }, + destination_root: Rails.root + File.exist?(Rails.root.join("config", "application.rb")) ? + gen.send(:app_const) : gen.send(:valid_const?) + gen + end end end # desc "Update config/boot.rb from your current rails install" task :configs do - invoke_from_app_generator :create_boot_file - invoke_from_app_generator :update_config_files + RailsUpdate.invoke_from_app_generator :create_boot_file + RailsUpdate.invoke_from_app_generator :update_config_files end # desc "Adds new executables to the application bin/ directory" task :bin do - invoke_from_app_generator :create_bin_files + RailsUpdate.invoke_from_app_generator :create_bin_files end end end diff --git a/railties/lib/rails/tasks/initializer.rake b/railties/lib/rails/tasks/initializer.rake deleted file mode 100644 index 83b9dc6b71..0000000000 --- a/railties/lib/rails/tasks/initializer.rake +++ /dev/null @@ -1,6 +0,0 @@ -desc "Prints out initializers for your application" -task initializer: :environment do - Rails.application.initializers.tsort_each do |initializer| - puts initializer.name - end -end diff --git a/railties/lib/rails/tasks/initializers.rake b/railties/lib/rails/tasks/initializers.rake new file mode 100644 index 0000000000..2968b5cb53 --- /dev/null +++ b/railties/lib/rails/tasks/initializers.rake @@ -0,0 +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 + end +end diff --git a/railties/lib/rails/tasks/restart.rake b/railties/lib/rails/tasks/restart.rake index 1e8940b675..f36c86d81b 100644 --- a/railties/lib/rails/tasks/restart.rake +++ b/railties/lib/rails/tasks/restart.rake @@ -1,4 +1,5 @@ desc "Restart app by touching tmp/restart.txt" task :restart do + FileUtils.mkdir_p('tmp') FileUtils.touch('tmp/restart.txt') end diff --git a/railties/lib/rails/tasks/statistics.rake b/railties/lib/rails/tasks/statistics.rake index 735c36eb3a..a919d36939 100644 --- a/railties/lib/rails/tasks/statistics.rake +++ b/railties/lib/rails/tasks/statistics.rake @@ -9,6 +9,7 @@ STATS_DIRECTORIES = [ %w(Mailers app/mailers), %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), diff --git a/railties/lib/rails/templates/rails/mailers/email.html.erb b/railties/lib/rails/templates/rails/mailers/email.html.erb index 0b08a01896..fed96fbc85 100644 --- a/railties/lib/rails/templates/rails/mailers/email.html.erb +++ b/railties/lib/rails/templates/rails/mailers/email.html.erb @@ -39,6 +39,10 @@ padding: 1px; } + dd:empty:before { + content: "\00a0"; // + } + iframe { border: 0; width: 100%; @@ -84,22 +88,43 @@ <% 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 }.inspect %> + <%= @email.attachments.map { |a| a.respond_to?(:original_filename) ? a.original_filename : a.filename }.join(', ') %> </dd> <% end %> <% if @email.multipart? %> <dd> - <select onchange="document.getElementsByName('messageBody')[0].src=this.options[this.selectedIndex].value;"> - <option <%= request.format == Mime::HTML ? 'selected' : '' %> value="?part=text%2Fhtml">View as HTML email</option> - <option <%= request.format == Mime::TEXT ? 'selected' : '' %> value="?part=text%2Fplain">View as plain-text email</option> + <select onchange="formatChanged(this);"> + <option <%= request.format == Mime[:html] ? 'selected' : '' %> value="?part=text%2Fhtml">View as HTML email</option> + <option <%= request.format == Mime[:text] ? 'selected' : '' %> value="?part=text%2Fplain">View as plain-text email</option> </select> </dd> <% end %> </dl> </header> -<iframe seamless name="messageBody" src="?part=<%= Rack::Utils.escape(@part.mime_type) %>"></iframe> +<% if @part && @part.mime_type %> + <iframe seamless name="messageBody" src="?part=<%= Rack::Utils.escape(@part.mime_type) %>"></iframe> +<% else %> + <p> + You are trying to preview an email that does not have any content. + This is probably because the <em>mail</em> method has not been called in <em><%= @preview.preview_name %>#<%= @email_action %></em>. + </p> +<% end %> + +<script> + function formatChanged(form) { + var part_name = form.options[form.selectedIndex].value + var iframe =document.getElementsByName('messageBody')[0]; + iframe.contentWindow.location.replace(part_name); + + if (history.replaceState) { + var url = location.pathname.replace(/\.(txt|html)$/, ''); + var format = /html/.test(part_name) ? '.html' : '.txt'; + window.history.replaceState({}, '', url + format); + } + } +</script> </body> </html> diff --git a/railties/lib/rails/templates/rails/mailers/index.html.erb b/railties/lib/rails/templates/rails/mailers/index.html.erb index c4c9757d57..000930c039 100644 --- a/railties/lib/rails/templates/rails/mailers/index.html.erb +++ b/railties/lib/rails/templates/rails/mailers/index.html.erb @@ -1,8 +1,8 @@ <% @previews.each do |preview| %> -<h3><%= link_to preview.preview_name.titleize, "/rails/mailers/#{preview.preview_name}" %></h3> +<h3><%= link_to preview.preview_name.titleize, url_for(controller: "rails/mailers", action: "preview", path: preview.preview_name) %></h3> <ul> <% preview.emails.each do |email| %> -<li><%= link_to email, "/rails/mailers/#{preview.preview_name}/#{email}" %></li> +<li><%= link_to email, url_for(controller: "rails/mailers", action: "preview", path: "#{preview.preview_name}/#{email}") %></li> <% end %> </ul> <% end %> diff --git a/railties/lib/rails/templates/rails/mailers/mailer.html.erb b/railties/lib/rails/templates/rails/mailers/mailer.html.erb index 607c8d1677..c12ead0f90 100644 --- a/railties/lib/rails/templates/rails/mailers/mailer.html.erb +++ b/railties/lib/rails/templates/rails/mailers/mailer.html.erb @@ -1,6 +1,6 @@ <h3><%= @preview.preview_name.titleize %></h3> <ul> <% @preview.emails.each do |email| %> -<li><%= link_to email, "/rails/mailers/#{@preview.preview_name}/#{email}" %></li> +<li><%= link_to email, url_for(controller: "rails/mailers", action: "preview", path: "#{@preview.preview_name}/#{email}") %></li> <% end %> </ul> diff --git a/railties/lib/rails/templates/rails/welcome/index.html.erb b/railties/lib/rails/templates/rails/welcome/index.html.erb index 6726c23fc9..acf04af416 100644 --- a/railties/lib/rails/templates/rails/welcome/index.html.erb +++ b/railties/lib/rails/templates/rails/welcome/index.html.erb @@ -18,7 +18,9 @@ color: #000; } - a {color: #03c} + a { + color: #03c; + } a:hover { background-color: #03c; @@ -64,7 +66,10 @@ height: 64px; } - #header h1, #header h2 {margin: 0} + #header h1, + #header h2 { + margin: 0; + } #header h2 { color: #888; @@ -104,7 +109,9 @@ color: #555; } - #about-content td.value {color: #000} + #about-content td.value { + color: #000; + } #about-content ul { padding: 0; diff --git a/railties/lib/rails/test_help.rb b/railties/lib/rails/test_help.rb index d52bb46728..5cc1b5b219 100644 --- a/railties/lib/rails/test_help.rb +++ b/railties/lib/rails/test_help.rb @@ -3,13 +3,14 @@ abort("Abort testing: Your Rails environment is running in production mode!") if Rails.env.production? require "rails/test_unit/minitest_plugin" -require 'active_support/testing/autorun' 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' + if defined?(ActiveRecord::Base) ActiveRecord::Migration.maintain_test_schema! @@ -27,14 +28,14 @@ if defined?(ActiveRecord::Base) end class ActionController::TestCase - def setup + def before_setup # :nodoc: @routes = Rails.application.routes super end end class ActionDispatch::IntegrationTest - def setup + def before_setup # :nodoc: @routes = Rails.application.routes super end diff --git a/railties/lib/rails/test_unit/minitest_plugin.rb b/railties/lib/rails/test_unit/minitest_plugin.rb index 70ce9d3360..d39d2f32bf 100644 --- a/railties/lib/rails/test_unit/minitest_plugin.rb +++ b/railties/lib/rails/test_unit/minitest_plugin.rb @@ -1,14 +1,91 @@ -require "minitest" +require "active_support/core_ext/module/attribute_accessors" require "rails/test_unit/reporter" +require "rails/test_unit/test_requirer" -def Minitest.plugin_rails_init(options) - self.reporter << Rails::TestUnitReporter.new(options[:io], options) - if $rails_test_runner && (method = $rails_test_runner.find_method) - options[:filter] = method +module Minitest + mattr_accessor(:hide_aggregated_results) { false } + + module AggregatedResultSuppresion + def aggregated_results + super unless Minitest.hide_aggregated_results + end + end + + SummaryReporter.prepend AggregatedResultSuppresion + + def self.plugin_rails_options(opts, options) + executable = ::Rails::TestUnitReporter.executable + opts.separator "" + opts.separator "Usage: #{executable} [options] [files or directories]" + opts.separator "You can run a single test by appending a line number to a filename:" + opts.separator "" + opts.separator " #{executable} test/models/user_test.rb:27" + opts.separator "" + opts.separator "You can run multiple files and directories at the same time:" + opts.separator "" + opts.separator " #{executable} test/controllers test/integration/login_test.rb" + opts.separator "" + opts.separator "By default test failures and errors are reported inline during a run." + opts.separator "" + + opts.separator "Rails options:" + opts.on("-e", "--environment ENV", + "Run tests in the ENV environment") do |env| + options[:environment] = env.strip + end + + opts.on("-b", "--backtrace", + "Show the complete backtrace") do + options[:full_backtrace] = true + end + + opts.on("-d", "--defer-output", + "Output test failures and errors after the test run") do + options[:output_inline] = false + end + + opts.on("-f", "--fail-fast", + "Abort test run on first failure") do + options[:fail_fast] = true + end + + options[:output_inline] = true + options[:patterns] = opts.order! end - if !($rails_test_runner && $rails_test_runner.show_backtrace?) - Minitest.backtrace_filter = Rails.backtrace_cleaner + # Running several Rake tasks in a single command would trip up the runner, + # as the patterns would also contain the other Rake tasks. + def self.rake_run(patterns) # :nodoc: + @rake_patterns = patterns + passed = run + exit passed unless passed + passed end + + def self.plugin_rails_init(options) + self.run_with_rails_extension = true + + ENV["RAILS_ENV"] = options[:environment] || "test" + + unless run_with_autorun + patterns = defined?(@rake_patterns) ? @rake_patterns : options[:patterns] + ::Rails::TestRequirer.require_files(patterns) + end + + unless options[:full_backtrace] || ENV["BACKTRACE"] + # Plugin can run without Rails loaded, check before filtering. + Minitest.backtrace_filter = ::Rails.backtrace_cleaner if ::Rails.respond_to?(:backtrace_cleaner) + end + + # Disable the extra failure output after a run, unless output is deferred. + self.hide_aggregated_results = options[:output_inline] + + self.reporter << ::Rails::TestUnitReporter.new(options[:io], options) + end + + mattr_accessor(:run_with_autorun) { false } + mattr_accessor(:run_with_rails_extension) { false } end + +Minitest.load_plugins Minitest.extensions << 'rails' diff --git a/railties/lib/rails/test_unit/reporter.rb b/railties/lib/rails/test_unit/reporter.rb index 64e99626eb..00ea32d1b8 100644 --- a/railties/lib/rails/test_unit/reporter.rb +++ b/railties/lib/rails/test_unit/reporter.rb @@ -1,9 +1,30 @@ +require "active_support/core_ext/class/attribute" require "minitest" module Rails class TestUnitReporter < Minitest::StatisticsReporter + class_attribute :executable + self.executable = "bin/rails test" + + def record(result) + super + + if output_inline? && result.failure && (!result.skipped? || options[:verbose]) + io.puts + io.puts + io.puts result.failures.map(&:message) + io.puts + io.puts format_rerun_snippet(result) + io.puts + end + + if fail_fast? && result.failure && !result.error? && !result.skipped? + raise Interrupt + end + end + def report - return if results.empty? + return if output_inline? || filtered_results.empty? io.puts io.puts "Failed tests:" io.puts @@ -11,12 +32,43 @@ module Rails end def aggregated_results # :nodoc: - filtered_results = results.dup - filtered_results.reject!(&:skipped?) unless options[:verbose] - filtered_results.map do |result| - location, line = result.method(result.name).source_location - "bin/rails test #{location}:#{line}" - end.join "\n" + filtered_results.map { |result| format_rerun_snippet(result) }.join "\n" + end + + def filtered_results + if options[:verbose] + results + else + results.reject(&:skipped?) + end end + + def relative_path_for(file) + file.sub(/^#{app_root}\/?/, '') + end + + private + def output_inline? + options[:output_inline] + end + + def fail_fast? + options[:fail_fast] + end + + def format_rerun_snippet(result) + # Try to extract path to assertion from backtrace. + if result.location =~ /\[(.*)\]\z/ + assertion_path = $1 + else + assertion_path = result.method(result.name).source_location.join(':') + end + + "#{self.executable} #{relative_path_for(assertion_path)}" + end + + def app_root + @app_root ||= defined?(ENGINE_ROOT) ? ENGINE_ROOT : Rails.root + end end end diff --git a/railties/lib/rails/test_unit/runner.rb b/railties/lib/rails/test_unit/runner.rb deleted file mode 100644 index 6700d90a33..0000000000 --- a/railties/lib/rails/test_unit/runner.rb +++ /dev/null @@ -1,138 +0,0 @@ -require "ostruct" -require "optparse" -require "rake/file_list" -require "method_source" - -module Rails - class TestRunner - class Options - def self.parse(args) - options = { backtrace: !ENV["BACKTRACE"].nil?, name: nil, environment: "test" } - - opt_parser = ::OptionParser.new do |opts| - opts.banner = "Usage: bin/rails test [options] [file or directory]" - - opts.separator "" - opts.on("-e", "--environment [ENV]", - "run tests in the ENV environment") do |env| - options[:environment] = env.strip - end - opts.separator "" - opts.separator "Filter options:" - opts.separator "" - opts.separator <<-DESC - You can run a single test by appending the line number to filename: - - bin/rails test test/models/user_test.rb:27 - - DESC - - opts.on("-n", "--name [NAME]", - "Only run tests matching NAME") do |name| - options[:name] = name - end - opts.on("-p", "--pattern [PATTERN]", - "Only run tests matching PATTERN") do |pattern| - options[:name] = "/#{pattern}/" - end - - opts.separator "" - opts.separator "Output options:" - - opts.on("-b", "--backtrace", - "show the complte backtrace") do - options[:backtrace] = true - end - - opts.separator "" - opts.separator "Common options:" - - opts.on_tail("-h", "--help", "Show this message") do - puts opts - exit - end - end - - opt_parser.order!(args) - - options[:patterns] = [] - while arg = args.shift - if (file_and_line = arg.split(':')).size > 1 - options[:filename], options[:line] = file_and_line - options[:filename] = File.expand_path options[:filename] - options[:line] &&= options[:line].to_i - else - arg = arg.gsub(':', '') - if Dir.exists?("#{arg}") - options[:patterns] << File.expand_path("#{arg}/**/*_test.rb") - elsif File.file?(arg) - options[:patterns] << File.expand_path(arg) - end - end - end - options - end - end - - def initialize(options = {}) - @options = options - end - - def self.run(arguments) - options = Rails::TestRunner::Options.parse(arguments) - Rails::TestRunner.new(options).run - end - - def run - $rails_test_runner = self - ENV["RAILS_ENV"] = @options[:environment] - run_tests - end - - def find_method - return @options[:name] if @options[:name] - return unless @options[:line] - method = test_methods.find do |location, test_method, start_line, end_line| - location == @options[:filename] && - (start_line..end_line).include?(@options[:line].to_i) - end - method[1] if method - end - - def show_backtrace? - @options[:backtrace] - end - - def test_files - return [@options[:filename]] if @options[:filename] - if @options[:patterns] && @options[:patterns].count > 0 - pattern = @options[:patterns] - else - pattern = "test/**/*_test.rb" - end - Rake::FileList[pattern] - end - - private - def run_tests - test_files.to_a.each do |file| - require File.expand_path file - end - end - - def test_methods - methods_map = [] - suites = Minitest::Runnable.runnables.shuffle - suites.each do |suite_class| - suite_class.runnable_methods.each do |test_method| - method = suite_class.instance_method(test_method) - location = method.source_location - start_line = location.last - end_line = method.source.split("\n").size + start_line - 1 - methods_map << [File.expand_path(location.first), test_method, start_line, end_line] - end - end - methods_map - end - end -end diff --git a/railties/lib/rails/test_unit/sub_test_task.rb b/railties/lib/rails/test_unit/sub_test_task.rb deleted file mode 100644 index 6fa96d2ced..0000000000 --- a/railties/lib/rails/test_unit/sub_test_task.rb +++ /dev/null @@ -1,126 +0,0 @@ -require 'rake/testtask' - -module Rails - class TestTask < Rake::TestTask # :nodoc: all - # A utility class which is used primarily in "rails/test_unit/testing.rake" - # to help define rake tasks corresponding to <tt>rake test</tt>. - # - # This class takes a TestInfo class and defines the appropriate rake task - # based on the information, then invokes it. - class TestCreator # :nodoc: - def initialize(info) - @info = info - end - - def invoke_rake_task - if @info.files.any? - create_and_run_single_test - reset_application_tasks - else - Rake::Task[ENV['TEST'] ? 'test:single' : 'test:run'].invoke - end - end - - private - - def create_and_run_single_test - Rails::TestTask.new('test:single') { |t| - t.test_files = @info.files - } - ENV['TESTOPTS'] ||= @info.opts - Rake::Task['test:single'].invoke - end - - def reset_application_tasks - Rake.application.top_level_tasks.replace @info.tasks - end - end - - # This is a utility class used by the <tt>TestTask::TestCreator</tt> class. - # This class takes a set of test tasks and checks to see if they correspond - # to test files (or can be transformed into test files). Calling <tt>files</tt> - # provides the set of test files and is used when initializing tests after - # a call to <tt>rake test</tt>. - class TestInfo # :nodoc: - def initialize(tasks) - @tasks = tasks - @files = nil - end - - def files - @files ||= @tasks.map { |task| - [task, translate(task)].find { |file| test_file?(file) } - }.compact - end - - def translate(file) - if file =~ /^app\/(.*)$/ - "test/#{$1.sub(/\.rb$/, '')}_test.rb" - else - "test/#{file}_test.rb" - end - end - - def tasks - @tasks - test_file_tasks - opt_names - end - - def opts - opts = opt_names - if opts.any? - "-n #{opts.join ' '}" - end - end - - private - - def test_file_tasks - @tasks.find_all { |task| - [task, translate(task)].any? { |file| test_file?(file) } - } - end - - def test_file?(file) - file =~ /^test/ && File.file?(file) && !File.directory?(file) - end - - def opt_names - (@tasks - test_file_tasks).reject { |t| task_defined? t } - end - - def task_defined?(task) - Rake::Task.task_defined? task - end - end - - def self.test_creator(tasks) - info = TestInfo.new(tasks) - TestCreator.new(info) - end - - def initialize(name = :test) - super - @libs << "test" # lib *and* test seem like a better default - end - - def define - task @name do - if ENV['TESTOPTS'] - ARGV.replace Shellwords.split ENV['TESTOPTS'] - end - libs = @libs - $LOAD_PATH - $LOAD_PATH.unshift(*libs) - file_list.each { |fl| - FileList[fl].to_a.each { |f| require File.expand_path f } - } - end - end - end - - # Silence the default description to cut down on `rake -T` noise. - class SubTestTask < Rake::TestTask # :nodoc: - def desc(string) - # Ignore the description. - end - end -end diff --git a/railties/lib/rails/test_unit/test_requirer.rb b/railties/lib/rails/test_unit/test_requirer.rb new file mode 100644 index 0000000000..83d2c55ffd --- /dev/null +++ b/railties/lib/rails/test_unit/test_requirer.rb @@ -0,0 +1,28 @@ +require 'active_support/core_ext/object/blank' +require 'rake/file_list' + +module Rails + class TestRequirer # :nodoc: + class << self + def require_files(patterns) + patterns = expand_patterns(patterns) + + Rake::FileList[patterns.compact.presence || 'test/**/*_test.rb'].to_a.each do |file| + require File.expand_path(file) + end + end + + private + def expand_patterns(patterns) + patterns.map do |arg| + arg = arg.gsub(/:(\d+)?$/, '') + if Dir.exist?(arg) + "#{arg}/**/*_test.rb" + else + arg + end + end + end + end + end +end diff --git a/railties/lib/rails/test_unit/testing.rake b/railties/lib/rails/test_unit/testing.rake index 0f26621b59..6676c6a079 100644 --- a/railties/lib/rails/test_unit/testing.rake +++ b/railties/lib/rails/test_unit/testing.rake @@ -1,12 +1,13 @@ -require "rails/test_unit/runner" +gem 'minitest' +require 'minitest' +require 'rails/test_unit/minitest_plugin' task default: :test desc "Runs all tests in test folder" task :test do $: << "test" - args = ARGV[0] == "test" ? ARGV[1..-1] : [] - Rails::TestRunner.run(args) + Minitest.rake_run(["test"]) end namespace :test do @@ -23,22 +24,22 @@ namespace :test do ["models", "helpers", "controllers", "mailers", "integration", "jobs"].each do |name| task name => "test:prepare" do $: << "test" - Rails::TestRunner.run(["test/#{name}"]) + Minitest.rake_run(["test/#{name}"]) end end task :generators => "test:prepare" do $: << "test" - Rails::TestRunner.run(["test/lib/generators"]) + Minitest.rake_run(["test/lib/generators"]) end task :units => "test:prepare" do $: << "test" - Rails::TestRunner.run(["test/models", "test/helpers", "test/unit"]) + Minitest.rake_run(["test/models", "test/helpers", "test/unit"]) end task :functionals => "test:prepare" do $: << "test" - Rails::TestRunner.run(["test/controllers", "test/mailers", "test/functional"]) + Minitest.rake_run(["test/controllers", "test/mailers", "test/functional"]) end end |