diff options
Diffstat (limited to 'guides')
33 files changed, 2388 insertions, 1398 deletions
diff --git a/guides/assets/images/getting_started/unknown_action_create_for_articles.png b/guides/assets/images/getting_started/unknown_action_create_for_articles.png Binary files differindex ec4758e085..e75b9780cc 100644 --- a/guides/assets/images/getting_started/unknown_action_create_for_articles.png +++ b/guides/assets/images/getting_started/unknown_action_create_for_articles.png diff --git a/guides/rails_guides/generator.rb b/guides/rails_guides/generator.rb index 7d4a15962c..2b2ccfa906 100644 --- a/guides/rails_guides/generator.rb +++ b/guides/rails_guides/generator.rb @@ -43,7 +43,6 @@ module RailsGuides end private - def register_kindle_mime_types Mime::Type.register_alias("application/xml", :opf, %w(opf)) Mime::Type.register_alias("application/xml", :ncx, %w(ncx)) diff --git a/guides/rails_guides/indexer.rb b/guides/rails_guides/indexer.rb index c707464cdf..576ec85b27 100644 --- a/guides/rails_guides/indexer.rb +++ b/guides/rails_guides/indexer.rb @@ -18,7 +18,6 @@ module RailsGuides end private - def process(string, current_level = 3, counters = [1]) s = StringScanner.new(string) diff --git a/guides/rails_guides/markdown.rb b/guides/rails_guides/markdown.rb index 018f49ffd0..d926d233bb 100644 --- a/guides/rails_guides/markdown.rb +++ b/guides/rails_guides/markdown.rb @@ -30,7 +30,6 @@ module RailsGuides end private - def dom_id(nodes) dom_id = dom_id_text(nodes.last.text) diff --git a/guides/rails_guides/markdown/renderer.rb b/guides/rails_guides/markdown/renderer.rb index 7f14c28bbc..4877e806fd 100644 --- a/guides/rails_guides/markdown/renderer.rb +++ b/guides/rails_guides/markdown/renderer.rb @@ -53,7 +53,6 @@ HTML end private - def convert_footnotes(text) text.gsub(/\[<sup>(\d+)\]<\/sup>/i) do %(<sup class="footnote" id="footnote-#{$1}-ref">) + diff --git a/guides/source/2_3_release_notes.md b/guides/source/2_3_release_notes.md index ee9a499953..b46d5ee4db 100644 --- a/guides/source/2_3_release_notes.md +++ b/guides/source/2_3_release_notes.md @@ -415,7 +415,7 @@ select_datetime(DateTime.now, :prompt => ### AssetTag Timestamp Caching -You're likely familiar with Rails' practice of adding timestamps to static asset paths as a "cache buster." This helps ensure that stale copies of things like images and stylesheets don't get served out of the user's browser cache when you change them on the server. You can now modify this behavior with the `cache_asset_timestamps` configuration option for Action View. If you enable the cache, then Rails will calculate the timestamp once when it first serves an asset, and save that value. This means fewer (expensive) file system calls to serve static assets - but it also means that you can't modify any of the assets while the server is running and expect the changes to get picked up by clients. +You're likely familiar with Rails' practice of adding timestamps to static asset paths as a "cache buster". This helps ensure that stale copies of things like images and stylesheets don't get served out of the user's browser cache when you change them on the server. You can now modify this behavior with the `cache_asset_timestamps` configuration option for Action View. If you enable the cache, then Rails will calculate the timestamp once when it first serves an asset, and save that value. This means fewer (expensive) file system calls to serve static assets - but it also means that you can't modify any of the assets while the server is running and expect the changes to get picked up by clients. ### Asset Hosts as Objects diff --git a/guides/source/5_1_release_notes.md b/guides/source/5_1_release_notes.md index e885b1e42e..f870c4c47c 100644 --- a/guides/source/5_1_release_notes.md +++ b/guides/source/5_1_release_notes.md @@ -41,8 +41,8 @@ Major Features [Pull Request](https://github.com/rails/rails/pull/26836) Rails 5.1 allows managing JavaScript dependencies -from NPM via Yarn. This will make it easy to use libraries like React, VueJS -or any other library from NPM world. The Yarn support is integrated with +from npm via Yarn. This will make it easy to use libraries like React, VueJS +or any other library from npm world. The Yarn support is integrated with the asset pipeline so that all dependencies will work seamlessly with the Rails 5.1 app. diff --git a/guides/source/5_2_release_notes.md b/guides/source/5_2_release_notes.md index ac247bc3f9..7aac07dbbe 100644 --- a/guides/source/5_2_release_notes.md +++ b/guides/source/5_2_release_notes.md @@ -326,7 +326,7 @@ Please refer to the [Changelog][action-view] for detailed changes. select divider `option`. ([Pull Request](https://github.com/rails/rails/pull/31088)) -* Change `form_with` to generates ids by default. +* Change `form_with` to generate ids by default. ([Commit](https://github.com/rails/rails/commit/260d6f112a0ffdbe03e6f5051504cb441c1e94cd)) * Add `preload_link_tag` helper. diff --git a/guides/source/6_0_release_notes.md b/guides/source/6_0_release_notes.md index 4eb5296c41..7c5478a03d 100644 --- a/guides/source/6_0_release_notes.md +++ b/guides/source/6_0_release_notes.md @@ -178,7 +178,7 @@ Please refer to the [Changelog][action-cable] for detailed changes. `ActionCable::Connection`. ([Pull Request](https://github.com/rails/rails/pull/34194)) -* Convert the Action Cable Javascript package from CoffeeScript to ES2015 and +* Convert the Action Cable JavaScript package from CoffeeScript to ES2015 and publish the source code in the npm distribution. ([Pull Request](https://github.com/rails/rails/pull/34370)) @@ -202,7 +202,7 @@ Please refer to the [Changelog][action-pack] for detailed changes. * Remove deprecated methods in `ActionDispatch::TestResponse`: `#success?` in favor of `#successful?`, `#missing?` in favor of `#not_found?`, - `#error?` in favor of `#server_error?` + `#error?` in favor of `#server_error?`. ([Commit](https://github.com/rails/rails/commit/13ddc92e079e59a0b894e31bf5bb4fdecbd235d1)) ### Deprecations @@ -215,6 +215,10 @@ Please refer to the [Changelog][action-pack] for detailed changes. ### Notable changes +* Change `ActionDispatch::Response#content_type` returning Content-Type + header as it is. + ([Pull Request](https://github.com/rails/rails/pull/36034)) + * Raise an `ArgumentError` if a resource param contains a colon. ([Pull Request](https://github.com/rails/rails/pull/35236)) @@ -229,7 +233,7 @@ Please refer to the [Changelog][action-pack] for detailed changes. * Allow the use of `parsed_body` in `ActionController::TestCase`. ([Pull Request](https://github.com/rails/rails/pull/34717)) -* Raise an `ArgumentError` when multiple root routes exists in the same context +* Raise an `ArgumentError` when multiple root routes exist in the same context without `as:` naming specifications. ([Pull Request](https://github.com/rails/rails/pull/34494)) @@ -245,7 +249,7 @@ Please refer to the [Changelog][action-pack] for detailed changes. * Expose `ActionController::Parameters#each_key`. ([Pull Request](https://github.com/rails/rails/pull/33758)) -* Add purpose metadata to signed/encrypted cookies to prevent copying the value of +* Add purpose and expiry metadata inside signed/encrypted cookies to prevent copying the value of cookies into one another. ([Pull Request](https://github.com/rails/rails/pull/32937)) @@ -298,14 +302,14 @@ Please refer to the [Changelog][action-view] for detailed changes. ### Notable changes -* Clear ActionView cache in development only on file changes, speeding up +* Clear Action View cache in development only on file changes, speeding up development mode. ([Pull Request](https://github.com/rails/rails/pull/35629)) * Move all of the Rails npm packages into a `@rails` scope. ([Pull Request](https://github.com/rails/rails/pull/34905)) -* Only accept formats from registered Mime types. +* Only accept formats from registered MIME types. ([Pull Request](https://github.com/rails/rails/pull/35604), [Pull Request](https://github.com/rails/rails/pull/35753)) * Add allocations to the template and partial rendering server output. @@ -323,7 +327,7 @@ Please refer to the [Changelog][action-view] for detailed changes. enable `ActionView::Template` finalizers. ([Pull Request](https://github.com/rails/rails/pull/32418)) -* Extract the JS `confirm` call to its own, overridable method in `rails_ujs`. +* Extract the JavaScript `confirm` call to its own, overridable method in `rails_ujs`. ([Pull Request](https://github.com/rails/rails/pull/32404)) * Add a `action_controller.default_enforce_utf8` configuration option to handle @@ -402,7 +406,7 @@ Please refer to the [Changelog][active-record] for detailed changes. * Remove support for passing the column name to `count` when a block is passed. ([Commit](https://github.com/rails/rails/commit/67356f2034ab41305af7218f7c8b2fee2d614129)) -* Remove support for delegation of missing methods in a relation to arel. +* Remove support for delegation of missing methods in a relation to Arel. ([Commit](https://github.com/rails/rails/commit/d97980a16d76ad190042b4d8578109714e9c53d0)) * Remove support for delegating missing methods in a relation to private methods of the class. @@ -445,7 +449,7 @@ Please refer to the [Changelog][active-record] for detailed changes. ### Notable changes -* Bump the minimum sqlite3 version to 1.4. +* Bump the minimum version of the `sqlite3` gem to 1.4. ([Pull Request](https://github.com/rails/rails/pull/35844)) * Add `rails db:prepare` to create a database if it doesn't exist, and run its migrations. @@ -467,7 +471,7 @@ Please refer to the [Changelog][active-record] for detailed changes. ([Pull Request](https://github.com/rails/rails/pull/35631)) * Add `rails db:seed:replant` that truncates tables of each database - for ther current environment and loads the seeds. + for the current environment and loads the seeds. ([Pull Request](https://github.com/rails/rails/pull/34779)) * Add `reselect` method, which is a short-hand for `unscope(:select).select(fields)`. @@ -509,7 +513,7 @@ Please refer to the [Changelog][active-record] for detailed changes. ([Pull Request](https://github.com/rails/rails/pull/34742)) * Add the ability to disable scopes generated by `ActiveRecord.enum`. - ([Pull Request](https://github.com/rails/rails/pull/34605/files)) + ([Pull Request](https://github.com/rails/rails/pull/34605)) * Make implicit ordering configurable for a column. ([Pull Request](https://github.com/rails/rails/pull/34480)) @@ -577,7 +581,7 @@ Please refer to the [Changelog][active-record] for detailed changes. * Allow the `:to_table` option of `remove_foreign_key` to be invertible. ([Pull Request](https://github.com/rails/rails/pull/33530)) -* Fix default value for mysql time types with specified precision. +* Fix default value for MySQL time types with specified precision. ([Pull Request](https://github.com/rails/rails/pull/33280)) * Fix the `touch` option to behave consistently with `Persistence#touch` method. @@ -668,6 +672,12 @@ Please refer to the [Changelog][active-storage] for detailed changes. is saved instead of immediately. ([Pull Request](https://github.com/rails/rails/pull/33303)) +* Optionally replace existing files instead of adding to them when assigning to + a collection of attachments (as in `@user.update!(images: [ … ])`). Use + `config.active_storage.replace_on_assign_to_many` to control this behavior. + ([Pull Request](https://github.com/rails/rails/pull/33303), + [Pull Request](https://github.com/rails/rails/pull/36716)) + * Add the ability to reflect on defined attachments using the existing Active Record reflection mechanism. ([Pull Request](https://github.com/rails/rails/pull/33018)) @@ -682,11 +692,7 @@ Please refer to the [Changelog][active-storage] for detailed changes. * Use the `image_processing` gem for Active Storage variants. This replaces using `mini_magick` directly. - ([Pull Request](https://github.com/rails/rails/pull/32471) - -* Replace existing images instead of adding to them when updating an - attached model via `update` or `update!` with, say, `@user.update!(images: [ … ])`. - ([Pull Request](https://github.com/rails/rails/pull/33303)) + ([Pull Request](https://github.com/rails/rails/pull/32471)) Active Model ------------ @@ -762,7 +768,7 @@ Please refer to the [Changelog][active-support] for detailed changes. ([Pull Request](https://github.com/rails/rails/pull/34123)) * Deprecate `ActiveSupport::Multibyte::Unicode#normalize` - and `ActiveSuppport::Multibyte::Chars#normalize` in favor of + and `ActiveSupport::Multibyte::Chars#normalize` in favor of `String#unicode_normalize`. ([Pull Request](https://github.com/rails/rails/pull/34202)) @@ -771,7 +777,7 @@ Please refer to the [Changelog][active-support] for detailed changes. ([Pull Request](https://github.com/rails/rails/pull/34215)) * Deprecate `ActiveSupport::Multibyte::Unicode#pack_graphemes(array)` - and `ActiveSuppport::Multibyte::Unicode#unpack_graphemes(string)` + and `ActiveSupport::Multibyte::Unicode#unpack_graphemes(string)` in favor of `array.flatten.pack("U*")` and `string.scan(/\X/).map(&:codepoints)`, respectively. ([Pull Request](https://github.com/rails/rails/pull/34254)) diff --git a/guides/source/action_text_overview.md b/guides/source/action_text_overview.md index 07919775e2..a735ec2b0e 100644 --- a/guides/source/action_text_overview.md +++ b/guides/source/action_text_overview.md @@ -46,6 +46,8 @@ happens after every keystroke, and avoids the need to use execCommand at all. ## Installation Run `rails action_text:install` to add the Yarn package and copy over the necessary migration. +Also, you need to set up Active Storage for embedded images and other attachments. +Please refer to the [Active Storage Overview](active_storage_overview.html) guide. ## Examples diff --git a/guides/source/action_view_overview.md b/guides/source/action_view_overview.md index a1b69edd22..dda3ae0863 100644 --- a/guides/source/action_view_overview.md +++ b/guides/source/action_view_overview.md @@ -1025,6 +1025,34 @@ If `@article.author_id` is 1, this would return: <label for="article_author_id_3">M. Clark</label> ``` +Recovering some option passed (e.g. programatically checking an object from collection): + +```ruby +collection_radio_buttons(:article, :author_id, Author.all, :id, :name_with_initial, {checked: Author.last}) +``` + +In this case, the last object from the collection will be checked: + +```html +<input id="article_author_id_1" name="article[author_id]" type="radio" value="1" /> +<label for="article_author_id_1">D. Heinemeier Hansson</label> +<input id="article_author_id_2" name="article[author_id]" type="radio" value="2" /> +<label for="article_author_id_2">D. Thomas</label> +<input id="article_author_id_3" name="article[author_id]" type="radio" value="3" checked="checked" /> +<label for="article_author_id_3">M. Clark</label> +``` + +To access the passed options programatically (e.g. adding a custom class if checked): + +**Sample html.erb** + +```html+erb +<%= collection_radio_buttons(:article, :author_id, Author.all, :id, :name_with_initial, {checked: Author.last, required: true} do |rb| %> + <%= rb.label(class: "#{'my-custom-class' if rb.value == Author.last.id}") { rb.radio_button + rb.text } %> +<% end %> +``` + + #### collection_check_boxes Returns `check_box` tags for the collection of existing return values of `method` for `object`'s class. diff --git a/guides/source/active_record_migrations.md b/guides/source/active_record_migrations.md index 270e4a3bf9..9398244ccf 100644 --- a/guides/source/active_record_migrations.md +++ b/guides/source/active_record_migrations.md @@ -225,6 +225,8 @@ class CreateProducts < ActiveRecord::Migration[5.0] create_table :products do |t| t.string :name t.string :part_number + + t.timestamps end end end diff --git a/guides/source/active_record_multiple_databases.md b/guides/source/active_record_multiple_databases.md new file mode 100644 index 0000000000..07be21a254 --- /dev/null +++ b/guides/source/active_record_multiple_databases.md @@ -0,0 +1,288 @@ +**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON https://guides.rubyonrails.org.** + +Multiple Databases with Active Record +===================================== + +This guide covers using multiple databases with your Rails application. + +After reading this guide you will know: + +* How to setup your application for multiple databases. +* How automatic connection switching works. +* What features are supported and what's still a work in progress. + +-------------------------------------------------------------------------------- + +As an application grows in popularity and usage you'll need to scale the application +to support your new users and their data. One way in which your application may need +to scale is on the database level. Rails now has support for multiple databases +so you don't have to store your data all in one place. + +At this time the following features are supported: + +* Multiple primary databases and a replica for each +* Automatic connection switching for the model you're working with +* Automatic swapping between the primary and replica depending on the HTTP verb +and recent writes +* Rails tasks for creating, dropping, migrating, and interacting with the multiple +databases + +The following features are not (yet) supported: + +* Sharding +* Joining across clusters +* Load balancing replicas +* Dumping schema caches for multiple databases + +## Setting up your application + +While Rails tries to do most of the work for you there are still some steps you'll +need to do to get your application ready for multiple databases. + +Let's say we have an application with a single primary database and we need to add a +new database for some new tables we're adding. The name of the new database will be +"animals". + +The database.yml looks like this: + +```yaml +production: + database: my_primary_database + user: root + adapter: mysql +``` + +Let's add a replica for the primary, a new writer called animals and a replica for that +as well. To do this we need to change our database.yml from a 2-tier to a 3-tier config. + +```yaml +production: + primary: + database: my_primary_database + user: root + adapter: mysql + primary_replica: + database: my_primary_database + user: root_readonly + adapter: mysql + replica: true + animals: + database: my_animals_database + user: animals_root + adapter: mysql + migrations_paths: db/animals_migrate + animals_replica: + database: my_animals_database + user: animals_readonly + adapter: mysql + replica: true +``` + +When using multiple databases there are a few important settings. + +First, the database name for the primary and replica should be the same because they contain +the same data. Second, the username for the primary and replica should be different, and the +replica user's permissions should be to read and not write. + +When using a replica database you need to add a `replica: true` entry to the replica in the +`database.yml`. This is because Rails otherwise has no way of knowing which one is a replica +and which one is the primary. + +Lastly, for new primary databases you need to set the `migrations_paths` to the directory +where you will store migrations for that database. We'll look more at `migrations_paths` +later on in this guide. + +Now that we have a new database, let's set up the model. In order to use the new database we +need to create a new abstract class and connect to the animals databases. + +```ruby +class AnimalsBase < ApplicationRecord + self.abstract_class = true + + connects_to database: { writing: :animals, reading: :animals_replica } +end +``` + Then we need to +update `ApplicationRecord` to be aware of our new replica. + +```ruby +class ApplicationRecord < ActiveRecord::Base + self.abstract_class = true + + connects_to database: { writing: :primary, reading: :primary_replica } +end +``` + +By default Rails expects the database roles to be `writing` and `reading` for the primary +and replica respectively. If you have a legacy system you may already have roles set up that +you don't want to change. In that case you can set a new role name in your application config. + +```ruby +config.active_record.writing_role = :default +config.active_record.reading_role = :readonly +``` + +It's important to connect to your database in a single model and then inherit from that model +for the tables rather than connect multiple individual models to the same database. Database +clients have a limit to the number of open connections there can be and if you do this it will +multiply the number of connections you have since Rails uses the model class name for the +connection specification name. + +Now that we have the database.yml and the new model set up it's time to create the databases. +Rails 6.0 ships with all the rails tasks you need to use multiple databases in Rails. + +You can run `rails -T` to see all the commands you're able to run. You should see the following: + +``` +$ rails -T +rails db:create # Creates the database from DATABASE_URL or config/database.yml for the ... +rails db:create:animals # Create animals database for current environment +rails db:create:primary # Create primary database for current environment +rails db:drop # Drops the database from DATABASE_URL or config/database.yml for the cu... +rails db:drop:animals # Drop animals database for current environment +rails db:drop:primary # Drop primary database for current environment +rails db:migrate # Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog) +rails db:migrate:animals # Migrate animals database for current environment +rails db:migrate:primary # Migrate primary database for current environment +rails db:migrate:status # Display status of migrations +rails db:migrate:status:animals # Display status of migrations for animals database +rails db:migrate:status:primary # Display status of migrations for primary database +``` + +Running a command like `rails db:create` will create both the primary and animals databases. +Note that there is no command for creating the users and you'll need to do that manually +to support the readonly users for your replicas. If you want to create just the animals +database you can run `rails db:create:animals`. + +## Migrations + +Migrations for multiple databases should live in their own folders prefixed with the +name of the database key in the configuration. + +You also need to set the `migrations_paths` in the database configurations to tell Rails +where to find the migrations. + +For example the `animals` database would look in the `db/animals_migrate` directory and +`primary` would look in `db/migrate`. Rails generators now take a `--database` option +so that the file is generated in the correct directory. The command can be run like so: + +``` +$ rails g migration CreateDogs name:string --database animals +``` + +## Activating automatic connection switching + +Finally, in order to use the read-only replica in your application you'll need to activate +the middleware for automatic switching. + +Automatic switching allows the application to switch from the primary to replica or replica +to primary based on the HTTP verb and whether there was a recent write. + +If the application is receiving a POST, PUT, DELETE, or PATCH request the application will +automatically write to the primary. For the specified time after the write the application +will read from the primary. For a GET or HEAD request the application will read from the +replica unless there was a recent write. + +To activate the automatic connection switching middleware, add or uncomment the following +lines in your application config. + +```ruby +config.active_record.database_selector = { delay: 2.seconds } +config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver +config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session +``` + +Rails guarantees "read your own write" and will send your GET or HEAD request to the +primary if it's within the `delay` window. By default the delay is set to 2 seconds. You +should change this based on your database infrastructure. Rails doesn't guarantee "read +a recent write" for other users within the delay window and will send GET and HEAD requests +to the replicas unless they wrote recently. + +The automatic connection switching in Rails is relatively primitive and deliberately doesn't +do a whole lot. The goal was a system that demonstrated how to do automatic connection +switching that was flexible enough to be customizable by app developers. + +The setup in Rails allows you to easily change how the switching is done and what +parameters it's based on. Let's say you want to use a cookie instead of a session to +decide when to swap connections. You can write your own class: + +```ruby +class MyCookieResolver + # code for your cookie class +end +``` + +And then pass it to the middleware: + +```ruby +config.active_record.database_selector = { delay: 2.seconds } +config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver +config.active_record.database_resolver_context = MyCookieResolver +``` + +## Using manual connection switching + +There are some cases where you may want your application to connect to a primary or a replica +and the automatic connection switching isn't adequate. For example, you may know that for a +particular request you always want to send the request to a replica, even when you are in a +POST request path. + +To do this Rails provides a `connected_to` method that will switch to the connection you +need. + +```ruby +ActiveRecord::Base.connected_to(role: :reading) do + # all code in this block will be connected to the reading role +end +``` + +The "role" in the `connected_to` call looks up the connections that are connected on that +connection handler (or role). The `reading` connection handler will hold all the connections +that were connected via `connects_to` with the role name of `reading`. + +There also may be a case where you have a database that you don't always want to connect to +on application boot but may need for a slow query or analytics. After defining that database +in the database.yml you can connect by passing a database argument to `connected_to` + +```ruby +ActiveRecord::Base.connected_to(database: { reading_slow: :animals_slow_replica }) do + # do something while connected to the slow replica +end +``` + +The `database` argument for `connected_to` will take a symbol or a config hash. + +Note that `connected_to` with a role will look up an existing connection and switch +using the connection specification name. This means that if you pass an unknown role +like `connected_to(role: :nonexistent)` you will get an error that says +`ActiveRecord::ConnectionNotEstablished (No connection pool with 'AnimalsBase' found +for the 'nonexistent' role.)` + +## Caveats + +### Sharding + +As noted at the top, Rails doesn't (yet) support sharding. We had to do a lot of work +to support multiple databases for Rails 6.0. The lack of support for sharding isn't +an oversight, but does require additional work that didn't make it in for 6.0. For now +if you need sharding it may be advisable to continue using one of the many gems +that supports this. + +### Load Balancing Replicas + +Rails also doesn't support automatic load balancing of replicas. This is very +dependent on your infrastructure. We may implement basic, primitive load balancing +in the future, but for an application at scale this should be something your application +handles outside of Rails. + +### Joining Across Databases + +Applications cannot join across databases. Rails 6.1 will support using `has_many` +relationships and creating 2 queries instead of joining, but Rails 6.0 will require +you to split the joins into 2 selects manually. + +### Schema Cache + +If you use a schema cache and multiple databases you'll need to write an initializer +that loads the schema cache from your app. This wasn't an issue we could resolve in +time for Rails 6.0 but hope to have it in a future version soon. diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md index e40f16e62d..5fb030fad4 100644 --- a/guides/source/active_record_querying.md +++ b/guides/source/active_record_querying.md @@ -1821,6 +1821,21 @@ Client.limit(1).pluck(:name) # => ["David"] ``` +NOTE: You should also know that using `pluck` will trigger eager loading if the relation object contains include values, even if the eager loading is not necessary for the query. For example: + +```ruby +# store association for reusing it +assoc = Company.includes(:account) +assoc.pluck(:id) +# SELECT "companies"."id" FROM "companies" LEFT OUTER JOIN "accounts" ON "accounts"."id" = "companies"."account_id" +``` + +One way to avoid this is to `unscope` the includes: + +```ruby +assoc.unscope(:includes).pluck(:id) +``` + ### `ids` `ids` can be used to pluck all the IDs for the relation using the table's primary key. diff --git a/guides/source/active_storage_overview.md b/guides/source/active_storage_overview.md index 615f576797..54f8f5c2b5 100644 --- a/guides/source/active_storage_overview.md +++ b/guides/source/active_storage_overview.md @@ -41,6 +41,10 @@ application (or upgrading your application to Rails 5.2), run `rails active_storage:install` to generate a migration that creates these tables. Use `rails db:migrate` to run the migration. +WARNING: `active_storage_attachments` is a polymorphic join table that stores your model's class name. If your model's class name changes, you will need to run a migration on this table to update the underlying `record_type` to your model's new class name. + +WARNING: If you are using UUIDs instead of integers as the primary key on your models you will need to change the column type of `record_id` for the `active_storage_attachments` table in the generated migration accordingly. + Declare Active Storage services in `config/storage.yml`. For each service your application uses, provide a name and the requisite configuration. The example below declares three services named `local`, `test`, and `amazon`: @@ -189,14 +193,21 @@ gem "google-cloud-storage", "~> 1.11", require: false ### Mirror Service -You can keep multiple services in sync by defining a mirror service. When a file -is uploaded or deleted, it's done across all the mirrored services. Mirrored -services can be used to facilitate a migration between services in production. -You can start mirroring to the new service, copy existing files from the old -service to the new, then go all-in on the new service. Define each of the -services you'd like to use as described above and reference them from a mirrored +You can keep multiple services in sync by defining a mirror service. A mirror +service replicates uploads and deletes across two or more subordinate services. + +A mirror service is intended to be used temporarily during a migration between +services in production. You can start mirroring to a new service, copy +pre-existing files from the old service to the new, then go all-in on the new service. +NOTE: Mirroring is not atomic. It is possible for an upload to succeed on the +primary service and fail on any of the subordinate services. Before going +all-in on a new service, verify that all files have been copied. + +Define each of the services you'd like to mirror as described above. Reference +them by name when defining a mirror service: + ```yaml s3_west_coast: service: S3 @@ -219,9 +230,12 @@ production: - s3_west_coast ``` -NOTE: Files are served from the primary service. +Although all secondary services receive uploads, downloads are always handled +by the primary service. -NOTE: This is not compatible with the [direct uploads](#direct-uploads) feature. +Mirror services are compatible with direct uploads. New files are directly +uploaded to the primary service. When a directly-uploaded file is attached to a +record, a background job is enqueued to copy it to the secondary services. Attaching Files to Records -------------------------- @@ -386,6 +400,10 @@ helper allows you to set the disposition. rails_blob_path(user.avatar, disposition: "attachment") ``` +WARNING: To prevent XSS attacks, ActiveStorage forces the Content-Disposition header +to "attachment" for some kind of files. To change this behaviour see the +available configuration opions in [Configuring Rails Applications](configuring.html#configuring-active-storage). + If you need to create a link from outside of controller/view context (Background jobs, Cronjobs, etc.), you can access the rails_blob_path like this: diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md index 1a057832d4..f36cacfe8d 100644 --- a/guides/source/active_support_core_extensions.md +++ b/guides/source/active_support_core_extensions.md @@ -155,15 +155,6 @@ Complex(1).duplicable? # => true 1.method(:+).duplicable? # => false ``` -`duplicable?` matches the current Ruby version's `dup` behavior, -so results will vary according the version of Ruby you're using. -In Ruby 2.4, for example, Complex and Rational are not duplicable: - -```ruby -Rational(1).duplicable? # => false -Complex(1).duplicable? # => false -``` - WARNING: Any class can disallow duplication by removing `dup` and `clone` or raising exceptions from them. Thus only `rescue` can tell whether a given arbitrary object is duplicable. `duplicable?` depends on the hard-coded list above, but it is much faster than `rescue`. Use it only if you know the hard-coded list is enough in your use case. NOTE: Defined in `active_support/core_ext/object/duplicable.rb`. @@ -2358,10 +2349,6 @@ There's also a related idiom that uses the splat operator: [*object] ``` -which in Ruby 1.8 returns `[nil]` for `nil`, and calls to `Array(object)` otherwise. (Please if you know the exact behavior in 1.9 contact fxn.) - -Thus, in this case the behavior is different for `nil`, and the differences with `Kernel#Array` explained above apply to the rest of `object`s. - NOTE: Defined in `active_support/core_ext/array/wrap.rb`. ### Duplicating @@ -2633,14 +2620,12 @@ The method `stringify_keys` returns a hash that has a stringified version of the # => {"" => nil, "1" => 1, "a" => :a} ``` -In case of key collision, one of the values will be chosen. The chosen value may not always be the same given the same hash: +In case of key collision, the value will be the one most recently inserted into the hash: ```ruby {"a" => 1, a: 2}.stringify_keys -# The result could either be +# The result will be # => {"a"=>2} -# or -# => {"a"=>1} ``` This method may be useful for example to easily accept both symbols and strings as options. For instance `ActionView::Helpers::FormHelper` defines: @@ -2677,14 +2662,12 @@ The method `symbolize_keys` returns a hash that has a symbolized version of the WARNING. Note in the previous example only one key was symbolized. -In case of key collision, one of the values will be chosen. The chosen value may not always be the same given the same hash: +In case of key collision, the value will be the one most recently inserted into the hash: ```ruby {"a" => 1, a: 2}.symbolize_keys -# The result could either be +# The result will be # => {:a=>2} -# or -# => {:a=>1} ``` This method may be useful for example to easily accept both symbols and strings as options. For instance `ActionController::UrlRewriter` defines @@ -3420,56 +3403,56 @@ NOTE: Defined in `active_support/core_ext/date_and_time/calculations.rb`. #### `prev_day`, `next_day` -In Ruby 1.9 `prev_day` and `next_day` return the date in the last or next day: +`prev_day` and `next_day` return the time in the last or next day: ```ruby -d = Date.new(2010, 5, 8) # => Sat, 08 May 2010 -d.prev_day # => Fri, 07 May 2010 -d.next_day # => Sun, 09 May 2010 +t = Time.new(2010, 5, 8) # => 2010-05-08 00:00:00 +0900 +t.prev_day # => 2010-05-07 00:00:00 +0900 +t.next_day # => 2010-05-09 00:00:00 +0900 ``` -NOTE: Defined in `active_support/core_ext/date_and_time/calculations.rb`. +NOTE: Defined in `active_support/core_ext/time/calculations.rb`. #### `prev_month`, `next_month` -In Ruby 1.9 `prev_month` and `next_month` return the date with the same day in the last or next month: +`prev_month` and `next_month` return the time with the same day in the last or next month: ```ruby -d = Date.new(2010, 5, 8) # => Sat, 08 May 2010 -d.prev_month # => Thu, 08 Apr 2010 -d.next_month # => Tue, 08 Jun 2010 +t = Time.new(2010, 5, 8) # => 2010-05-08 00:00:00 +0900 +t.prev_month # => 2010-04-08 00:00:00 +0900 +t.next_month # => 2010-06-08 00:00:00 +0900 ``` If such a day does not exist, the last day of the corresponding month is returned: ```ruby -Date.new(2000, 5, 31).prev_month # => Sun, 30 Apr 2000 -Date.new(2000, 3, 31).prev_month # => Tue, 29 Feb 2000 -Date.new(2000, 5, 31).next_month # => Fri, 30 Jun 2000 -Date.new(2000, 1, 31).next_month # => Tue, 29 Feb 2000 +Time.new(2000, 5, 31).prev_month # => 2000-04-30 00:00:00 +0900 +Time.new(2000, 3, 31).prev_month # => 2000-02-29 00:00:00 +0900 +Time.new(2000, 5, 31).next_month # => 2000-06-30 00:00:00 +0900 +Time.new(2000, 1, 31).next_month # => 2000-02-29 00:00:00 +0900 ``` -NOTE: Defined in `active_support/core_ext/date_and_time/calculations.rb`. +NOTE: Defined in `active_support/core_ext/time/calculations.rb`. #### `prev_year`, `next_year` -In Ruby 1.9 `prev_year` and `next_year` return a date with the same day/month in the last or next year: +`prev_year` and `next_year` return a time with the same day/month in the last or next year: ```ruby -d = Date.new(2010, 5, 8) # => Sat, 08 May 2010 -d.prev_year # => Fri, 08 May 2009 -d.next_year # => Sun, 08 May 2011 +t = Time.new(2010, 5, 8) # => 2010-05-08 00:00:00 +0900 +t.prev_year # => 2009-05-08 00:00:00 +0900 +t.next_year # => 2011-05-08 00:00:00 +0900 ``` If date is the 29th of February of a leap year, you obtain the 28th: ```ruby -d = Date.new(2000, 2, 29) # => Tue, 29 Feb 2000 -d.prev_year # => Sun, 28 Feb 1999 -d.next_year # => Wed, 28 Feb 2001 +t = Time.new(2000, 2, 29) # => 2000-02-29 00:00:00 +0900 +t.prev_year # => 1999-02-28 00:00:00 +0900 +t.next_year # => 2001-02-28 00:00:00 +0900 ``` -NOTE: Defined in `active_support/core_ext/date_and_time/calculations.rb`. +NOTE: Defined in `active_support/core_ext/time/calculations.rb`. #### `prev_quarter`, `next_quarter` diff --git a/guides/source/active_support_instrumentation.md b/guides/source/active_support_instrumentation.md index 4868b00bbe..9f15e70da6 100644 --- a/guides/source/active_support_instrumentation.md +++ b/guides/source/active_support_instrumentation.md @@ -643,7 +643,16 @@ The block receives the following arguments: ```ruby ActiveSupport::Notifications.subscribe "process_action.action_controller" do |name, started, finished, unique_id, data| # your own custom stuff - Rails.logger.info "#{name} Received!" + Rails.logger.info "#{name} Received! (started: #{started}, finished: #{finished})" # process_action.action_controller Received (started: 2019-05-05 13:43:57 -0800, finished: 2019-05-05 13:43:58 -0800) +end +``` + +If you are concerned about the accuracy of `started` and `finished` to compute a precise elapsed time then use `ActiveSupport::Notifications.monotonic_subscribe`. The given block would receive the same arguments as above but the `started` and `finished` will have values with an accurate monotonic time instead of wall-clock time. + +```ruby +ActiveSupport::Notifications.monotonic_subscribe "process_action.action_controller" do |name, started, finished, unique_id, data| + # your own custom stuff + Rails.logger.info "#{name} Received! (started: #{started}, finished: #{finished})" # process_action.action_controller Received (started: 1560978.425334, finished: 1560979.429234) end ``` diff --git a/guides/source/association_basics.md b/guides/source/association_basics.md index 62e9270539..27387ac3ac 100644 --- a/guides/source/association_basics.md +++ b/guides/source/association_basics.md @@ -2451,8 +2451,8 @@ Extensions can refer to the internals of the association proxy using these three * `proxy_association.reflection` returns the reflection object that describes the association. * `proxy_association.target` returns the associated object for `belongs_to` or `has_one`, or the collection of associated objects for `has_many` or `has_and_belongs_to_many`. -Single Table Inheritance ------------------------- +Single Table Inheritance (STI) +------------------------------ Sometimes, you may want to share fields and behavior between different models. Let's say we have Car, Motorcycle, and Bicycle models. We will want to share diff --git a/guides/source/autoloading_and_reloading_constants.md b/guides/source/autoloading_and_reloading_constants.md index 7dfc39e192..8cd2d353de 100644 --- a/guides/source/autoloading_and_reloading_constants.md +++ b/guides/source/autoloading_and_reloading_constants.md @@ -1,18 +1,18 @@ **DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON https://guides.rubyonrails.org.** -Autoloading and Reloading Constants -=================================== +Autoloading and Reloading Constants (Zeitwerk Mode) +====================================================== -This guide documents how constant autoloading and reloading works. +This guide documents how autoloading and reloading works in `zeitwerk` mode. After reading this guide, you will know: -* Key aspects of Ruby constants -* What are the `autoload_paths` and how does eager loading work in production? -* How constant autoloading works -* What is `require_dependency` -* How constant reloading works -* Solutions to common autoloading gotchas +* Autoloading modes +* Related Rails configuration +* Project structure +* Autoloading, reloading, and eager loading +* Single Table Inheritance +* And more -------------------------------------------------------------------------------- @@ -20,13 +20,15 @@ After reading this guide, you will know: Introduction ------------ -Ruby on Rails allows applications to be written as if their code was preloaded. +INFO. This guide documents autoloading in `zeitwerk` mode, which is new in Rails 6. If you'd like to read about `classic` mode instead, please check [Autoloading and Reloading Constants (Classic Mode)](autoloading_and_reloading_constants_classic_mode.html). -In a normal Ruby program classes need to load their dependencies: +In a normal Ruby program, dependencies need to be loaded by hand. For example, the following controller uses classes `ApplicationController` and `Post`, and normally you'd need to put `require` calls for them: ```ruby -require 'application_controller' -require 'post' +# DO NOT DO THIS. +require "application_controller" +require "post" +# DO NOT DO THIS. class PostsController < ApplicationController def index @@ -35,16 +37,7 @@ class PostsController < ApplicationController end ``` -Our Rubyist instinct quickly sees some redundancy in there: If classes were -defined in files matching their name, couldn't their loading be automated -somehow? We could save scanning the file for dependencies, which is brittle. - -Moreover, `Kernel#require` loads files once, but development is much more smooth -if code gets refreshed when it changes without restarting the server. It would -be nice to be able to use `Kernel#load` in development, and `Kernel#require` in -production. - -Indeed, those features are provided by Ruby on Rails, where we just write +This is not the case in Rails applications, where application classes and modules are just available everywhere: ```ruby class PostsController < ApplicationController @@ -54,1330 +47,255 @@ class PostsController < ApplicationController end ``` -This guide documents how that works. - - -Constants Refresher -------------------- - -While constants are trivial in most programming languages, they are a rich -topic in Ruby. - -It is beyond the scope of this guide to document Ruby constants, but we are -nevertheless going to highlight a few key topics. Truly grasping the following -sections is instrumental to understanding constant autoloading and reloading. - -### Nesting - -Class and module definitions can be nested to create namespaces: - -```ruby -module XML - class SAXParser - # (1) - end -end -``` - -The *nesting* at any given place is the collection of enclosing nested class and -module objects outwards. The nesting at any given place can be inspected with -`Module.nesting`. For example, in the previous example, the nesting at -(1) is - -```ruby -[XML::SAXParser, XML] -``` - -It is important to understand that the nesting is composed of class and module -*objects*, it has nothing to do with the constants used to access them, and is -also unrelated to their names. - -For instance, while this definition is similar to the previous one: - -```ruby -class XML::SAXParser - # (2) -end -``` - -the nesting in (2) is different: - -```ruby -[XML::SAXParser] -``` - -`XML` does not belong to it. - -We can see in this example that the name of a class or module that belongs to a -certain nesting does not necessarily correlate with the namespaces at the spot. - -Even more, they are totally independent, take for instance - -```ruby -module X - module Y - end -end - -module A - module B - end -end - -module X::Y - module A::B - # (3) - end -end -``` - -The nesting in (3) consists of two module objects: - -```ruby -[A::B, X::Y] -``` - -So, it not only doesn't end in `A`, which does not even belong to the nesting, -but it also contains `X::Y`, which is independent from `A::B`. - -The nesting is an internal stack maintained by the interpreter, and it gets -modified according to these rules: - -* The class object following a `class` keyword gets pushed when its body is -executed, and popped after it. - -* The module object following a `module` keyword gets pushed when its body is -executed, and popped after it. - -* A singleton class opened with `class << object` gets pushed, and popped later. - -* When `instance_eval` is called using a string argument, -the singleton class of the receiver is pushed to the nesting of the eval'ed -code. When `class_eval` or `module_eval` is called using a string argument, -the receiver is pushed to the nesting of the eval'ed code. - -* The nesting at the top-level of code interpreted by `Kernel#load` is empty -unless the `load` call receives a true value as second argument, in which case -a newly created anonymous module is pushed by Ruby. - -It is interesting to observe that blocks do not modify the stack. In particular -the blocks that may be passed to `Class.new` and `Module.new` do not get the -class or module being defined pushed to their nesting. That's one of the -differences between defining classes and modules in one way or another. - -### Class and Module Definitions are Constant Assignments - -Let's suppose the following snippet creates a class (rather than reopening it): - -```ruby -class C -end -``` - -Ruby creates a constant `C` in `Object` and stores in that constant a class -object. The name of the class instance is "C", a string, named after the -constant. +Idiomatic Rails applications only issue `require` calls to load stuff from their `lib` directory, the Ruby standard library, Ruby gems, etc. That is, anything that does not belong to their autoload paths, explained below. -That is, -```ruby -class Project < ApplicationRecord -end -``` +Enabling Zeitwerk Mode +---------------------- -performs a constant assignment equivalent to +The autoloading `zeitwerk` mode is enabled by default in Rails 6 applications running on CRuby: ```ruby -Project = Class.new(ApplicationRecord) +# config/application.rb +config.load_defaults "6.x" # enables zeitwerk mode in CRuby ``` -including setting the name of the class as a side-effect: +In `zeitwerk` mode, Rails uses [Zeitwerk](https://github.com/fxn/zeitwerk) internally to autoload, reload, and eager load. Rails instantiates and configures a dedicated Zeitwerk instance that manages the project. -```ruby -Project.name # => "Project" -``` +INFO. You do not configure Zeitwerk manually in a Rails application. Rather, you configure the application using the portable configuration points explained in this guide, and Rails translates that to Zeitwerk on your behalf. -Constant assignment has a special rule to make that happen: if the object -being assigned is an anonymous class or module, Ruby sets the object's name to -the name of the constant. +Project Structure +----------------- -INFO. From then on, what happens to the constant and the instance does not -matter. For example, the constant could be deleted, the class object could be -assigned to a different constant, be stored in no constant anymore, etc. Once -the name is set, it doesn't change. +In a Rails application file names have to match the constants they define, with directories acting as namespaces. -Similarly, module creation using the `module` keyword as in +For example, the file `app/helpers/users_helper.rb` should define `UsersHelper` and the file `app/controllers/admin/payments_controller.rb` should define `Admin::PaymentsController`. -```ruby -module Admin -end -``` - -performs a constant assignment equivalent to +Rails configures Zeitwerk to inflect file names with `String#camelize`. For example, it expects that `app/controllers/users_controller.rb` defines the constant `UsersController` because ```ruby -Admin = Module.new +"users_controller".camelize # => UsersController ``` -including setting the name as a side-effect: +If you need to customize any of these inflections, for example to add an acronym, please have a look at `config/initializers/inflections.rb`. -```ruby -Admin.name # => "Admin" -``` +Please, check the [Zeitwerk documentation](https://github.com/fxn/zeitwerk#file-structure) for further details. -WARNING. The execution context of a block passed to `Class.new` or `Module.new` -is not entirely equivalent to the one of the body of the definitions using the -`class` and `module` keywords. But both idioms result in the same constant -assignment. - -Thus, an informal expression like "the `String` class" technically means the -class object stored in the constant called "String". That constant, in turn, -belongs to the class object stored in the constant called "Object". - -`String` is an ordinary constant, and everything related to them such as -resolution algorithms applies to it. - -Likewise, in the controller - -```ruby -class PostsController < ApplicationController - def index - @posts = Post.all - end -end -``` - -`Post` is not syntax for a class. Rather, `Post` is a regular Ruby constant. If -all is good, the constant is evaluated to an object that responds to `all`. +Autoload paths +-------------- -That is why we talk about *constant* autoloading, Rails has the ability to -load constants on the fly. +We call _autoload paths_ to the list of application directories whose contents are to be autoloaded. For example, `app/models`. Such directories represent the root namespace: `Object`. -### Constants are Stored in Modules +INFO. Autoload paths are called _root directories_ in Zeitwerk documentation, but we'll stay with "autoload path" in this guide. -Constants belong to modules in a very literal sense. Classes and modules have -a constant table; think of it as a hash table. +Within an autoload path, file names must match the constants they define as documented [here](https://github.com/fxn/zeitwerk#file-structure). -Let's analyze an example to really understand what that means. While common -abuses of language like "the `String` class" are convenient, the exposition is -going to be precise here for didactic purposes. +By default, the autoload paths of an application consist of all the subdirectories of `app` that exist when the application boots ---except for `aasets`, `javascripts`, `views`,--- plus the autoload paths of engines it might depend on. -Let's consider the following module definition: +For example, if `UsersHelper` is implemented in `app/helpers/users_helper.rb`, the module is autoloadable, you do not need (and should not write) a `require` call for it: -```ruby -module Colors - RED = '0xff0000' -end ``` - -First, when the `module` keyword is processed, the interpreter creates a new -entry in the constant table of the class object stored in the `Object` constant. -Said entry associates the name "Colors" to a newly created module object. -Furthermore, the interpreter sets the name of the new module object to be the -string "Colors". - -Later, when the body of the module definition is interpreted, a new entry is -created in the constant table of the module object stored in the `Colors` -constant. That entry maps the name "RED" to the string "0xff0000". - -In particular, `Colors::RED` is totally unrelated to any other `RED` constant -that may live in any other class or module object. If there were any, they -would have separate entries in their respective constant tables. - -Pay special attention in the previous paragraphs to the distinction between -class and module objects, constant names, and value objects associated to them -in constant tables. - -### Resolution Algorithms - -#### Resolution Algorithm for Relative Constants - -At any given place in the code, let's define *cref* to be the first element of -the nesting if it is not empty, or `Object` otherwise. - -Without getting too much into the details, the resolution algorithm for relative -constant references goes like this: - -1. If the nesting is not empty the constant is looked up in its elements and in -order. The ancestors of those elements are ignored. - -2. If not found, then the algorithm walks up the ancestor chain of the cref. - -3. If not found and the cref is a module, the constant is looked up in `Object`. - -4. If not found, `const_missing` is invoked on the cref. The default -implementation of `const_missing` raises `NameError`, but it can be overridden. - -Rails autoloading **does not emulate this algorithm**, but its starting point is -the name of the constant to be autoloaded, and the cref. See more in [Relative -References](#autoloading-algorithms-relative-references). - -#### Resolution Algorithm for Qualified Constants - -Qualified constants look like this: - -```ruby -Billing::Invoice +$ bin/rails runner 'p UsersHelper' +UsersHelper ``` -`Billing::Invoice` is composed of two constants: `Billing` is relative and is -resolved using the algorithm of the previous section. - -INFO. Leading colons would make the first segment absolute rather than -relative: `::Billing::Invoice`. That would force `Billing` to be looked up -only as a top-level constant. - -`Invoice` on the other hand is qualified by `Billing` and we are going to see -its resolution next. Let's define *parent* to be that qualifying class or module -object, that is, `Billing` in the example above. The algorithm for qualified -constants goes like this: - -1. The constant is looked up in the parent and its ancestors. In Ruby >= 2.5, -`Object` is skipped if present among the ancestors. `Kernel` and `BasicObject` -are still checked though. +Autoload paths automatically pick any custom directories under `app`. For example, if your application has `app/presenters`, or `app/services`, etc., they are added to autoload paths. -2. If the lookup fails, `const_missing` is invoked in the parent. The default -implementation of `const_missing` raises `NameError`, but it can be overridden. +The array of autoload paths can be extended by mutating `config.autoload_paths`, in `config/application.rb`, but nowadays this is discouraged. -INFO. In Ruby < 2.5 `String::Hash` evaluates to `Hash` and the interpreter -issues a warning: "toplevel constant Hash referenced by String::Hash". Starting -with 2.5, `String::Hash` raises `NameError` because `Object` is skipped. +WARNING. Please, do not mutate `ActiveSupport::Dependencies.autoload_paths`, the public interface to change autoload paths is `config.autoload_paths`. -As you see, this algorithm is simpler than the one for relative constants. In -particular, the nesting plays no role here, and modules are not special-cased, -if neither they nor their ancestors have the constants, `Object` is **not** -checked. -Rails autoloading **does not emulate this algorithm**, but its starting point is -the name of the constant to be autoloaded, and the parent. See more in -[Qualified References](#autoloading-algorithms-qualified-references). - - -Vocabulary +$LOAD_PATH ---------- -### Parent Namespaces - -Given a string with a constant path we define its *parent namespace* to be the -string that results from removing its rightmost segment. - -For example, the parent namespace of the string "A::B::C" is the string "A::B", -the parent namespace of "A::B" is "A", and the parent namespace of "A" is "". - -The interpretation of a parent namespace when thinking about classes and modules -is tricky though. Let's consider a module M named "A::B": - -* The parent namespace, "A", may not reflect nesting at a given spot. - -* The constant `A` may no longer exist, some code could have removed it from -`Object`. - -* If `A` exists, the class or module that was originally in `A` may not be there -anymore. For example, if after a constant removal there was another constant -assignment there would generally be a different object in there. - -* In such case, it could even happen that the reassigned `A` held a new class or -module called also "A"! - -* In the previous scenarios M would no longer be reachable through `A::B` but -the module object itself could still be alive somewhere and its name would -still be "A::B". - -The idea of a parent namespace is at the core of the autoloading algorithms -and helps explain and understand their motivation intuitively, but as you see -that metaphor leaks easily. Given an edge case to reason about, take always into -account that by "parent namespace" the guide means exactly that specific string -derivation. - -### Loading Mechanism - -Rails autoloads files with `Kernel#load` when `config.cache_classes` is false, -the default in development mode, and with `Kernel#require` otherwise, the -default in production mode. - -`Kernel#load` allows Rails to execute files more than once if [constant -reloading](#constant-reloading) is enabled. - -This guide uses the word "load" freely to mean a given file is interpreted, but -the actual mechanism can be `Kernel#load` or `Kernel#require` depending on that -flag. - - -Autoloading Availability ------------------------- - -Rails is always able to autoload provided its environment is in place. For -example the `runner` command autoloads: - -``` -$ rails runner 'p User.column_names' -["id", "email", "created_at", "updated_at"] -``` - -The console autoloads, the test suite autoloads, and of course the application -autoloads. - -By default, Rails eager loads the application files when it boots in production -mode, so most of the autoloading going on in development does not happen. But -autoloading may still be triggered during eager loading. - -For example, given - -```ruby -class BeachHouse < House -end -``` - -if `House` is still unknown when `app/models/beach_house.rb` is being eager -loaded, Rails autoloads it. - - -autoload_paths and eager_load_paths ------------------------------------ - -As you probably know, when `require` gets a relative file name: +Autoload paths are added to `$LOAD_PATH` by default. However, Zeitwerk uses absolute file names internally, and your application should not issue `require` calls for autoloadable files, so those directories are actually not needed there. You can opt-out with this flag: ```ruby -require 'erb' +config.add_autoload_paths_to_load_path = false ``` -Ruby looks for the file in the directories listed in `$LOAD_PATH`. That is, Ruby -iterates over all its directories and for each one of them checks whether they -have a file called "erb.rb", or "erb.so", or "erb.o", or "erb.dll". If it finds -any of them, the interpreter loads it and ends the search. Otherwise, it tries -again in the next directory of the list. If the list gets exhausted, `LoadError` -is raised. - -We are going to cover how constant autoloading works in more detail later, but -the idea is that when a constant like `Post` is hit and missing, if there's a -`post.rb` file for example in `app/models` Rails is going to find it, evaluate -it, and have `Post` defined as a side-effect. - -All right, Rails has a collection of directories similar to `$LOAD_PATH` in which -to look up `post.rb`. That collection is called `autoload_paths` and by -default it contains: - -* All subdirectories of `app` in the application and engines present at boot - time. For example, `app/controllers`. They do not need to be the default - ones, any custom directories like `app/workers` belong automatically to - `autoload_paths`. +That may speed legit `require` calls a bit, since there are less lookups. Also, if your application uses [Bootsnap](https://github.com/Shopify/bootsnap), that saves the library from building unnecessary indexes, and saves the RAM they would need. -* Any existing second level directories called `app/*/concerns` in the - application and engines. -* The directory `test/mailers/previews`. +Reloading +--------- -`eager_load_paths` is initially the `app` paths above +Rails automatically reloads classes and modules if application files change. -How files are autoloaded depends on `eager_load` and `cache_classes` config settings which typically vary in development, production, and test modes: +More precisely, if the web server is running and application files have been modified, Rails unloads all autoloaded constants just before the next request is processed. That way, application classes or modules used during that request are going to be autoloaded, thus picking up their current implementation in the file system. - * In **development**, you want quicker startup with incremental loading of application code. So `eager_load` should be set to `false`, and Rails will autoload files as needed (see [Autoloading Algorithms](#autoloading-algorithms) below) -- and then reload them when they change (see [Constant Reloading](#constant-reloading) below). - * In **production**, however, you want consistency and thread-safety and can live with a longer boot time. So `eager_load` is set to `true`, and then during boot (before the app is ready to receive requests) Rails loads all files in the `eager_load_paths` and then turns off auto loading (NB: autoloading may be needed during eager loading). Not autoloading after boot is a `good thing`, as autoloading can cause the app to be have thread-safety problems. - * In **test**, for speed of execution (of individual tests) `eager_load` is `false`, so Rails follows development behaviour. +Reloading can be enabled or disabled. The setting that controls this behavior is `config.cache_classes`, which is false by default in `development` mode (reloading enabled), and true by default in `production` mode (reloading disabled). -What is described above are the defaults with a newly generated Rails app. There are multiple ways this can be configured differently (see [Configuring Rails Applications](configuring.html#rails-general-configuration). -). But using `autoload_paths` on its own in the past (before Rails 5) developers might configure `autoload_paths` to add in extra locations (e.g. `lib` which used to be an autoload path list years ago, but no longer is). However this is now discouraged for most purposes, as it is likely to lead to production-only errors. It is possible to add new locations to both `config.eager_load_paths` and `config.autoload_paths` but use at your own risk. +Rails detects files have changed using an evented file monitor (default), or walking the autoload paths, depending on `config.file_watcher`. -See also [Autoloading in the Test Environment](#autoloading-in-the-test-environment). +In a Rails console there is no file watcher active regardless of the value of `config.cache_classes`. This is so because, normally, it would be confusing to have code reloaded in the middle of a console session, the same way you generally want an individual request to be served by a consistent, non-changing set of application classes and modules. -`config.autoload_paths` is not changeable from environment-specific configuration files. - -The value of `autoload_paths` can be inspected. In a just-generated application -it is (edited): +However, you can force a reload in the console executing `reload!`: ``` -$ rails r 'puts ActiveSupport::Dependencies.autoload_paths' -.../app/assets -.../app/channels -.../app/controllers -.../app/controllers/concerns -.../app/helpers -.../app/jobs -.../app/mailers -.../app/models -.../app/models/concerns -.../activestorage/app/assets -.../activestorage/app/controllers -.../activestorage/app/javascript -.../activestorage/app/jobs -.../activestorage/app/models -.../actioncable/app/assets -.../actionview/app/assets -.../test/mailers/previews +$ bin/rails c +Loading development environment (Rails 6.0.0) +irb(main):001:0> User.object_id +=> 70136277390120 +irb(main):002:0> reload! +Reloading... +=> true +irb(main):003:0> User.object_id +=> 70136284426020 ``` -INFO. `autoload_paths` is computed and cached during the initialization process. -The application needs to be restarted to reflect any changes in the directory -structure. +as you can see, the class object stored in the `User` constant is different after reloading. +### Reloading and Stale Objects -Autoloading Algorithms ----------------------- +It is very important to understand that Ruby does not have a way to truly reload classes and modules in memory, and have that reflected everywhere they are already used. Technically, "unloading" the `User` class means removing the `User` constant via `Object.send(:remove_const, "User")`. -### Relative References +Therefore, if you store a reloadable class or module object in a place that is not reloaded, that value is going to become stale. -A relative constant reference may appear in several places, for example, in +For example, if an initializer stores and caches a certain class object ```ruby -class PostsController < ApplicationController - def index - @posts = Post.all - end -end +# config/initializers/configure_payment_gateway.rb +# DO NOT DO THIS. +$PAYMENT_GATEWAY = Rails.env.production? ? RealGateway : MockedGateway +# DO NOT DO THIS. ``` -all three constant references are relative. - -#### Constants after the `class` and `module` Keywords - -Ruby performs a lookup for the constant that follows a `class` or `module` -keyword because it needs to know if the class or module is going to be created -or reopened. - -If the constant is not defined at that point it is not considered to be a -missing constant, autoloading is **not** triggered. - -So, in the previous example, if `PostsController` is not defined when the file -is interpreted Rails autoloading is not going to be triggered, Ruby will just -define the controller. - -#### Top-Level Constants - -On the contrary, if `ApplicationController` is unknown, the constant is -considered missing and an autoload is going to be attempted by Rails. - -In order to load `ApplicationController`, Rails iterates over `autoload_paths`. -First it checks if `app/assets/application_controller.rb` exists. If it does not, -which is normally the case, it continues and finds -`app/controllers/application_controller.rb`. +and `MockedGateway` gets reloaded, `$PAYMENT_GATEWAY` still stores the class object `MockedGateway` evaluated to when the initializer ran. Reloading does not change the class object stored in `$PAYMENT_GATEWAY`. -If the file defines the constant `ApplicationController` all is fine, otherwise -`LoadError` is raised: +Similarly, in the Rails console, if you have a user instance and reload: ``` -unable to autoload constant ApplicationController, expected -<full path to application_controller.rb> to define it (LoadError) +> user = User.new +> reload! ``` -INFO. Rails does not require the value of autoloaded constants to be a class or -module object. For example, if the file `app/models/max_clients.rb` defines -`MAX_CLIENTS = 100` autoloading `MAX_CLIENTS` works just fine. - -#### Namespaces +the `user` object is instance of a stale class object. Ruby gives you a new class if you evaluate `User` again, but does not update the class `user` is instance of. -Autoloading `ApplicationController` looks directly under the directories of -`autoload_paths` because the nesting in that spot is empty. The situation of -`Post` is different, the nesting in that line is `[PostsController]` and support -for namespaces comes into play. - -The basic idea is that given +Another use case of this gotcha is subclassing reloadable classes in a place that is not reloaded: ```ruby -module Admin - class BaseController < ApplicationController - @@all_roles = Role.all - end +# lib/vip_user.rb +class VipUser < User end ``` -to autoload `Role` we are going to check if it is defined in the current or -parent namespaces, one at a time. So, conceptually we want to try to autoload -any of - -``` -Admin::BaseController::Role -Admin::Role -Role -``` - -in that order. That's the idea. To do so, Rails looks in `autoload_paths` -respectively for file names like these: - -``` -admin/base_controller/role.rb -admin/role.rb -role.rb -``` - -modulus some additional directory lookups we are going to cover soon. - -INFO. `'Constant::Name'.underscore` gives the relative path without extension of -the file name where `Constant::Name` is expected to be defined. - -Let's see how Rails autoloads the `Post` constant in the `PostsController` -above assuming the application has a `Post` model defined in -`app/models/post.rb`. - -First it checks for `posts_controller/post.rb` in `autoload_paths`: - -``` -app/assets/posts_controller/post.rb -app/controllers/posts_controller/post.rb -app/helpers/posts_controller/post.rb -... -test/mailers/previews/posts_controller/post.rb -``` - -Since the lookup is exhausted without success, a similar search for a directory -is performed, we are going to see why in the [next section](#automatic-modules): +if `User` is reloaded, since `VipUser` is not, the superclass of `VipUser` is the original stale class object. -``` -app/assets/posts_controller/post -app/controllers/posts_controller/post -app/helpers/posts_controller/post -... -test/mailers/previews/posts_controller/post -``` +Bottom line: **do not cache reloadable classes or modules**. -If all those attempts fail, then Rails starts the lookup again in the parent -namespace. In this case only the top-level remains: -``` -app/assets/post.rb -app/controllers/post.rb -app/helpers/post.rb -app/mailers/post.rb -app/models/post.rb -``` +Eager Loading +------------- -A matching file is found in `app/models/post.rb`. The lookup stops there and the -file is loaded. If the file actually defines `Post` all is fine, otherwise -`LoadError` is raised. +In production-like environments it is generally better to load all the application code when the application boots. Eager loading puts everything in memory ready to serve requests right away, and it is also [CoW](https://en.wikipedia.org/wiki/Copy-on-write)-friendly. -### Qualified References +Eager loading is controlled by the flag `config.eager_load`, which is enabled by default in `production` mode. -When a qualified constant is missing Rails does not look for it in the parent -namespaces. But there is a caveat: when a constant is missing, Rails is -unable to tell if the trigger was a relative reference or a qualified one. +The order in which files are eager loaded is undefined. -For example, consider +if the `Zeitwerk` constant is defined, Rails invokes `Zeitwerk::Loader.eager_load_all` regardless of the application autoloading mode. That ensures dependencies managed by Zeitwerk are eager loaded. -```ruby -module Admin - User -end -``` -and - -```ruby -Admin::User -``` - -If `User` is missing, in either case all Rails knows is that a constant called -"User" was missing in a module called "Admin". +Single Table Inheritance +------------------------ -If there is a top-level `User` Ruby would resolve it in the former example, but -wouldn't in the latter. In general, Rails does not emulate the Ruby constant -resolution algorithms, but in this case it tries using the following heuristic: +Single Table Inheritance is a feature that doesn't play well with lazy loading. Reason is, its API generally needs to be able to enumerate the STI hierarchy to work correctly, whereas lazy loading defers loading classes until they are referenced. You can't enumerate what you haven't referenced yet. -> If none of the parent namespaces of the class or module has the missing -> constant then Rails assumes the reference is relative. Otherwise qualified. +In a sense, applications need to eager load STI hierarchies regardless of the loading mode. -For example, if this code triggers autoloading +Of course, if the application eager loads on boot, that is already accomplished. When it does not, it is in practice enough to instantiate the existing types in the database, which in development or test modes is usually fine. One way to do that is to throw this module into the `lib` directory: ```ruby -Admin::User -``` - -and the `User` constant is already present in `Object`, it is not possible that -the situation is - -```ruby -module Admin - User -end -``` - -because otherwise Ruby would have resolved `User` and no autoloading would have -been triggered in the first place. Thus, Rails assumes a qualified reference and -considers the file `admin/user.rb` and directory `admin/user` to be the only -valid options. - -In practice, this works quite well as long as the nesting matches all parent -namespaces respectively and the constants that make the rule apply are known at -that time. - -However, autoloading happens on demand. If by chance the top-level `User` was -not yet loaded, then Rails assumes a relative reference by contract. - -Naming conflicts of this kind are rare in practice, but if one occurs, -`require_dependency` provides a solution by ensuring that the constant needed -to trigger the heuristic is defined in the conflicting place. - -### Automatic Modules - -When a module acts as a namespace, Rails does not require the application to -define a file for it, a directory matching the namespace is enough. +module StiPreload + unless Rails.application.config.eager_load + extend ActiveSupport::Concern -Suppose an application has a back office whose controllers are stored in -`app/controllers/admin`. If the `Admin` module is not yet loaded when -`Admin::UsersController` is hit, Rails needs first to autoload the constant -`Admin`. - -If `autoload_paths` has a file called `admin.rb` Rails is going to load that -one, but if there's no such file and a directory called `admin` is found, Rails -creates an empty module and assigns it to the `Admin` constant on the fly. - -### Generic Procedure - -Relative references are reported to be missing in the cref where they were hit, -and qualified references are reported to be missing in their parent (see -[Resolution Algorithm for Relative -Constants](#resolution-algorithm-for-relative-constants) at the beginning of -this guide for the definition of *cref*, and [Resolution Algorithm for Qualified -Constants](#resolution-algorithm-for-qualified-constants) for the definition of -*parent*). - -The procedure to autoload constant `C` in an arbitrary situation is as follows: - -``` -if the class or module in which C is missing is Object - let ns = '' -else - let M = the class or module in which C is missing - - if M is anonymous - let ns = '' - else - let ns = M.name - end -end - -loop do - # Look for a regular file. - for dir in autoload_paths - if the file "#{dir}/#{ns.underscore}/c.rb" exists - load/require "#{dir}/#{ns.underscore}/c.rb" - - if C is now defined - return - else - raise LoadError - end + included do + cattr_accessor :preloaded, instance_accessor: false end - end - # Look for an automatic module. - for dir in autoload_paths - if the directory "#{dir}/#{ns.underscore}/c" exists - if ns is an empty string - let C = Module.new in Object and return - else - let C = Module.new in ns.constantize and return + class_methods do + def descendants + preload_sti unless preloaded + super end - end - end - - if ns is empty - # We reached the top-level without finding the constant. - raise NameError - else - if C exists in any of the parent namespaces - # Qualified constants heuristic. - raise NameError - else - # Try again in the parent namespace. - let ns = the parent namespace of ns and retry - end - end -end -``` - - -require_dependency ------------------- - -Constant autoloading is triggered on demand and therefore code that uses a -certain constant may have it already defined or may trigger an autoload. That -depends on the execution path and it may vary between runs. - -There are times, however, in which you want to make sure a certain constant is -known when the execution reaches some code. `require_dependency` provides a way -to load a file using the current [loading mechanism](#loading-mechanism), and -keeping track of constants defined in that file as if they were autoloaded to -have them reloaded as needed. - -`require_dependency` is rarely needed, but see a couple of use cases in -[Autoloading and STI](#autoloading-and-sti) and [When Constants aren't -Triggered](#when-constants-aren-t-missed). - -WARNING. Unlike autoloading, `require_dependency` does not expect the file to -define any particular constant. Exploiting this behavior would be a bad practice -though, file and constant paths should match. - - -Constant Reloading ------------------- - -When `config.cache_classes` is false Rails is able to reload autoloaded -constants. -For example, if you're in a console session and edit some file behind the -scenes, the code can be reloaded with the `reload!` command: - -``` -> reload! -``` - -When the application runs, code is reloaded when something relevant to this -logic changes. In order to do that, Rails monitors a number of things: - -* `config/routes.rb`. - -* Locales. - -* Ruby files under `autoload_paths`. - -* `db/schema.rb` and `db/structure.sql`. - -If anything in there changes, there is a middleware that detects it and reloads -the code. - -Autoloading keeps track of autoloaded constants. Reloading is implemented by -removing them all from their respective classes and modules using -`Module#remove_const`. That way, when the code goes on, those constants are -going to be unknown again, and files reloaded on demand. - -INFO. This is an all-or-nothing operation, Rails does not attempt to reload only -what changed since dependencies between classes makes that really tricky. -Instead, everything is wiped. - - -Module#autoload isn't Involved ------------------------------- - -`Module#autoload` provides a lazy way to load constants that is fully integrated -with the Ruby constant lookup algorithms, dynamic constant API, etc. It is quite -transparent. - -Rails internals make extensive use of it to defer as much work as possible from -the boot process. But constant autoloading in Rails is **not** implemented with -`Module#autoload`. - -One possible implementation based on `Module#autoload` would be to walk the -application tree and issue `autoload` calls that map existing file names to -their conventional constant name. - -There are a number of reasons that prevent Rails from using that implementation. - -For example, `Module#autoload` is only capable of loading files using `require`, -so reloading would not be possible. Not only that, it uses an internal `require` -which is not `Kernel#require`. - -Then, it provides no way to remove declarations in case a file is deleted. If a -constant gets removed with `Module#remove_const` its `autoload` is not triggered -again. Also, it doesn't support qualified names, so files with namespaces should -be interpreted during the walk tree to install their own `autoload` calls, but -those files could have constant references not yet configured. - -An implementation based on `Module#autoload` would be awesome but, as you see, -at least as of today it is not possible. Constant autoloading in Rails is -implemented with `Module#const_missing`, and that's why it has its own contract, -documented in this guide. - - -Common Gotchas --------------- - -### Nesting and Qualified Constants - -Let's consider - -```ruby -module Admin - class UsersController < ApplicationController - def index - @users = User.all + # Constantizes all types present in the database. There might be more on + # disk, but that does not matter in practice as far as the STI API is + # concerned. + # + # Assumes store_full_sti_class is true, the default. + def preload_sti + types_in_db = \ + base_class. + select(inheritance_column). + distinct. + pluck(inheritance_column). + compact. + each(&:constantize) + + types_in_db.each do |type| + logger.debug("Preloading STI type #{type}") + type.constantize + end + + self.preloaded = true + end end end end ``` -and +and then include it in the STI root classes of your project: ```ruby -class Admin::UsersController < ApplicationController - def index - @users = User.all - end -end -``` - -To resolve `User` Ruby checks `Admin` in the former case, but it does not in -the latter because it does not belong to the nesting (see [Nesting](#nesting) -and [Resolution Algorithms](#resolution-algorithms)). - -Unfortunately Rails autoloading does not know the nesting in the spot where the -constant was missing and so it is not able to act as Ruby would. In particular, -`Admin::User` will get autoloaded in either case. - -Albeit qualified constants with `class` and `module` keywords may technically -work with autoloading in some cases, it is preferable to use relative constants -instead: +# app/models/shape.rb +require "sti_preload" -```ruby -module Admin - class UsersController < ApplicationController - def index - @users = User.all - end - end +class Shape < ApplicationRecord + include StiPreload # Only in the root class. end -``` -### Autoloading and STI - -Single Table Inheritance (STI) is a feature of Active Record that enables -storing a hierarchy of models in one single table. The API of such models is -aware of the hierarchy and encapsulates some common needs. For example, given -these classes: - -```ruby # app/models/polygon.rb -class Polygon < ApplicationRecord +class Polygon < Shape end # app/models/triangle.rb class Triangle < Polygon end - -# app/models/rectangle.rb -class Rectangle < Polygon -end -``` - -`Triangle.create` creates a row that represents a triangle, and -`Rectangle.create` creates a row that represents a rectangle. If `id` is the -ID of an existing record, `Polygon.find(id)` returns an object of the correct -type. - -Methods that operate on collections are also aware of the hierarchy. For -example, `Polygon.all` returns all the records of the table, because all -rectangles and triangles are polygons. Active Record takes care of returning -instances of their corresponding class in the result set. - -Types are autoloaded as needed. For example, if `Polygon.first` is a rectangle -and `Rectangle` has not yet been loaded, Active Record autoloads it and the -record is correctly instantiated. - -All good, but if instead of performing queries based on the root class we need -to work on some subclass, things get interesting. - -While working with `Polygon` you do not need to be aware of all its descendants, -because anything in the table is by definition a polygon, but when working with -subclasses Active Record needs to be able to enumerate the types it is looking -for. Let's see an example. - -`Rectangle.all` only loads rectangles by adding a type constraint to the query: - -```sql -SELECT "polygons".* FROM "polygons" -WHERE "polygons"."type" IN ("Rectangle") -``` - -Let's introduce now a subclass of `Rectangle`: - -```ruby -# app/models/square.rb -class Square < Rectangle -end -``` - -`Rectangle.all` should now return rectangles **and** squares: - -```sql -SELECT "polygons".* FROM "polygons" -WHERE "polygons"."type" IN ("Rectangle", "Square") -``` - -But there's a caveat here: How does Active Record know that the class `Square` -exists at all? - -Even if the file `app/models/square.rb` exists and defines the `Square` class, -if no code yet used that class, `Rectangle.all` issues the query - -```sql -SELECT "polygons".* FROM "polygons" -WHERE "polygons"."type" IN ("Rectangle") -``` - -That is not a bug, the query includes all *known* descendants of `Rectangle`. - -A way to ensure this works correctly regardless of the order of execution is to -manually load the direct subclasses at the bottom of the file that defines each -intermediate class: - -```ruby -# app/models/rectangle.rb -class Rectangle < Polygon -end -require_dependency 'square' -``` - -This needs to happen for every intermediate (non-root and non-leaf) class. The -root class does not scope the query by type, and therefore does not necessarily -have to know all its descendants. - -### Autoloading and `require` - -Files defining constants to be autoloaded should never be `require`d: - -```ruby -require 'user' # DO NOT DO THIS - -class UsersController < ApplicationController - ... -end -``` - -There are two possible gotchas here in development mode: - -1. If `User` is autoloaded before reaching the `require`, `app/models/user.rb` -runs again because `load` does not update `$LOADED_FEATURES`. - -2. If the `require` runs first Rails does not mark `User` as an autoloaded -constant and changes to `app/models/user.rb` aren't reloaded. - -Just follow the flow and use constant autoloading always, never mix -autoloading and `require`. As a last resort, if some file absolutely needs to -load a certain file use `require_dependency` to play nice with constant -autoloading. This option is rarely needed in practice, though. - -Of course, using `require` in autoloaded files to load ordinary 3rd party -libraries is fine, and Rails is able to distinguish their constants, they are -not marked as autoloaded. - -### Autoloading and Initializers - -Consider this assignment in `config/initializers/set_auth_service.rb`: - -```ruby -AUTH_SERVICE = if Rails.env.production? - RealAuthService -else - MockedAuthService -end -``` - -The purpose of this setup would be that the application uses the class that -corresponds to the environment via `AUTH_SERVICE`. In development mode -`MockedAuthService` gets autoloaded when the initializer runs. Let's suppose -we do some requests, change its implementation, and hit the application again. -To our surprise the changes are not reflected. Why? - -As [we saw earlier](#constant-reloading), Rails removes autoloaded constants, -but `AUTH_SERVICE` stores the original class object. Stale, non-reachable -using the original constant, but perfectly functional. - -The following code summarizes the situation: - -```ruby -class C - def quack - 'quack!' - end -end - -X = C -Object.instance_eval { remove_const(:C) } -X.new.quack # => quack! -X.name # => C -C # => uninitialized constant C (NameError) -``` - -Because of that, it is not a good idea to autoload constants on application -initialization. - -In the case above we could implement a dynamic access point: - -```ruby -# app/models/auth_service.rb -class AuthService - if Rails.env.production? - def self.instance - RealAuthService - end - else - def self.instance - MockedAuthService - end - end -end -``` - -and have the application use `AuthService.instance` instead. `AuthService` -would be loaded on demand and be autoload-friendly. - -### `require_dependency` and Initializers - -As we saw before, `require_dependency` loads files in an autoloading-friendly -way. Normally, though, such a call does not make sense in an initializer. - -One could think about doing some [`require_dependency`](#require-dependency) -calls in an initializer to make sure certain constants are loaded upfront, for -example as an attempt to address the [gotcha with STIs](#autoloading-and-sti). - -Problem is, in development mode [autoloaded constants are wiped](#constant-reloading) -if there is any relevant change in the file system. If that happens then -we are in the very same situation the initializer wanted to avoid! - -Calls to `require_dependency` have to be strategically written in autoloaded -spots. - -### When Constants aren't Missed - -#### Relative References - -Let's consider a flight simulator. The application has a default flight model - -```ruby -# app/models/flight_model.rb -class FlightModel -end -``` - -that can be overridden by each airplane, for instance - -```ruby -# app/models/bell_x1/flight_model.rb -module BellX1 - class FlightModel < FlightModel - end -end - -# app/models/bell_x1/aircraft.rb -module BellX1 - class Aircraft - def initialize - @flight_model = FlightModel.new - end - end -end -``` - -The initializer wants to create a `BellX1::FlightModel` and nesting has -`BellX1`, that looks good. But if the default flight model is loaded and the -one for the Bell-X1 is not, the interpreter is able to resolve the top-level -`FlightModel` and autoloading is thus not triggered for `BellX1::FlightModel`. - -That code depends on the execution path. - -These kind of ambiguities can often be resolved using qualified constants: - -```ruby -module BellX1 - class Plane - def flight_model - @flight_model ||= BellX1::FlightModel.new - end - end -end -``` - -Also, `require_dependency` is a solution: - -```ruby -require_dependency 'bell_x1/flight_model' - -module BellX1 - class Plane - def flight_model - @flight_model ||= FlightModel.new - end - end -end -``` - -#### Qualified References - -WARNING. This gotcha is only possible in Ruby < 2.5. - -Given - -```ruby -# app/models/hotel.rb -class Hotel -end - -# app/models/image.rb -class Image -end - -# app/models/hotel/image.rb -class Hotel - class Image < Image - end -end -``` - -the expression `Hotel::Image` is ambiguous because it depends on the execution -path. - -As [we saw before](#resolution-algorithm-for-qualified-constants), Ruby looks -up the constant in `Hotel` and its ancestors. If `app/models/image.rb` has -been loaded but `app/models/hotel/image.rb` hasn't, Ruby does not find `Image` -in `Hotel`, but it does in `Object`: - -``` -$ rails r 'Image; p Hotel::Image' 2>/dev/null -Image # NOT Hotel::Image! -``` - -The code evaluating `Hotel::Image` needs to make sure -`app/models/hotel/image.rb` has been loaded, possibly with -`require_dependency`. - -In these cases the interpreter issues a warning though: - -``` -warning: toplevel constant Image referenced by Hotel::Image -``` - -This surprising constant resolution can be observed with any qualifying class: - -``` -2.1.5 :001 > String::Array -(irb):1: warning: toplevel constant Array referenced by String::Array - => Array -``` - -WARNING. To find this gotcha the qualifying namespace has to be a class, -`Object` is not an ancestor of modules. - -### Autoloading within Singleton Classes - -Let's suppose we have these class definitions: - -```ruby -# app/models/hotel/services.rb -module Hotel - class Services - end -end - -# app/models/hotel/geo_location.rb -module Hotel - class GeoLocation - class << self - Services - end - end -end ``` -If `Hotel::Services` is known by the time `app/models/hotel/geo_location.rb` -is being loaded, `Services` is resolved by Ruby because `Hotel` belongs to the -nesting when the singleton class of `Hotel::GeoLocation` is opened. +Rails.autoloaders +----------------- -But if `Hotel::Services` is not known, Rails is not able to autoload it, the -application raises `NameError`. - -The reason is that autoloading is triggered for the singleton class, which is -anonymous, and as [we saw before](#generic-procedure), Rails only checks the -top-level namespace in that edge case. - -An easy solution to this caveat is to qualify the constant: +The Zeitwerk instances managing your application are availabe at ```ruby -module Hotel - class GeoLocation - class << self - Hotel::Services - end - end -end +Rails.autoloaders.main +Rails.autoloaders.once ``` -### Autoloading in `BasicObject` - -Direct descendants of `BasicObject` do not have `Object` among their ancestors -and cannot resolve top-level constants: - -```ruby -class C < BasicObject - String # NameError: uninitialized constant C::String -end -``` +The former is the main one. The latter is there mostly for backwards compatibily reasons, in case the application has something in `config.autoload_once_paths` (this is discouraged nowadays). -When autoloading is involved that plot has a twist. Let's consider: +You can check if `zeitwerk` mode is enabled with ```ruby -class C < BasicObject - def user - User # WRONG - end -end +Rails.autoloaders.zeitwerk_enabled? ``` -Since Rails checks the top-level namespace `User` gets autoloaded just fine the -first time the `user` method is invoked. You only get the exception if the -`User` constant is known at that point, in particular in a *second* call to -`user`: - -```ruby -c = C.new -c.user # surprisingly fine, User -c.user # NameError: uninitialized constant C::User -``` - -because it detects that a parent namespace already has the constant (see [Qualified -References](#autoloading-algorithms-qualified-references)). - -As with pure Ruby, within the body of a direct descendant of `BasicObject` use -always absolute constant paths: - -```ruby -class C < BasicObject - ::String # RIGHT - - def user - ::User # RIGHT - end -end -``` - -### Autoloading in the Test Environment - -When configuring the `test` environment for autoloading you might consider multiple factors. - -For example it might be worth running your tests with an identical setup to production (`config.eager_load = true`, `config.cache_classes = true`) in order to catch any problems before they hit production (this is compensation for the lack of dev-prod parity). However this will slow down the boot time for individual tests on a dev machine (and is not immediately compatible with spring see below). So one possibility is to do this on a -[CI](https://en.wikipedia.org/wiki/Continuous_integration) machine only (which should run without spring). - -On a development machine you can then have your tests running with whatever is fastest (ideally `config.eager_load = false`). - -With the [Spring](https://github.com/rails/spring) pre-loader (included with new Rails apps), you ideally keep `config.eager_load = false` as per development. Sometimes you may end up with a hybrid configuration (`config.eager_load = true`, `config.cache_classes = true` AND `config.enable_dependency_loading = true`), see [spring issue](https://github.com/rails/spring/issues/519#issuecomment-348324369). However it might be simpler to keep the same configuration as development, and work out whatever it is that is causing autoloading to fail (perhaps by the results of your CI test results). - -Occasionally you may need to explicitly eager_load by using `Rails -.application.eager_load!` in the setup of your tests -- this might occur if your [tests involve multithreading](https://stackoverflow.com/questions/25796409/in-rails-how-can-i-eager-load-all-code-before-a-specific-rspec-test). - -## Troubleshooting - -### Tracing Autoloads - -Active Support is able to report constants as they are autoloaded. To enable these traces in a Rails application, put the following two lines in some initializer: - -```ruby -ActiveSupport::Dependencies.logger = Rails.logger -ActiveSupport::Dependencies.verbose = true -``` - -### Where is a Given Autoload Triggered? +Opting Out +---------- -If constant `Foo` is being autoloaded, and you'd like to know where is that autoload coming from, just throw +Applications can load Rails 6 defaults and still use the classic autoloader this way: ```ruby -puts caller +# config/application.rb +config.load_defaults "6.x" +config.autoloader = :classic ``` -at the top of `foo.rb` and inspect the printed stack trace. - -### Which Constants Have Been Autoloaded? - -At any given time, - -```ruby -ActiveSupport::Dependencies.autoloaded_constants -``` +That may be handy if upgrading to Rails 6 in different phases, but classic mode is discouraged for new applications. -has the collection of constants that have been autoloaded so far. +`zeitwerk` mode is not available in versions of Rails previous to 6.0. diff --git a/guides/source/autoloading_and_reloading_constants_classic_mode.md b/guides/source/autoloading_and_reloading_constants_classic_mode.md new file mode 100644 index 0000000000..d0d9e076d6 --- /dev/null +++ b/guides/source/autoloading_and_reloading_constants_classic_mode.md @@ -0,0 +1,1351 @@ +**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON https://guides.rubyonrails.org.** + +Autoloading and Reloading Constants (Classic Mode) +================================================== + +This guide documents how constant autoloading and reloading works in `classic` mode. + +After reading this guide, you will know: + +* Key aspects of Ruby constants +* What are the `autoload_paths` and how does eager loading work in production? +* How constant autoloading works +* What is `require_dependency` +* How constant reloading works +* Solutions to common autoloading gotchas + +-------------------------------------------------------------------------------- + + +Introduction +------------ + +INFO. This guide documents autoloading in `classic` mode, which is the traditional one. If you'd like to read about `zeiwerk` mode instead, the new one in Rails 6, please check [Autoloading and Reloading Constants (Zeitwerk Mode)](autoloading_and_reloading_constants.html). + +Ruby on Rails allows applications to be written as if their code was preloaded. + +In a normal Ruby program classes need to load their dependencies: + +```ruby +require 'application_controller' +require 'post' + +class PostsController < ApplicationController + def index + @posts = Post.all + end +end +``` + +Our Rubyist instinct quickly sees some redundancy in there: If classes were +defined in files matching their name, couldn't their loading be automated +somehow? We could save scanning the file for dependencies, which is brittle. + +Moreover, `Kernel#require` loads files once, but development is much more smooth +if code gets refreshed when it changes without restarting the server. It would +be nice to be able to use `Kernel#load` in development, and `Kernel#require` in +production. + +Indeed, those features are provided by Ruby on Rails, where we just write + +```ruby +class PostsController < ApplicationController + def index + @posts = Post.all + end +end +``` + +This guide documents how that works. + + +Constants Refresher +------------------- + +While constants are trivial in most programming languages, they are a rich +topic in Ruby. + +It is beyond the scope of this guide to document Ruby constants, but we are +nevertheless going to highlight a few key topics. Truly grasping the following +sections is instrumental to understanding constant autoloading and reloading. + +### Nesting + +Class and module definitions can be nested to create namespaces: + +```ruby +module XML + class SAXParser + # (1) + end +end +``` + +The *nesting* at any given place is the collection of enclosing nested class and +module objects outwards. The nesting at any given place can be inspected with +`Module.nesting`. For example, in the previous example, the nesting at +(1) is + +```ruby +[XML::SAXParser, XML] +``` + +It is important to understand that the nesting is composed of class and module +*objects*, it has nothing to do with the constants used to access them, and is +also unrelated to their names. + +For instance, while this definition is similar to the previous one: + +```ruby +class XML::SAXParser + # (2) +end +``` + +the nesting in (2) is different: + +```ruby +[XML::SAXParser] +``` + +`XML` does not belong to it. + +We can see in this example that the name of a class or module that belongs to a +certain nesting does not necessarily correlate with the namespaces at the spot. + +Even more, they are totally independent, take for instance + +```ruby +module X + module Y + end +end + +module A + module B + end +end + +module X::Y + module A::B + # (3) + end +end +``` + +The nesting in (3) consists of two module objects: + +```ruby +[A::B, X::Y] +``` + +So, it not only doesn't end in `A`, which does not even belong to the nesting, +but it also contains `X::Y`, which is independent from `A::B`. + +The nesting is an internal stack maintained by the interpreter, and it gets +modified according to these rules: + +* The class object following a `class` keyword gets pushed when its body is +executed, and popped after it. + +* The module object following a `module` keyword gets pushed when its body is +executed, and popped after it. + +* A singleton class opened with `class << object` gets pushed, and popped later. + +* When `instance_eval` is called using a string argument, +the singleton class of the receiver is pushed to the nesting of the eval'ed +code. When `class_eval` or `module_eval` is called using a string argument, +the receiver is pushed to the nesting of the eval'ed code. + +* The nesting at the top-level of code interpreted by `Kernel#load` is empty +unless the `load` call receives a true value as second argument, in which case +a newly created anonymous module is pushed by Ruby. + +It is interesting to observe that blocks do not modify the stack. In particular +the blocks that may be passed to `Class.new` and `Module.new` do not get the +class or module being defined pushed to their nesting. That's one of the +differences between defining classes and modules in one way or another. + +### Class and Module Definitions are Constant Assignments + +Let's suppose the following snippet creates a class (rather than reopening it): + +```ruby +class C +end +``` + +Ruby creates a constant `C` in `Object` and stores in that constant a class +object. The name of the class instance is "C", a string, named after the +constant. + +That is, + +```ruby +class Project < ApplicationRecord +end +``` + +performs a constant assignment equivalent to + +```ruby +Project = Class.new(ApplicationRecord) +``` + +including setting the name of the class as a side-effect: + +```ruby +Project.name # => "Project" +``` + +Constant assignment has a special rule to make that happen: if the object +being assigned is an anonymous class or module, Ruby sets the object's name to +the name of the constant. + +INFO. From then on, what happens to the constant and the instance does not +matter. For example, the constant could be deleted, the class object could be +assigned to a different constant, be stored in no constant anymore, etc. Once +the name is set, it doesn't change. + +Similarly, module creation using the `module` keyword as in + +```ruby +module Admin +end +``` + +performs a constant assignment equivalent to + +```ruby +Admin = Module.new +``` + +including setting the name as a side-effect: + +```ruby +Admin.name # => "Admin" +``` + +WARNING. The execution context of a block passed to `Class.new` or `Module.new` +is not entirely equivalent to the one of the body of the definitions using the +`class` and `module` keywords. But both idioms result in the same constant +assignment. + +Thus, an informal expression like "the `String` class" technically means the +class object stored in the constant called "String". That constant, in turn, +belongs to the class object stored in the constant called "Object". + +`String` is an ordinary constant, and everything related to them such as +resolution algorithms applies to it. + +Likewise, in the controller + +```ruby +class PostsController < ApplicationController + def index + @posts = Post.all + end +end +``` + +`Post` is not syntax for a class. Rather, `Post` is a regular Ruby constant. If +all is good, the constant is evaluated to an object that responds to `all`. + +That is why we talk about *constant* autoloading, Rails has the ability to +load constants on the fly. + +### Constants are Stored in Modules + +Constants belong to modules in a very literal sense. Classes and modules have +a constant table; think of it as a hash table. + +Let's analyze an example to really understand what that means. While common +abuses of language like "the `String` class" are convenient, the exposition is +going to be precise here for didactic purposes. + +Let's consider the following module definition: + +```ruby +module Colors + RED = '0xff0000' +end +``` + +First, when the `module` keyword is processed, the interpreter creates a new +entry in the constant table of the class object stored in the `Object` constant. +Said entry associates the name "Colors" to a newly created module object. +Furthermore, the interpreter sets the name of the new module object to be the +string "Colors". + +Later, when the body of the module definition is interpreted, a new entry is +created in the constant table of the module object stored in the `Colors` +constant. That entry maps the name "RED" to the string "0xff0000". + +In particular, `Colors::RED` is totally unrelated to any other `RED` constant +that may live in any other class or module object. If there were any, they +would have separate entries in their respective constant tables. + +Pay special attention in the previous paragraphs to the distinction between +class and module objects, constant names, and value objects associated to them +in constant tables. + +### Resolution Algorithms + +#### Resolution Algorithm for Relative Constants + +At any given place in the code, let's define *cref* to be the first element of +the nesting if it is not empty, or `Object` otherwise. + +Without getting too much into the details, the resolution algorithm for relative +constant references goes like this: + +1. If the nesting is not empty the constant is looked up in its elements and in +order. The ancestors of those elements are ignored. + +2. If not found, then the algorithm walks up the ancestor chain of the cref. + +3. If not found and the cref is a module, the constant is looked up in `Object`. + +4. If not found, `const_missing` is invoked on the cref. The default +implementation of `const_missing` raises `NameError`, but it can be overridden. + +Rails autoloading **does not emulate this algorithm**, but its starting point is +the name of the constant to be autoloaded, and the cref. See more in [Relative +References](#autoloading-algorithms-relative-references). + +#### Resolution Algorithm for Qualified Constants + +Qualified constants look like this: + +```ruby +Billing::Invoice +``` + +`Billing::Invoice` is composed of two constants: `Billing` is relative and is +resolved using the algorithm of the previous section. + +INFO. Leading colons would make the first segment absolute rather than +relative: `::Billing::Invoice`. That would force `Billing` to be looked up +only as a top-level constant. + +`Invoice` on the other hand is qualified by `Billing` and we are going to see +its resolution next. Let's define *parent* to be that qualifying class or module +object, that is, `Billing` in the example above. The algorithm for qualified +constants goes like this: + +1. The constant is looked up in the parent and its ancestors. In Ruby >= 2.5, +`Object` is skipped if present among the ancestors. `Kernel` and `BasicObject` +are still checked though. + +2. If the lookup fails, `const_missing` is invoked in the parent. The default +implementation of `const_missing` raises `NameError`, but it can be overridden. + +INFO. In Ruby < 2.5 `String::Hash` evaluates to `Hash` and the interpreter +issues a warning: "toplevel constant Hash referenced by String::Hash". Starting +with 2.5, `String::Hash` raises `NameError` because `Object` is skipped. + +As you see, this algorithm is simpler than the one for relative constants. In +particular, the nesting plays no role here, and modules are not special-cased, +if neither they nor their ancestors have the constants, `Object` is **not** +checked. + +Rails autoloading **does not emulate this algorithm**, but its starting point is +the name of the constant to be autoloaded, and the parent. See more in +[Qualified References](#autoloading-algorithms-qualified-references). + + +Vocabulary +---------- + +### Parent Namespaces + +Given a string with a constant path we define its *parent namespace* to be the +string that results from removing its rightmost segment. + +For example, the parent namespace of the string "A::B::C" is the string "A::B", +the parent namespace of "A::B" is "A", and the parent namespace of "A" is "". + +The interpretation of a parent namespace when thinking about classes and modules +is tricky though. Let's consider a module M named "A::B": + +* The parent namespace, "A", may not reflect nesting at a given spot. + +* The constant `A` may no longer exist, some code could have removed it from +`Object`. + +* If `A` exists, the class or module that was originally in `A` may not be there +anymore. For example, if after a constant removal there was another constant +assignment there would generally be a different object in there. + +* In such case, it could even happen that the reassigned `A` held a new class or +module called also "A"! + +* In the previous scenarios M would no longer be reachable through `A::B` but +the module object itself could still be alive somewhere and its name would +still be "A::B". + +The idea of a parent namespace is at the core of the autoloading algorithms +and helps explain and understand their motivation intuitively, but as you see +that metaphor leaks easily. Given an edge case to reason about, take always into +account that by "parent namespace" the guide means exactly that specific string +derivation. + +### Loading Mechanism + +Rails autoloads files with `Kernel#load` when `config.cache_classes` is false, +the default in development mode, and with `Kernel#require` otherwise, the +default in production mode. + +`Kernel#load` allows Rails to execute files more than once if [constant +reloading](#constant-reloading) is enabled. + +This guide uses the word "load" freely to mean a given file is interpreted, but +the actual mechanism can be `Kernel#load` or `Kernel#require` depending on that +flag. + + +Autoloading Availability +------------------------ + +Rails is always able to autoload provided its environment is in place. For +example the `runner` command autoloads: + +``` +$ rails runner 'p User.column_names' +["id", "email", "created_at", "updated_at"] +``` + +The console autoloads, the test suite autoloads, and of course the application +autoloads. + +By default, Rails eager loads the application files when it boots in production +mode, so most of the autoloading going on in development does not happen. But +autoloading may still be triggered during eager loading. + +For example, given + +```ruby +class BeachHouse < House +end +``` + +if `House` is still unknown when `app/models/beach_house.rb` is being eager +loaded, Rails autoloads it. + + +autoload_paths and eager_load_paths +----------------------------------- + +As you probably know, when `require` gets a relative file name: + +```ruby +require 'erb' +``` + +Ruby looks for the file in the directories listed in `$LOAD_PATH`. That is, Ruby +iterates over all its directories and for each one of them checks whether they +have a file called "erb.rb", or "erb.so", or "erb.o", or "erb.dll". If it finds +any of them, the interpreter loads it and ends the search. Otherwise, it tries +again in the next directory of the list. If the list gets exhausted, `LoadError` +is raised. + +We are going to cover how constant autoloading works in more detail later, but +the idea is that when a constant like `Post` is hit and missing, if there's a +`post.rb` file for example in `app/models` Rails is going to find it, evaluate +it, and have `Post` defined as a side-effect. + +All right, Rails has a collection of directories similar to `$LOAD_PATH` in which +to look up `post.rb`. That collection is called `autoload_paths` and by +default it contains: + +* All subdirectories of `app` in the application and engines present at boot + time. For example, `app/controllers`. They do not need to be the default + ones, any custom directories like `app/workers` belong automatically to + `autoload_paths`. + +* Any existing second level directories called `app/*/concerns` in the + application and engines. + +* The directory `test/mailers/previews`. + +`eager_load_paths` is initially the `app` paths above + +How files are autoloaded depends on `eager_load` and `cache_classes` config settings which typically vary in development, production, and test modes: + + * In **development**, you want quicker startup with incremental loading of application code. So `eager_load` should be set to `false`, and Rails will autoload files as needed (see [Autoloading Algorithms](#autoloading-algorithms) below) -- and then reload them when they change (see [Constant Reloading](#constant-reloading) below). + * In **production**, however, you want consistency and thread-safety and can live with a longer boot time. So `eager_load` is set to `true`, and then during boot (before the app is ready to receive requests) Rails loads all files in the `eager_load_paths` and then turns off auto loading (NB: autoloading may be needed during eager loading). Not autoloading after boot is a `good thing`, as autoloading can cause the app to be have thread-safety problems. + * In **test**, for speed of execution (of individual tests) `eager_load` is `false`, so Rails follows development behaviour. + +What is described above are the defaults with a newly generated Rails app. There are multiple ways this can be configured differently (see [Configuring Rails Applications](configuring.html#rails-general-configuration). +). But using `autoload_paths` on its own in the past (before Rails 5) developers might configure `autoload_paths` to add in extra locations (e.g. `lib` which used to be an autoload path list years ago, but no longer is). However this is now discouraged for most purposes, as it is likely to lead to production-only errors. It is possible to add new locations to both `config.eager_load_paths` and `config.autoload_paths` but use at your own risk. + +See also [Autoloading in the Test Environment](#autoloading-in-the-test-environment). + +`config.autoload_paths` is not changeable from environment-specific configuration files. + +The value of `autoload_paths` can be inspected. In a just-generated application +it is (edited): + +``` +$ rails r 'puts ActiveSupport::Dependencies.autoload_paths' +.../app/assets +.../app/channels +.../app/controllers +.../app/controllers/concerns +.../app/helpers +.../app/jobs +.../app/mailers +.../app/models +.../app/models/concerns +.../activestorage/app/assets +.../activestorage/app/controllers +.../activestorage/app/javascript +.../activestorage/app/jobs +.../activestorage/app/models +.../actioncable/app/assets +.../actionview/app/assets +.../test/mailers/previews +``` + +INFO. `autoload_paths` is computed and cached during the initialization process. +The application needs to be restarted to reflect any changes in the directory +structure. + + +Autoloading Algorithms +---------------------- + +### Relative References + +A relative constant reference may appear in several places, for example, in + +```ruby +class PostsController < ApplicationController + def index + @posts = Post.all + end +end +``` + +all three constant references are relative. + +#### Constants after the `class` and `module` Keywords + +Ruby performs a lookup for the constant that follows a `class` or `module` +keyword because it needs to know if the class or module is going to be created +or reopened. + +If the constant is not defined at that point it is not considered to be a +missing constant, autoloading is **not** triggered. + +So, in the previous example, if `PostsController` is not defined when the file +is interpreted Rails autoloading is not going to be triggered, Ruby will just +define the controller. + +#### Top-Level Constants + +On the contrary, if `ApplicationController` is unknown, the constant is +considered missing and an autoload is going to be attempted by Rails. + +In order to load `ApplicationController`, Rails iterates over `autoload_paths`. +First it checks if `app/assets/application_controller.rb` exists. If it does not, +which is normally the case, it continues and finds +`app/controllers/application_controller.rb`. + +If the file defines the constant `ApplicationController` all is fine, otherwise +`LoadError` is raised: + +``` +unable to autoload constant ApplicationController, expected +<full path to application_controller.rb> to define it (LoadError) +``` + +INFO. Rails does not require the value of autoloaded constants to be a class or +module object. For example, if the file `app/models/max_clients.rb` defines +`MAX_CLIENTS = 100` autoloading `MAX_CLIENTS` works just fine. + +#### Namespaces + +Autoloading `ApplicationController` looks directly under the directories of +`autoload_paths` because the nesting in that spot is empty. The situation of +`Post` is different, the nesting in that line is `[PostsController]` and support +for namespaces comes into play. + +The basic idea is that given + +```ruby +module Admin + class BaseController < ApplicationController + @@all_roles = Role.all + end +end +``` + +to autoload `Role` we are going to check if it is defined in the current or +parent namespaces, one at a time. So, conceptually we want to try to autoload +any of + +``` +Admin::BaseController::Role +Admin::Role +Role +``` + +in that order. That's the idea. To do so, Rails looks in `autoload_paths` +respectively for file names like these: + +``` +admin/base_controller/role.rb +admin/role.rb +role.rb +``` + +modulus some additional directory lookups we are going to cover soon. + +INFO. `'Constant::Name'.underscore` gives the relative path without extension of +the file name where `Constant::Name` is expected to be defined. + +Let's see how Rails autoloads the `Post` constant in the `PostsController` +above assuming the application has a `Post` model defined in +`app/models/post.rb`. + +First it checks for `posts_controller/post.rb` in `autoload_paths`: + +``` +app/assets/posts_controller/post.rb +app/controllers/posts_controller/post.rb +app/helpers/posts_controller/post.rb +... +test/mailers/previews/posts_controller/post.rb +``` + +Since the lookup is exhausted without success, a similar search for a directory +is performed, we are going to see why in the [next section](#automatic-modules): + +``` +app/assets/posts_controller/post +app/controllers/posts_controller/post +app/helpers/posts_controller/post +... +test/mailers/previews/posts_controller/post +``` + +If all those attempts fail, then Rails starts the lookup again in the parent +namespace. In this case only the top-level remains: + +``` +app/assets/post.rb +app/controllers/post.rb +app/helpers/post.rb +app/mailers/post.rb +app/models/post.rb +``` + +A matching file is found in `app/models/post.rb`. The lookup stops there and the +file is loaded. If the file actually defines `Post` all is fine, otherwise +`LoadError` is raised. + +### Qualified References + +When a qualified constant is missing Rails does not look for it in the parent +namespaces. But there is a caveat: when a constant is missing, Rails is +unable to tell if the trigger was a relative reference or a qualified one. + +For example, consider + +```ruby +module Admin + User +end +``` + +and + +```ruby +Admin::User +``` + +If `User` is missing, in either case all Rails knows is that a constant called +"User" was missing in a module called "Admin". + +If there is a top-level `User` Ruby would resolve it in the former example, but +wouldn't in the latter. In general, Rails does not emulate the Ruby constant +resolution algorithms, but in this case it tries using the following heuristic: + +> If none of the parent namespaces of the class or module has the missing +> constant then Rails assumes the reference is relative. Otherwise qualified. + +For example, if this code triggers autoloading + +```ruby +Admin::User +``` + +and the `User` constant is already present in `Object`, it is not possible that +the situation is + +```ruby +module Admin + User +end +``` + +because otherwise Ruby would have resolved `User` and no autoloading would have +been triggered in the first place. Thus, Rails assumes a qualified reference and +considers the file `admin/user.rb` and directory `admin/user` to be the only +valid options. + +In practice, this works quite well as long as the nesting matches all parent +namespaces respectively and the constants that make the rule apply are known at +that time. + +However, autoloading happens on demand. If by chance the top-level `User` was +not yet loaded, then Rails assumes a relative reference by contract. + +Naming conflicts of this kind are rare in practice, but if one occurs, +`require_dependency` provides a solution by ensuring that the constant needed +to trigger the heuristic is defined in the conflicting place. + +### Automatic Modules + +When a module acts as a namespace, Rails does not require the application to +define a file for it, a directory matching the namespace is enough. + +Suppose an application has a back office whose controllers are stored in +`app/controllers/admin`. If the `Admin` module is not yet loaded when +`Admin::UsersController` is hit, Rails needs first to autoload the constant +`Admin`. + +If `autoload_paths` has a file called `admin.rb` Rails is going to load that +one, but if there's no such file and a directory called `admin` is found, Rails +creates an empty module and assigns it to the `Admin` constant on the fly. + +### Generic Procedure + +Relative references are reported to be missing in the cref where they were hit, +and qualified references are reported to be missing in their parent (see +[Resolution Algorithm for Relative +Constants](#resolution-algorithm-for-relative-constants) at the beginning of +this guide for the definition of *cref*, and [Resolution Algorithm for Qualified +Constants](#resolution-algorithm-for-qualified-constants) for the definition of +*parent*). + +The procedure to autoload constant `C` in an arbitrary situation is as follows: + +``` +if the class or module in which C is missing is Object + let ns = '' +else + let M = the class or module in which C is missing + + if M is anonymous + let ns = '' + else + let ns = M.name + end +end + +loop do + # Look for a regular file. + for dir in autoload_paths + if the file "#{dir}/#{ns.underscore}/c.rb" exists + load/require "#{dir}/#{ns.underscore}/c.rb" + + if C is now defined + return + else + raise LoadError + end + end + end + + # Look for an automatic module. + for dir in autoload_paths + if the directory "#{dir}/#{ns.underscore}/c" exists + if ns is an empty string + let C = Module.new in Object and return + else + let C = Module.new in ns.constantize and return + end + end + end + + if ns is empty + # We reached the top-level without finding the constant. + raise NameError + else + if C exists in any of the parent namespaces + # Qualified constants heuristic. + raise NameError + else + # Try again in the parent namespace. + let ns = the parent namespace of ns and retry + end + end +end +``` + + +require_dependency +------------------ + +Constant autoloading is triggered on demand and therefore code that uses a +certain constant may have it already defined or may trigger an autoload. That +depends on the execution path and it may vary between runs. + +There are times, however, in which you want to make sure a certain constant is +known when the execution reaches some code. `require_dependency` provides a way +to load a file using the current [loading mechanism](#loading-mechanism), and +keeping track of constants defined in that file as if they were autoloaded to +have them reloaded as needed. + +`require_dependency` is rarely needed, but see a couple of use cases in +[Autoloading and STI](#autoloading-and-sti) and [When Constants aren't +Triggered](#when-constants-aren-t-missed). + +WARNING. Unlike autoloading, `require_dependency` does not expect the file to +define any particular constant. Exploiting this behavior would be a bad practice +though, file and constant paths should match. + + +Constant Reloading +------------------ + +When `config.cache_classes` is false Rails is able to reload autoloaded +constants. + +For example, if you're in a console session and edit some file behind the +scenes, the code can be reloaded with the `reload!` command: + +``` +> reload! +``` + +When the application runs, code is reloaded when something relevant to this +logic changes. In order to do that, Rails monitors a number of things: + +* `config/routes.rb`. + +* Locales. + +* Ruby files under `autoload_paths`. + +* `db/schema.rb` and `db/structure.sql`. + +If anything in there changes, there is a middleware that detects it and reloads +the code. + +Autoloading keeps track of autoloaded constants. Reloading is implemented by +removing them all from their respective classes and modules using +`Module#remove_const`. That way, when the code goes on, those constants are +going to be unknown again, and files reloaded on demand. + +INFO. This is an all-or-nothing operation, Rails does not attempt to reload only +what changed since dependencies between classes makes that really tricky. +Instead, everything is wiped. + +Common Gotchas +-------------- + +### Nesting and Qualified Constants + +Let's consider + +```ruby +module Admin + class UsersController < ApplicationController + def index + @users = User.all + end + end +end +``` + +and + +```ruby +class Admin::UsersController < ApplicationController + def index + @users = User.all + end +end +``` + +To resolve `User` Ruby checks `Admin` in the former case, but it does not in +the latter because it does not belong to the nesting (see [Nesting](#nesting) +and [Resolution Algorithms](#resolution-algorithms)). + +Unfortunately Rails autoloading does not know the nesting in the spot where the +constant was missing and so it is not able to act as Ruby would. In particular, +`Admin::User` will get autoloaded in either case. + +Albeit qualified constants with `class` and `module` keywords may technically +work with autoloading in some cases, it is preferable to use relative constants +instead: + +```ruby +module Admin + class UsersController < ApplicationController + def index + @users = User.all + end + end +end +``` + +### Autoloading and STI + +Single Table Inheritance (STI) is a feature of Active Record that enables +storing a hierarchy of models in one single table. The API of such models is +aware of the hierarchy and encapsulates some common needs. For example, given +these classes: + +```ruby +# app/models/polygon.rb +class Polygon < ApplicationRecord +end + +# app/models/triangle.rb +class Triangle < Polygon +end + +# app/models/rectangle.rb +class Rectangle < Polygon +end +``` + +`Triangle.create` creates a row that represents a triangle, and +`Rectangle.create` creates a row that represents a rectangle. If `id` is the +ID of an existing record, `Polygon.find(id)` returns an object of the correct +type. + +Methods that operate on collections are also aware of the hierarchy. For +example, `Polygon.all` returns all the records of the table, because all +rectangles and triangles are polygons. Active Record takes care of returning +instances of their corresponding class in the result set. + +Types are autoloaded as needed. For example, if `Polygon.first` is a rectangle +and `Rectangle` has not yet been loaded, Active Record autoloads it and the +record is correctly instantiated. + +All good, but if instead of performing queries based on the root class we need +to work on some subclass, things get interesting. + +While working with `Polygon` you do not need to be aware of all its descendants, +because anything in the table is by definition a polygon, but when working with +subclasses Active Record needs to be able to enumerate the types it is looking +for. Let's see an example. + +`Rectangle.all` only loads rectangles by adding a type constraint to the query: + +```sql +SELECT "polygons".* FROM "polygons" +WHERE "polygons"."type" IN ("Rectangle") +``` + +Let's introduce now a subclass of `Rectangle`: + +```ruby +# app/models/square.rb +class Square < Rectangle +end +``` + +`Rectangle.all` should now return rectangles **and** squares: + +```sql +SELECT "polygons".* FROM "polygons" +WHERE "polygons"."type" IN ("Rectangle", "Square") +``` + +But there's a caveat here: How does Active Record know that the class `Square` +exists at all? + +Even if the file `app/models/square.rb` exists and defines the `Square` class, +if no code yet used that class, `Rectangle.all` issues the query + +```sql +SELECT "polygons".* FROM "polygons" +WHERE "polygons"."type" IN ("Rectangle") +``` + +That is not a bug, the query includes all *known* descendants of `Rectangle`. + +A way to ensure this works correctly regardless of the order of execution is to +manually load the direct subclasses at the bottom of the file that defines each +intermediate class: + +```ruby +# app/models/rectangle.rb +class Rectangle < Polygon +end +require_dependency 'square' +``` + +This needs to happen for every intermediate (non-root and non-leaf) class. The +root class does not scope the query by type, and therefore does not necessarily +have to know all its descendants. + +### Autoloading and `require` + +Files defining constants to be autoloaded should never be `require`d: + +```ruby +require 'user' # DO NOT DO THIS + +class UsersController < ApplicationController + ... +end +``` + +There are two possible gotchas here in development mode: + +1. If `User` is autoloaded before reaching the `require`, `app/models/user.rb` +runs again because `load` does not update `$LOADED_FEATURES`. + +2. If the `require` runs first Rails does not mark `User` as an autoloaded +constant and changes to `app/models/user.rb` aren't reloaded. + +Just follow the flow and use constant autoloading always, never mix +autoloading and `require`. As a last resort, if some file absolutely needs to +load a certain file use `require_dependency` to play nice with constant +autoloading. This option is rarely needed in practice, though. + +Of course, using `require` in autoloaded files to load ordinary 3rd party +libraries is fine, and Rails is able to distinguish their constants, they are +not marked as autoloaded. + +### Autoloading and Initializers + +Consider this assignment in `config/initializers/set_auth_service.rb`: + +```ruby +AUTH_SERVICE = if Rails.env.production? + RealAuthService +else + MockedAuthService +end +``` + +The purpose of this setup would be that the application uses the class that +corresponds to the environment via `AUTH_SERVICE`. In development mode +`MockedAuthService` gets autoloaded when the initializer runs. Let's suppose +we do some requests, change its implementation, and hit the application again. +To our surprise the changes are not reflected. Why? + +As [we saw earlier](#constant-reloading), Rails removes autoloaded constants, +but `AUTH_SERVICE` stores the original class object. Stale, non-reachable +using the original constant, but perfectly functional. + +The following code summarizes the situation: + +```ruby +class C + def quack + 'quack!' + end +end + +X = C +Object.instance_eval { remove_const(:C) } +X.new.quack # => quack! +X.name # => C +C # => uninitialized constant C (NameError) +``` + +Because of that, it is not a good idea to autoload constants on application +initialization. + +In the case above we could implement a dynamic access point: + +```ruby +# app/models/auth_service.rb +class AuthService + if Rails.env.production? + def self.instance + RealAuthService + end + else + def self.instance + MockedAuthService + end + end +end +``` + +and have the application use `AuthService.instance` instead. `AuthService` +would be loaded on demand and be autoload-friendly. + +### `require_dependency` and Initializers + +As we saw before, `require_dependency` loads files in an autoloading-friendly +way. Normally, though, such a call does not make sense in an initializer. + +One could think about doing some [`require_dependency`](#require-dependency) +calls in an initializer to make sure certain constants are loaded upfront, for +example as an attempt to address the [gotcha with STIs](#autoloading-and-sti). + +Problem is, in development mode [autoloaded constants are wiped](#constant-reloading) +if there is any relevant change in the file system. If that happens then +we are in the very same situation the initializer wanted to avoid! + +Calls to `require_dependency` have to be strategically written in autoloaded +spots. + +### When Constants aren't Missed + +#### Relative References + +Let's consider a flight simulator. The application has a default flight model + +```ruby +# app/models/flight_model.rb +class FlightModel +end +``` + +that can be overridden by each airplane, for instance + +```ruby +# app/models/bell_x1/flight_model.rb +module BellX1 + class FlightModel < FlightModel + end +end + +# app/models/bell_x1/aircraft.rb +module BellX1 + class Aircraft + def initialize + @flight_model = FlightModel.new + end + end +end +``` + +The initializer wants to create a `BellX1::FlightModel` and nesting has +`BellX1`, that looks good. But if the default flight model is loaded and the +one for the Bell-X1 is not, the interpreter is able to resolve the top-level +`FlightModel` and autoloading is thus not triggered for `BellX1::FlightModel`. + +That code depends on the execution path. + +These kind of ambiguities can often be resolved using qualified constants: + +```ruby +module BellX1 + class Plane + def flight_model + @flight_model ||= BellX1::FlightModel.new + end + end +end +``` + +Also, `require_dependency` is a solution: + +```ruby +require_dependency 'bell_x1/flight_model' + +module BellX1 + class Plane + def flight_model + @flight_model ||= FlightModel.new + end + end +end +``` + +#### Qualified References + +WARNING. This gotcha is only possible in Ruby < 2.5. + +Given + +```ruby +# app/models/hotel.rb +class Hotel +end + +# app/models/image.rb +class Image +end + +# app/models/hotel/image.rb +class Hotel + class Image < Image + end +end +``` + +the expression `Hotel::Image` is ambiguous because it depends on the execution +path. + +As [we saw before](#resolution-algorithm-for-qualified-constants), Ruby looks +up the constant in `Hotel` and its ancestors. If `app/models/image.rb` has +been loaded but `app/models/hotel/image.rb` hasn't, Ruby does not find `Image` +in `Hotel`, but it does in `Object`: + +``` +$ rails r 'Image; p Hotel::Image' 2>/dev/null +Image # NOT Hotel::Image! +``` + +The code evaluating `Hotel::Image` needs to make sure +`app/models/hotel/image.rb` has been loaded, possibly with +`require_dependency`. + +In these cases the interpreter issues a warning though: + +``` +warning: toplevel constant Image referenced by Hotel::Image +``` + +This surprising constant resolution can be observed with any qualifying class: + +``` +2.1.5 :001 > String::Array +(irb):1: warning: toplevel constant Array referenced by String::Array + => Array +``` + +WARNING. To find this gotcha the qualifying namespace has to be a class, +`Object` is not an ancestor of modules. + +### Autoloading within Singleton Classes + +Let's suppose we have these class definitions: + +```ruby +# app/models/hotel/services.rb +module Hotel + class Services + end +end + +# app/models/hotel/geo_location.rb +module Hotel + class GeoLocation + class << self + Services + end + end +end +``` + +If `Hotel::Services` is known by the time `app/models/hotel/geo_location.rb` +is being loaded, `Services` is resolved by Ruby because `Hotel` belongs to the +nesting when the singleton class of `Hotel::GeoLocation` is opened. + +But if `Hotel::Services` is not known, Rails is not able to autoload it, the +application raises `NameError`. + +The reason is that autoloading is triggered for the singleton class, which is +anonymous, and as [we saw before](#generic-procedure), Rails only checks the +top-level namespace in that edge case. + +An easy solution to this caveat is to qualify the constant: + +```ruby +module Hotel + class GeoLocation + class << self + Hotel::Services + end + end +end +``` + +### Autoloading in `BasicObject` + +Direct descendants of `BasicObject` do not have `Object` among their ancestors +and cannot resolve top-level constants: + +```ruby +class C < BasicObject + String # NameError: uninitialized constant C::String +end +``` + +When autoloading is involved that plot has a twist. Let's consider: + +```ruby +class C < BasicObject + def user + User # WRONG + end +end +``` + +Since Rails checks the top-level namespace `User` gets autoloaded just fine the +first time the `user` method is invoked. You only get the exception if the +`User` constant is known at that point, in particular in a *second* call to +`user`: + +```ruby +c = C.new +c.user # surprisingly fine, User +c.user # NameError: uninitialized constant C::User +``` + +because it detects that a parent namespace already has the constant (see [Qualified +References](#autoloading-algorithms-qualified-references)). + +As with pure Ruby, within the body of a direct descendant of `BasicObject` use +always absolute constant paths: + +```ruby +class C < BasicObject + ::String # RIGHT + + def user + ::User # RIGHT + end +end +``` + +### Autoloading in the Test Environment + +When configuring the `test` environment for autoloading you might consider multiple factors. + +For example it might be worth running your tests with an identical setup to production (`config.eager_load = true`, `config.cache_classes = true`) in order to catch any problems before they hit production (this is compensation for the lack of dev-prod parity). However this will slow down the boot time for individual tests on a dev machine (and is not immediately compatible with spring see below). So one possibility is to do this on a +[CI](https://en.wikipedia.org/wiki/Continuous_integration) machine only (which should run without spring). + +On a development machine you can then have your tests running with whatever is fastest (ideally `config.eager_load = false`). + +With the [Spring](https://github.com/rails/spring) pre-loader (included with new Rails apps), you ideally keep `config.eager_load = false` as per development. Sometimes you may end up with a hybrid configuration (`config.eager_load = true`, `config.cache_classes = true` AND `config.enable_dependency_loading = true`), see [spring issue](https://github.com/rails/spring/issues/519#issuecomment-348324369). However it might be simpler to keep the same configuration as development, and work out whatever it is that is causing autoloading to fail (perhaps by the results of your CI test results). + +Occasionally you may need to explicitly eager_load by using `Rails +.application.eager_load!` in the setup of your tests -- this might occur if your [tests involve multithreading](https://stackoverflow.com/questions/25796409/in-rails-how-can-i-eager-load-all-code-before-a-specific-rspec-test). + +## Troubleshooting + +### Tracing Autoloads + +Active Support is able to report constants as they are autoloaded. To enable these traces in a Rails application, put the following two lines in some initializer: + +```ruby +ActiveSupport::Dependencies.logger = Rails.logger +ActiveSupport::Dependencies.verbose = true +``` + +### Where is a Given Autoload Triggered? + +If constant `Foo` is being autoloaded, and you'd like to know where is that autoload coming from, just throw + +```ruby +puts caller +``` + +at the top of `foo.rb` and inspect the printed stack trace. + +### Which Constants Have Been Autoloaded? + +At any given time, + +```ruby +ActiveSupport::Dependencies.autoloaded_constants +``` + +has the collection of constants that have been autoloaded so far. diff --git a/guides/source/command_line.md b/guides/source/command_line.md index 55f8c84b66..60d0de17bc 100644 --- a/guides/source/command_line.md +++ b/guides/source/command_line.md @@ -92,6 +92,28 @@ $ rails new commandsapp Rails will set you up with what seems like a huge amount of stuff for such a tiny command! You've got the entire Rails directory structure now with all the code you need to run our simple application right out of the box. +If you wish to skip some files or components from being generated, you can append the following arguments to your `rails new` command: + +| Argument | Description | +| ----------------------- | ----------------------------------------------------------- | +| `--skip-gemfile` | Don't create a Gemfile | +| `--skip-git` | Skip .gitignore file | +| `--skip-keeps` | Skip source control .keep files | +| `--skip-action-mailer` | Skip Action Mailer files | +| `--skip-action-text` | Skip Action Text gem | +| `--skip-active-record` | Skip Active Record files | +| `--skip-active-storage` | Skip Active Storage files | +| `--skip-puma` | Skip Puma related files | +| `--skip-action-cable` | Skip Action Cable files | +| `--skip-sprockets` | Skip Sprockets files | +| `--skip-spring` | Don't install Spring application preloader | +| `--skip-listen` | Don't generate configuration that depends on the listen gem | +| `--skip-javascript` | Skip JavaScript files | +| `--skip-turbolinks` | Skip turbolinks gem | +| `--skip-test` | Skip test files | +| `--skip-system-test` | Skip system test files | +| `--skip-bootsnap` | Skip bootsnap gem | + ### `rails server` The `rails server` command launches a web server named Puma which comes bundled with Rails. You'll use this any time you want to access your application through a web browser. @@ -579,6 +601,8 @@ The `tmp:` namespaced commands will help you clear and create the `Rails.root/tm ### Miscellaneous +* `rails initializers` prints out all defined initializers in the order they are invoked by Rails. +* `rails middleware` lists Rack middleware stack enabled for your app. * `rails stats` is great for looking at statistics on your code, displaying things like KLOCs (thousands of lines of code) and your code to test ratio. * `rails secret` will give you a pseudo-random key to use for your session secret. * `rails time:zones:all` lists all the timezones Rails knows about. diff --git a/guides/source/configuring.md b/guides/source/configuring.md index 3863323bd2..c5d3d09bd0 100644 --- a/guides/source/configuring.md +++ b/guides/source/configuring.md @@ -69,7 +69,7 @@ These configuration methods are to be called on a `Rails::Railtie` object, such * `config.cache_classes` controls whether or not application classes and modules should be reloaded on each request. Defaults to `false` in development mode, and `true` in test and production modes. * `config.beginning_of_week` sets the default beginning of week for the -application. Accepts a valid week day symbol (e.g. `:monday`). +application. Accepts a valid day of week as a symbol (e.g. `:monday`). * `config.cache_store` configures which cache store to use for Rails caching. Options include one of the symbols `:memory_store`, `:file_store`, `:mem_cache_store`, `:null_store`, `:redis_cache_store`, or an object that implements the cache API. Defaults to `:file_store`. @@ -145,7 +145,7 @@ defaults to `:debug` for all environments. The available log levels are: `:debug * `secret_key_base` is used for specifying a key which allows sessions for the application to be verified against a known secure key to prevent tampering. Applications get a random generated key in test and development environments, other environments should set one in `config/credentials.yml.enc`. -* `config.public_file_server.enabled` configures Rails to serve static files from the public directory. This option defaults to `true`, but in the production environment it is set to `false` because the server software (e.g. NGINX or Apache) used to run the application should serve static files instead. If you are running or testing your app in production mode using WEBrick (it is not recommended to use WEBrick in production) set the option to `true.` Otherwise, you won't be able to use page caching and request for files that exist under the public directory. +* `config.public_file_server.enabled` configures Rails to serve static files from the public directory. This option defaults to `true`, but in the production environment it is set to `false` because the server software (e.g. NGINX or Apache) used to run the application should serve static files instead. If you are running or testing your app in production mode using WEBrick (it is not recommended to use WEBrick in production) set the option to `true`. Otherwise, you won't be able to use page caching and request for files that exist under the public directory. * `config.session_store` specifies what class to use to store the session. Possible values are `:cookie_store` which is the default, `:mem_cache_store`, and `:disabled`. The last one tells Rails not to deal with sessions. Defaults to a cookie store with application name as the session key. Custom session stores can also be specified: @@ -157,6 +157,13 @@ defaults to `:debug` for all environments. The available log levels are: `:debug * `config.time_zone` sets the default time zone for the application and enables time zone awareness for Active Record. +* `config.autoloader` sets the autoloading mode. This option defaults to `:zeitwerk` if `6.0` is specified in `config.load_defaults`. Applications can still use the classic autoloader by setting this value to `:classic` after loading the framework defaults: + + ```ruby + config.load_defaults "6.0" + config.autoloader = :classic + ``` + ### Configuring Assets * `config.assets.enabled` a flag that controls whether the asset @@ -346,7 +353,7 @@ All these configuration options are delegated to the `I18n` library. * `config.active_record.lock_optimistically` controls whether Active Record will use optimistic locking and is `true` by default. -* `config.active_record.cache_timestamp_format` controls the format of the timestamp value in the cache key. Default is `:nsec`. +* `config.active_record.cache_timestamp_format` controls the format of the timestamp value in the cache key. Default is `:usec`. * `config.active_record.record_timestamps` is a boolean value which controls whether or not timestamping of `create` and `update` operations on a model occur. The default value is `true`. @@ -383,6 +390,12 @@ All these configuration options are delegated to the `I18n` library. having to send a query to the database to get this information. Defaults to `true`. +* `config.active_record.collection_cache_versioning` enables the same cache key + to be reused when the object being cached of type `ActiveRecord::Relation` + changes by moving the volatile information (max updated at and count) of + the relation's cache key into the cache version to support recycling cache key. + Defaults to `false`. + The MySQL adapter adds one additional configuration option: * `ActiveRecord::ConnectionAdapters::Mysql2Adapter.emulate_booleans` controls whether Active Record will consider all `tinyint(1)` columns as booleans. Defaults to `true`. @@ -540,6 +553,10 @@ Defaults to `'signed cookie'`. Any exceptions that are not configured will be mapped to 500 Internal Server Error. +* `config.action_dispatch.return_only_media_type_on_content_type` change the + return value of `ActionDispatch::Response#content_type` to the Content-Type + header without modification. Defaults to `false`. + * `ActionDispatch::Callbacks.before` takes a block of code to run before the request. * `ActionDispatch::Callbacks.after` takes a block of code to run after the request. @@ -822,10 +839,12 @@ You can find more detailed configuration options in the config.active_storage.paths[:ffprobe] = '/usr/local/bin/ffprobe' ``` -* `config.active_storage.variable_content_types` accepts an array of strings indicating the content types that Active Storage can transform through ImageMagick. The default is `%w(image/png image/gif image/jpg image/jpeg image/pjpeg image/tiff image/vnd.adobe.photoshop image/vnd.microsoft.icon)`. +* `config.active_storage.variable_content_types` accepts an array of strings indicating the content types that Active Storage can transform through ImageMagick. The default is `%w(image/png image/gif image/jpg image/jpeg image/pjpeg image/tiff image/bmp image/vnd.adobe.photoshop image/vnd.microsoft.icon)`. * `config.active_storage.content_types_to_serve_as_binary` accepts an array of strings indicating the content types that Active Storage will always serve as an attachment, rather than inline. The default is `%w(text/html -text/javascript image/svg+xml application/postscript application/x-shockwave-flash text/xml application/xml application/xhtml+xml)`. +text/javascript image/svg+xml application/postscript application/x-shockwave-flash text/xml application/xml application/xhtml+xml application/mathml+xml text/cache-manifest)`. + +* `config.active_storage.content_types_allowed_inline` accepts an array of strings indicating the content types that Active Storage allows to serve as inline. The default is `%w(image/png image/gif image/jpg image/jpeg image/vnd.adobe.photoshop image/vnd.microsoft.icon application/pdf)`. * `config.active_storage.queues.analysis` accepts a symbol indicating the Active Job queue to use for analysis jobs. When this option is `nil`, analysis jobs are sent to the default Active Job queue (see `config.active_job.default_queue_name`). @@ -839,6 +858,12 @@ text/javascript image/svg+xml application/postscript application/x-shockwave-fla config.active_storage.queues.purge = :low_priority ``` +* `config.active_storage.queues.mirror` accepts a symbol indicating the Active Job queue to use for direct upload mirroring jobs. The default is `:active_storage_mirror`. + + ```ruby + config.active_storage.queues.mirror = :low_priority + ``` + * `config.active_storage.logger` can be used to set the logger used by Active Storage. Accepts a logger conforming to the interface of Log4r or the default Ruby Logger class. ```ruby @@ -858,7 +883,11 @@ text/javascript image/svg+xml application/postscript application/x-shockwave-fla config.active_storage.routes_prefix = '/files' ``` - The default is `/rails/active_storage` + The default is `/rails/active_storage`. + +* `config.active_storage.replace_on_assign_to_many` determines whether assigning to a collection of attachments declared with `has_many_attached` replaces any existing attachments or appends to them. The default is `true`. + +* `config.active_storage.draw_routes` can be used to toggle Active Storage route generation. The default is `true`. ### Results of `load_defaults` @@ -878,7 +907,7 @@ text/javascript image/svg+xml application/postscript application/x-shockwave-fla #### With '5.2': - `config.active_record.cache_versioning`: `true` -- `action_dispatch.use_authenticated_cookie_encryption`: `true` +- `config.action_dispatch.use_authenticated_cookie_encryption`: `true` - `config.active_support.use_authenticated_message_encryption`: `true` - `config.active_support.use_sha1_digests`: `true` - `config.action_controller.default_protect_from_forgery`: `true` @@ -886,12 +915,16 @@ text/javascript image/svg+xml application/postscript application/x-shockwave-fla #### With '6.0': +- `config.autoloader`: `:zeitwerk` - `config.action_view.default_enforce_utf8`: `false` - `config.action_dispatch.use_cookies_with_metadata`: `true` +- `config.action_dispatch.return_only_media_type_on_content_type`: `false` - `config.action_mailer.delivery_job`: `"ActionMailer::MailDeliveryJob"` - `config.active_job.return_false_on_aborted_enqueue`: `true` - `config.active_storage.queues.analysis`: `:active_storage_analysis` - `config.active_storage.queues.purge`: `:active_storage_purge` +- `config.active_storage.replace_on_assign_to_many`: `true` +- `config.active_record.collection_cache_versioning`: `true` ### Configuring a Database @@ -1515,7 +1548,7 @@ Disallow: / ``` To block just specific pages, it's necessary to use a more complex syntax. Learn -it on the [official documentation](http://www.robotstxt.org/robotstxt.html). +it on the [official documentation](https://www.robotstxt.org/robotstxt.html). Evented File System Monitor --------------------------- diff --git a/guides/source/contributing_to_ruby_on_rails.md b/guides/source/contributing_to_ruby_on_rails.md index f86589bdf1..9c28ff6a9c 100644 --- a/guides/source/contributing_to_ruby_on_rails.md +++ b/guides/source/contributing_to_ruby_on_rails.md @@ -13,7 +13,7 @@ After reading this guide, you will know: * How to contribute to the Ruby on Rails documentation. * How to contribute to the Ruby on Rails code. -Ruby on Rails is not "someone else's framework." Over the years, thousands of people have contributed to Ruby on Rails ranging from a single character to massive architectural changes or significant documentation - all with the goal of making Ruby on Rails better for everyone. Even if you don't feel up to writing code or documentation yet, there are a variety of other ways that you can contribute, from reporting issues to testing patches. +Ruby on Rails is not "someone else's framework". Over the years, thousands of people have contributed to Ruby on Rails ranging from a single character to massive architectural changes or significant documentation - all with the goal of making Ruby on Rails better for everyone. Even if you don't feel up to writing code or documentation yet, there are a variety of other ways that you can contribute, from reporting issues to testing patches. As mentioned in [Rails' README](https://github.com/rails/rails/blob/master/README.md), everyone interacting in Rails and its sub-projects' codebases, issue trackers, chat rooms, and mailing lists is expected to follow the Rails [code of conduct](https://rubyonrails.org/conduct/). @@ -76,7 +76,7 @@ a patch, please send an email to the [rails-core mailing list](https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core). You might get no response, which means that everyone is indifferent. You might find someone who's also interested in building that feature. You might get a "This -won't be accepted." But it's the proper place to discuss new ideas. GitHub +won't be accepted". But it's the proper place to discuss new ideas. GitHub Issues are not a particularly good venue for the sometimes long and involved discussions new features require. @@ -139,7 +139,7 @@ changes to the master branch. When working with documentation, please take into account the [API Documentation Guidelines](api_documentation_guidelines.html) and the [Ruby on Rails Guides Guidelines](ruby_on_rails_guides_guidelines.html). -NOTE: To help our CI servers you should add [ci skip] to your documentation commit message to skip build on that commit. Please remember to use it for commits containing only documentation changes. +NOTE: For documentation changes, your commit message should include [ci skip]. This will skip running the test suite, helping us to cut down on our server costs. Keep in mind that you should only skip CI when your change touches documentation exclusively. Translating Rails Guides ------------------------ @@ -340,7 +340,7 @@ $ TEST_DIR=generators bundle exec rake test You can run the tests for a particular file by using: ```bash -$ cd actionpack +$ cd actionview $ bundle exec ruby -w -Itest test/template/form_helper_test.rb ``` diff --git a/guides/source/documents.yaml b/guides/source/documents.yaml index 1e67b2bce7..da11236064 100644 --- a/guides/source/documents.yaml +++ b/guides/source/documents.yaml @@ -139,9 +139,13 @@ url: initialization.html description: This guide explains the internals of the Rails initialization process. - - name: Autoloading and Reloading Constants + name: Autoloading and Reloading Constants (Zeitwerk Mode) url: autoloading_and_reloading_constants.html - description: This guide documents how autoloading and reloading constants work. + description: This guide documents how autoloading and reloading constants work (Zeitwerk mode). + - + name: Autoloading and Reloading Constants (Classic Mode) + url: autoloading_and_reloading_constants_classic_mode.html + description: This guide documents how autoloading and reloading constants work (Classic mode). - name: "Caching with Rails: An Overview" url: caching_with_rails.html @@ -160,6 +164,11 @@ work_in_progress: true url: active_record_postgresql.html description: This guide covers PostgreSQL specific usage of Active Record. + - + name: Multiple Databases with Active Record + work_in_progress: true + url: active_record_multiple_databases.html + description: This guide covers using multiple databases in your application. - name: Extending Rails @@ -193,7 +202,7 @@ - name: Contributing to Ruby on Rails url: contributing_to_ruby_on_rails.html - description: Rails is not 'somebody else's framework.' This guide covers a variety of ways that you can get involved in the ongoing development of Rails. + description: Rails is not "someone else's framework". This guide covers a variety of ways that you can get involved in the ongoing development of Rails. - name: API Documentation Guidelines url: api_documentation_guidelines.html diff --git a/guides/source/engines.md b/guides/source/engines.md index 3031c62928..8961a079b5 100644 --- a/guides/source/engines.md +++ b/guides/source/engines.md @@ -220,7 +220,7 @@ Inside the `app` directory are the standard `assets`, `controllers`, `helpers`, `jobs`, `mailers`, `models`, and `views` directories that you should be familiar with from an application. We'll look more into models in a future section, when we're writing the engine. -Within the `app/assets` directory, there are the `images`, `javascripts` and +Within the `app/assets` directory, there are the `images` and `stylesheets` directories which, again, you should be familiar with due to their similarity to an application. One difference here, however, is that each directory contains a sub-directory with the engine name. Because this engine is @@ -1511,34 +1511,35 @@ These are the hooks you can use in your own code. To hook into the initialization process of one of the following classes use the available hook. -| Class | Available Hooks | -| --------------------------------- | ------------------------------------ | -| `ActionCable` | `action_cable` | -| `ActionCable::Channel::Base` | `action_cable_channel` | -| `ActionCable::Connection::Base` | `action_cable_connection` | -| `ActionController::API` | `action_controller_api` | -| `ActionController::API` | `action_controller` | -| `ActionController::Base` | `action_controller_base` | -| `ActionController::Base` | `action_controller` | -| `ActionController::TestCase` | `action_controller_test_case` | -| `ActionDispatch::IntegrationTest` | `action_dispatch_integration_test` | -| `ActionDispatch::SystemTestCase` | `action_dispatch_system_test_case` | -| `ActionMailbox::Base` | `action_mailbox` | -| `ActionMailbox::InboundEmail` | `action_mailbox_inbound_email` | -| `ActionMailbox::TestCase` | `action_mailbox_test_case` | -| `ActionMailer::Base` | `action_mailer` | -| `ActionMailer::TestCase` | `action_mailer_test_case` | -| `ActionText::Content` | `action_text_content` | -| `ActionText::RichText` | `action_text_rich_text` | -| `ActionView::Base` | `action_view` | -| `ActionView::TestCase` | `action_view_test_case` | -| `ActiveJob::Base` | `active_job` | -| `ActiveJob::TestCase` | `active_job_test_case` | -| `ActiveRecord::Base` | `active_record` | -| `ActiveStorage::Attachment` | `active_storage_attachment` | -| `ActiveStorage::Blob` | `active_storage_blob` | -| `ActiveSupport::TestCase` | `active_support_test_case` | -| `i18n` | `i18n` | +| Class | Available Hooks | +| -------------------------------------| ------------------------------------ | +| `ActionCable` | `action_cable` | +| `ActionCable::Channel::Base` | `action_cable_channel` | +| `ActionCable::Connection::Base` | `action_cable_connection` | +| `ActionCable::Connection::TestCase` | `action_cable_connection_test_case` | +| `ActionController::API` | `action_controller_api` | +| `ActionController::API` | `action_controller` | +| `ActionController::Base` | `action_controller_base` | +| `ActionController::Base` | `action_controller` | +| `ActionController::TestCase` | `action_controller_test_case` | +| `ActionDispatch::IntegrationTest` | `action_dispatch_integration_test` | +| `ActionDispatch::SystemTestCase` | `action_dispatch_system_test_case` | +| `ActionMailbox::Base` | `action_mailbox` | +| `ActionMailbox::InboundEmail` | `action_mailbox_inbound_email` | +| `ActionMailbox::TestCase` | `action_mailbox_test_case` | +| `ActionMailer::Base` | `action_mailer` | +| `ActionMailer::TestCase` | `action_mailer_test_case` | +| `ActionText::Content` | `action_text_content` | +| `ActionText::RichText` | `action_text_rich_text` | +| `ActionView::Base` | `action_view` | +| `ActionView::TestCase` | `action_view_test_case` | +| `ActiveJob::Base` | `active_job` | +| `ActiveJob::TestCase` | `active_job_test_case` | +| `ActiveRecord::Base` | `active_record` | +| `ActiveStorage::Attachment` | `active_storage_attachment` | +| `ActiveStorage::Blob` | `active_storage_blob` | +| `ActiveSupport::TestCase` | `active_support_test_case` | +| `i18n` | `i18n` | ## Configuration hooks diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md index 7000fa408c..ce45dbb2a7 100644 --- a/guides/source/getting_started.md +++ b/guides/source/getting_started.md @@ -28,7 +28,7 @@ curve diving straight into Rails. There are several curated lists of online reso for learning Ruby: * [Official Ruby Programming Language website](https://www.ruby-lang.org/en/documentation/) -* [List of Free Programming Books](https://github.com/vhf/free-programming-books/blob/master/free-programming-books.md#ruby) +* [List of Free Programming Books](https://github.com/EbookFoundation/free-programming-books/blob/master/free-programming-books.md#ruby) Be aware that some resources, while still excellent, cover versions of Ruby as old as 1.6, and commonly 1.8, and will not include some syntax that you will see in day-to-day @@ -55,7 +55,7 @@ The Rails philosophy includes two major guiding principles: * **Don't Repeat Yourself:** DRY is a principle of software development which states that "Every piece of knowledge must have a single, unambiguous, authoritative - representation within a system." By not writing the same information over and over + representation within a system". By not writing the same information over and over again, our code is more maintainable, more extensible, and less buggy. * **Convention Over Configuration:** Rails has opinions about the best way to do many things in a web application, and defaults to this set of conventions, rather than @@ -207,7 +207,7 @@ folder directly to the Ruby interpreter e.g. `ruby bin\rails server`. TIP: JavaScript asset compression requires you have a JavaScript runtime available on your system, in the absence -of a runtime you will see an `execjs` error during asset compilation. +of a runtime you will see an `execjs` error during asset compression. Usually macOS and Windows come with a JavaScript runtime installed. `therubyrhino` is the recommended runtime for JRuby users and is added by default to the `Gemfile` in apps generated under JRuby. You can investigate diff --git a/guides/source/initialization.md b/guides/source/initialization.md index c41eae18cf..556c85cc0f 100644 --- a/guides/source/initialization.md +++ b/guides/source/initialization.md @@ -108,6 +108,8 @@ A standard Rails application depends on several gems, specifically: * activerecord * activestorage * activesupport +* actionmailbox +* actiontext * arel * builder * bundler @@ -160,8 +162,8 @@ namespace and executes the command if found. If Rails doesn't recognize the command, it hands the reins over to Rake to run a task of the same name. -As shown, `Rails::Command` displays the help output automatically if the `args` -are empty. +As shown, `Rails::Command` displays the help output automatically if the `namespace` +is empty. ```ruby module Rails::Command @@ -289,7 +291,7 @@ def default_options environment: (ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development").dup, daemonize: false, caching: nil, - pid: Options::DEFAULT_PID_PATH, + pid: ENV.fetch("PIDFILE", Options::DEFAULT_PIDFILE).dup, restart_cmd: restart_command) end ``` @@ -538,6 +540,8 @@ require "rails" action_mailer/railtie active_job/railtie action_cable/engine + action_mailbox/engine + action_text/engine rails/test_unit/railtie sprockets/railtie ).each do |railtie| diff --git a/guides/source/layouts_and_rendering.md b/guides/source/layouts_and_rendering.md index 39935cd2ef..ce90a60e36 100644 --- a/guides/source/layouts_and_rendering.md +++ b/guides/source/layouts_and_rendering.md @@ -149,25 +149,6 @@ Rails knows that this view belongs to a different controller because of the embe render template: "products/show" ``` -#### Rendering an Arbitrary File - -The `render` method can also use a view that's entirely outside of your application: - -```ruby -render file: "/u/apps/warehouse_app/current/app/views/products/show" -``` - -The `:file` option takes an absolute file-system path. Of course, you need to have rights -to the view that you're using to render the content. - -NOTE: Using the `:file` option in combination with users input can lead to security problems -since an attacker could use this action to access security sensitive files in your file system. - -NOTE: By default, the file is rendered using the current layout. - -TIP: If you're running Rails on Microsoft Windows, you should use the `:file` option to -render a file, because Windows filenames do not have the same format as Unix filenames. - #### Wrapping it up The above three ways of rendering (rendering another template within the controller, rendering a template within another controller, and rendering an arbitrary file on the file system) are actually variants of the same action. @@ -178,17 +159,9 @@ In fact, in the BooksController class, inside of the update action where we want render :edit render action: :edit render "edit" -render "edit.html.erb" render action: "edit" -render action: "edit.html.erb" render "books/edit" -render "books/edit.html.erb" render template: "books/edit" -render template: "books/edit.html.erb" -render "/path/to/rails/app/views/books/edit" -render "/path/to/rails/app/views/books/edit.html.erb" -render file: "/path/to/rails/app/views/books/edit" -render file: "/path/to/rails/app/views/books/edit.html.erb" ``` Which one you use is really a matter of style and convention, but the rule of thumb is to use the simplest one that makes sense for the code you are writing. @@ -287,6 +260,23 @@ time. NOTE: Unless overridden, your response returned from this render option will be `text/plain`, as that is the default content type of Action Dispatch response. +#### Rendering raw file + +Rails can render a raw file from an absolute path. This is useful for +conditionally rendering static files like error pages. + +```ruby +render file: "#{Rails.root}/public/404.html", layout: false +``` + +This renders the raw file (it doesn't support ERB or other handlers). By +default it is rendered within the current layout. + +WARNING: Using the `:file` option in combination with users input can lead to security problems +since an attacker could use this action to access security sensitive files in your file system. + +TIP: `send_file` is often a faster and better option if a layout isn't required. + #### Options for `render` Calls to the `render` method generally accept five options: @@ -303,7 +293,7 @@ Calls to the `render` method generally accept five options: By default, Rails will serve the results of a rendering operation with the MIME content-type of `text/html` (or `application/json` if you use the `:json` option, or `application/xml` for the `:xml` option.). There are times when you might like to change this, and you can do so by setting the `:content_type` option: ```ruby -render file: filename, content_type: "application/rss" +render template: "feed", content_type: "application/rss" ``` ##### The `:layout` Option diff --git a/guides/source/rails_application_templates.md b/guides/source/rails_application_templates.md index 982df26987..e0e79fc41b 100644 --- a/guides/source/rails_application_templates.md +++ b/guides/source/rails_application_templates.md @@ -82,10 +82,10 @@ end Adds the given source to the generated application's `Gemfile`. -For example, if you need to source a gem from `"http://code.whytheluckystiff.net"`: +For example, if you need to source a gem from `"http://gems.github.com"`: ```ruby -add_source "http://code.whytheluckystiff.net" +add_source "http://gems.github.com" ``` If block is given, gem entries in block are wrapped into the source group. diff --git a/guides/source/routing.md b/guides/source/routing.md index e3a6bbb138..4aeb9ee585 100644 --- a/guides/source/routing.md +++ b/guides/source/routing.md @@ -508,7 +508,7 @@ end This will recognize `/photos/1/preview` with GET, and route to the `preview` action of `PhotosController`, with the resource id value passed in `params[:id]`. It will also create the `preview_photo_url` and `preview_photo_path` helpers. -Within the block of member routes, each route name specifies the HTTP verb +Within the block of member routes, each route name specifies the HTTP verb that will be recognized. You can use `get`, `patch`, `put`, `post`, or `delete` here . If you don't have multiple `member` routes, you can also pass `:on` to a route, eliminating the block: diff --git a/guides/source/security.md b/guides/source/security.md index 22c122d4b9..5bb7a51524 100644 --- a/guides/source/security.md +++ b/guides/source/security.md @@ -1211,4 +1211,4 @@ The security landscape shifts and it is important to keep up to date, because mi * Subscribe to the Rails security [mailing list](https://groups.google.com/forum/#!forum/rubyonrails-security). * [Brakeman - Rails Security Scanner](https://brakemanscanner.org/) - To perform static security analysis for Rails applications. * [Keep up to date on the other application layers](http://secunia.com/) (they have a weekly newsletter, too). -* A [good security blog](https://www.owasp.org) including the [Cross-Site scripting Cheat Sheet](https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet). +* A [good security blog](https://www.owasp.org) including the [Cross-Site scripting Cheat Sheet](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.md). diff --git a/guides/source/testing.md b/guides/source/testing.md index 18eecf49fa..41bc54b924 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -781,7 +781,7 @@ This can be helpful for viewing the browser at the point a test failed, or to view screenshots later for debugging. Two methods are provided: `take_screenshot` and `take_failed_screenshot`. -`take_failed_screenshot` is automatically included in `after_teardown` inside +`take_failed_screenshot` is automatically included in `before_teardown` inside Rails. The `take_screenshot` helper method can be included anywhere in your tests to @@ -1144,7 +1144,7 @@ test "ajax request" do get article_url(article), xhr: true assert_equal 'hello world', @response.body - assert_equal "text/javascript", @response.content_type + assert_equal "text/javascript", @response.media_type end ``` diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md index 7e4152aa51..05980d1614 100644 --- a/guides/source/upgrading_ruby_on_rails.md +++ b/guides/source/upgrading_ruby_on_rails.md @@ -85,13 +85,14 @@ Rails 6.1. You are encouraged to enable `config.force_ssl` to enforce HTTPS connections throughout your application. If you need to exempt certain endpoints from redirection, you can use `config.ssl_options` to configure that behavior. -### Purpose in signed or encrypted cookie is now embedded within cookies +### Purpose and expiry metadata is now embedded inside signed and encrypted cookies for increased security + +To improve security, Rails embeds the purpose and expiry metadata inside encrypted or signed cookies value. -To improve security, Rails embeds the purpose information in encrypted or signed cookies value. Rails can then thwart attacks that attempt to copy the signed/encrypted value of a cookie and use it as the value of another cookie. -This new embed information make those cookies incompatible with versions of Rails older than 6.0. +This new embed metadata make those cookies incompatible with versions of Rails older than 6.0. If you require your cookies to be read by Rails 5.2 and older, or you are still validating your 6.0 deploy and want to be able to rollback set @@ -133,6 +134,318 @@ Action Cable JavaScript API: + ActionCable.logger.enabled = false ``` +### `ActionDispatch::Response#content_type` now returns the Content-Type header without modification + +Previously, the return value of `ActionDispatch::Response#content_type` did NOT contain the charset part. +This behavior has changed to include the previously omitted charset part as well. + +If you want just the MIME type, please use `ActionDispatch::Response#media_type` instead. + +Before: + +```ruby +resp = ActionDispatch::Response.new(200, "Content-Type" => "text/csv; header=present; charset=utf-16") +resp.content_type #=> "text/csv; header=present" +``` + +After: + +```ruby +resp = ActionDispatch::Response.new(200, "Content-Type" => "text/csv; header=present; charset=utf-16") +resp.content_type #=> "text/csv; header=present; charset=utf-16" +resp.media_type #=> "text/csv" +``` + +### Autoloading + +The default configuration for Rails 6 + +```ruby +# config/application.rb + +config.load_defaults "6.0" +``` + +enables `zeitwerk` autoloading mode on CRuby. In that mode, autoloading, reloading, and eager loading are managed by [Zeitwerk](https://github.com/fxn/zeitwerk). + +#### Public API + +In general, applications do not need to use the API of Zeitwerk directly. Rails sets things up according to the existing contract: `config.autoload_paths`, `config.cache_classes`, etc. + +While applications should stick to that interface, the actual Zeitwerk loader object can be accessed as + +```ruby +Rails.autoloaders.main +``` + +That may be handy if you need to preload STIs or configure a custom inflector, for example. + +#### Project Structure + +If the application being upgraded autoloads correctly, the project structure should be already mostly compatible. + +However, `classic` mode infers file names from missing constant names (`underscore`), whereas `zeitwerk` mode infers constant names from file names (`camelize`). These helpers are not always inverse of each other, in particular if acronyms are involved. For instance, `"FOO".underscore` is `"foo"`, but `"foo".camelize` is `"Foo"`, not `"FOO"`. + +Compatibility can be checked with the `zeitwerk:check` task: + +``` +$ bin/rails zeitwerk:check +Hold on, I am eager loading the application. +All is good! +``` + +#### require_dependency + +All known use cases of `require_dependency` have been eliminated, you should grep the project and delete them. + +If your application has STIs, please check their section in the guide [Autoloading and Reloading Constants (Zeitwerk Mode)](autoloading_and_reloading_constants.html#single-table-inheritance). + +#### Qualified names in class and module definitions + +You can now robustly use constant paths in class and module definitions: + +```ruby +# Autoloading in this class' body matches Ruby semantics now. +class Admin::UsersController < ApplicationController + # ... +end +``` + +A gotcha to be aware of is that, depending on the order of execution, the classic autoloader could sometimes be able to autoload `Foo::Wadus` in + +```ruby +class Foo::Bar + Wadus +end +``` + +That does not match Ruby semantics because `Foo` is not in the nesting, and won't work at all in `zeitwerk` mode. If you find such corner case you can use the qualified name `Foo::Wadus`: + +```ruby +class Foo::Bar + Foo::Wadus +end +``` + +or add `Foo` to the nesting: + +```ruby +module Foo + class Bar + Wadus + end +end +``` + +#### Concerns + +You can autoload and eager load from a standard structure like + +``` +app/models +app/models/concerns +``` + +In that case, `app/models/concerns` is assumed to be a root directory (because it belongs to the autoload paths), and it is ignored as namespace. So, `app/models/concerns/foo.rb` should define `Foo`, not `Concerns::Foo`. + +The `Concerns::` namespace worked with the classic autoloader as a side-effect of the implementation, but it was not really an intended behavior. An application using `Concerns::` needs to rename those classes and modules to be able to run in `zeitwerk` mode. + +#### Having `app` in the autoload paths + +Some projects want something like `app/api/base.rb` to define `API::Base`, and add `app` to the autoload paths to accomplish that in `classic` mode. Since Rails adds all subdirectories of `app` to the autoload paths automatically, we have another situation in which there are nested root directories, so that setup no longer works. Similar principle we explained above with `concerns`. + +If you want to keep that structure, you'll need to delete the subdirectory from the autoload paths in an initializer: + +```ruby +ActiveSupport::Dependencies.autoload_paths.delete("#{Rails.root}/app/api") +``` + +#### Autoloaded Constants and Explicit Namespaces + +If a namespace is defined in a file, as `Hotel` is here: + +``` +app/models/hotel.rb # Defines Hotel. +app/models/hotel/pricing.rb # Defines Hotel::Pricing. +``` + +the `Hotel` constant has to be set using the `class` or `module` keywords. For example: + +```ruby +class Hotel +end +``` + +is good. + +Alternatives like + +```ruby +Hotel = Class.new +``` + +or + +```ruby +Hotel = Struct.new +``` + +won't work, child objects like `Hotel::Pricing` won't be found. + +This restriction only applies to explicit namespaces. Classes and modules not defining a namespace can be defined using those idioms. + +#### One file, one constant (at the same top-level) + +In `classic` mode you could technically define several constants at the same top-level and have them all reloaded. For example, given + +```ruby +# app/models/foo.rb + +class Foo +end + +class Bar +end +``` + +while `Bar` could not be autoloaded, autoloading `Foo` would mark `Bar` as autoloaded too. This is not the case in `zeitwerk` mode, you need to move `Bar` to its own file `bar.rb`. One file, one constant. + +This affects only to constants at the same top-level as in the example above. Inner classes and modules are fine. For example, consider + +```ruby +# app/models/foo.rb + +class Foo + class InnerClass + end +end +``` + +If the application reloads `Foo`, it will reload `Foo::InnerClass` too. + +#### Spring and the `test` Environment + +Spring reloads the application code if something changes. In the `test` environment you need to enable reloading for that to work: + +```ruby +# config/environments/test.rb + +config.cache_classes = false +``` + +Otherwise you'll get this error: + +``` +reloading is disabled because config.cache_classes is true +``` + +#### Bootsnap + +Bootsnap should be at least version 1.4.2. + +In addition to that, Bootsnap needs to disable the iseq cache due to a bug in the interpreter if running Ruby 2.5. Please make sure to depend on at least Bootsnap 1.4.4 in that case. + +#### `config.add_autoload_paths_to_load_path` + +The new configuration point + +```ruby +config.add_autoload_paths_to_load_path +``` + +is `true` by default for backwards compatibility, but allows you to opt-out from adding the autoload paths to `$LOAD_PATH`. + +This makes sense in most applications, since you never should require a file in `app/models`, for example, and Zeitwerk only uses absolute file names internally. + +By opting-out you optimize `$LOAD_PATH` lookups (less directories to check), and save Bootsnap work and memory consumption, since it does not need to build an index for these directories. + +#### Thread-safety + +In classic mode, constant autoloading is not thread-safe, though Rails has locks in place for example to make web requests thread-safe when autoloading is enabled, as it is common in `development` mode. + +Constant autoloading is thread-safe in `zeitwerk` mode. For example, you can now autoload in multi-threaded scripts executed by the `runner` command. + +#### Globs in config.autoload_paths + +Beware of configurations like + +```ruby +config.autoload_paths += Dir["#{config.root}/lib/**/"] +``` + +Every element of `config.autoload_paths` should represent the top-level namespace (`Object`) and they cannot be nested in consequence (with the exception of `concerns` directories explained above). + +To fix this, just remove the wildcards: + +```ruby +config.autoload_paths << "#{config.root}/lib" +``` + +#### Eager loading and autoloading are consistent + +In `classic` mode, if `app/models/foo.rb` defines `Bar`, you won't be able to autoload that file, but eager loading will work because it loads files recursively blindly. This can be a source of errors if you test things first eager loading, execution may fail later autoloading. + +In `zeitwerk` mode both loading modes are consistent, they fail and err in the same files. + +#### How to Use the Classic Autoloader in Rails 6 + +Applications can load Rails 6 defaults and still use the classic autoloader by setting `config.autoloader` this way: + +```ruby +# config/application.rb + +config.load_defaults "6.0" +config.autoloader = :classic +``` + +### Active Storage assignment behavior change + +In Rails 5.2, assigning to a collection of attachments declared with `has_many_attached` appended new files: + +```ruby +class User < ApplicationRecord + has_many_attached :highlights +end + +user.highlights.attach(filename: "funky.jpg", ...) +user.higlights.count # => 1 + +blob = ActiveStorage::Blob.create_after_upload!(filename: "town.jpg", ...) +user.update!(highlights: [ blob ]) + +user.highlights.count # => 2 +user.highlights.first.filename # => "funky.jpg" +user.highlights.second.filename # => "town.jpg" +``` + +With the default configuration for Rails 6.0, assigning to a collection of attachments replaces existing files +instead of appending to them. This matches Active Record behavior when assigning to a collection association: + +```ruby +user.highlights.attach(filename: "funky.jpg", ...) +user.highlights.count # => 1 + +blob = ActiveStorage::Blob.create_after_upload!(filename: "town.jpg", ...) +user.update!(highlights: [ blob ]) + +user.highlights.count # => 1 +user.highlights.first.filename # => "town.jpg" +``` + +`#attach` can be used to add new attachments without removing the existing ones: + +```ruby +blob = ActiveStorage::Blob.create_after_upload!(filename: "town.jpg", ...) +user.highlights.attach(blob) + +user.highlights.count # => 2 +user.highlights.first.filename # => "funky.jpg" +user.highlights.second.filename # => "town.jpg" +``` + +Opt in to the new default behavior by setting `config.active_storage.replace_on_assign_to_many` to `true`. +The old behavior will be deprecated in Rails 6.1 and removed in a subsequent release. + Upgrading from Rails 5.1 to Rails 5.2 ------------------------------------- @@ -1557,7 +1870,7 @@ config.assets.enabled = true config.assets.version = '1.0' ``` -If your application is using an "/assets" route for a resource you may want change the prefix used for assets to avoid conflicts: +If your application is using an "/assets" route for a resource you may want to change the prefix used for assets to avoid conflicts: ```ruby # Defaults to '/assets' |