diff options
Diffstat (limited to 'guides')
-rw-r--r-- | guides/CHANGELOG.md | 4 | ||||
-rw-r--r-- | guides/bug_report_templates/action_controller_master.rb | 2 | ||||
-rw-r--r-- | guides/bug_report_templates/active_record_master.rb | 2 | ||||
-rw-r--r-- | guides/source/4_2_release_notes.md | 30 | ||||
-rw-r--r-- | guides/source/action_controller_overview.md | 4 | ||||
-rw-r--r-- | guides/source/active_record_querying.md | 60 | ||||
-rw-r--r-- | guides/source/asset_pipeline.md | 5 | ||||
-rw-r--r-- | guides/source/association_basics.md | 8 | ||||
-rw-r--r-- | guides/source/command_line.md | 6 | ||||
-rw-r--r-- | guides/source/configuring.md | 2 | ||||
-rw-r--r-- | guides/source/constant_autoloading_and_reloading.md | 389 | ||||
-rw-r--r-- | guides/source/getting_started.md | 25 | ||||
-rw-r--r-- | guides/source/rails_on_rack.md | 2 | ||||
-rw-r--r-- | guides/source/security.md | 8 | ||||
-rw-r--r-- | guides/source/upgrading_ruby_on_rails.md | 4 |
15 files changed, 338 insertions, 213 deletions
diff --git a/guides/CHANGELOG.md b/guides/CHANGELOG.md index afaa404ac1..cd3fa9f65b 100644 --- a/guides/CHANGELOG.md +++ b/guides/CHANGELOG.md @@ -1 +1,5 @@ +* New section in Active Record Querying: Understanding The Method Chaining + + *Andrey Nering* + Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/guides/CHANGELOG.md) for previous changes. diff --git a/guides/bug_report_templates/action_controller_master.rb b/guides/bug_report_templates/action_controller_master.rb index 0e51eaa0db..9be8130884 100644 --- a/guides/bug_report_templates/action_controller_master.rb +++ b/guides/bug_report_templates/action_controller_master.rb @@ -3,8 +3,6 @@ unless File.exist?('Gemfile') source 'https://rubygems.org' gem 'rails', github: 'rails/rails' gem 'arel', github: 'rails/arel' - gem 'rack', github: 'rack/rack' - gem 'i18n', github: 'svenfuchs/i18n' GEMFILE system 'bundle' diff --git a/guides/bug_report_templates/active_record_master.rb b/guides/bug_report_templates/active_record_master.rb index e7f5d0d5ff..d95354e12d 100644 --- a/guides/bug_report_templates/active_record_master.rb +++ b/guides/bug_report_templates/active_record_master.rb @@ -3,8 +3,6 @@ unless File.exist?('Gemfile') source 'https://rubygems.org' gem 'rails', github: 'rails/rails' gem 'arel', github: 'rails/arel' - gem 'rack', github: 'rack/rack' - gem 'i18n', github: 'svenfuchs/i18n' gem 'sqlite3' GEMFILE diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md index 1e9107a8c6..f5575ac523 100644 --- a/guides/source/4_2_release_notes.md +++ b/guides/source/4_2_release_notes.md @@ -509,6 +509,17 @@ Please refer to the [Changelog][action-pack] for detailed changes. serving assets from your Rails server in production. ([Pull Request](https://github.com/rails/rails/pull/16466)) +* When calling the `process` helpers in an integration test the path needs to have + a leading slash. Previously you could omit it but that was a byproduct of the + implementation and not an intentional feature, e.g.: + + ```ruby + test "list all posts" do + get "/posts" + assert_response :success + end + ``` + Action View ----------- @@ -544,17 +555,6 @@ Please refer to the [Changelog][action-view] for detailed changes. * Placeholder I18n follows the same convention as `label` I18n. ([Pull Request](https://github.com/rails/rails/pull/16438)) -* When calling the `process` helpers in an integration test the path needs to have - a leading slash. Previously you could omit it but that was a byproduct of the - implementation and not an intentional feature, e.g.: - - ```ruby - test "list all posts" do - get "/posts" - assert_response :success - end - ``` - Action Mailer ------------- @@ -640,6 +640,10 @@ Please refer to the [Changelog][active-record] for detailed changes. `Relation` for performing queries and updates is the preferred API. ([Commit](https://github.com/rails/rails/commit/d5902c9e)) +* Deprecated `add_timestamps` and `t.timestamps` without passing the `:null` + option. The default of `null: true` will change in Rails 5 to `null: false`. + ([Pull Request](https://github.com/rails/rails/pull/16481)) + * Deprecated `Reflection#source_macro` without replacement as it is no longer needed in Active Record. ([Pull Request](https://github.com/rails/rails/pull/16373)) @@ -658,6 +662,9 @@ Please refer to the [Changelog][active-record] for detailed changes. ### Notable changes +* `SchemaDumper` uses `force: :cascade` on `create_table`. This makes it + possible to reload a schema when foreign keys are in place. + * Added a `:required` option to singular associations, which defines a presence validation on the association. ([Pull Request](https://github.com/rails/rails/pull/16056)) @@ -824,6 +831,7 @@ Please refer to the [Changelog][active-support] for detailed changes. `module Foo; extend ActiveSupport::Concern; end` boilerplate. ([Commit](https://github.com/rails/rails/commit/b16c36e688970df2f96f793a759365b248b582ad)) +* New [guide](constant_autoloading_and_reloading.html) about constant autoloading and reloading. Credits ------- diff --git a/guides/source/action_controller_overview.md b/guides/source/action_controller_overview.md index 4e36a62583..57546da389 100644 --- a/guides/source/action_controller_overview.md +++ b/guides/source/action_controller_overview.md @@ -112,8 +112,8 @@ NOTE: The actual URL in this example will be encoded as "/clients?ids%5b%5d=1&id The value of `params[:ids]` will now be `["1", "2", "3"]`. Note that parameter values are always strings; Rails makes no attempt to guess or cast the type. -NOTE: Values such as `[]`, `[nil]` or `[nil, nil, ...]` in `params` are replaced -with `nil` for security reasons by default. See [Security Guide](security.html#unsafe-query-generation) +NOTE: Values such as `[nil]` or `[nil, nil, ...]` in `params` are replaced +with `[]` for security reasons by default. See [Security Guide](security.html#unsafe-query-generation) for more information. To send a hash you include the key name inside the brackets: diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md index e1a465c64f..2e7bb74d0b 100644 --- a/guides/source/active_record_querying.md +++ b/guides/source/active_record_querying.md @@ -9,6 +9,7 @@ After reading this guide, you will know: * How to specify the order, retrieved attributes, grouping, and other properties of the found records. * How to use eager loading to reduce the number of database queries needed for data retrieval. * How to use dynamic finders methods. +* How to use method chaining to use multiple ActiveRecord methods together. * How to check for the existence of particular records. * How to perform various calculations on Active Record models. * How to run EXPLAIN on relations. @@ -1327,10 +1328,67 @@ You can specify an exclamation point (`!`) on the end of the dynamic finders to If you want to find both by name and locked, you can chain these finders together by simply typing "`and`" between the fields. For example, `Client.find_by_first_name_and_locked("Ryan", true)`. +Understanding The Method Chaining +--------------------------------- + +The Active Record pattern implements [Method Chaining](http://en.wikipedia.org/wiki/Method_chaining), +which allow us to use multiple Active Record methods together in a simple and straightforward way. + +You can chain a method in a sentence when the previous method called returns `ActiveRecord::Relation`, +like `all`, `where`, and `joins`. Methods that returns a instance of a single object +(see [Retrieving a Single Object Section](#retrieving-a-single-object)) have to be be the last +in the sentence. + +There are some examples below. This guide won't cover all the possibilities, just a few as example. +When a Active Record method is called, the query is not immediately generated and sent to the database, +this just happen when the data is actually needed. So each example below generate a single query. + +### Retrieving filtered data from multiple tables + +```ruby +Person + .select('people.id, people.name, comments.text') + .joins(:comments) + .where('comments.created_at > ?', 1.week.ago) +``` + +The result should be something like this: + +```sql +SELECT people.id, people.name, comments.text +FROM people +INNER JOIN comments + ON comments.person_id = people.id +WHERE comments.created_at = '2015-01-01' +``` + +### Retrieving specific data from multiple tables + +```ruby +Person + .select('people.id, people.name, companies.name') + .joins(:company) + .find_by('people.name' => 'John') # this should be the last +``` + +The above should generate: + +```sql +SELECT people.id, people.name, companies.name +FROM people +INNER JOIN companies + ON companies.person_id = people.id +WHERE people.name = 'John' +LIMIT 1 +``` + +NOTE: Remember that, if `find_by` return more than one registry, it will take just the first +and ignore the others. Note the `LIMIT 1` statement above. + Find or Build a New Object -------------------------- -NOTE: Some dynamic finders have been deprecated in Rails 4.0 and will be +NOTE: Some dynamic finders were deprecated in Rails 4.0 and removed in Rails 4.1. The best practice is to use Active Record scopes instead. You can find the deprecation gem at https://github.com/rails/activerecord-deprecated_finders diff --git a/guides/source/asset_pipeline.md b/guides/source/asset_pipeline.md index 8764546873..156daf1bac 100644 --- a/guides/source/asset_pipeline.md +++ b/guides/source/asset_pipeline.md @@ -167,9 +167,8 @@ directory. Files in this directory are served by the Sprockets middleware. Assets can still be placed in the `public` hierarchy. Any assets under `public` will be served as static files by the application or web server when -`config.serve_static_assets` is set to true. You should use -`app/assets` for files that must undergo some pre-processing before they are -served. +`config.serve_static_files` is set to true. You should use `app/assets` for +files that must undergo some pre-processing before they are served. In production, Rails precompiles these files to `public/assets` by default. The precompiled copies are then served as static assets by the web server. The files diff --git a/guides/source/association_basics.md b/guides/source/association_basics.md index 3a2e522fa7..5c05f0c4b7 100644 --- a/guides/source/association_basics.md +++ b/guides/source/association_basics.md @@ -879,10 +879,12 @@ class Order < ActiveRecord::Base belongs_to :customer, counter_cache: :count_of_orders end class Customer < ActiveRecord::Base - has_many :orders + has_many :orders, counter_cache: :count_of_orders end ``` +NOTE: You only need to specify the :counter_cache option on the "has_many side" of the association when using a custom name for the counter cache. + Counter cache columns are added to the containing model's list of read-only attributes through `attr_readonly`. ##### `:dependent` @@ -1495,6 +1497,7 @@ The `has_many` association supports these options: * `:as` * `:autosave` * `:class_name` +* `:counter_cache` * `:dependent` * `:foreign_key` * `:inverse_of` @@ -1522,6 +1525,9 @@ class Customer < ActiveRecord::Base end ``` +##### `:counter_cache` +This option can be used to configure a custom named `:counter_cache`. You only need this option when you customized the name of your `:counter_cache` on the [belongs_to association](#options-for-belongs-to). + ##### `:dependent` Controls what happens to the associated objects when their owner is destroyed: diff --git a/guides/source/command_line.md b/guides/source/command_line.md index e72bc81766..713c91d167 100644 --- a/guides/source/command_line.md +++ b/guides/source/command_line.md @@ -24,7 +24,7 @@ There are a few commands that are absolutely critical to your everyday usage of * `rails dbconsole` * `rails new app_name` -All commands can run with ```-h or --help``` to list more information. +All commands can run with `-h` or `--help` to list more information. Let's create a simple Rails application to step through each of these commands in context. @@ -368,7 +368,7 @@ Rake is Ruby Make, a standalone Ruby utility that replaces the Unix utility 'mak You can get a list of Rake tasks available to you, which will often depend on your current directory, by typing `rake --tasks`. Each task has a description, and should help you find the thing you need. -To get the full backtrace for running rake task you can pass the option ```--trace``` to command line, for example ```rake db:create --trace```. +To get the full backtrace for running rake task you can pass the option `--trace` to command line, for example `rake db:create --trace`. ```bash $ bin/rake --tasks @@ -384,7 +384,7 @@ rake middleware # Prints out your Rack middleware stack rake tmp:clear # Clear session, cache, and socket files from tmp/ (narrow w/ tmp:sessions:clear, tmp:cache:clear, tmp:sockets:clear) rake tmp:create # Creates tmp directories for sessions, cache, sockets, and pids ``` -INFO: You can also use ```rake -T``` to get the list of tasks. +INFO: You can also use `rake -T` to get the list of tasks. ### `about` diff --git a/guides/source/configuring.md b/guides/source/configuring.md index 7688962c01..ee46533e16 100644 --- a/guides/source/configuring.md +++ b/guides/source/configuring.md @@ -120,7 +120,7 @@ numbers. New applications filter out passwords by adding the following `config.f * `secrets.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 `secrets.secret_key_base` initialized to a random key present in `config/secrets.yml`. -* `config.serve_static_assets` configures Rails itself to serve static assets. Defaults to true, but in the production environment is turned off as the server software (e.g. NGINX or Apache) used to run the application should serve static assets instead. Unlike the default setting set this to true when running (absolutely not recommended!) or testing your app in production mode using WEBrick. Otherwise you won't be able use page caching and requests for files that exist regularly under the public directory will anyway hit your Rails app. +* `config.serve_static_files` configures Rails itself to serve static files. Defaults to true, but in the production environment is turned off as the server software (e.g. NGINX or Apache) used to run the application should serve static assets instead. Unlike the default setting set this to true when running (absolutely not recommended!) or testing your app in production mode using WEBrick. Otherwise you won't be able use page caching and requests for files that exist regularly under the public directory will anyway hit your Rails app. * `config.session_store` is usually set up in `config/initializers/session_store.rb` and 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. Custom session stores can also be specified: diff --git a/guides/source/constant_autoloading_and_reloading.md b/guides/source/constant_autoloading_and_reloading.md index 5cd62c22a8..c54816c4c2 100644 --- a/guides/source/constant_autoloading_and_reloading.md +++ b/guides/source/constant_autoloading_and_reloading.md @@ -6,17 +6,10 @@ This guide documents how constant autoloading and reloading works. After reading this guide, you will know: * Key aspects of Ruby constants - * What is `autoload_paths` - * How constant autoloading works - * What is `require_dependency` - * How constant reloading works - -* That autoloading is not based on `Module#autoload` - * Solutions to common autoloading gotchas -------------------------------------------------------------------------------- @@ -27,7 +20,7 @@ Introduction Ruby on Rails allows applications to be written as if their code was preloaded. -In a normal Ruby program a class needs to load its dependencies: +In a normal Ruby program classes need to load their dependencies: ```ruby require 'application_controller' @@ -104,12 +97,14 @@ class XML::SAXParser end ``` -the nesting in (2) is different, `XML` does not belong to it: +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. @@ -184,6 +179,21 @@ performs a constant assignment equivalent to Project = Class.new(ActiveRecord::Base) ``` +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 its name to be the +one 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 @@ -197,16 +207,21 @@ performs a constant assignment equivalent to 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, when one informally says "the `String` class", that really means: the -class object the interpreter creates and stores in a constant called "String" in -the class object stored in the `Object` constant. `String` is otherwise an -ordinary Ruby constant and everything related to constants applies to it, -resolution algorithms, etc. +class object stored in the constant called "String" in the class object stored +in the `Object` constant. `String` is otherwise an ordinary Ruby constant and +everything related to constants applies to it, resolution algorithms, etc. Likewise, in the controller @@ -221,17 +236,17 @@ end `Post` is not syntax for a class. Rather, `Post` is a regular Ruby constant. If all is good, the constant evaluates 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. +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. +a constant table; think of it as a hash table. -Let's analyze an example to really understand what that means. While in a -casual setting some abuses of language are customary, the exposition is going -to be exact here for didactic purposes. +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: @@ -259,7 +274,9 @@ Put 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 Algorithm for Relative Constants +### 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. @@ -277,9 +294,9 @@ 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](#relative-references). +References](#autoloading-algorithms-relative-references). -### Resolution Algorithm for Qualified Constants +#### Resolution Algorithm for Qualified Constants Qualified constants look like this: @@ -288,10 +305,16 @@ Billing::Invoice ``` `Billing::Invoice` is composed of two constants: `Billing` is relative and is -resolved using the algorithm of the previous section; `Invoice` is qualified by -`Billing` and we are going to see its resolution next. Let's call *parent* to -that qualifying class or module object, that is, `Billing` in the example above. -The algorithm for qualified constants goes like this: +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 call *parent* to 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. @@ -341,7 +364,7 @@ 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 the by "parent namespace" the guide means exactly that specific string +account that by "parent namespace" the guide means exactly that specific string derivation. ### Loading Mechanism @@ -405,11 +428,11 @@ 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 +`post.rb` file for example in `app/models` Rails is going to find it, evaluate it, and have `Post` defined as a side-effect. Alright, Rails has a collection of directories similar to `$LOAD_PATH` in which -to lookup that *post.rb*. That collection is called `autoload_paths` and by +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. For example, @@ -539,10 +562,10 @@ role.rb modulus some additional directory lookups we are going to cover soon. -INFO. 'Constant::Name'.underscore gives the relative path without extension of +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 does Rails autoload the `Post` constant in the `PostsController` +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`. @@ -585,8 +608,8 @@ file is loaded. If the file actually defines `Post` all is fine, otherwise ### Qualified References When a qualified constant is missing Rails does not look for it in the parent -namespaces. But there's a caveat: Unfortunately, when a constant is missing -Rails is not able to say if the trigger was a relative or qualified reference. +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 @@ -632,24 +655,23 @@ 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 +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. -But since autoloading happens on demand, if the top-level `User` by chance was -not yet loaded then Rails has no way to know whether `Admin::User` should load it -or raise `NameError`. +However, autoloading happens on demand. If by chance the top-level `User` was +not yet loaded, then Rails assumes a relative reference by contract. -These kind of name conflicts are rare in practice, but in case there's one -`require_dependency` provides a solution by making sure the constant needed to -trigger the heuristic is defined in the conflicting place. +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 defines a file for it, a directory matching the namespace is enough. -Suppose an application has a backoffice whose controllers are stored in +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`. @@ -843,13 +865,13 @@ class Admin::UsersController < ApplicationController end ``` -If Ruby resolves `User` in the former case it checks whether there's a `User` -constant in the `Admin` module. It does not in the latter case, because `Admin` -does not belong to the nesting. +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, -if `Admin::User` is autoloadable, it will get autoloaded in either case. +`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 @@ -867,10 +889,10 @@ end ### Autoloading and STI -STI (Single Table Inheritance) is a feature of Active Record that easies storing -records that belong to a hierarchy of classes in one single table. The API of -such models is aware of the hierarchy and encapsulates some common needs. For -example, given these classes: +Single Table Inheritance (STI) is a feature of Active Record that easies +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 @@ -887,37 +909,35 @@ 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. +`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 perform operations on collections are also aware of the hierarchy. -For example, `Polygon.all` returns all the records of the table, because all +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. -When Active Record does this, it autoloads constants as needed. For example, if -the class of `Polygon.first` is `Rectangle` and it has not yet been loaded, -Active Record autoloads it and the record is fetched and correctly instantiated, -transparently. +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, then things get interesting. +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` should return all the rectangles in the "polygons" table. In -particular, no triangle should be fetched. To accomplish this, Active Record -constraints the query to rows whose type column is “Rectangle”: +`Rectangle.all` only loads rectangles by adding a type constraint to the query: ```sql SELECT "polygons".* FROM "polygons" WHERE "polygons"."type" IN ("Rectangle") ``` -That works, but let’s introduce now a child of `Rectangle`: +Let’s introduce now a subclass of `Rectangle`: ```ruby # app/models/square.rb @@ -925,16 +945,15 @@ class Square < Rectangle end ``` -`Rectangle.all` should return rectangles **and** squares, the query should -become +`Rectangle.all` should now return rectangles **and** squares: ```sql SELECT "polygons".* FROM "polygons" WHERE "polygons"."type" IN ("Rectangle", "Square") ``` -But there’s a subtle caveat here: How does Active Record know that the class -`Square` exists at all? +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 @@ -944,8 +963,7 @@ SELECT "polygons".* FROM "polygons" WHERE "polygons"."type" IN ("Rectangle") ``` -That is not a bug in Active Record, as we saw above the query does include all -*known* descendants of `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 load the leaves of the tree by hand at the bottom of the file that defines the @@ -958,15 +976,14 @@ end require_dependency ‘square’ ``` -Only the leaves that are **at least grandchildren** have to be loaded that way. -Direct subclasses do not need to be preloaded, and if the hierarchy is deeper -intermediate superclasses will be autoloaded recursively from the bottom because -their constant will appear in the definitions. +Only the leaves that are **at least grandchildren** need to be loaded this +way. Direct subclasses do not need to be preloaded. If the hierarchy is +deeper, intermediate classes will be autoloaded recursively from the bottom +because their constant will appear in the class definitions as superclass. ### Autoloading and `require` -Files defining constants that should be autoloaded should never be loaded with -`require`: +Files defining constants to be autoloaded should never be `require`d: ```ruby require 'user' # DO NOT DO THIS @@ -976,25 +993,21 @@ class UsersController < ApplicationController end ``` -If some part of the application autoloads the `User` constant before, then the -application will interpret `app/models/user.rb` twice in development mode. +There are two possible gotchas here in development mode: -As we saw before, in development mode autoloading uses `Kernel#load` by default. -Since `load` does not store the name of the interpreted file in -`$LOADED_FEATURES` (`$"`) `require` executes, again, `app/models/user.rb`. +1. If `User` is autoloaded before reaching the `require`, `app/models/user.rb` +runs again because `load` does not update `$LOADED_FEATURES`. -On the other hand, if `app/controllers/users_controllers.rb` happens to be -evaluated before `User` is autoloaded then dependencies won’t mark `User` as an -autoloaded constant, and therefore changes to `app/models/user.rb` won’t be -updated in development mode. +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 by hand use `require_dependency` to play nice with constant autoloading. -This option is rarely needed in practice, though. +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, so they are +libraries is fine, and Rails is able to distinguish their constants, they are not marked as autoloaded. ### Autoloading and Initializers @@ -1002,24 +1015,22 @@ not marked as autoloaded. Consider this assignment in `config/initializers/set_auth_service.rb`: ```ruby -AUTH_SERVICE = Rails.env.production? ? RealAuthService : MockedAuthService +AUTH_SERVICE = if Rails.env.production? + RealAuthService +else + MockedAuthService +end ``` -The purpose of this setup would be that the application code uses always -`AUTH_SERVICE` and that constant holds the proper class for the runtime -environment. In development mode `MockedAuthService` gets autoloaded when the -initializer is run. Let’s suppose we do some requests, change the implementation -of `MockedAuthService`, and hit the application again. To our surprise the -changes are not reflected. Why? +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, Rails wipes autoloaded constants by removing them from their -containers using `remove_const`. But the object the constant holds may remain -stored somewhere else. Constant removal can’t do anything about that. - -That is precisely the case in this example. `AUTH_SERVICE` stores the original -class object which is perfectly functional regardless of the fact that there is -no longer a constant in `Object` that matches its class name. The class object -is independent of the constants it may or may not be stored in. +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: @@ -1040,10 +1051,10 @@ 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 for instance implement a dynamic access point that -returns something that depends on the environment: +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 @@ -1057,102 +1068,145 @@ class AuthService end ``` -and have the application use `AuthService.instance` instead of `AUTH_SERVICE`. -The code in that `AuthService` would be loaded on demand and be -autoload-friendly. +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 a autoloading-friendly +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. -`require_dependency` provides a way to ensure a certain constant is defined at -some point regardless of the execution path, and one could think about doing -some calls in an initializer to make sure certain constants are loaded upfront, -for example as an attempt to address the gotcha with STIs. +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 all autoloaded constants are wiped on a -subsequent request as soon as there is some relevant change in the file system. -When that happens the application is in the very same situation the initializer -wanted to avoid! +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 -Let’s imagine that a Rails application has an `Image` model, and a subclass -`Hotel::Image`: +#### Relative References + +Let's consider a flight simulator. The application has a default flight model ```ruby -# app/models/image.rb -class Image +# app/models/flight_model.rb +class FlightModel end +``` -# app/models/hotel/image.rb -module Hotel - class Image < Image +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 ``` -No matter which file is interpreted first, `app/models/hotel/image.rb` is -well-defined. +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. -Now consider a third file with this apparently harmless code: +These kind of ambiguities can often be resolved using qualified constants: ```ruby -# app/models/hotel/poster.rb -module Hotel - class Poster < Image +module BellX1 + class Plane + def flight_model + @flight_model ||= BellX1::FlightModel.new + end end end ``` -The intention is to subclass `Hotel::Image`, but which is actually the -superclass of `Hotel::Poster`? Well, it depends on the order of execution of the -files: +Also, `require_dependency` is a solution: -1. If neither `app/models/image.rb` nor `app/models/hotel/image.rb` have been -loaded at that point, the superclass is `Hotel::Image` because Rails is told -`Hotel` is missing a constant called "Image" and loads -`app/models/hotel/image.rb`. Good. +```ruby +require_dependency 'bell_x1/flight_model' -2. If `app/models/hotel/image.rb` has been loaded at that point, the superclass -is `Hotel::Image` because Ruby is able to resolve the constant. Good. +module BellX1 + class Plane + def flight_model + @flight_model ||= FlightModel.new + end + end +end +``` -3. Lastly, if only `app/models/image.rb` has been loaded so far, the superclass -is `Image`. Gotcha! +#### Qualified References -The last scenario (3) may be surprising. Why isn't `Hotel::Image` autoloaded? +Given -Constant autoloading cannot happen at that point because Ruby is able to -resolve `Image` as a top-level constant, in consequence autoloading is not -triggered. +```ruby +# app/models/hotel.rb +class Hotel +end -Most of the time, these kind of ambiguities can be resolved using qualified -constants. In this case we would write +# app/models/image.rb +class Image +end -```ruby -module Hotel - class Poster < Hotel::Image +# app/models/hotel/image.rb +class Hotel + class Image < Image end end ``` -That class definition now is robust. No matter which files have been -previously loaded, we know for certain that the superclass is unambiguously -set. +the expression `Hotel::Image` is ambiguous, 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`: + +``` +$ bin/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: -It is interesting to note here that fix works because `Hotel` is a module, and -`Hotel::Image` won’t look for `Image` in `Object` as it would if `Hotel` was a -class with `Object` in its ancestors. If `Hotel` was a class we would resort to -loading `Hotel::Image` with `require_dependency`. Furthermore, with that -solution the qualified name would no longer be necessary. +``` +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: +Let's suppose we have these class definitions: ```ruby # app/models/hotel/services.rb @@ -1171,17 +1225,15 @@ module Hotel end ``` -1. If `Hotel::Services` is known by the time `Hotel::GeoLocation` is being loaded, -everything works because `Hotel` belongs to the nesting when the singleton class -of `Hotel::GeoLocation` is opened, and thus Ruby itself is able to resolve the -constant. +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. -2. But if `Hotel::Services` is not known and we rely on autoloading for the -`Services` constant in `Hotel::GeoLocation`, Rails is not able to find -`Hotel::Services`. The application raises `NameError`. +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 +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: @@ -1228,7 +1280,8 @@ c.user # surprisingly fine, User c.user # NameError: uninitialized constant C::User ``` -because it detects a parent namespace already has the constant. +because it detects a parent namespace already has the constant (see [Qualified +References](#qualified-references).) As with pure Ruby, within the body of a direct descendant of `BasicObject` use always absolute constant paths: diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md index a5e35f75a0..e68e07a519 100644 --- a/guides/source/getting_started.md +++ b/guides/source/getting_started.md @@ -90,18 +90,18 @@ current version of Ruby installed: TIP: A number of tools exist to help you quickly install Ruby and Ruby on Rails on your system. Windows users can use [Rails Installer](http://railsinstaller.org), while Mac OS X users can use [Tokaido](https://github.com/tokaido/tokaidoapp). +For more installation methods for most Operating Systems take a look at +[ruby-lang.org](https://www.ruby-lang.org/en/documentation/installation/). ```bash $ ruby -v ruby 2.0.0p353 ``` -If you don't have Ruby installed have a look at -[ruby-lang.org](https://www.ruby-lang.org/en/installation/) for possible ways to -install Ruby on your platform. - -Many popular UNIX-like OSes ship with an acceptable version of SQLite3. Windows -users and others can find installation instructions at the [SQLite3 website](https://www.sqlite.org). +Many popular UNIX-like OSes ship with an acceptable version of SQLite3. +On Windows, if you installed Rails through Rails Installer, you +already have SQLite installed. Others can find installation instructions +at the [SQLite3 website](https://www.sqlite.org). Verify that it is correctly installed and in your PATH: ```bash @@ -259,9 +259,9 @@ invoke helper create app/helpers/welcome_helper.rb invoke assets invoke coffee -create app/assets/javascripts/welcome.js.coffee +create app/assets/javascripts/welcome.coffee invoke scss -create app/assets/stylesheets/welcome.css.scss +create app/assets/stylesheets/welcome.scss ``` Most important of these are of course the controller, located at @@ -300,8 +300,9 @@ Rails.application.routes.draw do # ... ``` -This is your application's _routing file_ which holds entries in a special DSL -(domain-specific language) that tells Rails how to connect incoming requests to +This is your application's _routing file_ which holds entries in a special +[DSL (domain-specific language)](http://en.wikipedia.org/wiki/Domain-specific_language) +that tells Rails how to connect incoming requests to controllers and actions. This file contains many sample routes on commented lines, and one of them actually shows you how to connect the root of your site to a specific controller and action. Find the line beginning with `root` and @@ -1637,8 +1638,8 @@ This creates five files and one empty directory: | app/views/comments/ | Views of the controller are stored here | | test/controllers/comments_controller_test.rb | The test for the controller | | app/helpers/comments_helper.rb | A view helper file | -| app/assets/javascripts/comment.js.coffee | CoffeeScript for the controller | -| app/assets/stylesheets/comment.css.scss | Cascading style sheet for the controller | +| app/assets/javascripts/comment.coffee | CoffeeScript for the controller | +| app/assets/stylesheets/comment.scss | Cascading style sheet for the controller | Like with any blog, our readers will create their comments directly after reading the article, and once they have added their comment, will be sent back diff --git a/guides/source/rails_on_rack.md b/guides/source/rails_on_rack.md index 0dec0e139b..042ebde9bb 100644 --- a/guides/source/rails_on_rack.md +++ b/guides/source/rails_on_rack.md @@ -233,7 +233,7 @@ Much of Action Controller's functionality is implemented as Middlewares. The fol **`ActionDispatch::Static`** -* Used to serve static assets. Disabled if `config.serve_static_assets` is `false`. +* Used to serve static files. Disabled if `config.serve_static_files` is `false`. **`Rack::Lock`** diff --git a/guides/source/security.md b/guides/source/security.md index b1c5b22338..b3869b1ba5 100644 --- a/guides/source/security.md +++ b/guides/source/security.md @@ -942,7 +942,7 @@ unless params[:token].nil? end ``` -When `params[:token]` is one of: `[]`, `[nil]`, `[nil, nil, ...]` or +When `params[:token]` is one of: `[nil]`, `[nil, nil, ...]` or `['foo', nil]` it will bypass the test for `nil`, but `IS NULL` or `IN ('foo', NULL)` where clauses still will be added to the SQL query. @@ -953,9 +953,9 @@ request: | JSON | Parameters | |-----------------------------------|--------------------------| | `{ "person": null }` | `{ :person => nil }` | -| `{ "person": [] }` | `{ :person => nil }` | -| `{ "person": [null] }` | `{ :person => nil }` | -| `{ "person": [null, null, ...] }` | `{ :person => nil }` | +| `{ "person": [] }` | `{ :person => [] }` | +| `{ "person": [null] }` | `{ :person => [] }` | +| `{ "person": [null, null, ...] }` | `{ :person => [] }` | | `{ "person": ["foo", null] }` | `{ :person => ["foo"] }` | It is possible to return to old behaviour and disable `deep_munge` configuring diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md index 7ef51b6dc0..51c144993c 100644 --- a/guides/source/upgrading_ruby_on_rails.md +++ b/guides/source/upgrading_ruby_on_rails.md @@ -235,8 +235,8 @@ mail = Notifier.notify(user, ...) # Notifier#notify is not yet called at this po mail = mail.deliver_now # Prints "Called" ``` -This should not result in any noticible differnces for most applications. -However, if you need some non-mailer methods to be exectuted synchronously, and +This should not result in any noticeable differences for most applications. +However, if you need some non-mailer methods to be executed synchronously, and you were previously relying on the synchronous proxying behavior, you should define them as class methods on the mailer class directly: |