diff options
Diffstat (limited to 'railties/lib')
70 files changed, 301 insertions, 306 deletions
diff --git a/railties/lib/rails.rb b/railties/lib/rails.rb index 6bf2d8db20..bb98bbe5bf 100644 --- a/railties/lib/rails.rb +++ b/railties/lib/rails.rb @@ -21,41 +21,17 @@ end module Rails autoload :Info, 'rails/info' - autoload :InfoController, 'rails/info_controller' + autoload :InfoController, 'rails/info_controller' + autoload :WelcomeController, 'rails/welcome_controller' class << self - def application - @application ||= nil - end - - def application=(application) - @application = application - end + attr_accessor :application, :cache, :logger # The Configuration instance used to configure the Rails environment def configuration application.config end - # Rails.queue is the application's queue. You can push a job onto - # the queue by: - # - # Rails.queue.push job - # - # A job is an object that responds to +run+. Queue consumers will - # pop jobs off of the queue and invoke the queue's +run+ method. - # - # Note that depending on your queue implementation, jobs may not - # be executed in the same process as they were created in, and - # are never executed in the same thread as they were created in. - # - # If necessary, a queue implementation may need to serialize your - # job for distribution to another process. The documentation of - # your queue will specify the requirements for that serialization. - def queue - application.queue - end - def initialize! application.initialize! end @@ -64,14 +40,6 @@ module Rails application.initialized? end - def logger - @logger ||= nil - end - - def logger=(logger) - @logger = logger - end - def backtrace_cleaner @backtrace_cleaner ||= begin # Relies on Active Support, so we have to lazy load to postpone definition until AS has been loaded @@ -85,24 +53,13 @@ module Rails end def env - @_env ||= begin - ENV["RAILS_ENV"] ||= ENV["RACK_ENV"] || "development" - ActiveSupport::StringInquirer.new(ENV["RAILS_ENV"]) - end + @_env ||= ActiveSupport::StringInquirer.new(ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development") end def env=(environment) @_env = ActiveSupport::StringInquirer.new(environment) end - def cache - @cache ||= nil - end - - def cache=(cache) - @cache = cache - end - # Returns all rails groups for loading based on: # # * The Rails environment; diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb index ae3993fbd8..cff75872b2 100644 --- a/railties/lib/rails/application.rb +++ b/railties/lib/rails/application.rb @@ -1,5 +1,4 @@ require 'fileutils' -require 'active_support/queueing' # FIXME remove DummyKeyGenerator and this require in 4.1 require 'active_support/key_generator' require 'rails/engine' @@ -68,10 +67,9 @@ module Rails end end - attr_accessor :assets, :sandbox, :queue_consumer + attr_accessor :assets, :sandbox alias_method :sandbox?, :sandbox attr_reader :reloaders - attr_writer :queue delegate :default_url_options, :default_url_options=, to: :routes @@ -83,7 +81,6 @@ module Rails @env_config = nil @ordered_railties = nil @railties = nil - @queue = nil end # Returns true if the application is initialized. @@ -123,6 +120,7 @@ module Rails # Currently stores: # # * "action_dispatch.parameter_filter" => config.filter_parameters + # * "action_dispatch.redirect_filter" => config.filter_redirect # * "action_dispatch.secret_token" => config.secret_token, # * "action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions # * "action_dispatch.show_detailed_exceptions" => config.consider_all_requests_local @@ -134,14 +132,13 @@ module Rails # * "action_dispatch.encrypted_cookie_salt" => config.action_dispatch.encrypted_cookie_salt # * "action_dispatch.encrypted_signed_cookie_salt" => config.action_dispatch.encrypted_signed_cookie_salt # - # These parameters will be used by middlewares and engines to configure themselves - # def env_config @env_config ||= begin if config.secret_key_base.nil? - ActiveSupport::Deprecation.warn "You didn't set config.secret_key_base. " + - "This should be used instead of the old deprecated config.secret_token. " + - "Set config.secret_key_base instead of config.secret_token in config/initializers/secret_token.rb" + ActiveSupport::Deprecation.warn "You didn't set config.secret_key_base in config/initializers/secret_token.rb file. " + + "This should be used instead of the old deprecated config.secret_token in order to use the new EncryptedCookieStore. " + + "To convert safely to the encrypted store (without losing existing cookies and sessions), see http://guides.rubyonrails.org/upgrading_ruby_on_rails.html#action-pack" + if config.secret_token.blank? raise "You must set config.secret_key_base in your app's config" end @@ -149,6 +146,7 @@ module Rails super.merge({ "action_dispatch.parameter_filter" => config.filter_parameters, + "action_dispatch.redirect_filter" => config.filter_redirect, "action_dispatch.secret_token" => config.secret_token, "action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions, "action_dispatch.show_detailed_exceptions" => config.consider_all_requests_local, @@ -226,10 +224,6 @@ module Rails @config ||= Application::Configuration.new(find_root_with_flag("config.ru", Dir.pwd)) end - def queue #:nodoc: - @queue ||= config.queue || ActiveSupport::Queue.new - end - def to_app #:nodoc: self end diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb index f97e66985c..2c7ddd86e7 100644 --- a/railties/lib/rails/application/configuration.rb +++ b/railties/lib/rails/application/configuration.rb @@ -1,6 +1,5 @@ require 'active_support/core_ext/kernel/reporting' require 'active_support/file_update_checker' -require 'active_support/queueing' require 'rails/engine/configuration' module Rails @@ -13,7 +12,7 @@ module Rails :railties_order, :relative_url_root, :secret_key_base, :secret_token, :serve_static_assets, :ssl_options, :static_cache_control, :session_options, :time_zone, :reload_classes_only_on_change, - :queue, :queue_consumer, :beginning_of_week + :beginning_of_week, :filter_redirect attr_writer :log_level attr_reader :encoding @@ -23,6 +22,7 @@ module Rails self.encoding = "utf-8" @consider_all_requests_local = false @filter_parameters = [] + @filter_redirect = [] @helpers_paths = [] @serve_static_assets = true @static_cache_control = nil @@ -43,19 +43,17 @@ module Rails @exceptions_app = nil @autoflush_log = true @log_formatter = ActiveSupport::Logger::SimpleFormatter.new - @queue = ActiveSupport::SynchronousQueue.new - @queue_consumer = nil @eager_load = nil @secret_token = nil @secret_key_base = nil @assets = ActiveSupport::OrderedOptions.new - @assets.enabled = false + @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 = '' + @assets.version = '1.0' @assets.debug = false @assets.compile = true @assets.digest = false @@ -105,6 +103,10 @@ module Rails def database_configuration require 'erb' YAML.load ERB.new(IO.read(paths["config/database"].first)).result + rescue Psych::SyntaxError => e + raise "YAML syntax error occurred while parsing #{paths["config/database"].first}. " \ + "Please note that YAML must be consistently indented using spaces. Tabs are not allowed. " \ + "Error: #{e.message}" end def log_level diff --git a/railties/lib/rails/application/finisher.rb b/railties/lib/rails/application/finisher.rb index 2d87b8594a..872d78d9a4 100644 --- a/railties/lib/rails/application/finisher.rb +++ b/railties/lib/rails/application/finisher.rb @@ -25,6 +25,7 @@ module Rails get '/rails/info/properties' => "rails/info#properties" get '/rails/info/routes' => "rails/info#routes" get '/rails/info' => "rails/info#index" + get '/' => "rails/welcome#index" end end end @@ -95,15 +96,6 @@ module Rails ActiveSupport::Dependencies.unhook! end end - - initializer :activate_queue_consumer do |app| - if config.queue.class == ActiveSupport::Queue - app.queue_consumer = config.queue_consumer || config.queue.consumer - app.queue_consumer.logger ||= Rails.logger if app.queue_consumer.respond_to?(:logger=) - app.queue_consumer.start - at_exit { app.queue_consumer.shutdown } - end - end end end end diff --git a/railties/lib/rails/code_statistics.rb b/railties/lib/rails/code_statistics.rb index 1aed2796c1..039360fcf6 100644 --- a/railties/lib/rails/code_statistics.rb +++ b/railties/lib/rails/code_statistics.rb @@ -1,6 +1,12 @@ class CodeStatistics #:nodoc: - TEST_TYPES = %w(Units Functionals Unit\ tests Functional\ tests Integration\ tests) + TEST_TYPES = ['Controller tests', + 'Helper tests', + 'Model tests', + 'Mailer tests', + 'Integration tests', + 'Functional tests (old)', + 'Unit tests (old)'] def initialize(*pairs) @pairs = pairs diff --git a/railties/lib/rails/commands.rb b/railties/lib/rails/commands.rb index b0fae13192..5ccec8082c 100644 --- a/railties/lib/rails/commands.rb +++ b/railties/lib/rails/commands.rb @@ -60,7 +60,7 @@ when 'console' require 'rails/commands/console' options = Rails::Console.parse_arguments(ARGV) - # RAILS_ENV needs to be set before config/application is required + # RAILS_ENV needs to be set before config/application is required ENV['RAILS_ENV'] = options[:environment] if options[:environment] # shift ARGV so IRB doesn't freak @@ -77,13 +77,13 @@ when 'server' Dir.chdir(File.expand_path('../../', APP_PATH)) unless File.exists?(File.expand_path("config.ru")) require 'rails/commands/server' - Rails::Server.new.tap { |server| + Rails::Server.new.tap do |server| # We need to require application after the server sets environment, # otherwise the --environment option given to the server won't propagate. require APP_PATH Dir.chdir(Rails.application.root) server.start - } + end when 'dbconsole' require 'rails/commands/dbconsole' diff --git a/railties/lib/rails/commands/application.rb b/railties/lib/rails/commands/application.rb index ff0eda3413..2d9708e5b5 100644 --- a/railties/lib/rails/commands/application.rb +++ b/railties/lib/rails/commands/application.rb @@ -14,8 +14,7 @@ else extra_args_string = File.open(railsrc).read extra_args = extra_args_string.split(/\n+/).map {|l| l.split}.flatten puts "Using #{extra_args.join(" ")} from #{railsrc}" - ARGV << extra_args - ARGV.flatten! + ARGV.insert(1, *extra_args) end end diff --git a/railties/lib/rails/commands/console.rb b/railties/lib/rails/commands/console.rb index 92cee6b638..86ab1aabbf 100644 --- a/railties/lib/rails/commands/console.rb +++ b/railties/lib/rails/commands/console.rb @@ -24,11 +24,21 @@ module Rails if arguments.first && arguments.first[0] != '-' env = arguments.first - options[:environment] = %w(production development test).detect {|e| e =~ /^#{env}/} || env + if available_environments.include? env + options[:environment] = env + else + options[:environment] = %w(production development test).detect {|e| e =~ /^#{env}/} || env + end end options end + + private + + def available_environments + Dir['config/environments/*.rb'].map { |fname| File.basename(fname, '.*') } + end end attr_reader :options, :app, :console @@ -45,7 +55,7 @@ module Rails end def environment - options[:environment] ||= ENV['RAILS_ENV'] || 'development' + options[:environment] ||= ENV['RAILS_ENV'] || ENV['RACK_ENV'] || 'development' end def environment? @@ -79,13 +89,11 @@ module Rails end def require_debugger - begin - require 'debugger' - puts "=> Debugger enabled" - rescue Exception - puts "You're missing the 'debugger' gem. Add it to your Gemfile, bundle, and try again." - exit - end + require 'debugger' + puts "=> Debugger enabled" + rescue LoadError + puts "You're missing the 'debugger' gem. Add it to your Gemfile, bundle, and try again." + exit end end end diff --git a/railties/lib/rails/commands/dbconsole.rb b/railties/lib/rails/commands/dbconsole.rb index 90359d1c08..5914c9e4ae 100644 --- a/railties/lib/rails/commands/dbconsole.rb +++ b/railties/lib/rails/commands/dbconsole.rb @@ -5,8 +5,8 @@ require 'rbconfig' module Rails class DBConsole - attr_reader :config, :arguments - + attr_reader :arguments + def self.start new.start end @@ -59,7 +59,7 @@ module Rails args << "-#{options['mode']}" if options['mode'] args << "-header" if options['header'] - args << File.expand_path(config['database'], Rails.root) + args << File.expand_path(config['database'], Rails.respond_to?(:root) ? Rails.root : nil) find_cmd_and_exec('sqlite3', *args) @@ -82,17 +82,13 @@ module Rails def config @config ||= begin cfg = begin - cfg = YAML.load(ERB.new(IO.read("config/database.yml")).result) + YAML.load(ERB.new(IO.read("config/database.yml")).result) rescue SyntaxError, StandardError require APP_PATH Rails.application.config.database_configuration end - unless cfg[environment] - abort "No database is configured for the environment '#{environment}'" - end - - cfg[environment] + cfg[environment] || abort("No database is configured for the environment '#{environment}'") end end @@ -108,7 +104,7 @@ module Rails 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| @@ -123,7 +119,7 @@ module Rails opt.on("--header") do |h| options['header'] = h end - + opt.on("-h", "--help", "Show this help message.") do puts opt exit @@ -140,12 +136,20 @@ module Rails if arguments.first && arguments.first[0] != '-' env = arguments.first - options[:environment] = %w(production development test).detect {|e| e =~ /^#{env}/} || env + 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 + def find_cmd_and_exec(commands, *args) commands = Array(commands) diff --git a/railties/lib/rails/commands/profiler.rb b/railties/lib/rails/commands/profiler.rb index 3f6966b4f0..315bcccf61 100644 --- a/railties/lib/rails/commands/profiler.rb +++ b/railties/lib/rails/commands/profiler.rb @@ -8,7 +8,7 @@ def options defaults = ActiveSupport::Testing::Performance::DEFAULTS OptionParser.new do |opt| - opt.banner = "Usage: rails benchmarker 'Ruby.code' 'Ruby.more_code' ... [OPTS]" + opt.banner = "Usage: rails profiler 'Ruby.code' 'Ruby.more_code' ... [OPTS]" opt.on('-r', '--runs N', Numeric, 'Number of runs.', "Default: #{defaults[:runs]}") { |r| options[:runs] = r } opt.on('-o', '--output PATH', String, 'Directory to use when writing the results.', "Default: #{defaults[:output]}") { |o| options[:output] = o } opt.on('-m', '--metrics a,b,c', Array, 'Metrics to use.', "Default: #{defaults[:metrics].join(",")}") { |m| options[:metrics] = m.map(&:to_sym) } diff --git a/railties/lib/rails/commands/runner.rb b/railties/lib/rails/commands/runner.rb index 0cc672e01c..6adbdc6e0b 100644 --- a/railties/lib/rails/commands/runner.rb +++ b/railties/lib/rails/commands/runner.rb @@ -1,7 +1,7 @@ require 'optparse' require 'rbconfig' -options = { environment: (ENV['RAILS_ENV'] || "development").dup } +options = { environment: (ENV['RAILS_ENV'] || ENV['RACK_ENV'] || "development").dup } code_or_file = nil if ARGV.first.nil? @@ -41,7 +41,7 @@ ENV["RAILS_ENV"] = options[:environment] require APP_PATH Rails.application.require_environment! - Rails.application.load_runner +Rails.application.load_runner if code_or_file.nil? $stderr.puts "Run '#{$0} -h' for help." diff --git a/railties/lib/rails/commands/server.rb b/railties/lib/rails/commands/server.rb index 0b897d736d..cdb29a8156 100644 --- a/railties/lib/rails/commands/server.rb +++ b/railties/lib/rails/commands/server.rb @@ -108,7 +108,7 @@ module Rails super.merge({ Port: 3000, DoNotReverseLookup: true, - environment: (ENV['RAILS_ENV'] || "development").dup, + environment: (ENV['RAILS_ENV'] || ENV['RACK_ENV'] || "development").dup, daemonize: false, debugger: false, pid: File.expand_path("tmp/pids/server.pid"), diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb index 2c2bb1c714..3ba62039de 100644 --- a/railties/lib/rails/engine.rb +++ b/railties/lib/rails/engine.rb @@ -106,7 +106,7 @@ module Rails # # The <tt>Application</tt> class adds a couple more paths to this set. And as in your # <tt>Application</tt>, all folders under +app+ are automatically added to the load path. - # If you have an <tt>app/observers</tt> folder for example, it will be added by default. + # If you have an <tt>app/services/tt> folder for example, it will be added by default. # # == Endpoint # @@ -407,8 +407,10 @@ module Rails end end + self.isolated = false + delegate :middleware, :root, :paths, to: :config - delegate :engine_name, :isolated?, to: "self.class" + delegate :engine_name, :isolated?, to: :class def initialize @_all_autoload_paths = nil diff --git a/railties/lib/rails/engine/configuration.rb b/railties/lib/rails/engine/configuration.rb index 22e885a3a6..10d1821709 100644 --- a/railties/lib/rails/engine/configuration.rb +++ b/railties/lib/rails/engine/configuration.rb @@ -38,6 +38,7 @@ module Rails def paths @paths ||= begin paths = Rails::Paths::Root.new(@root) + paths.add "app", eager_load: true, glob: "*" paths.add "app/assets", glob: "*" paths.add "app/controllers", eager_load: true @@ -45,19 +46,27 @@ module Rails paths.add "app/models", eager_load: true paths.add "app/mailers", eager_load: true paths.add "app/views" + + paths.add "app/controllers/concerns", eager_load: true + paths.add "app/models/concerns", eager_load: true + paths.add "lib", load_path: true paths.add "lib/assets", glob: "*" paths.add "lib/tasks", glob: "**/*.rake" + paths.add "config" paths.add "config/environments", glob: "#{Rails.env}.rb" paths.add "config/initializers", glob: "**/*.rb" paths.add "config/locales", glob: "*.{rb,yml}" paths.add "config/routes.rb" + paths.add "db" paths.add "db/migrate" paths.add "db/seeds.rb" + paths.add "vendor", load_path: true paths.add "vendor/assets", glob: "*" + paths end end diff --git a/railties/lib/rails/generators.rb b/railties/lib/rails/generators.rb index 367f9288b8..d9a91b74d1 100644 --- a/railties/lib/rails/generators.rb +++ b/railties/lib/rails/generators.rb @@ -172,13 +172,11 @@ module Rails "resource_route", "#{orm}:migration", "#{orm}:model", - "#{orm}:observer", "#{test}:controller", "#{test}:helper", "#{test}:integration", "#{test}:mailer", "#{test}:model", - "#{test}:observer", "#{test}:scaffold", "#{test}:view", "#{test}:performance", diff --git a/railties/lib/rails/generators/actions.rb b/railties/lib/rails/generators/actions.rb index 5c4e81431c..b96ee9295e 100644 --- a/railties/lib/rails/generators/actions.rb +++ b/railties/lib/rails/generators/actions.rb @@ -78,7 +78,7 @@ module Rails # end # # environment(nil, env: "development") do - # "config.active_record.observers = :cacher" + # "config.autoload_paths += %W(#{config.root}/extras)" # end def environment(data=nil, options={}, &block) sentinel = /class [a-z_:]+ < Rails::Application/i diff --git a/railties/lib/rails/generators/active_model.rb b/railties/lib/rails/generators/active_model.rb index 0e51b9c568..6183944bb0 100644 --- a/railties/lib/rails/generators/active_model.rb +++ b/railties/lib/rails/generators/active_model.rb @@ -59,8 +59,8 @@ module Rails end # PATCH/PUT update - def update_attributes(params=nil) - "#{name}.update_attributes(#{params})" + def update(params=nil) + "#{name}.update(#{params})" end # POST create diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb index de3127f43e..ca3652c703 100644 --- a/railties/lib/rails/generators/app_base.rb +++ b/railties/lib/rails/generators/app_base.rb @@ -28,7 +28,7 @@ module Rails class_option :skip_gemfile, type: :boolean, default: false, desc: "Don't create a Gemfile" - class_option :skip_bundle, type: :boolean, default: false, + class_option :skip_bundle, type: :boolean, aliases: '-B', default: false, desc: "Don't run bundle install" class_option :skip_git, type: :boolean, aliases: '-G', default: false, @@ -52,9 +52,6 @@ module Rails class_option :skip_javascript, type: :boolean, aliases: '-J', default: false, desc: 'Skip JavaScript files' - class_option :skip_index_html, type: :boolean, aliases: '-I', default: false, - desc: 'Skip public/index.html and app/assets/images/rails.png files' - class_option :dev, type: :boolean, default: false, desc: "Setup the #{name} with Gemfile pointing to your Rails checkout" @@ -141,14 +138,12 @@ module Rails if options.dev? <<-GEMFILE.strip_heredoc gem 'rails', path: '#{Rails::Generators::RAILS_DEV_PATH}' - gem 'journey', github: 'rails/journey' gem 'arel', github: 'rails/arel' gem 'activerecord-deprecated_finders', github: 'rails/activerecord-deprecated_finders' GEMFILE elsif options.edge? <<-GEMFILE.strip_heredoc gem 'rails', github: 'rails/rails' - gem 'journey', github: 'rails/journey' gem 'arel', github: 'rails/arel' gem 'activerecord-deprecated_finders', github: 'rails/activerecord-deprecated_finders' GEMFILE 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 f5182bcc50..90d8db1df5 100644 --- a/railties/lib/rails/generators/erb/scaffold/templates/index.html.erb +++ b/railties/lib/rails/generators/erb/scaffold/templates/index.html.erb @@ -3,9 +3,9 @@ <table> <thead> <tr> - <% attributes.each do |attribute| -%> +<% attributes.each do |attribute| -%> <th><%= attribute.human_name %></th> - <% end -%> +<% end -%> <th></th> <th></th> <th></th> @@ -13,13 +13,15 @@ </thead> <tbody> - <%%= content_tag_for(:tr, @<%= plural_table_name %>) do |<%= singular_table_name %>| %> - <% attributes.each do |attribute| -%> + <%% @<%= plural_table_name %>.each do |<%= singular_table_name %>| %> + <tr> +<% attributes.each do |attribute| -%> <td><%%= <%= singular_table_name %>.<%= attribute.name %> %></td> - <% end -%> +<% end -%> <td><%%= link_to 'Show', <%= singular_table_name %> %></td> <td><%%= link_to 'Edit', edit_<%= singular_table_name %>_path(<%= singular_table_name %>) %></td> <td><%%= link_to 'Destroy', <%= singular_table_name %>, method: :delete, data: { confirm: 'Are you sure?' } %></td> + </tr> <%% end %> </tbody> </table> diff --git a/railties/lib/rails/generators/generated_attribute.rb b/railties/lib/rails/generators/generated_attribute.rb index d8a4f15b4b..4ae8756ed0 100644 --- a/railties/lib/rails/generators/generated_attribute.rb +++ b/railties/lib/rails/generators/generated_attribute.rb @@ -99,13 +99,17 @@ module Rails end def index_name - @index_name ||= if reference? - polymorphic? ? %w(id type).map { |t| "#{name}_#{t}" } : "#{name}_id" + @index_name ||= if polymorphic? + %w(id type).map { |t| "#{name}_#{t}" } else - name + column_name end end + def column_name + @column_name ||= reference? ? "#{name}_id" : name + end + def foreign_key? !!(name =~ /_id$/) end diff --git a/railties/lib/rails/generators/named_base.rb b/railties/lib/rails/generators/named_base.rb index 84f8f76838..9965db98de 100644 --- a/railties/lib/rails/generators/named_base.rb +++ b/railties/lib/rails/generators/named_base.rb @@ -160,6 +160,13 @@ module Rails end end + def attributes_names + @attributes_names ||= attributes.each_with_object([]) do |a, names| + names << a.column_name + names << "#{a.name}_type" if a.polymorphic? + end + end + def pluralize_table_names? !defined?(ActiveRecord::Base) || ActiveRecord::Base.pluralize_table_names end @@ -169,10 +176,10 @@ module Rails # # ==== Examples # - # check_class_collision suffix: "Observer" + # check_class_collision suffix: "Decorator" # # If the generator is invoked with class name Admin, it will check for - # the presence of "AdminObserver". + # the presence of "AdminDecorator". # def self.check_class_collision(options={}) define_method :check_class_collision do diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb index 18637451ac..372790df59 100644 --- a/railties/lib/rails/generators/rails/app/app_generator.rb +++ b/railties/lib/rails/generators/rails/app/app_generator.rb @@ -55,8 +55,12 @@ module Rails def app directory 'app' + keep_file 'app/mailers' keep_file 'app/models' + + keep_file 'app/controllers/concerns' + keep_file 'app/models/concerns' end def config @@ -97,11 +101,6 @@ module Rails def public_directory directory "public", "public", recursive: false - if options[:skip_index_html] - remove_file "public/index.html" - remove_file 'app/assets/images/rails.png' - keep_file 'app/assets/images' - end end def script diff --git a/railties/lib/rails/generators/rails/app/templates/Gemfile b/railties/lib/rails/generators/rails/app/templates/Gemfile index 5b7a653a09..c4846b2c11 100644 --- a/railties/lib/rails/generators/rails/app/templates/Gemfile +++ b/railties/lib/rails/generators/rails/app/templates/Gemfile @@ -21,5 +21,7 @@ source 'https://rubygems.org' # Deploy with Capistrano # gem 'capistrano', group: :development +<% unless defined?(JRUBY_VERSION) -%> # To use debugger # gem 'debugger' +<% end -%> diff --git a/railties/lib/rails/generators/rails/app/templates/README b/railties/lib/rails/generators/rails/app/templates/README index b5d7b6436b..2bd7c27f2a 100644 --- a/railties/lib/rails/generators/rails/app/templates/README +++ b/railties/lib/rails/generators/rails/app/templates/README @@ -57,7 +57,7 @@ shown in the browser on requests from 127.0.0.1. You can also log your own messages directly into the log file from your code using the Ruby logger class from inside your controllers. Example: - class WeblogController < ActionController::Base + class WeblogsController < ActionController::Base def destroy @weblog = Weblog.find(params[:id]) @weblog.destroy @@ -89,7 +89,7 @@ execution at any point in the code, investigate and change the model, and then, resume execution! You need to install the 'debugger' gem to run the server in debugging mode. Add gem 'debugger' to your Gemfile and run <tt>bundle</tt> to install it. Example: - class WeblogController < ActionController::Base + class PostsController < ActionController::Base def index @posts = Post.all debugger @@ -100,17 +100,15 @@ So the controller will accept the action, run the first line, then present you with a IRB prompt in the server window. Here you can do things like: >> @posts.inspect - => "[#<Post:0x14a6be8 - @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>, - #<Post:0x14a6620 - @attributes={"title"=>"Rails", "body"=>"Only ten..", "id"=>"2"}>]" + => "#<ActiveRecord::Relation [#<Post id: 1, title: nil, body: nil>, + #<Post id: 2, title: \"Rails\", body: "Only ten..">]>" >> @posts.first.title = "hello from a debugger" => "hello from a debugger" ...and even better, you can examine how your runtime objects actually work: >> f = @posts.first - => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}> + => #<Post id: 1, title: nil, body: nil> >> f. Display all 152 possibilities? (y or n) @@ -157,13 +155,15 @@ The default directory structure of a generated Ruby on Rails application: |-- app | |-- assets - | |-- images - | |-- javascripts - | `-- stylesheets + | | |-- images + | | |-- javascripts + | | `-- stylesheets | |-- controllers + | | `-- concerns | |-- helpers | |-- mailers | |-- models + | | `-- concerns | `-- views | `-- layouts |-- config @@ -173,23 +173,25 @@ The default directory structure of a generated Ruby on Rails application: |-- db |-- doc |-- lib + | |-- assets | `-- tasks |-- log |-- public |-- script |-- test + | |-- controllers | |-- fixtures - | |-- functional + | |-- helpers | |-- integration - | |-- performance - | `-- unit + | |-- mailers + | |-- models + | `-- performance |-- tmp - | |-- cache - | |-- pids - | |-- sessions - | `-- sockets + | `-- cache + | `-- assets `-- vendor - |-- assets + `-- assets + |-- javascripts `-- stylesheets app @@ -216,7 +218,7 @@ app/views/layouts Holds the template files for layouts to be used with views. This models the common header/footer method of wrapping views. In your views, define a layout using the <tt>layout :default</tt> and create a file named default.html.erb. - Inside default.html.erb, call <% yield %> to render the view using this + Inside default.html.erb, call <%= yield %> to render the view using this layout. app/helpers @@ -255,5 +257,5 @@ test directory. vendor - External libraries that the application depends on. If the app has frozen rails, - those gems also go here, under vendor/rails/. This directory is in the load path. + External libraries that the application depends on. This directory is in the + load path. diff --git a/railties/lib/rails/generators/rails/app/templates/app/mailers/.empty_directory b/railties/lib/rails/generators/rails/app/templates/app/mailers/.empty_directory deleted file mode 100644 index e69de29bb2..0000000000 --- a/railties/lib/rails/generators/rails/app/templates/app/mailers/.empty_directory +++ /dev/null diff --git a/railties/lib/rails/generators/rails/app/templates/app/models/.empty_directory b/railties/lib/rails/generators/rails/app/templates/app/models/.empty_directory deleted file mode 100644 index e69de29bb2..0000000000 --- a/railties/lib/rails/generators/rails/app/templates/app/models/.empty_directory +++ /dev/null diff --git a/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt b/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt index e0539aa8bb..d87c7b7268 100644 --- a/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt +++ b/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt @@ -2,8 +2,8 @@ <html> <head> <title><%= camelized %></title> - <%%= stylesheet_link_tag "application", media: "all" %> - <%%= javascript_include_tag "application" %> + <%%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %> + <%%= javascript_include_tag "application", "data-turbolinks-track" => true %> <%%= csrf_meta_tags %> </head> <body> 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 5f15c973c6..f5d7d698a3 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/application.rb +++ b/railties/lib/rails/generators/rails/app/templates/config/application.rb @@ -22,21 +22,10 @@ module <%= app_const_base %> # Custom directories with classes and modules you want to be autoloadable. # config.autoload_paths += %W(#{config.root}/extras) +<% if options.skip_sprockets? -%> - # Configure sensitive parameters which will be filtered from the log file. - config.filter_parameters += [:password] - - # Use SQL instead of Active Record's schema dumper when creating the database. - # This is necessary if your schema can't be completely dumped by the schema dumper, - # like if you have constraints or database-specific column types. - # config.active_record.schema_format = :sql - -<% unless options.skip_sprockets? -%> - # Enable the asset pipeline. - config.assets.enabled = true - - # Version of your assets, change this if you want to expire all your assets. - config.assets.version = '1.0' + # Disable the asset pipeline. + config.assets.enabled = false <% end -%> end end diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml index 22c9194fad..eb569b7dab 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml @@ -26,7 +26,7 @@ development: # domain socket that doesn't need configuration. Windows does not have # domain sockets, so uncomment these lines. #host: localhost - + # The TCP port the server listens on. Defaults to 5432. # If your server runs on a different port number, change accordingly. #port: 5432 diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/sqlserver.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/sqlserver.yml index b52b733c56..53620dc8e2 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/databases/sqlserver.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/databases/sqlserver.yml @@ -1,5 +1,5 @@ # SQL Server (2005 or higher recommended) -# +# # Install the adapters and driver # gem install tiny_tds # gem install activerecord-sqlserver-adapter @@ -8,8 +8,8 @@ # gem 'tiny_tds' # gem 'activerecord-sqlserver-adapter' # -# You should make sure freetds is configured correctly first. -# freetds.conf contains host/port/protocol_versions settings. +# You should make sure freetds is configured correctly first. +# freetds.conf contains host/port/protocol_versions settings. # http://freetds.schemamania.org/userguide/freetdsconf.htm # # A typical Microsoft server 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 593d2acfc7..0ab91d9864 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 @@ -32,6 +32,9 @@ # Generate digests for assets URLs. config.assets.digest = true + + # Version of your assets, change this if you want to expire all your assets. + config.assets.version = '1.0' <%- end -%> # Specifies the header that your server uses for sending files. @@ -84,8 +87,4 @@ # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new - - # Default the production mode queue to an synchronous queue. You will probably - # want to replace this with an out-of-process queueing solution. - # config.queue = ActiveSupport::SynchronousQueue.new end diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt index a5ef0cd9cd..3c9c787948 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt +++ b/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt @@ -33,7 +33,4 @@ # Print deprecation notices to the stderr. config.active_support.deprecation = :stderr - - # Use the synchronous queue to run jobs immediately. - config.queue = ActiveSupport::SynchronousQueue.new end diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/filter_parameter_logging.rb b/railties/lib/rails/generators/rails/app/templates/config/initializers/filter_parameter_logging.rb new file mode 100644 index 0000000000..4a994e1e7b --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/filter_parameter_logging.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Configure sensitive parameters which will be filtered from the log file. +Rails.application.config.filter_parameters += [:password] diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/locale.rb b/railties/lib/rails/generators/rails/app/templates/config/initializers/locale.rb index a8285f88ca..d89dac7c6a 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/initializers/locale.rb +++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/locale.rb @@ -1,3 +1,5 @@ +# Be sure to restart your server when you modify this file. + # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # Rails.application.config.time_zone = 'Central Time (US & Canada)' diff --git a/railties/lib/rails/generators/rails/app/templates/config/routes.rb b/railties/lib/rails/generators/rails/app/templates/config/routes.rb index 631543c705..22a6aeb5fe 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/routes.rb +++ b/railties/lib/rails/generators/rails/app/templates/config/routes.rb @@ -2,7 +2,7 @@ # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". - # You can have the root of your site routed with "root" just remember to delete public/index.html. + # You can have the root of your site routed with "root" # root to: 'welcome#index' # Example of regular route: diff --git a/railties/lib/rails/generators/rails/app/templates/gitignore b/railties/lib/rails/generators/rails/app/templates/gitignore index 8910bf5a06..25a742dff0 100644 --- a/railties/lib/rails/generators/rails/app/templates/gitignore +++ b/railties/lib/rails/generators/rails/app/templates/gitignore @@ -2,9 +2,9 @@ # # If you find yourself ignoring temporary files generated by your text editor # or operating system, you probably want to add a global ignore instead: -# git config --global core.excludesfile ~/.gitignore_global +# git config --global core.excludesfile '~/.gitignore_global' -# Ignore bundler config +# Ignore bundler config. /.bundle # Ignore the default SQLite database. diff --git a/railties/lib/rails/generators/rails/app/templates/public/stylesheets/.empty_directory b/railties/lib/rails/generators/rails/app/templates/public/stylesheets/.empty_directory deleted file mode 100644 index e69de29bb2..0000000000 --- a/railties/lib/rails/generators/rails/app/templates/public/stylesheets/.empty_directory +++ /dev/null diff --git a/railties/lib/rails/generators/rails/app/templates/test/fixtures/.empty_directory b/railties/lib/rails/generators/rails/app/templates/test/fixtures/.empty_directory deleted file mode 100644 index e69de29bb2..0000000000 --- a/railties/lib/rails/generators/rails/app/templates/test/fixtures/.empty_directory +++ /dev/null diff --git a/railties/lib/rails/generators/rails/app/templates/test/functional/.empty_directory b/railties/lib/rails/generators/rails/app/templates/test/functional/.empty_directory deleted file mode 100644 index e69de29bb2..0000000000 --- a/railties/lib/rails/generators/rails/app/templates/test/functional/.empty_directory +++ /dev/null diff --git a/railties/lib/rails/generators/rails/app/templates/test/integration/.empty_directory b/railties/lib/rails/generators/rails/app/templates/test/integration/.empty_directory deleted file mode 100644 index e69de29bb2..0000000000 --- a/railties/lib/rails/generators/rails/app/templates/test/integration/.empty_directory +++ /dev/null diff --git a/railties/lib/rails/generators/rails/app/templates/test/unit/.empty_directory b/railties/lib/rails/generators/rails/app/templates/test/unit/.empty_directory deleted file mode 100644 index e69de29bb2..0000000000 --- a/railties/lib/rails/generators/rails/app/templates/test/unit/.empty_directory +++ /dev/null diff --git a/railties/lib/rails/generators/rails/controller/USAGE b/railties/lib/rails/generators/rails/controller/USAGE index 9def4af65c..64239ad599 100644 --- a/railties/lib/rails/generators/rails/controller/USAGE +++ b/railties/lib/rails/generators/rails/controller/USAGE @@ -6,7 +6,7 @@ Description: path like 'parent_module/controller_name'. This generates a controller class in app/controllers and invokes helper, - template engine and test framework generators. + template engine, assets, and test framework generators. Example: `rails generate controller CreditCards open debit credit close` diff --git a/railties/lib/rails/generators/rails/migration/USAGE b/railties/lib/rails/generators/rails/migration/USAGE index af74963b01..baf3d9894f 100644 --- a/railties/lib/rails/generators/rails/migration/USAGE +++ b/railties/lib/rails/generators/rails/migration/USAGE @@ -15,15 +15,21 @@ Example: `rails generate migration AddTitleBodyToPost title:string body:text published:boolean` - This will create the AddTitleBodyToPost in db/migrate/20080514090912_add_title_body_to_post.rb with - this in the Up migration: + This will create the AddTitleBodyToPost in db/migrate/20080514090912_add_title_body_to_post.rb with this in the Change migration: add_column :posts, :title, :string add_column :posts, :body, :text add_column :posts, :published, :boolean - And this in the Down migration: +Migration names containing JoinTable will generate join tables for use with +has_and_belongs_to_many associations. - remove_column :posts, :published - remove_column :posts, :body - remove_column :posts, :title +Example: + `rails g migration CreateMediaJoinTable artists musics:uniq` + + will create the migration + + create_join_table :artists, :musics do |t| + # t.index [:artist_id, :music_id] + t.index [:music_id, :artist_id], unique: true + end diff --git a/railties/lib/rails/generators/rails/model/USAGE b/railties/lib/rails/generators/rails/model/USAGE index e29e19490e..6574200fbf 100644 --- a/railties/lib/rails/generators/rails/model/USAGE +++ b/railties/lib/rails/generators/rails/model/USAGE @@ -21,12 +21,12 @@ Description: Available field types: - Just after the field name you can specify a type like text or boolean. + Just after the field name you can specify a type like text or boolean. It will generate the column with the associated SQL type. For instance: `rails generate model post title:string body:text` - will generate a title column with a varchar type and a body column with a text + will generate a title column with a varchar type and a body column with a text type. You can use the following types: integer @@ -57,16 +57,16 @@ Available field types: limit Set the maximum size of the field giving a number between curly braces default Set a default value for the field - precision Defines the precision for the decimal fields + precision Defines the precision for the decimal fields scale Defines the scale for the decimal fields - uniq Defines the field values as unique + uniq Defines the field values as unique index Will add an index on the field Examples: `rails generate model user pseudo:string{30}` `rails generate model user pseudo:string:uniq` - + Examples: `rails generate model account` @@ -76,7 +76,7 @@ Examples: Model: app/models/account.rb Test: test/models/account_test.rb Fixtures: test/fixtures/accounts.yml - Migration: db/migrate/XXX_add_accounts.rb + Migration: db/migrate/XXX_create_accounts.rb `rails generate model post title:string body:text published:boolean` @@ -90,5 +90,5 @@ Examples: Model: app/models/admin/account.rb Test: test/models/admin/account_test.rb Fixtures: test/fixtures/admin/accounts.yml - Migration: db/migrate/XXX_add_admin_accounts.rb + Migration: db/migrate/XXX_create_admin_accounts.rb diff --git a/railties/lib/rails/generators/rails/observer/USAGE b/railties/lib/rails/generators/rails/observer/USAGE deleted file mode 100644 index 177ff49e4a..0000000000 --- a/railties/lib/rails/generators/rails/observer/USAGE +++ /dev/null @@ -1,12 +0,0 @@ -Description: - Stubs out a new observer. Pass the observer name, either CamelCased or - under_scored, as an argument. - - This generator only invokes your ORM and test framework generators. - -Example: - `rails generate observer Account` - - For ActiveRecord and TestUnit it creates: - Observer: app/models/account_observer.rb - TestUnit: test/models/account_observer_test.rb diff --git a/railties/lib/rails/generators/rails/observer/observer_generator.rb b/railties/lib/rails/generators/rails/observer/observer_generator.rb deleted file mode 100644 index 7a4d701ac6..0000000000 --- a/railties/lib/rails/generators/rails/observer/observer_generator.rb +++ /dev/null @@ -1,7 +0,0 @@ -module Rails - module Generators - class ObserverGenerator < NamedBase # :nodoc: - hook_for :orm, required: true - end - end -end diff --git a/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb b/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb index 6f25cd266e..cd756a729d 100644 --- a/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb +++ b/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb @@ -173,7 +173,7 @@ task default: :test "skip adding entry to Gemfile" def initialize(*args) - raise Error, "Options should be given after the plugin name. For details run: rails plugin --help" if args[0].blank? + raise Error, "Options should be given after the plugin name. For details run: rails plugin new --help" if args[0].blank? @dummy_path = nil super diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile b/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile index 6701630a77..a8b5bfaf3f 100644 --- a/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile +++ b/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile @@ -1,4 +1,4 @@ -source "http://rubygems.org" +source "https://rubygems.org" <% if options[:skip_gemspec] -%> <%= '# ' if options.dev? || options.edge? -%>gem "rails", "~> <%= Rails::VERSION::STRING %>" diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/rails/application.rb b/railties/lib/rails/generators/rails/plugin_new/templates/rails/application.rb index 8a8ba04a70..310c975262 100644 --- a/railties/lib/rails/generators/rails/plugin_new/templates/rails/application.rb +++ b/railties/lib/rails/generators/rails/plugin_new/templates/rails/application.rb @@ -11,7 +11,7 @@ require "action_mailer/railtie" <%= comment_if :skip_test_unit %>require "rails/test_unit/railtie" <% end -%> -Bundler.require +Bundler.require(*Rails.groups) require "<%= name %>" <%= application_definition %> diff --git a/railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb b/railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb index b4f466fbd8..dd636ed3cf 100644 --- a/railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb +++ b/railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb @@ -2,13 +2,22 @@ require 'rails/generators/rails/resource/resource_generator' module Rails module Generators - class ScaffoldGenerator < ResourceGenerator # :nodoc: + class ScaffoldGenerator < ResourceGenerator # :nodoc: remove_hook_for :resource_controller remove_class_option :actions class_option :stylesheets, type: :boolean, desc: "Generate Stylesheets" class_option :stylesheet_engine, desc: "Engine for Stylesheets" + class_option :html, type: :boolean, default: true, + desc: "Generate a scaffold with HTML output" + + def handle_skip + if !options[:html] || !options[:stylesheets] + @options = @options.merge(stylesheet_engine: false) + end + end + hook_for :scaffold_controller, required: true hook_for :assets do |assets| @@ -16,7 +25,9 @@ module Rails end hook_for :stylesheet_engine do |stylesheet_engine| - invoke stylesheet_engine, [controller_name] if options[:stylesheets] && behavior == :invoke + if behavior == :invoke + invoke stylesheet_engine, [controller_name] + end end end end 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 4f36b612ae..32fa54a362 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,8 +10,17 @@ module Rails class_option :orm, banner: "NAME", type: :string, required: true, desc: "ORM to generate the controller for" + class_option :html, type: :boolean, default: true, + desc: "Generate a scaffold with HTML output" + argument :attributes, type: :array, default: [], banner: "field:type field:type" + def handle_skip + unless options[:html] + @options = @options.merge(template_engine: false, helper: false) + end + end + def create_controller_files template "controller.rb", File.join('app/controllers', class_path, "#{controller_file_name}_controller.rb") end diff --git a/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb b/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb index d6bce40b0c..e11d357314 100644 --- a/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb +++ b/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb @@ -4,13 +4,17 @@ 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, :edit, :update, :destroy] + # GET <%= route_url %> # GET <%= route_url %>.json def index @<%= plural_table_name %> = <%= orm_class.all(class_name) %> respond_to do |format| + <%- if options[:html] -%> format.html # index.html.erb + <%- end -%> format.json { render json: <%= "@#{plural_table_name}" %> } end end @@ -18,14 +22,15 @@ class <%= controller_class_name %>Controller < ApplicationController # GET <%= route_url %>/1 # GET <%= route_url %>/1.json def show - @<%= singular_table_name %> = <%= orm_class.find(class_name, "params[:id]") %> - respond_to do |format| + <%- if options[:html] -%> format.html # show.html.erb + <%- end -%> format.json { render json: <%= "@#{singular_table_name}" %> } end end + <%- if options[:html] -%> # GET <%= route_url %>/new # GET <%= route_url %>/new.json def new @@ -39,8 +44,8 @@ class <%= controller_class_name %>Controller < ApplicationController # GET <%= route_url %>/1/edit def edit - @<%= singular_table_name %> = <%= orm_class.find(class_name, "params[:id]") %> end + <%- end -%> # POST <%= route_url %> # POST <%= route_url %>.json @@ -49,10 +54,14 @@ class <%= controller_class_name %>Controller < ApplicationController respond_to do |format| if @<%= orm_instance.save %> + <%- if options[:html] -%> format.html { redirect_to @<%= singular_table_name %>, notice: <%= "'#{human_name} was successfully created.'" %> } + <%- end -%> format.json { render json: <%= "@#{singular_table_name}" %>, status: :created, location: <%= "@#{singular_table_name}" %> } else + <%- if options[:html] -%> format.html { render action: "new" } + <%- end -%> format.json { render json: <%= "@#{orm_instance.errors}" %>, status: :unprocessable_entity } end end @@ -61,14 +70,16 @@ class <%= controller_class_name %>Controller < ApplicationController # PATCH/PUT <%= route_url %>/1 # PATCH/PUT <%= route_url %>/1.json def update - @<%= singular_table_name %> = <%= orm_class.find(class_name, "params[:id]") %> - respond_to do |format| - if @<%= orm_instance.update_attributes("#{singular_table_name}_params") %> + if @<%= orm_instance.update("#{singular_table_name}_params") %> + <%- if options[:html] -%> format.html { redirect_to @<%= singular_table_name %>, notice: <%= "'#{human_name} was successfully updated.'" %> } + <%- end -%> format.json { head :no_content } else + <%- if options[:html] -%> format.html { render action: "edit" } + <%- end -%> format.json { render json: <%= "@#{orm_instance.errors}" %>, status: :unprocessable_entity } end end @@ -77,24 +88,28 @@ class <%= controller_class_name %>Controller < ApplicationController # DELETE <%= route_url %>/1 # DELETE <%= route_url %>/1.json def destroy - @<%= singular_table_name %> = <%= orm_class.find(class_name, "params[:id]") %> @<%= orm_instance.destroy %> respond_to do |format| + <%- if options[:html] -%> format.html { redirect_to <%= index_helper %>_url } + <%- end -%> format.json { head :no_content } end 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 - # Use this method to whitelist the permissible parameters. Example: params.require(:person).permit(:name, :age) - # Also, you can specialize this method with per-user checking of permissible attributes. + # Never trust parameters from the scary internet, only allow the white list through. def <%= "#{singular_table_name}_params" %> - <%- if attributes.empty? -%> + <%- if attributes_names.empty? -%> params[<%= ":#{singular_table_name}" %>] <%- else -%> - params.require(<%= ":#{singular_table_name}" %>).permit(<%= attributes.map {|a| ":#{a.name}" }.join(', ') %>) + params.require(<%= ":#{singular_table_name}" %>).permit(<%= attributes_names.map { |name| ":#{name}" }.join(', ') %>) <%- end -%> end end diff --git a/railties/lib/rails/generators/test_case.rb b/railties/lib/rails/generators/test_case.rb index 24308dcf6c..85a8914ccc 100644 --- a/railties/lib/rails/generators/test_case.rb +++ b/railties/lib/rails/generators/test_case.rb @@ -163,8 +163,8 @@ module Rails # end # end def assert_instance_method(method, content) - assert content =~ /def #{method}(\(.+\))?(.*?)\n end/m, "Expected to have method #{method}" - yield $2.strip if block_given? + assert content =~ /(\s+)def #{method}(\(.+\))?(.*?)\n\1end/m, "Expected to have method #{method}" + yield $3.strip if block_given? end alias :assert_method :assert_instance_method 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 2801749ffe..2826a3ffa1 100644 --- a/railties/lib/rails/generators/test_unit/model/model_generator.rb +++ b/railties/lib/rails/generators/test_unit/model/model_generator.rb @@ -3,6 +3,9 @@ require 'rails/generators/test_unit' module TestUnit # :nodoc: module Generators # :nodoc: class ModelGenerator < Base # :nodoc: + + RESERVED_YAML_KEYWORDS = %w(y yes n no true false on off null) + argument :attributes, type: :array, default: [], banner: "field:type field:type" class_option :fixture, type: :boolean @@ -19,6 +22,15 @@ module TestUnit # :nodoc: template 'fixtures.yml', File.join('test/fixtures', class_path, "#{plural_file_name}.yml") end end + + private + def yaml_key_value(key, value) + if RESERVED_YAML_KEYWORDS.include?(key.downcase) + "'#{key}': #{value}" + else + "#{key}: #{value}" + end + end end end end diff --git a/railties/lib/rails/generators/test_unit/model/templates/fixtures.yml b/railties/lib/rails/generators/test_unit/model/templates/fixtures.yml index 5c8780aa64..c9d505c84a 100644 --- a/railties/lib/rails/generators/test_unit/model/templates/fixtures.yml +++ b/railties/lib/rails/generators/test_unit/model/templates/fixtures.yml @@ -3,12 +3,18 @@ <% unless attributes.empty? -%> one: <% attributes.each do |attribute| -%> - <%= attribute.name %>: <%= attribute.default %> + <%= yaml_key_value(attribute.column_name, attribute.default) %> + <%- if attribute.polymorphic? -%> + <%= yaml_key_value("#{attribute.name}_type", attribute.human_name) %> + <%- end -%> <% end -%> two: <% attributes.each do |attribute| -%> - <%= attribute.name %>: <%= attribute.default %> + <%= yaml_key_value(attribute.column_name, attribute.default) %> + <%- if attribute.polymorphic? -%> + <%= yaml_key_value("#{attribute.name}_type", attribute.human_name) %> + <%- end -%> <% end -%> <% else -%> # This model initially had no columns defined. If you add columns to the diff --git a/railties/lib/rails/generators/test_unit/observer/observer_generator.rb b/railties/lib/rails/generators/test_unit/observer/observer_generator.rb deleted file mode 100644 index 64fe694a8b..0000000000 --- a/railties/lib/rails/generators/test_unit/observer/observer_generator.rb +++ /dev/null @@ -1,13 +0,0 @@ -require 'rails/generators/test_unit' - -module TestUnit # :nodoc: - module Generators # :nodoc: - class ObserverGenerator < Base # :nodoc: - check_class_collision suffix: "ObserverTest" - - def create_test_files - template 'unit_test.rb', File.join('test/models', class_path, "#{file_name}_observer_test.rb") - end - end - end -end diff --git a/railties/lib/rails/generators/test_unit/observer/templates/unit_test.rb b/railties/lib/rails/generators/test_unit/observer/templates/unit_test.rb deleted file mode 100644 index 28aa23626a..0000000000 --- a/railties/lib/rails/generators/test_unit/observer/templates/unit_test.rb +++ /dev/null @@ -1,9 +0,0 @@ -require 'test_helper' - -<% module_namespacing do -%> -class <%= class_name %>ObserverTest < ActiveSupport::TestCase - # test "the truth" do - # assert true - # end -end -<% end -%> diff --git a/railties/lib/rails/generators/test_unit/plugin/templates/test_helper.rb b/railties/lib/rails/generators/test_unit/plugin/templates/test_helper.rb index c9af2ca832..30a861f09d 100644 --- a/railties/lib/rails/generators/test_unit/plugin/templates/test_helper.rb +++ b/railties/lib/rails/generators/test_unit/plugin/templates/test_helper.rb @@ -1,2 +1,2 @@ -require 'minitest/autorun' +require 'active_support/testing/autorun' require 'active_support' 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 3b4fec2e83..8f3ecaadea 100644 --- a/railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb +++ b/railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb @@ -18,17 +18,12 @@ module TestUnit # :nodoc: private def attributes_hash - return if accessible_attributes.empty? + return if attributes_names.empty? - accessible_attributes.map do |a| - name = a.name + attributes_names.map do |name| "#{name}: @#{singular_table_name}.#{name}" end.sort.join(', ') end - - def accessible_attributes - attributes.reject(&:reference?) - end 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 30e1650555..18bd1ece9d 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 @@ -36,7 +36,7 @@ class <%= controller_class_name %>ControllerTest < ActionController::TestCase end test "should update <%= singular_table_name %>" do - put :update, id: <%= "@#{singular_table_name}" %>, <%= "#{singular_table_name}: { #{attributes_hash} }" %> + patch :update, id: <%= "@#{singular_table_name}" %>, <%= "#{singular_table_name}: { #{attributes_hash} }" %> assert_redirected_to <%= singular_table_name %>_path(assigns(:<%= singular_table_name %>)) end diff --git a/railties/lib/rails/info_controller.rb b/railties/lib/rails/info_controller.rb index e94c6a2030..fa5668a5b5 100644 --- a/railties/lib/rails/info_controller.rb +++ b/railties/lib/rails/info_controller.rb @@ -1,13 +1,14 @@ require 'action_dispatch/routing/inspector' -class Rails::InfoController < ActionController::Base - self.view_paths = File.join(File.dirname(__FILE__), 'templates') - layout 'application' +class Rails::InfoController < ActionController::Base # :nodoc: + self.view_paths = File.expand_path('../templates', __FILE__) + prepend_view_path ActionDispatch::DebugExceptions::RESCUES_TEMPLATE_PATH + layout -> { request.xhr? ? nil : 'application' } before_filter :require_local! def index - redirect_to '/rails/info/routes' + redirect_to action: :routes end def properties @@ -15,8 +16,7 @@ class Rails::InfoController < ActionController::Base end def routes - inspector = ActionDispatch::Routing::RoutesInspector.new - @info = inspector.format(_routes.routes).join("\n") + @routes_inspector = ActionDispatch::Routing::RoutesInspector.new(_routes.routes) end protected diff --git a/railties/lib/rails/paths.rb b/railties/lib/rails/paths.rb index cfdb15a14e..e52d1a8b90 100644 --- a/railties/lib/rails/paths.rb +++ b/railties/lib/rails/paths.rb @@ -56,8 +56,8 @@ module Rails end def add(path, options={}) - with = options[:with] || path - @root[path] = Path.new(self, path, [with].flatten, options) + with = Array(options[:with] || path) + @root[path] = Path.new(self, path, with, options) end def [](path) @@ -99,15 +99,14 @@ module Rails protected def filter_by(constraint) - yes = [] - no = [] - + all = [] all_paths.each do |path| - paths = path.existent + path.existent_base_paths - path.send(constraint) ? yes.concat(paths) : no.concat(paths) + if path.send(constraint) + paths = path.existent + paths -= path.children.map { |p| p.send(constraint) ? [] : p.existent }.flatten + all.concat(paths) + end end - - all = yes - no all.uniq! all end @@ -135,7 +134,6 @@ module Rails keys.delete(@current) @root.values_at(*keys.sort) end - deprecate :children def first expanded.first @@ -212,10 +210,6 @@ module Rails expanded.select { |d| File.directory?(d) } end - def existent_base_paths - map { |p| File.expand_path(p, @root.path) }.select{ |f| File.exist? f } - end - alias to_a expanded end end diff --git a/railties/lib/rails/railtie.rb b/railties/lib/rails/railtie.rb index 5b454e7f20..9437e9c406 100644 --- a/railties/lib/rails/railtie.rb +++ b/railties/lib/rails/railtie.rb @@ -172,7 +172,7 @@ module Rails end end - delegate :railtie_name, to: "self.class" + delegate :railtie_name, to: :class def config @config ||= Railtie::Configuration.new diff --git a/railties/lib/rails/source_annotation_extractor.rb b/railties/lib/rails/source_annotation_extractor.rb index 3474b02af4..ac806e8006 100644 --- a/railties/lib/rails/source_annotation_extractor.rb +++ b/railties/lib/rails/source_annotation_extractor.rb @@ -15,7 +15,7 @@ class SourceAnnotationExtractor class Annotation < Struct.new(:line, :tag, :text) def self.directories - @@directories ||= %w(app config lib script test) + (ENV['SOURCE_ANNOTATION_DIRECTORIES'] || '').split(',') + @@directories ||= %w(app config db lib script test) + (ENV['SOURCE_ANNOTATION_DIRECTORIES'] || '').split(',') end # Returns a representation of the annotation that looks like this: diff --git a/railties/lib/rails/tasks/routes.rake b/railties/lib/rails/tasks/routes.rake index 676b475640..1815c2fdc7 100644 --- a/railties/lib/rails/tasks/routes.rake +++ b/railties/lib/rails/tasks/routes.rake @@ -2,6 +2,6 @@ desc 'Print out all defined routes in match order, with names. Target specific c task routes: :environment do all_routes = Rails.application.routes.routes require 'action_dispatch/routing/inspector' - inspector = ActionDispatch::Routing::RoutesInspector.new - puts inspector.format(all_routes, ENV['CONTROLLER']).join "\n" + inspector = ActionDispatch::Routing::RoutesInspector.new(all_routes) + puts inspector.format(ActionDispatch::Routing::ConsoleFormatter.new, ENV['CONTROLLER']) end diff --git a/railties/lib/rails/templates/layouts/application.html.erb b/railties/lib/rails/templates/layouts/application.html.erb index 53276d3e7c..7352d48e7b 100644 --- a/railties/lib/rails/templates/layouts/application.html.erb +++ b/railties/lib/rails/templates/layouts/application.html.erb @@ -22,6 +22,10 @@ a { color: #000; } a:visited { color: #666; } a:hover { color: #fff; background-color:#000; } + + h2 { padding-left: 10px; } + + <%= yield :style %> </style> </head> <body> diff --git a/railties/lib/rails/templates/rails/info/routes.html.erb b/railties/lib/rails/templates/rails/info/routes.html.erb index 890f6f5b03..2d8a190986 100644 --- a/railties/lib/rails/templates/rails/info/routes.html.erb +++ b/railties/lib/rails/templates/rails/info/routes.html.erb @@ -6,4 +6,4 @@ Routes match in priority from top to bottom </p> -<p><pre><%= @info %></pre></p>
\ No newline at end of file +<%= @routes_inspector.format(ActionDispatch::Routing::HtmlTableFormatter.new(self)) %> diff --git a/railties/lib/rails/generators/rails/app/templates/public/index.html b/railties/lib/rails/templates/rails/welcome/index.html.erb index dd09a96de9..abe705618a 100644 --- a/railties/lib/rails/generators/rails/app/templates/public/index.html +++ b/railties/lib/rails/templates/rails/welcome/index.html.erb @@ -173,15 +173,18 @@ </style> <script> function about() { - info = document.getElementById('about-content'); - if (window.XMLHttpRequest) - { xhr = new XMLHttpRequest(); } - else - { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } - xhr.open("GET","rails/info/properties",false); - xhr.send(""); - info.innerHTML = xhr.responseText; - info.style.display = 'block' + var info = document.getElementById('about-content'), + xhr; + + if (info.innerHTML === '') { + xhr = new XMLHttpRequest(); + xhr.open("GET", "rails/info/properties", false); + xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); + xhr.send(""); + info.innerHTML = xhr.responseText; + } + + info.style.display = info.style.display === 'none' ? 'block' : 'none'; } </script> </head> @@ -223,7 +226,8 @@ </li> <li> - <h2>Set up a default route and remove <span class="filename">public/index.html</span></h2> + <h2>Set up a root route to replace this page</h2> + <p>You're seeing this page because you're running in development mode and you haven't set a root route yet.</p> <p>Routes are set up in <span class="filename">config/routes.rb</span>.</p> </li> diff --git a/railties/lib/rails/test_help.rb b/railties/lib/rails/test_help.rb index aed7fd4b14..616206dd0b 100644 --- a/railties/lib/rails/test_help.rb +++ b/railties/lib/rails/test_help.rb @@ -2,7 +2,7 @@ # so fixtures aren't loaded into that environment abort("Abort testing: Your Rails environment is running in production mode!") if Rails.env.production? -require 'minitest/autorun' +require 'active_support/testing/autorun' require 'active_support/test_case' require 'action_controller/test_case' require 'action_dispatch/testing/integration' diff --git a/railties/lib/rails/welcome_controller.rb b/railties/lib/rails/welcome_controller.rb new file mode 100644 index 0000000000..45b764fa6b --- /dev/null +++ b/railties/lib/rails/welcome_controller.rb @@ -0,0 +1,7 @@ +class Rails::WelcomeController < ActionController::Base # :nodoc: + self.view_paths = File.expand_path('../templates', __FILE__) + layout nil + + def index + end +end |