diff options
Diffstat (limited to 'railties/lib')
119 files changed, 983 insertions, 705 deletions
diff --git a/railties/lib/rails.rb b/railties/lib/rails.rb index b1f7c29b5a..fe789f3c2a 100644 --- a/railties/lib/rails.rb +++ b/railties/lib/rails.rb @@ -52,6 +52,11 @@ module Rails end end + # Returns a Pathname object of the current rails project, + # otherwise it returns nil if there is no project: + # + # Rails.root + # # => #<Pathname:/Users/someuser/some/path/project> def root application && application.config.root end @@ -94,6 +99,11 @@ module Rails groups end + # Returns a Pathname object of the public folder of the current + # rails project, otherwise it returns nil if there is no project: + # + # Rails.public_path + # # => #<Pathname:/Users/someuser/some/path/project/public> def public_path application && Pathname.new(application.paths["public"].first) end diff --git a/railties/lib/rails/api/task.rb b/railties/lib/rails/api/task.rb index 4d49244807..a082932632 100644 --- a/railties/lib/rails/api/task.rb +++ b/railties/lib/rails/api/task.rb @@ -152,19 +152,5 @@ module Rails File.read('RAILS_VERSION').strip end end - - class AppTask < Task - def component_root_dir(gem_name) - $:.grep(%r{#{gem_name}[\w.-]*/lib\z}).first[0..-5] - end - - def api_dir - 'doc/api' - end - - def rails_version - Rails::VERSION::STRING - end - end end end 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 8da73db821..8075068b3f 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 # @@ -159,8 +159,9 @@ module Rails # 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"] + req = ActionDispatch::Request.new env + env["ORIGINAL_FULLPATH"] = req.fullpath + env["ORIGINAL_SCRIPT_NAME"] = req.script_name super(env) end @@ -227,7 +228,6 @@ module Rails yaml = Pathname.new("#{paths["config"].existent.first}/#{name}.yml") if yaml.exist? - require "yaml" require "erb" (YAML.load(ERB.new(yaml.read).result) || {})[Rails.env] || {} else @@ -427,9 +427,9 @@ module Rails # Return an array of railties respecting the order they're loaded # and the order specified by the +railties_order+ config. # - # While when running initializers we need engines in reverse - # order here when copying migrations from railties we need then in the same - # order as given by +railties_order+ + # While running initializers we need engines in reverse order here when + # copying migrations from railties ; we need them in the order given by + # +railties_order+. def migration_railties # :nodoc: ordered_railties.flatten - [self] end @@ -504,25 +504,13 @@ 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 diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb index 2821c8d757..4fc7a1db62 100644 --- a/railties/lib/rails/application/configuration.rb +++ b/railties/lib/rails/application/configuration.rb @@ -6,17 +6,17 @@ require 'rails/source_annotation_extractor' module Rails class Application class Configuration < ::Rails::Engine::Configuration - attr_accessor :allow_concurrency, :asset_host, :assets, :autoflush_log, + attr_accessor :allow_concurrency, :asset_host, :autoflush_log, :cache_classes, :cache_store, :consider_all_requests_local, :console, :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, + :serve_static_files, :ssl_options, :static_cache_control, :static_index, + :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 def initialize(*) super @@ -28,6 +28,7 @@ module Rails @helpers_paths = [] @serve_static_files = true @static_cache_control = nil + @static_index = "index" @force_ssl = false @ssl_options = {} @session_store = :cookie_store @@ -48,22 +49,8 @@ module Rails @eager_load = nil @secret_token = nil @secret_key_base = nil + @api_only = false @x = Custom.new - - @assets = ActiveSupport::OrderedOptions.new - @assets.enabled = true - @assets.paths = [] - @assets.precompile = [ Proc.new { |path, fn| fn =~ /app\/assets/ && !%w(.js .css).include?(File.extname(path)) }, - /(?:\/|\\|\A)application\.(css|js)$/ ] - @assets.prefix = "/assets" - @assets.version = '1.0' - @assets.debug = false - @assets.compile = true - @assets.digest = false - @assets.cache_store = [ :file_store, "#{root}/tmp/cache/assets/#{Rails.env}/" ] - @assets.js_compressor = nil - @assets.css_compressor = nil - @assets.logger = nil end def encoding=(value) @@ -74,6 +61,11 @@ module Rails end end + def api_only=(value) + @api_only = value + generators.api_only = value + end + def paths @paths ||= begin paths = super diff --git a/railties/lib/rails/application/default_middleware_stack.rb b/railties/lib/rails/application/default_middleware_stack.rb index 02eea82b0c..6f9ccec137 100644 --- a/railties/lib/rails/application/default_middleware_stack.rb +++ b/railties/lib/rails/application/default_middleware_stack.rb @@ -18,7 +18,7 @@ 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 + middleware.use ::ActionDispatch::Static, paths["public"].first, config.static_cache_control, index: config.static_index end if rack_cache = load_rack_cache @@ -28,7 +28,7 @@ module Rails middleware.use ::Rack::Lock unless allow_concurrency? 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 @@ -42,9 +42,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 diff --git a/railties/lib/rails/application/finisher.rb b/railties/lib/rails/application/finisher.rb index 7a1bb1e25c..0599e988d9 100644 --- a/railties/lib/rails/application/finisher.rb +++ b/railties/lib/rails/application/finisher.rb @@ -108,6 +108,13 @@ module Rails ActionDispatch::Reloader.to_cleanup(&callback) end end + + # Disable dependency loading during request cycle + initializer :disable_dependency_loading do + if config.eager_load && config.cache_classes + ActiveSupport::Dependencies.unhook! + end + end end 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 27779857b7..fd352dc9b7 100644 --- a/railties/lib/rails/code_statistics.rb +++ b/railties/lib/rails/code_statistics.rb @@ -7,9 +7,7 @@ class CodeStatistics #:nodoc: 'Model tests', 'Mailer tests', 'Job tests', - 'Integration tests', - 'Functional tests (old)', - 'Unit tests (old)'] + 'Integration tests'] def initialize(*pairs) @pairs = pairs @@ -43,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 @@ -73,12 +69,12 @@ class CodeStatistics #:nodoc: def print_header print_splitter - puts "| Name | Lines | LOC | Classes | Methods | M/C | LOC/M |" + puts "| Name | Lines | LOC | Classes | Methods | M/C | LOC/M |" print_splitter end def print_splitter - puts "+----------------------+-------+-------+---------+---------+-----+-------+" + puts "+----------------------+--------+--------+---------+---------+-----+-------+" end def print_line(name, statistics) @@ -86,8 +82,8 @@ class CodeStatistics #:nodoc: loc_over_m = (statistics.code_lines / statistics.methods) - 2 rescue loc_over_m = 0 puts "| #{name.ljust(20)} " \ - "| #{statistics.lines.to_s.rjust(5)} " \ - "| #{statistics.code_lines.to_s.rjust(5)} " \ + "| #{statistics.lines.to_s.rjust(6)} " \ + "| #{statistics.code_lines.to_s.rjust(6)} " \ "| #{statistics.classes.to_s.rjust(7)} " \ "| #{statistics.methods.to_s.rjust(7)} " \ "| #{m_over_c.to_s.rjust(3)} " \ diff --git a/railties/lib/rails/code_statistics_calculator.rb b/railties/lib/rails/code_statistics_calculator.rb index 60e4aef9b7..a142236dbe 100644 --- a/railties/lib/rails/code_statistics_calculator.rb +++ b/railties/lib/rails/code_statistics_calculator.rb @@ -24,6 +24,8 @@ class CodeStatisticsCalculator #:nodoc: } } + PATTERNS[:minitest] = PATTERNS[:rb].merge method: /^\s*(def|test)\s+['"_a-z]/ + def initialize(lines = 0, code_lines = 0, classes = 0, methods = 0) @lines = lines @code_lines = code_lines @@ -74,6 +76,10 @@ class CodeStatisticsCalculator #:nodoc: private def file_type(file_path) - File.extname(file_path).sub(/\A\./, '').downcase.to_sym + if file_path.end_with? '_test.rb' + :minitest + else + File.extname(file_path).sub(/\A\./, '').downcase.to_sym + end end end diff --git a/railties/lib/rails/commands.rb b/railties/lib/rails/commands.rb index f32bf772a5..12bd73db24 100644 --- a/railties/lib/rails/commands.rb +++ b/railties/lib/rails/commands.rb @@ -6,7 +6,8 @@ aliases = { "c" => "console", "s" => "server", "db" => "dbconsole", - "r" => "runner" + "r" => "runner", + "t" => "test", } command = ARGV.shift diff --git a/railties/lib/rails/commands/commands_tasks.rb b/railties/lib/rails/commands/commands_tasks.rb index 8bae08e44e..685d55eea8 100644 --- a/railties/lib/rails/commands/commands_tasks.rb +++ b/railties/lib/rails/commands/commands_tasks.rb @@ -14,6 +14,7 @@ The most common rails commands are: generate Generate new code (short-cut alias: "g") console Start the Rails console (short-cut alias: "c") server Start the Rails server (short-cut alias: "s") + test Run tests (short-cut alias: "t") dbconsole Start a console for the database specified in config/database.yml (short-cut alias: "db") new Create a new Rails application. "rails new my_app" creates a @@ -27,7 +28,7 @@ In addition to those, there are: All commands can be run with -h (or --help) for more information. EOT - COMMAND_WHITELIST = %w(plugin generate destroy console server dbconsole runner new version help) + COMMAND_WHITELIST = %w(plugin generate destroy console server dbconsole runner new version help test) def initialize(argv) @argv = argv @@ -81,6 +82,10 @@ EOT end end + def test + require_command!("test") + end + def dbconsole require_command!("dbconsole") Rails::DBConsole.start @@ -146,6 +151,17 @@ EOT puts HELP_MESSAGE end + # Output an error message stating that the attempted command is not a valid rails command. + # Run the attempted command as a rake command with the --dry-run flag. If successful, suggest + # to the user that they possibly meant to run the given rails command as a rake command. + # Append the help message. + # + # Example: + # $ rails db:migrate + # Error: Command 'db:migrate' not recognized + # Did you mean: `$ rake db:migrate` ? + # (Help message output) + # def write_error_message(command) puts "Error: Command '#{command}' not recognized" if %x{rake #{command} --dry-run 2>&1 } && $?.success? diff --git a/railties/lib/rails/commands/console.rb b/railties/lib/rails/commands/console.rb index 35a815a34f..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'] || ENV['RACK_ENV'] || 'development' - end - - def environment? - environment + options[:environment] ||= super end + alias_method :environment?, :environment def set_environment! Rails.env = environment @@ -79,7 +60,7 @@ module Rails end if defined?(console::ExtendCommandBundle) - console::ExtendCommandBundle.send :include, Rails::ConsoleMethods + console::ExtendCommandBundle.include(Rails::ConsoleMethods) end console.start end 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 0d8b3de0eb..dca60f948f 100644 --- a/railties/lib/rails/commands/dbconsole.rb +++ b/railties/lib/rails/commands/dbconsole.rb @@ -1,14 +1,49 @@ require 'erb' require 'yaml' require 'optparse' -require 'rbconfig' +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) @@ -16,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"] @@ -51,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 = [] @@ -90,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 @@ -105,88 +137,37 @@ module Rails end def environment - if Rails.respond_to?(:env) - Rails.env - else - ENV["RAILS_ENV"] || ENV["RACK_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) - commands += commands.map{|cmd| "#{cmd}.exe"} if RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ - - 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/runner.rb b/railties/lib/rails/commands/runner.rb index 3a71f8d3f8..86bce9b2fe 100644 --- a/railties/lib/rails/commands/runner.rb +++ b/railties/lib/rails/commands/runner.rb @@ -1,5 +1,4 @@ require 'optparse' -require 'rbconfig' options = { environment: (ENV['RAILS_ENV'] || ENV['RACK_ENV'] || "development").dup } code_or_file = nil diff --git a/railties/lib/rails/commands/server.rb b/railties/lib/rails/commands/server.rb index bc8f1a8dea..546d3725d8 100644 --- a/railties/lib/rails/commands/server.rb +++ b/railties/lib/rails/commands/server.rb @@ -91,10 +91,6 @@ module Rails Hash.new(middlewares) end - def log_path - "log/#{options[:environment]}.log" - end - def default_options super.merge({ Port: 3000, diff --git a/railties/lib/rails/commands/test.rb b/railties/lib/rails/commands/test.rb new file mode 100644 index 0000000000..fe5307788a --- /dev/null +++ b/railties/lib/rails/commands/test.rb @@ -0,0 +1,5 @@ +require "rails/test_unit/minitest_plugin" + +$: << File.expand_path("../../test", APP_PATH) + +exit Minitest.run(ARGV) diff --git a/railties/lib/rails/configuration.rb b/railties/lib/rails/configuration.rb index f99cec04c5..d99d27a756 100644 --- a/railties/lib/rails/configuration.rb +++ b/railties/lib/rails/configuration.rb @@ -35,6 +35,7 @@ module Rails class MiddlewareStackProxy def initialize @operations = [] + @delete_operations = [] end def insert_before(*args, &block) @@ -56,7 +57,7 @@ module Rails end def delete(*args, &block) - @operations << [__method__, args, block] + @delete_operations << [__method__, args, block] end def unshift(*args, &block) @@ -64,15 +65,16 @@ module Rails end def merge_into(other) #:nodoc: - @operations.each do |operation, args, block| + (@operations + @delete_operations).each do |operation, args, block| other.send(operation, *args, &block) end + other 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 @@ -81,6 +83,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/engine.rb b/railties/lib/rails/engine.rb index a338f31f15..1dede32dd4 100644 --- a/railties/lib/rails/engine.rb +++ b/railties/lib/rails/engine.rb @@ -6,7 +6,7 @@ require 'pathname' 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 +15,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 +68,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 +204,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 do 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 # @@ -296,7 +303,7 @@ module Rails # helper MyEngine::SharedEngineHelper # end # - # If you want to include all of the engine's helpers, you can use #helper method on an engine's + # If you want to include all of the engine's helpers, you can use the #helper method on an engine's # instance: # # class ApplicationController < ActionController::Base @@ -312,7 +319,7 @@ module Rails # Engines can have their own migrations. The default path for migrations is exactly the same # as in application: <tt>db/migrate</tt> # - # To use engine's migrations in application you can use rake task, which copies them to + # To use engine's migrations in application you can use the rake task below, which copies them to # application's dir: # # rake ENGINE_NAME:install:migrations @@ -328,7 +335,7 @@ module Rails # # == Loading priority # - # In order to change engine's priority you can use +config.railties_order+ in main application. + # In order to change engine's priority you can use +config.railties_order+ in the main application. # It will affect the priority of loading views, helpers, assets and all the other files # related to engine or application. # @@ -405,7 +412,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| @@ -484,7 +491,7 @@ module Rails helpers = Module.new all = ActionController::Base.all_helpers_from_path(helpers_paths) ActionController::Base.modules_for_helpers(all).each do |mod| - helpers.send(:include, mod) + helpers.include(mod) end helpers end @@ -513,7 +520,7 @@ module Rails def call(env) env.merge!(env_config) if env['SCRIPT_NAME'] - env["ROUTES_#{routes.object_id}_SCRIPT_NAME"] = env['SCRIPT_NAME'].dup + env[routes.env_key] = env['SCRIPT_NAME'].dup end app.call(env) end @@ -528,7 +535,7 @@ module Rails # Defines the routes for this engine. If a block is given to # routes, it is appended to the engine. def routes - @routes ||= ActionDispatch::Routing::RouteSet.new + @routes ||= ActionDispatch::Routing::RouteSet.new_with_config(config) @routes.append(&Proc.new) if block_given? @routes end @@ -559,7 +566,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) @@ -599,12 +606,6 @@ module Rails end end - initializer :append_assets_path, group: :all do |app| - app.config.assets.paths.unshift(*paths["vendor/assets"].existent_directories) - app.config.assets.paths.unshift(*paths["lib/assets"].existent_directories) - app.config.assets.paths.unshift(*paths["app/assets"].existent_directories) - end - initializer :prepend_helpers_path do |app| if !isolated? || (app == self) app.config.helpers_paths.unshift(*paths["app/helpers"].existent) diff --git a/railties/lib/rails/generators.rb b/railties/lib/rails/generators.rb index e25c364178..b430cf1909 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 @@ -156,10 +175,10 @@ module Rails args << "--help" if args.empty? && klass.arguments.any?(&:required?) klass.start(args, config) else - options = sorted_groups.map(&:last).flatten + 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}'"}.join(" or ") }\n" + msg << "Maybe you meant #{ suggestions.map {|s| "'#{s}'"}.to_sentence(last_word_connector: " or ") }\n" msg << "Run `rails generate --help` for more options." puts msg end @@ -260,19 +279,20 @@ module Rails t = str2 n = s.length m = t.length - max = n/2 return m if (0 == n) return n if (0 == m) - return n if (n - m).abs > max 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 @@ -286,7 +306,7 @@ module Rails d[m] = x end - return x + x end # Prints a list of generators. diff --git a/railties/lib/rails/generators/actions.rb b/railties/lib/rails/generators/actions.rb index 5373121835..70a20801a0 100644 --- a/railties/lib/rails/generators/actions.rb +++ b/railties/lib/rails/generators/actions.rb @@ -1,5 +1,4 @@ require 'open-uri' -require 'rbconfig' module Rails module Generators @@ -219,10 +218,10 @@ module Rails # route "root 'welcome#index'" def route(routing_code) log :route, routing_code - sentinel = /\.routes\.draw do\s*$/ + sentinel = /\.routes\.draw do\s*\n/m in_root do - inject_into_file 'config/routes.rb', "\n #{routing_code}", { after: sentinel, verbose: false } + inject_into_file 'config/routes.rb', " #{routing_code}\n", { after: sentinel, verbose: false, force: true } end end diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb index 71186891a3..249fe96772 100644 --- a/railties/lib/rails/generators/app_base.rb +++ b/railties/lib/rails/generators/app_base.rb @@ -69,8 +69,8 @@ module Rails class_option :skip_turbolinks, type: :boolean, default: false, desc: 'Skip turbolinks gem' - class_option :skip_test_unit, type: :boolean, aliases: '-T', default: false, - desc: 'Skip Test::Unit files' + class_option :skip_test, type: :boolean, aliases: '-T', default: false, + desc: 'Skip test files' class_option :rc, type: :string, default: false, desc: "Path to file containing extra configuration options for rails command" @@ -113,7 +113,6 @@ module Rails assets_gemfile_entry, javascript_gemfile_entry, jbuilder_gemfile_entry, - sdoc_gemfile_entry, psych_gemfile_entry, @extra_entries].flatten.find_all(&@gem_filter) end @@ -127,7 +126,7 @@ module Rails def builder @builder ||= begin builder_class = get_builder_class - builder_class.send(:include, ActionMethods) + builder_class.include(ActionMethods) builder_class.new(self) end end @@ -168,13 +167,17 @@ module Rails end def include_all_railties? - options.values_at(:skip_active_record, :skip_action_mailer, :skip_test_unit, :skip_sprockets).none? + options.values_at(:skip_active_record, :skip_action_mailer, :skip_test, :skip_sprockets).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 @@ -205,11 +208,13 @@ module Rails if options.dev? [ GemfileEntry.path('rails', Rails::Generators::RAILS_DEV_PATH), + GemfileEntry.github('sprockets-rails', 'rails/sprockets-rails'), GemfileEntry.github('arel', 'rails/arel') ] elsif options.edge? [ GemfileEntry.github('rails', 'rails/rails'), + GemfileEntry.github('sprockets-rails', 'rails/sprockets-rails'), GemfileEntry.github('arel', 'rails/arel') ] else @@ -261,15 +266,12 @@ module Rails end def jbuilder_gemfile_entry + return [] if options[:api] + comment = 'Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder' GemfileEntry.version('jbuilder', '~> 2.0', comment) end - def sdoc_gemfile_entry - comment = 'bundle exec rake doc:rails generates the API under doc/api.' - GemfileEntry.new('sdoc', '~> 0.4.0', comment, group: :doc) - end - def coffee_gemfile_entry comment = 'Use CoffeeScript for .coffee assets and views' if options.dev? || options.edge? @@ -297,7 +299,7 @@ module Rails end def javascript_runtime_gemfile_entry - comment = 'See https://github.com/sstephenson/execjs#readme for more supported runtimes' + comment = 'See https://github.com/rails/execjs#readme for more supported runtimes' if defined?(JRUBY_VERSION) GemfileEntry.version 'therubyrhino', nil, comment else @@ -321,10 +323,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. @@ -332,8 +330,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 @@ -342,7 +344,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 @@ -361,7 +363,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/erb/mailer/mailer_generator.rb b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb index 7d27321610..65563aa6db 100644 --- a/railties/lib/rails/generators/erb/mailer/mailer_generator.rb +++ b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb @@ -6,7 +6,7 @@ module Erb # :nodoc: argument :actions, type: :array, default: [], banner: "method method" def copy_view_files - view_base_path = File.join("app/views", class_path, file_name) + view_base_path = File.join("app/views", class_path, file_name + '_mailer') empty_directory view_base_path if self.behavior == :invoke @@ -31,6 +31,10 @@ module Erb # :nodoc: def formats [:text, :html] end + + def file_name + @_file_name ||= super.gsub(/\_mailer/i, '') + end end end end 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..d99b27cb2d 100644 --- a/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb +++ b/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb @@ -17,6 +17,7 @@ <%%= f.label :password %><br> <%%= f.password_field :password %> </div> + <div class="field"> <%%= f.label :password_confirmation %><br> <%%= f.password_field :password_confirmation %> @@ -25,6 +26,7 @@ <%%= 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 5e194783ff..c3b8ef1181 100644 --- a/railties/lib/rails/generators/erb/scaffold/templates/index.html.erb +++ b/railties/lib/rails/generators/erb/scaffold/templates/index.html.erb @@ -1,6 +1,6 @@ <p id="notice"><%%= notice %></p> -<h1>Listing <%= plural_table_name.titleize %></h1> +<h1><%= plural_table_name.titleize %></h1> <table> <thead> diff --git a/railties/lib/rails/generators/generated_attribute.rb b/railties/lib/rails/generators/generated_attribute.rb index 77a3dbf9a2..8145a26e22 100644 --- a/railties/lib/rails/generators/generated_attribute.rb +++ b/railties/lib/rails/generators/generated_attribute.rb @@ -142,7 +142,11 @@ module Rails end def password_digest? - name == 'password' && type == :digest + name == 'password' && type == :digest + end + + def token? + type == :token end def inject_options diff --git a/railties/lib/rails/generators/migration.rb b/railties/lib/rails/generators/migration.rb index cd388e590a..51e6d68bf0 100644 --- a/railties/lib/rails/generators/migration.rb +++ b/railties/lib/rails/generators/migration.rb @@ -3,8 +3,8 @@ require 'rails/generators/actions/create_migration' module Rails module Generators - # Holds common methods for migrations. It assumes that migrations has the - # [0-9]*_name format and can be used by another frameworks (like Sequel) + # Holds common methods for migrations. It assumes that migrations have the + # [0-9]*_name format and can be used by other frameworks (like Sequel) # just by implementing the next migration version method. module Migration extend ActiveSupport::Concern diff --git a/railties/lib/rails/generators/named_base.rb b/railties/lib/rails/generators/named_base.rb index 36456e64f5..01a8e2e9b4 100644 --- a/railties/lib/rails/generators/named_base.rb +++ b/railties/lib/rails/generators/named_base.rb @@ -141,6 +141,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 diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb index 0550bf113e..4b73313388 100644 --- a/railties/lib/rails/generators/rails/app/app_generator.rb +++ b/railties/lib/rails/generators/rails/app/app_generator.rb @@ -38,7 +38,7 @@ module Rails end def readme - copy_file "README.rdoc", "README.rdoc" + copy_file "README.md", "README.md" end def gemfile @@ -89,6 +89,7 @@ module Rails def config_when_updating cookie_serializer_config_exist = File.exist?('config/initializers/cookies_serializer.rb') callback_terminator_config_exist = File.exist?('config/initializers/callback_terminator.rb') + active_record_belongs_to_required_by_default_config_exist = File.exist?('config/initializers/active_record_belongs_to_required_by_default.rb') config @@ -99,6 +100,10 @@ module Rails unless cookie_serializer_config_exist gsub_file 'config/initializers/cookies_serializer.rb', /json/, 'marshal' end + + unless active_record_belongs_to_required_by_default_config_exist + remove_file 'config/initializers/active_record_belongs_to_required_by_default.rb' + end end def database_yml @@ -125,6 +130,7 @@ module Rails def test empty_directory_with_keep_file 'test/fixtures' + empty_directory_with_keep_file 'test/fixtures/files' empty_directory_with_keep_file 'test/controllers' empty_directory_with_keep_file 'test/mailers' empty_directory_with_keep_file 'test/models' @@ -135,6 +141,7 @@ module Rails end def tmp + empty_directory_with_keep_file "tmp" empty_directory "tmp/cache" empty_directory "tmp/cache/assets" end @@ -168,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 @@ -178,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! @@ -234,7 +248,7 @@ module Rails end def create_test_files - build(:test) unless options[:skip_test_unit] + build(:test) unless options[:skip_test] end def create_tmp_files @@ -245,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' @@ -257,6 +293,19 @@ module Rails 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' + end + end + def finish_template build(:leftovers) end @@ -307,7 +356,7 @@ 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}" 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 3659edcfcd..606f1d4f96 100644 --- a/railties/lib/rails/generators/rails/app/templates/Gemfile +++ b/railties/lib/rails/generators/rails/app/templates/Gemfile @@ -21,11 +21,21 @@ source 'https://rubygems.org' # Use Capistrano for deployment # gem 'capistrano-rails', group: :development -group :development, :test do +<%- if options.api? -%> +# Use ActiveModelSerializers to serialize JSON responses +gem 'active_model_serializers', '~> 0.10.0.rc1' + +# 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 # 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" @@ -36,10 +46,10 @@ group :development, :test do # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring' <% end -%> -<% end -%> end - +<% end -%> <% if RUBY_PLATFORM.match(/bccwin|cygwin|emx|mingw|mswin|wince|java/) -%> + # 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/README.rdoc b/railties/lib/rails/generators/rails/app/templates/README.md index dd4e97e22e..55e144da18 100644 --- a/railties/lib/rails/generators/rails/app/templates/README.rdoc +++ b/railties/lib/rails/generators/rails/app/templates/README.md @@ -1,4 +1,4 @@ -== README +## README This README would normally document whatever steps are necessary to get the application up and running. @@ -22,7 +22,3 @@ Things you may want to cover: * Deployment instructions * ... - - -Please feel free to use a different markup language if you do not plan to run -<tt>rake doc:app</tt>. 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 c1a77944e8..cb86978d4c 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 @@ -7,7 +7,7 @@ // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // -// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details +// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // <% unless options[:skip_javascript] -%> 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 f9cd5b3483..0cdd2788d0 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 @@ -6,9 +6,8 @@ * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path. * * You're free to add application-wide styles to this file and they'll appear at the bottom of the - * compiled file so the styles you add here take precedence over styles defined in any styles - * defined in the other CSS/SCSS files in this directory. It is generally better to create a new - * file per style scope. + * 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. * *= require_tree . *= require_self 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/bin/setup b/railties/lib/rails/generators/rails/app/templates/bin/setup index eee810be30..0d41f2fe4c 100644 --- a/railties/lib/rails/generators/rails/app/templates/bin/setup +++ b/railties/lib/rails/generators/rails/app/templates/bin/setup @@ -22,9 +22,8 @@ chdir APP_ROOT do system 'ruby bin/rake db:setup' puts "\n== Removing old logs and tempfiles ==" - rm_f Dir.glob('log/*') - rm_rf 'tmp/cache' + system 'ruby bin/rake log:clear tmp:clear' puts "\n== Restarting application server ==" - touch 'tmp/restart.txt' + system 'ruby bin/rake restart' end 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 c59ffb3491..6b7d7abd0b 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/application.rb +++ b/railties/lib/rails/generators/rails/app/templates/config/application.rb @@ -3,6 +3,7 @@ require File.expand_path('../boot', __FILE__) <% if include_all_railties? -%> require 'rails/all' <% else -%> +require "rails" # Pick the frameworks you want: require "active_model/railtie" require "active_job/railtie" @@ -11,7 +12,7 @@ require "action_controller/railtie" <%= comment_if :skip_action_mailer %>require "action_mailer/railtie" require "action_view/railtie" <%= comment_if :skip_sprockets %>require "sprockets/railtie" -<%= comment_if :skip_test_unit %>require "rails/test_unit/railtie" +<%= comment_if :skip_test %>require "rails/test_unit/railtie" <% end -%> # Require the gems listed in Gemfile, including any gems @@ -31,5 +32,12 @@ module <%= app_const_base %> # 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 +<%- if options[:api] -%> + + # 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 acb93939e1..f5b62e8fb3 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.0/en/old-client.html +# http://dev.mysql.com/doc/refman/5.6/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 596c916573..b0767bd93a 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.0/en/old-client.html +# http://dev.mysql.com/doc/refman/5.6/en/old-client.html # default: &default adapter: mysql2 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 99d7bfb3c9..8c09396fc1 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 @@ -14,12 +14,6 @@ Rails.application.configure do config.consider_all_requests_local = false config.action_controller.perform_caching = true - # Enable Rack::Cache to put a simple HTTP cache in front of your application - # Add `rack-cache` to your Gemfile before enabling this. - # For large-scale production use, consider using a caching reverse proxy like - # NGINX, varnish or squid. - # config.action_dispatch.rack_cache = true - # 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? @@ -39,6 +33,9 @@ Rails.application.configure do # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb <%- end -%> + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.action_controller.asset_host = 'http://assets.example.com' + # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX @@ -51,7 +48,7 @@ Rails.application.configure do config.log_level = :debug # Prepend all log lines with the following tags. - # config.log_tags = [ :subdomain, :uuid ] + # config.log_tags = [ :subdomain, :request_id ] # Use a different logger for distributed setups. # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) @@ -59,8 +56,9 @@ Rails.application.configure do # Use a different cache store in production. # config.cache_store = :mem_cache_store - # Enable serving of images, stylesheets, and JavaScripts from an asset server. - # config.action_controller.asset_host = 'http://assets.example.com' + # Use a real queuing backend for Active Job (and separate queues per environment) + # config.active_job.queue_adapter = :resque + # config.active_job.queue_name_prefix = "<%= app_name %>_#{Rails.env}" <%- unless options.skip_action_mailer? -%> # Ignore bad email addresses and do not raise email delivery errors. 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 new file mode 100644 index 0000000000..30c4f89792 --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/active_record_belongs_to_required_by_default.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Require `belongs_to` associations by default. +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 new file mode 100644 index 0000000000..ea930f54da --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/application_controller_renderer.rb @@ -0,0 +1,6 @@ +## Change renderer defaults here. +# +# 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..a70a1b9cde 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,4 @@ # 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 +ActiveSupport.halt_callback_chains_on_return_false = false 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..45c44d24f8 --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/cors.rb @@ -0,0 +1,14 @@ +# 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/wrap_parameters.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt index f2110c2c70..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,12 +5,12 @@ # 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? -%> # To enable root element in JSON for ActiveRecord objects. # ActiveSupport.on_load(:active_record) do -# self.include_root_in_json = true +# self.include_root_in_json = true # end <%- end -%> diff --git a/railties/lib/rails/generators/rails/app/templates/gitignore b/railties/lib/rails/generators/rails/app/templates/gitignore index 7c6f2098b8..1b8cf8a9fa 100644 --- a/railties/lib/rails/generators/rails/app/templates/gitignore +++ b/railties/lib/rails/generators/rails/app/templates/gitignore @@ -15,5 +15,8 @@ <% end -%> # Ignore all logfiles and tempfiles. /log/* +/tmp/* +<% if keeps? -%> !/log/.keep -/tmp +!/tmp/.keep +<% end -%> 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/migration/migration_generator.rb b/railties/lib/rails/generators/rails/migration/migration_generator.rb index 965c42db36..fca2a8fef4 100644 --- a/railties/lib/rails/generators/rails/migration/migration_generator.rb +++ b/railties/lib/rails/generators/rails/migration/migration_generator.rb @@ -2,7 +2,7 @@ module Rails module Generators class MigrationGenerator < NamedBase # :nodoc: argument :attributes, type: :array, default: [], banner: "field[:type][:index] field[:type][:index]" - hook_for :orm, required: true + hook_for :orm, required: true, desc: "ORM to be invoked" end end end diff --git a/railties/lib/rails/generators/rails/model/USAGE b/railties/lib/rails/generators/rails/model/USAGE index 8c3b63c3b4..11daa5c3cb 100644 --- a/railties/lib/rails/generators/rails/model/USAGE +++ b/railties/lib/rails/generators/rails/model/USAGE @@ -22,7 +22,7 @@ Description: If you pass a namespaced model name (e.g. admin/account or Admin::Account) then the generator will create a module with a table_name_prefix method - to prefix the model's table name with the module name (e.g. admin_account) + to prefix the model's table name with the module name (e.g. admin_accounts) Available field types: @@ -79,10 +79,15 @@ Available field types: `rails generate model product supplier:references{polymorphic}:index` If you require a `password_digest` string column for use with - has_secure_password, you should specify `password:digest`: + has_secure_password, you can specify `password:digest`: `rails generate model user password:digest` + If you require a `token` string column for use with + has_secure_token, you can specify `auth_token:token`: + + `rails generate model user auth_token:token` + Examples: `rails generate model account` diff --git a/railties/lib/rails/generators/rails/model/model_generator.rb b/railties/lib/rails/generators/rails/model/model_generator.rb index 87bab129bb..ec78fd855d 100644 --- a/railties/lib/rails/generators/rails/model/model_generator.rb +++ b/railties/lib/rails/generators/rails/model/model_generator.rb @@ -6,7 +6,7 @@ module Rails include Rails::Generators::ModelHelpers argument :attributes, type: :array, default: [], banner: "field[:type][:index] field[:type][:index]" - hook_for :orm, required: true + hook_for :orm, required: true, desc: "ORM to be invoked" end end end diff --git a/railties/lib/rails/generators/rails/plugin/plugin_generator.rb b/railties/lib/rails/generators/rails/plugin/plugin_generator.rb index 1c270dd7d4..7f5bf0c8b8 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 @@ -18,14 +18,14 @@ module Rails def app if mountable? directory 'app' - empty_directory_with_keep_file "app/assets/images/#{name}" + empty_directory_with_keep_file "app/assets/images/#{namespaced_name}" 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/#{name}" + empty_directory_with_keep_file "app/assets/images/#{namespaced_name}" end end @@ -50,10 +50,10 @@ module Rails end def lib - template "lib/%name%.rb" - template "lib/tasks/%name%_tasks.rake" - template "lib/%name%/version.rb" - template "lib/%name%/engine.rb" if engine? + template "lib/%namespaced_name%.rb" + template "lib/tasks/%namespaced_name%_tasks.rake" + template "lib/%namespaced_name%/version.rb" + template "lib/%namespaced_name%/engine.rb" if engine? end def config @@ -62,7 +62,7 @@ module Rails def test template "test/test_helper.rb" - template "test/%name%_test.rb" + template "test/%namespaced_name%_test.rb" append_file "Rakefile", <<-EOF #{rakefile_test_tasks} @@ -117,9 +117,9 @@ task default: :test def stylesheets if mountable? copy_file "rails/stylesheets.css", - "app/assets/stylesheets/#{name}/application.css" + "app/assets/stylesheets/#{namespaced_name}/application.css" elsif full? - empty_directory_with_keep_file "app/assets/stylesheets/#{name}" + empty_directory_with_keep_file "app/assets/stylesheets/#{namespaced_name}" end end @@ -128,9 +128,9 @@ task default: :test if mountable? template "rails/javascripts.js", - "app/assets/javascripts/#{name}/application.js" + "app/assets/javascripts/#{namespaced_name}/application.js" elsif full? - empty_directory_with_keep_file "app/assets/javascripts/#{name}" + empty_directory_with_keep_file "app/assets/javascripts/#{namespaced_name}" end end @@ -226,7 +226,7 @@ task default: :test end def create_test_files - build(:test) unless options[:skip_test_unit] + build(:test) unless options[:skip_test] end def create_test_dummy_files @@ -256,6 +256,14 @@ task default: :test end end + def underscored_name + @underscored_name ||= original_name.underscore + end + + def namespaced_name + @namespaced_name ||= name.gsub('-', '/') + end + protected def app_templates_dir @@ -294,7 +302,7 @@ task default: :test end def with_dummy_app? - options[:skip_test_unit].blank? || options[:dummy_path] != 'test/dummy' + options[:skip_test].blank? || options[:dummy_path] != 'test/dummy' end def self.banner @@ -305,6 +313,27 @@ task default: :test @original_name ||= File.basename(destination_root) end + def modules + @modules ||= namespaced_name.camelize.split("::") + end + + def wrap_in_modules(unwrapped_code) + unwrapped_code = "#{unwrapped_code}".strip.gsub(/\W$\n/, '') + modules.reverse.inject(unwrapped_code) do |content, mod| + str = "module #{mod}\n" + str += content.lines.map { |line| " #{line}" }.join + str += content.present? ? "\nend" : "end" + end + end + + def camelized_modules + @camelized_modules ||= namespaced_name.camelize + end + + def humanized + @humanized ||= original_name.underscore.humanize + end + def camelized @camelized ||= name.gsub(/\W/, '_').squeeze('_').camelize end @@ -328,12 +357,14 @@ task default: :test end def valid_const? - if original_name =~ /[^0-9a-zA-Z_]+/ - raise Error, "Invalid plugin name #{original_name}. Please give a name which use only alphabetic or numeric or \"_\" characters." + if original_name =~ /-\d/ + raise Error, "Invalid plugin name #{original_name}. Please give a name which does not contain a namespace starting with numeric characters." + elsif original_name =~ /[^\w-]+/ + raise Error, "Invalid plugin name #{original_name}. Please give a name which uses only alphabetic, numeric, \"_\" or \"-\" characters." 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}" 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 919c349470..f8ece4fe73 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/%name%.gemspec +++ b/railties/lib/rails/generators/rails/plugin/templates/%name%.gemspec @@ -1,21 +1,21 @@ $:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: -require "<%= name %>/version" +require "<%= namespaced_name %>/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "<%= name %>" - s.version = <%= camelized %>::VERSION + s.version = <%= camelized_modules %>::VERSION s.authors = ["<%= author %>"] s.email = ["<%= email %>"] s.homepage = "TODO" - s.summary = "TODO: Summary of <%= camelized %>." - s.description = "TODO: Description of <%= camelized %>." + s.summary = "TODO: Summary of <%= camelized_modules %>." + 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_unit? -%> +<% unless options.skip_test? -%> s.test_files = Dir["test/**/*"] <% end -%> diff --git a/railties/lib/rails/generators/rails/plugin/templates/Gemfile b/railties/lib/rails/generators/rails/plugin/templates/Gemfile index f325455bac..2c91c6a0ea 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/Gemfile +++ b/railties/lib/rails/generators/rails/plugin/templates/Gemfile @@ -41,7 +41,7 @@ end # To use a debugger # gem 'byebug', group: [:development, :test] <% end -%> - <% if RUBY_PLATFORM.match(/bccwin|cygwin|emx|mingw|mswin|wince|java/) -%> + gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] <% end -%> diff --git a/railties/lib/rails/generators/rails/plugin/templates/README.rdoc b/railties/lib/rails/generators/rails/plugin/templates/README.rdoc index 301d647731..25983ca5da 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/README.rdoc +++ b/railties/lib/rails/generators/rails/plugin/templates/README.rdoc @@ -1,3 +1,3 @@ -= <%= camelized %> += <%= 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 c338a0bdb1..bda55bae29 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/Rakefile +++ b/railties/lib/rails/generators/rails/plugin/templates/Rakefile @@ -8,7 +8,7 @@ require 'rdoc/task' RDoc::Task.new(:rdoc) do |rdoc| rdoc.rdoc_dir = 'rdoc' - rdoc.title = '<%= camelized %>' + rdoc.title = '<%= camelized_modules %>' rdoc.options << '--line-numbers' rdoc.rdoc_files.include('README.rdoc') rdoc.rdoc_files.include('lib/**/*.rb') diff --git a/railties/lib/rails/generators/rails/plugin/templates/app/controllers/%name%/application_controller.rb.tt b/railties/lib/rails/generators/rails/plugin/templates/app/controllers/%namespaced_name%/application_controller.rb.tt index 448ad7f989..7157e48c42 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/app/controllers/%name%/application_controller.rb.tt +++ b/railties/lib/rails/generators/rails/plugin/templates/app/controllers/%namespaced_name%/application_controller.rb.tt @@ -1,4 +1,5 @@ -module <%= camelized %> +<%= wrap_in_modules <<-rb.strip_heredoc class ApplicationController < ActionController::Base end -end +rb +%> diff --git a/railties/lib/rails/generators/rails/plugin/templates/app/helpers/%name%/application_helper.rb.tt b/railties/lib/rails/generators/rails/plugin/templates/app/helpers/%name%/application_helper.rb.tt deleted file mode 100644 index 40ae9f52c2..0000000000 --- a/railties/lib/rails/generators/rails/plugin/templates/app/helpers/%name%/application_helper.rb.tt +++ /dev/null @@ -1,4 +0,0 @@ -module <%= camelized %> - module ApplicationHelper - end -end diff --git a/railties/lib/rails/generators/rails/plugin/templates/app/helpers/%namespaced_name%/application_helper.rb.tt b/railties/lib/rails/generators/rails/plugin/templates/app/helpers/%namespaced_name%/application_helper.rb.tt new file mode 100644 index 0000000000..25d692732d --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin/templates/app/helpers/%namespaced_name%/application_helper.rb.tt @@ -0,0 +1,5 @@ +<%= wrap_in_modules <<-rb.strip_heredoc + module ApplicationHelper + end +rb +%> diff --git a/railties/lib/rails/generators/rails/plugin/templates/app/views/layouts/%name%/application.html.erb.tt b/railties/lib/rails/generators/rails/plugin/templates/app/views/layouts/%name%/application.html.erb.tt deleted file mode 100644 index 1d380420b4..0000000000 --- a/railties/lib/rails/generators/rails/plugin/templates/app/views/layouts/%name%/application.html.erb.tt +++ /dev/null @@ -1,14 +0,0 @@ -<!DOCTYPE html> -<html> -<head> - <title><%= camelized %></title> - <%%= stylesheet_link_tag "<%= name %>/application", media: "all" %> - <%%= javascript_include_tag "<%= name %>/application" %> - <%%= csrf_meta_tags %> -</head> -<body> - -<%%= yield %> - -</body> -</html> diff --git a/railties/lib/rails/generators/rails/plugin/templates/app/views/layouts/%namespaced_name%/application.html.erb.tt b/railties/lib/rails/generators/rails/plugin/templates/app/views/layouts/%namespaced_name%/application.html.erb.tt new file mode 100644 index 0000000000..6bc480161d --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin/templates/app/views/layouts/%namespaced_name%/application.html.erb.tt @@ -0,0 +1,14 @@ +<!DOCTYPE html> +<html> +<head> + <title><%= humanized %></title> + <%%= stylesheet_link_tag "<%= namespaced_name %>/application", media: "all" %> + <%%= javascript_include_tag "<%= namespaced_name %>/application" %> + <%%= csrf_meta_tags %> +</head> +<body> + +<%%= yield %> + +</body> +</html> diff --git a/railties/lib/rails/generators/rails/plugin/templates/bin/rails.tt b/railties/lib/rails/generators/rails/plugin/templates/bin/rails.tt index c3314d7e68..3edaac35c9 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/bin/rails.tt +++ b/railties/lib/rails/generators/rails/plugin/templates/bin/rails.tt @@ -1,7 +1,7 @@ # This command will automatically be run when you run "rails" with Rails 4 gems installed from the root of your application. ENGINE_ROOT = File.expand_path('../..', __FILE__) -ENGINE_PATH = File.expand_path('../../lib/<%= name -%>/engine', __FILE__) +ENGINE_PATH = File.expand_path('../../lib/<%= namespaced_name -%>/engine', __FILE__) # Set up gems listed in the Gemfile. ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) diff --git a/railties/lib/rails/generators/rails/plugin/templates/config/routes.rb b/railties/lib/rails/generators/rails/plugin/templates/config/routes.rb index 8e158d5831..154452bfe5 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/config/routes.rb +++ b/railties/lib/rails/generators/rails/plugin/templates/config/routes.rb @@ -1,5 +1,5 @@ <% if mountable? -%> -<%= camelized %>::Engine.routes.draw do +<%= camelized_modules %>::Engine.routes.draw do <% else -%> Rails.application.routes.draw do <% end -%> diff --git a/railties/lib/rails/generators/rails/plugin/templates/gitignore b/railties/lib/rails/generators/rails/plugin/templates/gitignore index 086d87818a..d524fcbc4e 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/gitignore +++ b/railties/lib/rails/generators/rails/plugin/templates/gitignore @@ -1,10 +1,10 @@ .bundle/ log/*.log pkg/ -<% unless options[:skip_test_unit] && options[:dummy_path] == 'test/dummy' -%> +<% unless options[:skip_test] && options[:dummy_path] == 'test/dummy' -%> <%= dummy_path %>/db/*.sqlite3 <%= dummy_path %>/db/*.sqlite3-journal <%= dummy_path %>/log/*.log <%= dummy_path %>/tmp/ <%= dummy_path %>/.sass-cache -<% end -%>
\ No newline at end of file +<% end -%> diff --git a/railties/lib/rails/generators/rails/plugin/templates/lib/%name%.rb b/railties/lib/rails/generators/rails/plugin/templates/lib/%name%.rb deleted file mode 100644 index 40c074cced..0000000000 --- a/railties/lib/rails/generators/rails/plugin/templates/lib/%name%.rb +++ /dev/null @@ -1,6 +0,0 @@ -<% if engine? -%> -require "<%= name %>/engine" - -<% end -%> -module <%= camelized %> -end diff --git a/railties/lib/rails/generators/rails/plugin/templates/lib/%name%/engine.rb b/railties/lib/rails/generators/rails/plugin/templates/lib/%name%/engine.rb deleted file mode 100644 index 967668fe66..0000000000 --- a/railties/lib/rails/generators/rails/plugin/templates/lib/%name%/engine.rb +++ /dev/null @@ -1,7 +0,0 @@ -module <%= camelized %> - class Engine < ::Rails::Engine -<% if mountable? -%> - isolate_namespace <%= camelized %> -<% end -%> - end -end diff --git a/railties/lib/rails/generators/rails/plugin/templates/lib/%name%/version.rb b/railties/lib/rails/generators/rails/plugin/templates/lib/%name%/version.rb deleted file mode 100644 index ef07ef2e19..0000000000 --- a/railties/lib/rails/generators/rails/plugin/templates/lib/%name%/version.rb +++ /dev/null @@ -1,3 +0,0 @@ -module <%= camelized %> - VERSION = "0.0.1" -end diff --git a/railties/lib/rails/generators/rails/plugin/templates/lib/%namespaced_name%.rb b/railties/lib/rails/generators/rails/plugin/templates/lib/%namespaced_name%.rb new file mode 100644 index 0000000000..40b1c4cee7 --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin/templates/lib/%namespaced_name%.rb @@ -0,0 +1,5 @@ +<% if engine? -%> +require "<%= namespaced_name %>/engine" + +<% end -%> +<%= wrap_in_modules "# Your code goes here..." %> 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 new file mode 100644 index 0000000000..17afd52177 --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin/templates/lib/%namespaced_name%/engine.rb @@ -0,0 +1,6 @@ +<%= wrap_in_modules <<-rb.strip_heredoc + class Engine < ::Rails::Engine + #{mountable? ? ' isolate_namespace ' + camelized_modules : ' '} + 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 new file mode 100644 index 0000000000..d257295988 --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin/templates/lib/%namespaced_name%/version.rb @@ -0,0 +1 @@ +<%= wrap_in_modules 'VERSION = "0.0.1"' %> diff --git a/railties/lib/rails/generators/rails/plugin/templates/lib/tasks/%name%_tasks.rake b/railties/lib/rails/generators/rails/plugin/templates/lib/tasks/%namespaced_name%_tasks.rake index 7121f5ae23..88a2c4120f 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/lib/tasks/%name%_tasks.rake +++ b/railties/lib/rails/generators/rails/plugin/templates/lib/tasks/%namespaced_name%_tasks.rake @@ -1,4 +1,4 @@ # desc "Explaining what the task does" -# task :<%= name %> do +# task :<%= underscored_name %> do # # Task goes here # end diff --git a/railties/lib/rails/generators/rails/plugin/templates/rails/application.rb b/railties/lib/rails/generators/rails/plugin/templates/rails/application.rb index 3a9a7e5437..b1038c839e 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/rails/application.rb +++ b/railties/lib/rails/generators/rails/plugin/templates/rails/application.rb @@ -9,10 +9,10 @@ require "action_controller/railtie" <%= comment_if :skip_action_mailer %>require "action_mailer/railtie" require "action_view/railtie" <%= comment_if :skip_sprockets %>require "sprockets/railtie" -<%= comment_if :skip_test_unit %>require "rails/test_unit/railtie" +<%= comment_if :skip_test %>require "rails/test_unit/railtie" <% end -%> Bundler.require(*Rails.groups) -require "<%= name %>" +require "<%= namespaced_name %>" <%= application_definition %> 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 c28e5badc6..8913b40f69 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/rails/javascripts.js +++ b/railties/lib/rails/generators/rails/plugin/templates/rails/javascripts.js @@ -7,7 +7,7 @@ // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // -// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details +// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require_tree . 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 730ee31c3d..673de44108 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,4 @@ Rails.application.routes.draw do - mount <%= camelized %>::Engine => "/<%= name %>" + 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 f9cd5b3483..0cdd2788d0 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/rails/stylesheets.css +++ b/railties/lib/rails/generators/rails/plugin/templates/rails/stylesheets.css @@ -6,9 +6,8 @@ * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path. * * You're free to add application-wide styles to this file and they'll appear at the bottom of the - * compiled file so the styles you add here take precedence over styles defined in any styles - * defined in the other CSS/SCSS files in this directory. It is generally better to create a new - * file per style scope. + * 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. * *= require_tree . *= require_self diff --git a/railties/lib/rails/generators/rails/plugin/templates/test/%name%_test.rb b/railties/lib/rails/generators/rails/plugin/templates/test/%name%_test.rb deleted file mode 100644 index 0a8bbd4aaf..0000000000 --- a/railties/lib/rails/generators/rails/plugin/templates/test/%name%_test.rb +++ /dev/null @@ -1,7 +0,0 @@ -require 'test_helper' - -class <%= camelized %>Test < ActiveSupport::TestCase - test "truth" do - assert_kind_of Module, <%= camelized %> - end -end diff --git a/railties/lib/rails/generators/rails/plugin/templates/test/%namespaced_name%_test.rb b/railties/lib/rails/generators/rails/plugin/templates/test/%namespaced_name%_test.rb new file mode 100644 index 0000000000..1ee05d7871 --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin/templates/test/%namespaced_name%_test.rb @@ -0,0 +1,7 @@ +require 'test_helper' + +class <%= camelized_modules %>::Test < ActiveSupport::TestCase + test "truth" do + assert_kind_of Module, <%= camelized_modules %> + end +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 bf3da1fc4d..0852ffce9a 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 @@ -20,4 +20,6 @@ Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f } # 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" + 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 e4a2bc2b0f..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 @@ -29,8 +28,10 @@ module Rails write("end", route_length - index) end - # route prepends two spaces onto the front of the string that is passed, this corrects that - route route_string[2..-1] + # route prepends two spaces onto the front of the string that is passed, this corrects that. + # Also it adds a \n to the end of each line, as route already adds that + # we need to correct that too. + route route_string[2..-2] end private 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 1ae7000299..b7818883d1 100644 --- a/railties/lib/rails/generators/rails/scaffold/templates/scaffold.css +++ b/railties/lib/rails/generators/rails/scaffold/templates/scaffold.css @@ -1,9 +1,13 @@ -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; } pre { @@ -12,11 +16,31 @@ 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; +} + +td { + padding-bottom: 7px; + padding-left: 5px; + padding-right: 5px; +} -div.field, div.actions { +div.field, +div.actions { margin-bottom: 10px; } @@ -45,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; } 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..bc3c9b3f6b --- /dev/null +++ b/railties/lib/rails/generators/rails/scaffold_controller/templates/api_controller.rb @@ -0,0 +1,61 @@ +<% if namespaced? -%> +require_dependency "<%= namespaced_file_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[:<%= 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/resource_helpers.rb b/railties/lib/rails/generators/resource_helpers.rb index 3f84d76ae0..9c2037783e 100644 --- a/railties/lib/rails/generators/resource_helpers.rb +++ b/railties/lib/rails/generators/resource_helpers.rb @@ -8,7 +8,7 @@ module Rails module ResourceHelpers # :nodoc: def self.included(base) #:nodoc: - base.send :include, Rails::Generators::ModelHelpers + base.include(Rails::Generators::ModelHelpers) base.class_option :model_name, type: :string, desc: "ModelName to be used" 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..7106096b60 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 @@ -2,6 +2,12 @@ require 'test_helper' <% module_namespacing do -%> class <%= class_name %>ControllerTest < ActionController::TestCase +<% if defined?(ENGINE_ROOT) -%> + setup do + @routes = Engine.routes + end + +<% end -%> <% if actions.empty? -%> # test "the truth" do # assert true diff --git a/railties/lib/rails/generators/test_unit/mailer/mailer_generator.rb b/railties/lib/rails/generators/test_unit/mailer/mailer_generator.rb index 85dee1a066..343c8a3949 100644 --- a/railties/lib/rails/generators/test_unit/mailer/mailer_generator.rb +++ b/railties/lib/rails/generators/test_unit/mailer/mailer_generator.rb @@ -6,16 +6,21 @@ module TestUnit # :nodoc: argument :actions, type: :array, default: [], banner: "method method" def check_class_collision - class_collisions "#{class_name}Test", "#{class_name}Preview" + class_collisions "#{class_name}MailerTest", "#{class_name}MailerPreview" end def create_test_files - template "functional_test.rb", File.join('test/mailers', class_path, "#{file_name}_test.rb") + template "functional_test.rb", File.join('test/mailers', class_path, "#{file_name}_mailer_test.rb") end def create_preview_files - template "preview.rb", File.join('test/mailers/previews', class_path, "#{file_name}_preview.rb") + template "preview.rb", File.join('test/mailers/previews', class_path, "#{file_name}_mailer_preview.rb") end + + protected + def file_name + @_file_name ||= super.gsub(/\_mailer/i, '') + end end end end diff --git a/railties/lib/rails/generators/test_unit/mailer/templates/functional_test.rb b/railties/lib/rails/generators/test_unit/mailer/templates/functional_test.rb index 7e204105a3..a2f2d30de5 100644 --- a/railties/lib/rails/generators/test_unit/mailer/templates/functional_test.rb +++ b/railties/lib/rails/generators/test_unit/mailer/templates/functional_test.rb @@ -1,10 +1,10 @@ require 'test_helper' <% module_namespacing do -%> -class <%= class_name %>Test < ActionMailer::TestCase +class <%= class_name %>MailerTest < ActionMailer::TestCase <% actions.each do |action| -%> test "<%= action %>" do - mail = <%= class_name %>.<%= action %> + mail = <%= class_name %>Mailer.<%= action %> assert_equal <%= action.to_s.humanize.inspect %>, mail.subject assert_equal ["to@example.org"], mail.to assert_equal ["from@example.com"], mail.from diff --git a/railties/lib/rails/generators/test_unit/mailer/templates/preview.rb b/railties/lib/rails/generators/test_unit/mailer/templates/preview.rb index 3bfd5426e8..b063cbc47b 100644 --- a/railties/lib/rails/generators/test_unit/mailer/templates/preview.rb +++ b/railties/lib/rails/generators/test_unit/mailer/templates/preview.rb @@ -1,11 +1,11 @@ <% module_namespacing do -%> -# Preview all emails at http://localhost:3000/rails/mailers/<%= file_path %> -class <%= class_name %>Preview < ActionMailer::Preview +# Preview all emails at http://localhost:3000/rails/mailers/<%= file_path %>_mailer +class <%= class_name %>MailerPreview < ActionMailer::Preview <% actions.each do |action| -%> - # Preview this email at http://localhost:3000/rails/mailers/<%= file_path %>/<%= action %> + # Preview this email at http://localhost:3000/rails/mailers/<%= file_path %>_mailer/<%= action %> def <%= action %> - <%= class_name %>.<%= action %> + <%= class_name %>Mailer.<%= action %> end <% end -%> diff --git a/railties/lib/rails/generators/test_unit/model/model_generator.rb b/railties/lib/rails/generators/test_unit/model/model_generator.rb index 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..d634584beb 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 defined?(ENGINE_ROOT) + "%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..896b38bc8f --- /dev/null +++ b/railties/lib/rails/generators/test_unit/scaffold/templates/api_functional_test.rb @@ -0,0 +1,40 @@ +require 'test_helper' + +<% module_namespacing do -%> +class <%= controller_class_name %>ControllerTest < ActionController::TestCase + setup do + @<%= singular_table_name %> = <%= table_name %>(:one) + end + + test "should get index" do + get :index + 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} }" %> } + end + + assert_response 201 + end + + test "should show <%= singular_table_name %>" do + get :show, params: { id: <%= "@#{singular_table_name}" %> } + assert_response :success + end + + test "should update <%= singular_table_name %>" do + patch :update, params: { id: <%= "@#{singular_table_name}" %>, <%= "#{singular_table_name}: { #{attributes_hash} }" %> } + assert_response 200 + end + + test "should destroy <%= singular_table_name %>" do + assert_difference('<%= class_name %>.count', -1) do + delete :destroy, params: { id: <%= "@#{singular_table_name}" %> } + 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 18bd1ece9d..d12a5ba733 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 @@ -3,13 +3,15 @@ require 'test_helper' <% module_namespacing do -%> class <%= controller_class_name %>ControllerTest < ActionController::TestCase setup do - @<%= singular_table_name %> = <%= table_name %>(:one) + @<%= singular_table_name %> = <%= fixture_name %>(:one) +<% if defined?(ENGINE_ROOT) -%> + @routes = Engine.routes +<% end -%> end test "should get index" do get :index assert_response :success - assert_not_nil assigns(:<%= table_name %>) end test "should get new" do @@ -19,30 +21,30 @@ class <%= controller_class_name %>ControllerTest < ActionController::TestCase test "should create <%= singular_table_name %>" do assert_difference('<%= class_name %>.count') do - post :create, <%= "#{singular_table_name}: { #{attributes_hash} }" %> + post :create, 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, id: <%= "@#{singular_table_name}" %> + get :show, params: { id: <%= "@#{singular_table_name}" %> } assert_response :success end test "should get edit" do - get :edit, id: <%= "@#{singular_table_name}" %> + get :edit, params: { id: <%= "@#{singular_table_name}" %> } assert_response :success end test "should update <%= singular_table_name %>" do - patch :update, id: <%= "@#{singular_table_name}" %>, <%= "#{singular_table_name}: { #{attributes_hash} }" %> - assert_redirected_to <%= singular_table_name %>_path(assigns(:<%= singular_table_name %>)) + patch :update, params: { id: <%= "@#{singular_table_name}" %>, <%= "#{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, id: <%= "@#{singular_table_name}" %> + delete :destroy, params: { id: <%= "@#{singular_table_name}" %> } end assert_redirected_to <%= index_helper %>_path diff --git a/railties/lib/rails/generators/testing/behaviour.rb b/railties/lib/rails/generators/testing/behaviour.rb index fd2ea274e1..c9700e1cd7 100644 --- a/railties/lib/rails/generators/testing/behaviour.rb +++ b/railties/lib/rails/generators/testing/behaviour.rb @@ -2,6 +2,7 @@ require 'active_support/core_ext/class/attribute' require 'active_support/core_ext/module/delegation' require 'active_support/core_ext/hash/reverse_merge' require 'active_support/core_ext/kernel/reporting' +require 'active_support/testing/stream' require 'active_support/concern' require 'rails/generators' @@ -10,6 +11,7 @@ module Rails module Testing module Behaviour extend ActiveSupport::Concern + include ActiveSupport::Testing::Stream included do class_attribute :destination_root, :current_path, :generator_class, :default_arguments @@ -101,22 +103,6 @@ module Rails Dir.glob("#{dirname}/[0-9]*_*.rb").grep(/\d+_#{file_name}.rb$/).first end - def capture(stream) - stream = stream.to_s - captured_stream = Tempfile.new(stream) - stream_io = eval("$#{stream}") - origin_stream = stream_io.dup - stream_io.reopen(captured_stream) - - yield - - stream_io.rewind - return captured_stream.read - ensure - captured_stream.close - captured_stream.unlink - stream_io.reopen(origin_stream) - end end end end diff --git a/railties/lib/rails/info_controller.rb b/railties/lib/rails/info_controller.rb index 49e5431a16..778105c5f7 100644 --- a/railties/lib/rails/info_controller.rb +++ b/railties/lib/rails/info_controller.rb @@ -17,7 +17,28 @@ class Rails::InfoController < Rails::ApplicationController # :nodoc: end def routes - @routes_inspector = ActionDispatch::Routing::RoutesInspector.new(_routes.routes) - @page_title = 'Routes' + if path = params[:path] + path = URI.parser.escape path + normalized_path = with_leading_slash path + render json: { + exact: match_route {|it| it.match normalized_path }, + fuzzy: match_route {|it| it.spec.to_s.match path } + } + else + @routes_inspector = ActionDispatch::Routing::RoutesInspector.new(_routes.routes) + @page_title = 'Routes' + end + end + + private + + def match_route + _routes.routes.select {|route| + yield route.path + }.map {|route| route.path.spec.to_s } + end + + def with_leading_slash(path) + ('/' + path).squeeze('/') end end diff --git a/railties/lib/rails/mailers_controller.rb b/railties/lib/rails/mailers_controller.rb index 32740d66da..41422a656c 100644 --- a/railties/lib/rails/mailers_controller.rb +++ b/railties/lib/rails/mailers_controller.rb @@ -16,10 +16,10 @@ 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]) @@ -28,14 +28,14 @@ class Rails::MailersController < Rails::ApplicationController # :nodoc: response.content_type = part_type render text: 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) 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 @@ -54,18 +54,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 5458036219..ebcaaaba46 100644 --- a/railties/lib/rails/paths.rb +++ b/railties/lib/rails/paths.rb @@ -7,7 +7,7 @@ module Rails # root = Root.new "/rails" # root.add "app/controllers", eager_load: true # - # The command above creates a new root object and add "app/controllers" as a path. + # The command above creates a new root object and adds "app/controllers" as a path. # This means we can get a <tt>Rails::Paths::Path</tt> object back like below: # # path = root["app/controllers"] 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/railtie.rb b/railties/lib/rails/railtie.rb index 2b33beaa2b..8c24d1d56d 100644 --- a/railties/lib/rails/railtie.rb +++ b/railties/lib/rails/railtie.rb @@ -93,7 +93,7 @@ module Rails # end # end # - # By default, Rails load generators from your load path. However, if you want to place + # By default, Rails loads generators from your load path. However, if you want to place # your generators at a different location, you can specify in your Railtie a block which # will load them during normal generators lookup: # diff --git a/railties/lib/rails/ruby_version_check.rb b/railties/lib/rails/ruby_version_check.rb index aea3d2339c..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.0' +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.0 or newer. + Rails 5 requires Ruby 2.2.2 or newer. You're running #{desc} - Please upgrade to Ruby 2.2.0 or newer to continue. + Please upgrade to Ruby 2.2.2 or newer to continue. end_message end diff --git a/railties/lib/rails/tasks.rb b/railties/lib/rails/tasks.rb index 2f82d1285d..2c3d278eca 100644 --- a/railties/lib/rails/tasks.rb +++ b/railties/lib/rails/tasks.rb @@ -3,11 +3,12 @@ require 'rake' # Load Rails Rakefile extensions %w( annotations - documentation framework + initializers log middleware misc + restart routes statistics tmp diff --git a/railties/lib/rails/tasks/documentation.rake b/railties/lib/rails/tasks/documentation.rake deleted file mode 100644 index 8544890553..0000000000 --- a/railties/lib/rails/tasks/documentation.rake +++ /dev/null @@ -1,70 +0,0 @@ -begin - require 'rdoc/task' -rescue LoadError - # Rubinius installs RDoc as a gem, and for this interpreter "rdoc/task" is - # available only if the application bundle includes "rdoc" (normally as a - # dependency of the "sdoc" gem.) - # - # If RDoc is not available it is fine that we do not generate the tasks that - # depend on it. Just be robust to this gotcha and go on. -else - require 'rails/api/task' - - # Monkey-patch to remove redoc'ing and clobber descriptions to cut down on rake -T noise - class RDocTaskWithoutDescriptions < RDoc::Task - include ::Rake::DSL - - def define - task rdoc_task_name - - task rerdoc_task_name => [clobber_task_name, rdoc_task_name] - - task clobber_task_name do - rm_r rdoc_dir rescue nil - end - - task :clobber => [clobber_task_name] - - directory @rdoc_dir - task rdoc_task_name => [rdoc_target] - file rdoc_target => @rdoc_files + [Rake.application.rakefile] do - rm_r @rdoc_dir rescue nil - @before_running_rdoc.call if @before_running_rdoc - args = option_list + @rdoc_files - if @external - argstring = args.join(' ') - sh %{ruby -Ivendor vendor/rd #{argstring}} - else - require 'rdoc/rdoc' - RDoc::RDoc.new.document(args) - end - end - self - end - end - - namespace :doc do - RDocTaskWithoutDescriptions.new("app") { |rdoc| - rdoc.rdoc_dir = 'doc/app' - rdoc.template = ENV['template'] if ENV['template'] - rdoc.title = ENV['title'] || "Rails Application Documentation" - rdoc.options << '--line-numbers' - rdoc.options << '--charset' << 'utf-8' - rdoc.rdoc_files.include('README.rdoc') - rdoc.rdoc_files.include('app/**/*.rb') - rdoc.rdoc_files.include('lib/**/*.rb') - } - Rake::Task['doc:app'].comment = "Generate docs for the app -- also available doc:rails, doc:guides (options: TEMPLATE=/rdoc-template.rb, TITLE=\"Custom Title\")" - - # desc 'Generate documentation for the Rails framework.' - Rails::API::AppTask.new('rails') - end -end - -namespace :doc do - task :guides do - rails_gem_dir = Gem::Specification.find_by_name("rails").gem_dir - require File.expand_path(File.join(rails_gem_dir, "/guides/rails_guides")) - RailsGuides::Generator.new(Rails.root.join("doc/guides")).generate - end -end 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/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 new file mode 100644 index 0000000000..f36c86d81b --- /dev/null +++ b/railties/lib/rails/tasks/restart.rake @@ -0,0 +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 ba6168e208..735c36eb3a 100644 --- a/railties/lib/rails/tasks/statistics.rake +++ b/railties/lib/rails/tasks/statistics.rake @@ -14,10 +14,8 @@ STATS_DIRECTORIES = [ %w(Helper\ tests test/helpers), %w(Model\ tests test/models), %w(Mailer\ tests test/mailers), - %w(Job\ tests test/jobs), + %w(Job\ tests test/jobs), %w(Integration\ tests test/integration), - %w(Functional\ tests\ (old) test/functional), - %w(Unit\ tests \ (old) test/unit) ].collect do |name, dir| [ name, "#{File.dirname(Rake.application.rakefile_location)}/#{dir}" ] end.select { |name, dir| File.directory?(dir) } diff --git a/railties/lib/rails/tasks/tmp.rake b/railties/lib/rails/tasks/tmp.rake index b33ae9862b..9162ef234a 100644 --- a/railties/lib/rails/tasks/tmp.rake +++ b/railties/lib/rails/tasks/tmp.rake @@ -11,7 +11,7 @@ namespace :tmp do tmp_dirs.each { |d| directory d } - desc "Creates tmp directories for sessions, cache, sockets, and pids" + desc "Creates tmp directories for cache, sockets, and pids" task create: tmp_dirs namespace :cache do diff --git a/railties/lib/rails/templates/rails/mailers/email.html.erb b/railties/lib/rails/templates/rails/mailers/email.html.erb index 0b08a01896..bb6e49966d 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,7 +88,7 @@ <% 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 %> @@ -99,7 +103,14 @@ </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 %> </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 c837fadb40..828039dc43 100644 --- a/railties/lib/rails/test_help.rb +++ b/railties/lib/rails/test_help.rb @@ -2,18 +2,14 @@ # so fixtures aren't loaded into that environment abort("Abort testing: Your Rails environment is running in production mode!") if Rails.env.production? -require 'active_support/testing/autorun' +require "rails/test_unit/minitest_plugin" require 'active_support/test_case' require 'action_controller' require 'action_controller/test_case' require 'action_dispatch/testing/integration' require 'rails/generators/test_case' -# Config Rails backtrace in tests. -require 'rails/backtrace_cleaner' -if ENV["BACKTRACE"].nil? - Minitest.backtrace_filter = Rails.backtrace_cleaner -end +require 'active_support/testing/autorun' if defined?(ActiveRecord::Base) ActiveRecord::Migration.maintain_test_schema! @@ -21,6 +17,7 @@ if defined?(ActiveRecord::Base) class ActiveSupport::TestCase include ActiveRecord::TestFixtures self.fixture_path = "#{Rails.root}/test/fixtures/" + self.file_fixture_path = self.fixture_path + "files" end ActionDispatch::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path @@ -31,13 +28,15 @@ if defined?(ActiveRecord::Base) end class ActionController::TestCase - setup do + def before_setup @routes = Rails.application.routes + super end end class ActionDispatch::IntegrationTest - setup do + def before_setup @routes = Rails.application.routes + super end end diff --git a/railties/lib/rails/test_unit/minitest_plugin.rb b/railties/lib/rails/test_unit/minitest_plugin.rb new file mode 100644 index 0000000000..421f032d81 --- /dev/null +++ b/railties/lib/rails/test_unit/minitest_plugin.rb @@ -0,0 +1,51 @@ +require "active_support/core_ext/module/attribute_accessors" +require "rails/test_unit/reporter" +require "rails/test_unit/test_requirer" + +module Minitest + def self.plugin_rails_options(opts, options) + opts.separator "" + opts.separator "Usage: bin/rails test [options] [files or directories]" + opts.separator "You can run a single test by appending a line number to a filename:" + opts.separator "" + opts.separator " bin/rails test 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 " bin/rails test test/controllers test/integration/login_test.rb" + 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 + + options[:patterns] = opts.order! + end + + def self.plugin_rails_init(options) + self.run_with_rails_extension = true + + ENV["RAILS_ENV"] = options[:environment] || "test" + + Rails::TestRequirer.require_files options[:patterns] unless run_with_autorun + + 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 + + self.reporter << Rails::TestUnitReporter.new(options[:io], options) + end + + mattr_accessor(:run_with_autorun) { false } + mattr_accessor(:run_with_rails_extension) { false } +end + +Minitest.extensions << 'rails' diff --git a/railties/lib/rails/test_unit/reporter.rb b/railties/lib/rails/test_unit/reporter.rb new file mode 100644 index 0000000000..bfdc9754d4 --- /dev/null +++ b/railties/lib/rails/test_unit/reporter.rb @@ -0,0 +1,26 @@ +require "minitest" + +module Rails + class TestUnitReporter < Minitest::StatisticsReporter + def report + return if results.empty? + io.puts + io.puts "Failed tests:" + io.puts + io.puts aggregated_results + 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 #{relative_path_for(location)}:#{line}" + end.join "\n" + end + + def relative_path_for(file) + file.sub(/^#{Rails.root}\/?/, '') + 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..84c2256729 --- /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" + elsif File.file?(arg) + 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 d836c0d6d6..dda492f974 100644 --- a/railties/lib/rails/test_unit/testing.rake +++ b/railties/lib/rails/test_unit/testing.rake @@ -1,11 +1,13 @@ -require 'rake/testtask' -require 'rails/test_unit/sub_test_task' +gem 'minitest' +require 'minitest' +require 'rails/test_unit/minitest_plugin' task default: :test desc "Runs all tests in test folder" task :test do - Rails::TestTask.test_creator(Rake.application.top_level_tasks).invoke_rake_task + $: << "test" + Minitest.run(['test']) end namespace :test do @@ -14,30 +16,30 @@ namespace :test do # If used with Active Record, this task runs before the database schema is synchronized. end - Rails::TestTask.new(:run) do |t| - t.pattern = "test/**/*_test.rb" - end + task :run => %w[test] desc "Run tests quickly, but also reset db" task :db => %w[db:test:prepare test] - Rails::TestTask.new(single: "test:prepare") - ["models", "helpers", "controllers", "mailers", "integration", "jobs"].each do |name| - Rails::TestTask.new(name => "test:prepare") do |t| - t.pattern = "test/#{name}/**/*_test.rb" + task name => "test:prepare" do + $: << "test" + Minitest.run(["test/#{name}"]) end end - Rails::TestTask.new(generators: "test:prepare") do |t| - t.pattern = "test/lib/generators/**/*_test.rb" + task :generators => "test:prepare" do + $: << "test" + Minitest.run(["test/lib/generators"]) end - Rails::TestTask.new(units: "test:prepare") do |t| - t.pattern = 'test/{models,helpers,unit}/**/*_test.rb' + task :units => "test:prepare" do + $: << "test" + Minitest.run(["test/models", "test/helpers", "test/unit"]) end - Rails::TestTask.new(functionals: "test:prepare") do |t| - t.pattern = 'test/{controllers,mailers,functional}/**/*_test.rb' + task :functionals => "test:prepare" do + $: << "test" + Minitest.run(["test/controllers", "test/mailers", "test/functional"]) end end |