From 18dba79bf27a370c823b34380120bff49cec08e2 Mon Sep 17 00:00:00 2001 From: Pierre Hedkvist Date: Mon, 27 Nov 2017 12:24:29 +0000 Subject: Example of mobile configuration for system test in guide [ci skip] --- guides/source/testing.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) (limited to 'guides/source') diff --git a/guides/source/testing.md b/guides/source/testing.md index e0a2d281d9..d9227f3c0a 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -778,6 +778,34 @@ send a POST request to create the new article in the database. We will be redirected back to the the articles index page and there we assert that the text from the new article's title is on the articles index page. +#### Testing for multiple screen sizes +If you want to test for mobile sizes on top of testing for desktop, +you can create another class that inherits from SystemTestCase and use in your +test suite. In this example a file called `mobile_system_test_case.rb` is created +in the `/test` directory with the following configuration. + +```ruby +require "test_helper" + +class MobileSystemTestCase < ActionDispatch::SystemTestCase + driven_by :selenium, using: :chrome, screen_size: [375, 667] +end +``` +To use this configuration, create a test inside `test/system` that inherits from `MobileSystemTestCase`. +Now you can test your app using multiple different configurations. + +```ruby +require "mobile_system_test_case" + +class PostsTest < MobileSystemTestCase + + test "visiting the index" do + visit posts_url + assert_selector "h1", text: "Posts" + end +end +``` + #### Taking it further The beauty of system testing is that it is similar to integration testing in -- cgit v1.2.3 From f96699511a2c426e036c57196a6eaaa540f9617c Mon Sep 17 00:00:00 2001 From: Prathamesh Sonpatki Date: Wed, 27 Dec 2017 21:50:06 +0530 Subject: Added a note about bootsnap in the Rails 5.2 upgrade guide [ci skip] --- guides/source/upgrading_ruby_on_rails.md | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'guides/source') diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md index bb4ef26876..cba2600182 100644 --- a/guides/source/upgrading_ruby_on_rails.md +++ b/guides/source/upgrading_ruby_on_rails.md @@ -65,6 +65,17 @@ Overwrite /myapp/config/application.rb? (enter "h" for help) [Ynaqdh] Don't forget to review the difference, to see if there were any unexpected changes. +Upgrading from Rails 5.1 to Rails 5.2 +------------------------------------- + +For more information on changes made to Rails 5.2 please see the [release notes](5_2_release_notes.html). + +### Bootsnap + +Rails 5.2 adds bootsnap gem in the [newly generated app's Gemfile](https://github.com/rails/rails/pull/29313). +The `app:update` task sets it up in `boot.rb`. If you want to use it, then add it in the Gemfile, +otherwise change the `boot.rb` to not use bootsnap. + Upgrading from Rails 5.0 to Rails 5.1 ------------------------------------- -- cgit v1.2.3 From 6fb3ac1536d60bc12cf531e83e4060fe1fdf3d87 Mon Sep 17 00:00:00 2001 From: George Claghorn Date: Tue, 16 Jan 2018 20:32:02 -0500 Subject: Provide a sensible default host --- guides/source/active_storage_overview.md | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) (limited to 'guides/source') diff --git a/guides/source/active_storage_overview.md b/guides/source/active_storage_overview.md index c5bd09ead6..d9f5aa8385 100644 --- a/guides/source/active_storage_overview.md +++ b/guides/source/active_storage_overview.md @@ -49,12 +49,10 @@ below declares three services named `local`, `test`, and `amazon`: local: service: Disk root: <%= Rails.root.join("storage") %> - host: http://localhost:3000 test: service: Disk root: <%= Rails.root.join("tmp/storage") %> - host: http://localhost:3000 amazon: service: S3 @@ -93,7 +91,15 @@ Declare a Disk service in `config/storage.yml`: local: service: Disk root: <%= Rails.root.join("storage") %> - host: http://localhost:3000 +``` + +Optionally specify a host for generating URLs (the default is `http://localhost:3000`): + +```yaml +local: + service: Disk + root: <%= Rails.root.join("storage") %> + host: http://myapp.test ``` ### Amazon S3 Service -- cgit v1.2.3 From 264f4a6b1456d8ab66bd444a1f8d96ebd44d17f3 Mon Sep 17 00:00:00 2001 From: bogdanvlviv Date: Tue, 26 Dec 2017 21:20:13 +0200 Subject: Update "Layouts and Rendering in Rails" guide [ci skip] - Remove mention about `ActionView::TemplateHandlers` since this module was removed by c1304098cca8a9247a9ad1461a1a343354650843. Change word `subclasses` to `nested classes`. See c7408a0e40545558872efb4129fe4bf097c9ce2f - Remove useless sentence "Beginning with Rails 2, the standard extensions are `.erb` for ERB (HTML with embedded Ruby), and `.builder` for Builder (XML generator)." --- guides/source/layouts_and_rendering.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/layouts_and_rendering.md b/guides/source/layouts_and_rendering.md index 4d79b2db89..15345c94b7 100644 --- a/guides/source/layouts_and_rendering.md +++ b/guides/source/layouts_and_rendering.md @@ -97,7 +97,7 @@ If we want to display the properties of all the books in our view, we can do so <%= link_to "New book", new_book_path %> ``` -NOTE: The actual rendering is done by subclasses of `ActionView::TemplateHandlers`. This guide does not dig into that process, but it's important to know that the file extension on your view controls the choice of template handler. Beginning with Rails 2, the standard extensions are `.erb` for ERB (HTML with embedded Ruby), and `.builder` for Builder (XML generator). +NOTE: The actual rendering is done by nested classes of the module [`ActionView::Template::Handlers`](http://api.rubyonrails.org/classes/ActionView/Template/Handlers.html). This guide does not dig into that process, but it's important to know that the file extension on your view controls the choice of template handler. ### Using `render` -- cgit v1.2.3 From a2aa18f897dbcd503ed3b782258a44b21ca752bd Mon Sep 17 00:00:00 2001 From: bogdanvlviv Date: Thu, 18 Jan 2018 01:06:34 +0200 Subject: Allow `false` for `config.generators.system_tests=` Mention `config.generators.system_tests` in the "Configuring Rails Applications" guide. --- guides/source/configuring.md | 1 + 1 file changed, 1 insertion(+) (limited to 'guides/source') diff --git a/guides/source/configuring.md b/guides/source/configuring.md index 879a1ea89f..98cd5e8fe5 100644 --- a/guides/source/configuring.md +++ b/guides/source/configuring.md @@ -200,6 +200,7 @@ The full set of methods that can be used in this block are as follows: * `force_plural` allows pluralized model names. Defaults to `false`. * `helper` defines whether or not to generate helpers. Defaults to `true`. * `integration_tool` defines which integration tool to use to generate integration tests. Defaults to `:test_unit`. +* `system_tests` defines which integration tool to use to generate system tests. Defaults to `:test_unit`. * `javascripts` turns on the hook for JavaScript files in generators. Used in Rails for when the `scaffold` generator is run. Defaults to `true`. * `javascript_engine` configures the engine to be used (for eg. coffee) when generating assets. Defaults to `:js`. * `orm` defines which orm to use. Defaults to `false` and will use Active Record by default. -- cgit v1.2.3 From 1ac67a5ed60040755c96b0bc8a4ec7f44d581765 Mon Sep 17 00:00:00 2001 From: Tom Copeland Date: Thu, 18 Jan 2018 17:21:09 -0500 Subject: Fix minor typo [ci skip] Updated the method counts and unified them all on numerals. --- guides/source/association_basics.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'guides/source') diff --git a/guides/source/association_basics.md b/guides/source/association_basics.md index 02d012d702..52c30f226f 100644 --- a/guides/source/association_basics.md +++ b/guides/source/association_basics.md @@ -795,7 +795,7 @@ The `belongs_to` association creates a one-to-one match with another model. In d #### Methods Added by `belongs_to` -When you declare a `belongs_to` association, the declaring class automatically gains five methods related to the association: +When you declare a `belongs_to` association, the declaring class automatically gains 6 methods related to the association: * `association` * `association=(associate)` @@ -1146,7 +1146,7 @@ The `has_one` association creates a one-to-one match with another model. In data #### Methods Added by `has_one` -When you declare a `has_one` association, the declaring class automatically gains five methods related to the association: +When you declare a `has_one` association, the declaring class automatically gains 6 methods related to the association: * `association` * `association=(associate)` @@ -1419,7 +1419,7 @@ The `has_many` association creates a one-to-many relationship with another model #### Methods Added by `has_many` -When you declare a `has_many` association, the declaring class automatically gains 16 methods related to the association: +When you declare a `has_many` association, the declaring class automatically gains 17 methods related to the association: * `collection` * `collection<<(object, ...)` @@ -1952,7 +1952,7 @@ The `has_and_belongs_to_many` association creates a many-to-many relationship wi #### Methods Added by `has_and_belongs_to_many` -When you declare a `has_and_belongs_to_many` association, the declaring class automatically gains 16 methods related to the association: +When you declare a `has_and_belongs_to_many` association, the declaring class automatically gains 17 methods related to the association: * `collection` * `collection<<(object, ...)` -- cgit v1.2.3 From f349ffac27f947820dbd7c4bc39b17c038a0863a Mon Sep 17 00:00:00 2001 From: Tim Diggins Date: Sun, 21 Jan 2018 21:18:20 +0000 Subject: Clarify autoload_paths and eager_load in guides per current usage. [CI SKIP] --- .../source/autoloading_and_reloading_constants.md | 41 ++++++++++++++++------ guides/source/configuring.md | 2 +- 2 files changed, 31 insertions(+), 12 deletions(-) (limited to 'guides/source') diff --git a/guides/source/autoloading_and_reloading_constants.md b/guides/source/autoloading_and_reloading_constants.md index dea87a18f8..8d28007671 100644 --- a/guides/source/autoloading_and_reloading_constants.md +++ b/guides/source/autoloading_and_reloading_constants.md @@ -8,7 +8,7 @@ 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` +* 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 @@ -430,8 +430,8 @@ if `House` is still unknown when `app/models/beach_house.rb` is being eager loaded, Rails autoloads it. -autoload_paths --------------- +autoload_paths and eager_load_paths +----------------------------------- As you probably know, when `require` gets a relative file name: @@ -451,7 +451,7 @@ 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. -Alright, Rails has a collection of directories similar to `$LOAD_PATH` in which +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: @@ -465,17 +465,22 @@ default it contains: * The directory `test/mailers/previews`. -Also, this collection is configurable via `config.autoload_paths`. For example, -`lib` was in the list years ago, but no longer is. An application can opt-in -by adding this to `config/application.rb`: +`eager_load_paths` is initially the `app` paths above -```ruby -config.autoload_paths << "#{Rails.root}/lib" -``` +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 (pre-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 +The value of `autoload_paths` can be inspected. In a just-generated application it is (edited): ``` @@ -1329,3 +1334,17 @@ class C < BasicObject 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 explictly 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). diff --git a/guides/source/configuring.md b/guides/source/configuring.md index 98cd5e8fe5..36c2fdb0b8 100644 --- a/guides/source/configuring.md +++ b/guides/source/configuring.md @@ -62,7 +62,7 @@ These configuration methods are to be called on a `Rails::Railtie` object, such * `config.autoload_once_paths` accepts an array of paths from which Rails will autoload constants that won't be wiped per request. Relevant if `config.cache_classes` is `false`, which is the case in development mode by default. Otherwise, all autoloading happens only once. All elements of this array must also be in `autoload_paths`. Default is an empty array. -* `config.autoload_paths` accepts an array of paths from which Rails will autoload constants. Default is all directories under `app`. +* `config.autoload_paths` accepts an array of paths from which Rails will autoload constants. Default is all directories under `app`. It is no longer recommended to adjust this. See [Autoloading and Reloading Constants](autoloading_and_reloading_constants.html#autoload-paths-and-eager-load-paths) * `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. -- cgit v1.2.3 From 4819b2a0ec84511a8fe87213b1e1befa21584a7c Mon Sep 17 00:00:00 2001 From: utilum Date: Mon, 22 Jan 2018 22:11:57 +0100 Subject: Update guide text not to contradict image The bottom line in the image of `ActionController::UnknownFormat`is not truncated. Now the text does not say it is. [ci skip] --- guides/source/getting_started.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'guides/source') diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md index b007baea87..e30909aa62 100644 --- a/guides/source/getting_started.md +++ b/guides/source/getting_started.md @@ -462,8 +462,7 @@ You're getting this error now because Rails expects plain actions like this one to have views associated with them to display their information. With no view available, Rails will raise an exception. -In the above image, the bottom line has been truncated. Let's see what the full -error message looks like: +Let's look at the full error message looks again: >ArticlesController#new is missing a template for this request format and variant. request.formats: ["text/html"] request.variant: [] NOTE! For XHR/Ajax or API requests, this action would normally respond with 204 No Content: an empty white screen. Since you're loading it in a web browser, we assume that you expected to actually render a template, not… nothing, so we're showing an error to be extra-clear. If you expect 204 No Content, carry on. That's what you'll get from an XHR or API request. Give it a shot. -- cgit v1.2.3 From a43bf9f12f4facaae98cba8dec8435c60b633e09 Mon Sep 17 00:00:00 2001 From: utilum Date: Mon, 22 Jan 2018 23:08:26 +0100 Subject: remove text repetition [ci skip] --- guides/source/getting_started.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md index e30909aa62..6cf99a7e5c 100644 --- a/guides/source/getting_started.md +++ b/guides/source/getting_started.md @@ -462,7 +462,7 @@ You're getting this error now because Rails expects plain actions like this one to have views associated with them to display their information. With no view available, Rails will raise an exception. -Let's look at the full error message looks again: +Let's look at the full error message again: >ArticlesController#new is missing a template for this request format and variant. request.formats: ["text/html"] request.variant: [] NOTE! For XHR/Ajax or API requests, this action would normally respond with 204 No Content: an empty white screen. Since you're loading it in a web browser, we assume that you expected to actually render a template, not… nothing, so we're showing an error to be extra-clear. If you expect 204 No Content, carry on. That's what you'll get from an XHR or API request. Give it a shot. -- cgit v1.2.3 From 97e9331317a15dbd4a865daaa1d5255a0820597e Mon Sep 17 00:00:00 2001 From: loothunter1 <35389681+loothunter1@users.noreply.github.com> Date: Wed, 24 Jan 2018 01:39:40 +0300 Subject: Clarification for noobs. (#31704) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Update active_record_basics.md I made a bit of clarification for people, who are not familiar with SQL (pretty much like me). However, I don't know what tutorial for MySQL is better, so I haven't inserted a link yet. * [ci skip] For those who new to GitHub Added more instructions for contributing guides. Without them, it was somewhat confusing for me to find what I should actually do. * Update active_record_basics.md Fixed grammar and text wrapping as requested. * Update contributing_to_ruby_on_rails.md Revised instructions. * Update contributing_to_ruby_on_rails.md Typos * Update active_record_basics.md * [ci skip] Update active_record_basics Added a few links to SQL tutorials found on the net. Also, changed MySQL to SQL (or one of its extensions) - I think that it's a good compromise. * [ci skip] I think now it's more clear what to do. * [ci skip] Fixed strings [Rafael Mendonça França + loothunter1] --- guides/source/active_record_basics.md | 9 ++++++--- guides/source/contributing_to_ruby_on_rails.md | 3 ++- 2 files changed, 8 insertions(+), 4 deletions(-) (limited to 'guides/source') diff --git a/guides/source/active_record_basics.md b/guides/source/active_record_basics.md index 9be9c6c7b7..859679d53a 100644 --- a/guides/source/active_record_basics.md +++ b/guides/source/active_record_basics.md @@ -45,6 +45,8 @@ relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code. +NOTE: If you are not familiar enough with relational database management systems (rDBMS) or structured query language (SQL), please go through [this tutorial](https://www.w3schools.com/sql/default.asp) (or [this one](http://www.sqlcourse.com/)) or study them by other means. Understanding how relational databases work is crucial to understanding Active Records and Rails in general. + ### Active Record as an ORM Framework Active Record gives us several mechanisms, the most important being the ability @@ -142,7 +144,7 @@ end This will create a `Product` model, mapped to a `products` table at the database. By doing this you'll also have the ability to map the columns of each row in that table with the attributes of the instances of your model. Suppose -that the `products` table was created using an SQL statement like: +that the `products` table was created using a SQL (or one of its extensions) statement like: ```sql CREATE TABLE products ( @@ -152,8 +154,9 @@ CREATE TABLE products ( ); ``` -Following the table schema above, you would be able to write code like the -following: +Schema above declares a table with two columns: `id` and `name`. Each row of +this table represents a certain product with these two parameters. Thus, you +would be able to write code like the following: ```ruby p = Product.new diff --git a/guides/source/contributing_to_ruby_on_rails.md b/guides/source/contributing_to_ruby_on_rails.md index 967c992c05..c1668f989b 100644 --- a/guides/source/contributing_to_ruby_on_rails.md +++ b/guides/source/contributing_to_ruby_on_rails.md @@ -134,7 +134,8 @@ learn about Ruby on Rails, and the API, which serves as a reference. You can help improve the Rails guides by making them more coherent, consistent or readable, adding missing information, correcting factual errors, fixing typos, or bringing them up to date with the latest edge Rails. -To do so, open a pull request to [Rails](https://github.com/rails/rails) on GitHub. +To do so, make changes to Rails guides source files (located [here](https://github.com/rails/rails/tree/master/guides/source) on GitHub). Then open a pull request to apply your +changes to 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). -- cgit v1.2.3 From e08e7453457395680607726a56c97e8a01f3bcd0 Mon Sep 17 00:00:00 2001 From: Ryuta Kamizono Date: Wed, 24 Jan 2018 09:11:18 +0900 Subject: tweaks for #31704 [ci skip] * rDBMS -> RDBMS. There is only place using rDBMS. * a SQL -> an SQL --- guides/source/active_record_basics.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'guides/source') diff --git a/guides/source/active_record_basics.md b/guides/source/active_record_basics.md index 859679d53a..2f85b765a3 100644 --- a/guides/source/active_record_basics.md +++ b/guides/source/active_record_basics.md @@ -45,7 +45,7 @@ relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code. -NOTE: If you are not familiar enough with relational database management systems (rDBMS) or structured query language (SQL), please go through [this tutorial](https://www.w3schools.com/sql/default.asp) (or [this one](http://www.sqlcourse.com/)) or study them by other means. Understanding how relational databases work is crucial to understanding Active Records and Rails in general. +NOTE: If you are not familiar enough with relational database management systems (RDBMS) or structured query language (SQL), please go through [this tutorial](https://www.w3schools.com/sql/default.asp) (or [this one](http://www.sqlcourse.com/)) or study them by other means. Understanding how relational databases work is crucial to understanding Active Records and Rails in general. ### Active Record as an ORM Framework @@ -144,7 +144,7 @@ end This will create a `Product` model, mapped to a `products` table at the database. By doing this you'll also have the ability to map the columns of each row in that table with the attributes of the instances of your model. Suppose -that the `products` table was created using a SQL (or one of its extensions) statement like: +that the `products` table was created using an SQL (or one of its extensions) statement like: ```sql CREATE TABLE products ( -- cgit v1.2.3 From cb8da7aca4d426058d3c67b8f206224e5856770e Mon Sep 17 00:00:00 2001 From: Ryan Lue Date: Fri, 26 Jan 2018 12:26:46 +0800 Subject: Fix example migrations in Associations guide --- guides/source/association_basics.md | 26 +++++++++----------------- 1 file changed, 9 insertions(+), 17 deletions(-) (limited to 'guides/source') diff --git a/guides/source/association_basics.md b/guides/source/association_basics.md index 52c30f226f..f895cadea5 100644 --- a/guides/source/association_basics.md +++ b/guides/source/association_basics.md @@ -572,40 +572,32 @@ class Book < ApplicationRecord end ``` -This declaration needs to be backed up by the proper foreign key declaration on the books table: +This declaration needs to be backed up by a corresponding foreign key column in the books table. For a brand new table, the migration might look something like this: ```ruby class CreateBooks < ActiveRecord::Migration[5.0] def change create_table :books do |t| - t.datetime :published_at - t.string :book_number - t.integer :author_id + t.datetime :published_at + t.string :book_number + t.references :author end end end ``` -If you create an association some time after you build the underlying model, you need to remember to create an `add_column` migration to provide the necessary foreign key. - -It's a good practice to add an index on the foreign key to improve queries -performance and a foreign key constraint to ensure referential data integrity: +Whereas for an existing table, it might look like this: ```ruby -class CreateBooks < ActiveRecord::Migration[5.0] +class AddAuthorToBooks < ActiveRecord::Migration[5.0] def change - create_table :books do |t| - t.datetime :published_at - t.string :book_number - t.integer :author_id - end - - add_index :books, :author_id - add_foreign_key :books, :authors + add_reference :books, :author end end ``` +NOTE: If you wish to [enforce referential integrity at the database level](/active_record_migrations.html#foreign-keys), add the `foreign_key: true` option to the ‘reference’ column declarations above. + #### Creating Join Tables for `has_and_belongs_to_many` Associations If you create a `has_and_belongs_to_many` association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the `:join_table` option, Active Record creates the name by using the lexical book of the class names. So a join between author and book models will give the default join table name of "authors_books" because "a" outranks "b" in lexical ordering. -- cgit v1.2.3 From c045637c94b702ab7ae4d624cc8f97087826c548 Mon Sep 17 00:00:00 2001 From: "yuuji.yaginuma" Date: Sun, 28 Jan 2018 10:38:53 +0900 Subject: Update `google-cloud-storage` gem version [ci skip] Because we use `credentials` in an example of configuration files, but `credentials` can not be used unless it is 1.8.0 or later. Ref: 9d65ac3 --- guides/source/active_storage_overview.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/active_storage_overview.md b/guides/source/active_storage_overview.md index d9f5aa8385..97c56dfd93 100644 --- a/guides/source/active_storage_overview.md +++ b/guides/source/active_storage_overview.md @@ -175,7 +175,7 @@ google: Add the [`google-cloud-storage`](https://github.com/GoogleCloudPlatform/google-cloud-ruby/tree/master/google-cloud-storage) gem to your `Gemfile`: ```ruby -gem "google-cloud-storage", "~> 1.3", require: false +gem "google-cloud-storage", "~> 1.8", require: false ``` ### Mirror Service -- cgit v1.2.3 From a88eb9087260cca256c6faba40bf538d4a0289b3 Mon Sep 17 00:00:00 2001 From: "yuuji.yaginuma" Date: Sun, 28 Jan 2018 16:00:33 +0900 Subject: Update `action_dispatch.default_headers` default value [ci skip] This was changed with 5d7b70f and 428939b. --- guides/source/configuring.md | 5 ++++- guides/source/security.md | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) (limited to 'guides/source') diff --git a/guides/source/configuring.md b/guides/source/configuring.md index 36c2fdb0b8..a0bf6046da 100644 --- a/guides/source/configuring.md +++ b/guides/source/configuring.md @@ -462,7 +462,10 @@ The schema dumper adds one additional configuration option: config.action_dispatch.default_headers = { 'X-Frame-Options' => 'SAMEORIGIN', 'X-XSS-Protection' => '1; mode=block', - 'X-Content-Type-Options' => 'nosniff' + 'X-Content-Type-Options' => 'nosniff', + 'X-Download-Options' => 'noopen', + 'X-Permitted-Cross-Domain-Policies' => 'none', + 'Referrer-Policy' => 'strict-origin-when-cross-origin' } ``` diff --git a/guides/source/security.md b/guides/source/security.md index ab5a5a7a31..de0b523057 100644 --- a/guides/source/security.md +++ b/guides/source/security.md @@ -1070,7 +1070,10 @@ Every HTTP response from your Rails application receives the following default s config.action_dispatch.default_headers = { 'X-Frame-Options' => 'SAMEORIGIN', 'X-XSS-Protection' => '1; mode=block', - 'X-Content-Type-Options' => 'nosniff' + 'X-Content-Type-Options' => 'nosniff', + 'X-Download-Options' => 'noopen', + 'X-Permitted-Cross-Domain-Policies' => 'none', + 'Referrer-Policy' => 'strict-origin-when-cross-origin' } ``` -- cgit v1.2.3 From 091806388a757b30c85b5888dabc3f705af440ef Mon Sep 17 00:00:00 2001 From: Daniel Colson Date: Sun, 28 Jan 2018 15:36:30 -0500 Subject: Remove out-of-date references to jQuery Fixes #31703 --- guides/source/asset_pipeline.md | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) (limited to 'guides/source') diff --git a/guides/source/asset_pipeline.md b/guides/source/asset_pipeline.md index e6d5aed135..618896d458 100644 --- a/guides/source/asset_pipeline.md +++ b/guides/source/asset_pipeline.md @@ -22,8 +22,7 @@ The asset pipeline provides a framework to concatenate and minify or compress JavaScript and CSS assets. It also adds the ability to write these assets in other languages and pre-processors such as CoffeeScript, Sass and ERB. It allows assets in your application to be automatically combined with assets -from other gems. For example, jquery-rails includes a copy of jquery.js -and enables AJAX features in Rails. +from other gems. The asset pipeline is implemented by the [sprockets-rails](https://github.com/rails/sprockets-rails) gem, @@ -1205,10 +1204,10 @@ Adding Assets to Your Gems Assets can also come from external sources in the form of gems. -A good example of this is the `jquery-rails` gem which comes with Rails as the -standard JavaScript library gem. This gem contains an engine class which -inherits from `Rails::Engine`. By doing this, Rails is informed that the -directory for this gem may contain assets and the `app/assets`, `lib/assets` and +A good example of this is the `jquery-rails` gem. +This gem contains an engine class which inherits from `Rails::Engine`. +By doing this, Rails is informed that the directory for this +gem may contain assets and the `app/assets`, `lib/assets` and `vendor/assets` directories of this engine are added to the search path of Sprockets. @@ -1244,11 +1243,7 @@ moving the files from `public/` to the new locations. See [Asset Organization](#asset-organization) above for guidance on the correct locations for different file types. -Next will be avoiding duplicate JavaScript files. Since jQuery is the default -JavaScript library from Rails 3.1 onwards, you don't need to copy `jquery.js` -into `app/assets` and it will be included automatically. - -The third is updating the various environment files with the correct default +Next is updating the various environment files with the correct default options. In `application.rb`: -- cgit v1.2.3 From 600c4138dd778f4e5633846b5b68a89dbb77193d Mon Sep 17 00:00:00 2001 From: Daniel Colson Date: Sun, 28 Jan 2018 17:44:01 -0500 Subject: Remove joke in security guide [ci skip] I think this is a joke, although not a great one. It's mildly unprofessional, so I think we should get rid of it. --- guides/source/security.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/security.md b/guides/source/security.md index ab5a5a7a31..724d952d4e 100644 --- a/guides/source/security.md +++ b/guides/source/security.md @@ -551,7 +551,7 @@ Here are some ideas how to hide honeypot fields by JavaScript and/or CSS: * make the elements very small or color them the same as the background of the page * leave the fields displayed, but tell humans to leave them blank -The most simple negative CAPTCHA is one hidden honeypot field. On the server side, you will check the value of the field: If it contains any text, it must be a bot. Then, you can either ignore the post or return a positive result, but not saving the post to the database. This way the bot will be satisfied and moves on. You can do this with annoying users, too. +The most simple negative CAPTCHA is one hidden honeypot field. On the server side, you will check the value of the field: If it contains any text, it must be a bot. Then, you can either ignore the post or return a positive result, but not saving the post to the database. This way the bot will be satisfied and moves on. You can find more sophisticated negative CAPTCHAs in Ned Batchelder's [blog post](http://nedbatchelder.com/text/stopbots.html): -- cgit v1.2.3 From 5ea2d0224ff9011512754bea73a6eca7c7a7665f Mon Sep 17 00:00:00 2001 From: claudiob Date: Tue, 30 Jan 2018 08:20:58 -0800 Subject: Add ContentSecurityPolicy to list of middleware Document in the guides the new middleware added in #31162 [ci skip] --- guides/source/rails_on_rack.md | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'guides/source') diff --git a/guides/source/rails_on_rack.md b/guides/source/rails_on_rack.md index 5718b9ddfc..6780e7c0de 100644 --- a/guides/source/rails_on_rack.md +++ b/guides/source/rails_on_rack.md @@ -284,6 +284,10 @@ Much of Action Controller's functionality is implemented as Middlewares. The fol * Sets up the flash keys. Only available if `config.action_controller.session_store` is set to a value. +**`ActionDispatch::ContentSecurityPolicy::Middleware`** + +* Provides a DSL to configure a Content-Security-Policy header. + **`Rack::Head`** * Converts HEAD requests to `GET` requests and serves them as so. -- cgit v1.2.3 From 54bb2f74b5156b4251582842b0edc8e216958e01 Mon Sep 17 00:00:00 2001 From: George Claghorn Date: Tue, 30 Jan 2018 18:21:07 -0500 Subject: Add Rack::TempfileReaper to tests and docs --- guides/source/rails_on_rack.md | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'guides/source') diff --git a/guides/source/rails_on_rack.md b/guides/source/rails_on_rack.md index 6780e7c0de..1627205b7b 100644 --- a/guides/source/rails_on_rack.md +++ b/guides/source/rails_on_rack.md @@ -126,6 +126,7 @@ use ActionDispatch::ContentSecurityPolicy::Middleware use Rack::Head use Rack::ConditionalGet use Rack::ETag +use Rack::TempfileReaper run MyApp::Application.routes ``` @@ -300,6 +301,10 @@ Much of Action Controller's functionality is implemented as Middlewares. The fol * Adds ETag header on all String bodies. ETags are used to validate cache. +**`Rack::TempfileReaper`** + +* Cleans up tempfiles used to buffer multipart requests. + TIP: It's possible to use any of the above middlewares in your custom Rack stack. Resources -- cgit v1.2.3 From ac3df409951430df79dc53f4e0acb13fc0f62cab Mon Sep 17 00:00:00 2001 From: Sam Yamashita <1587053+sotayamashita@users.noreply.github.com> Date: Wed, 31 Jan 2018 13:52:56 +0900 Subject: Fix typo --- guides/source/autoloading_and_reloading_constants.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/autoloading_and_reloading_constants.md b/guides/source/autoloading_and_reloading_constants.md index 8d28007671..f7f048e271 100644 --- a/guides/source/autoloading_and_reloading_constants.md +++ b/guides/source/autoloading_and_reloading_constants.md @@ -1346,5 +1346,5 @@ On a development machine you can then have your tests running with whatever is f 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 explictly eager_load by using `Rails +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). -- cgit v1.2.3 From 053e3fa1e5aaebc5023fb06b3a670319ea5edf21 Mon Sep 17 00:00:00 2001 From: Tim Diggins Date: Sat, 3 Feb 2018 17:34:34 +0000 Subject: Correct capitalization of "Rails" in the guide text. correction to #31755 as per https://github.com/rails/rails/pull/31755#discussion_r165819798 --- guides/source/autoloading_and_reloading_constants.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'guides/source') diff --git a/guides/source/autoloading_and_reloading_constants.md b/guides/source/autoloading_and_reloading_constants.md index f7f048e271..6d30910ce8 100644 --- a/guides/source/autoloading_and_reloading_constants.md +++ b/guides/source/autoloading_and_reloading_constants.md @@ -469,12 +469,12 @@ default it contains: 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. + * 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 (pre-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. +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). @@ -1344,7 +1344,7 @@ For example it might be worth running your tests with an identical setup to prod 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). +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). -- cgit v1.2.3 From 013fd84373ca5dd49d42170a82648ada5a2025bb Mon Sep 17 00:00:00 2001 From: Daniel Colson Date: Wed, 7 Feb 2018 18:00:03 -0500 Subject: Remove password anecdotes from guides [ci skip] --- guides/source/security.md | 12 ------------ 1 file changed, 12 deletions(-) (limited to 'guides/source') diff --git a/guides/source/security.md b/guides/source/security.md index 74256c7b84..28ddbdc26a 100644 --- a/guides/source/security.md +++ b/guides/source/security.md @@ -573,18 +573,6 @@ config.filter_parameters << :password NOTE: Provided parameters will be filtered out by partial matching regular expression. Rails adds default `:password` in the appropriate initializer (`initializers/filter_parameter_logging.rb`) and cares about typical application parameters `password` and `password_confirmation`. -### Good Passwords - -INFO: _Do you find it hard to remember all your passwords? Don't write them down, but use the initial letters of each word in an easy to remember sentence._ - -Bruce Schneier, a security technologist, [has analyzed](http://www.schneier.com/blog/archives/2006/12/realworld_passw.html) 34,000 real-world user names and passwords from the MySpace phishing attack mentioned [below](#examples-from-the-underground). It turns out that most of the passwords are quite easy to crack. The 20 most common passwords are: - -password1, abc123, myspace1, password, blink182, qwerty1, ****you, 123abc, baseball1, football1, 123456, soccer, monkey1, liverpool1, princess1, jordan23, slipknot1, superman1, iloveyou1, and monkey. - -It is interesting that only 4% of these passwords were dictionary words and the great majority is actually alphanumeric. However, password cracker dictionaries contain a large number of today's passwords, and they try out all kinds of (alphanumerical) combinations. If an attacker knows your user name and you use a weak password, your account will be easily cracked. - -A good password is a long alphanumeric combination of mixed cases. As this is quite hard to remember, it is advisable to enter only the _first letters of a sentence that you can easily remember_. For example "The quick brown fox jumps over the lazy dog" will be "Tqbfjotld". Note that this is just an example, you should not use well known phrases like these, as they might appear in cracker dictionaries, too. - ### Regular Expressions INFO: _A common pitfall in Ruby's regular expressions is to match the string's beginning and end by ^ and $, instead of \A and \z._ -- cgit v1.2.3 From cc488b40d2bde10083984df5bb85417e0c2f7c0c Mon Sep 17 00:00:00 2001 From: claudiob Date: Wed, 7 Feb 2018 20:35:22 -0800 Subject: Add docs on how to configure Active Storage [ci skip] --- guides/source/configuring.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) (limited to 'guides/source') diff --git a/guides/source/configuring.md b/guides/source/configuring.md index a0bf6046da..b0f39e7ab5 100644 --- a/guides/source/configuring.md +++ b/guides/source/configuring.md @@ -752,6 +752,41 @@ main application. You can set this as nil to not mount Action Cable as part of your normal Rails server. + +### Configuring Active Storage + +`config.active_storage` provides the following configuration options: + +* `config.active_storage.analyzers` accepts an array of classes indicating the analyzers available for Active Storage blobs. The default is `[ActiveStorage::Analyzer::ImageAnalyzer, ActiveStorage::Analyzer::VideoAnalyzer]`. The former can extract width and height of an image blob; the latter can extract width, height, duration, angle, and aspect ratio of a video blob. + +* `config.active_storage.previewers` accepts an array of classes indicating the image previewers available in Active Storage blobs. The default is `[ActiveStorage::Previewer::PDFPreviewer, ActiveStorage::Previewer::VideoPreviewer]`. The former can generate a thumbnail from the first page of a PDF blob; the latter from the relevant frame of a video blob. + +* `config.active_storage.paths` accepts a hash of options indicating the locations of previewer/analyzer commands. The default is `{}`, meaning the commands will be looked for in the default path. Can include any of these options: + * `:ffprobe` - The location of the ffprobe executable. + * `:mutool` - The location of the mutool executable. + * `:ffmpeg` - The location of the ffmpeg executable. + + ```ruby + 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/vnd.adobe.photoshop)`. + +* `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)`. + +* `config.active_storage.queue` can be used to set the name of the Active Job queue used to perform jobs like analyzing the content of a blob or purging a blog. + + ```ruby + config.active_job.queue = :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 + config.active_job.logger = ActiveSupport::Logger.new(STDOUT) + ``` + ### Configuring a Database Just about every Rails application will interact with a database. You can connect to the database by setting an environment variable `ENV['DATABASE_URL']` or by using a configuration file called `config/database.yml`. -- cgit v1.2.3 From b62eed173f924af075540d87e57b79ef90db8316 Mon Sep 17 00:00:00 2001 From: James Lovejoy Date: Fri, 9 Feb 2018 22:16:24 -0800 Subject: Improve wording in getting started guide [ci skip] --- guides/source/getting_started.md | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) (limited to 'guides/source') diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md index 6cf99a7e5c..ad587d6117 100644 --- a/guides/source/getting_started.md +++ b/guides/source/getting_started.md @@ -100,7 +100,7 @@ For more installation methods for most Operating Systems take a look at [ruby-lang.org](https://www.ruby-lang.org/en/documentation/installation/). If you are working on Windows, you should also install the -[Ruby Installer Development Kit](http://rubyinstaller.org/downloads/). +[Ruby Installer Development Kit](https://rubyinstaller.org/downloads/). You will also need an installation of the SQLite3 database. Many popular UNIX-like OSes ship with an acceptable version of SQLite3. @@ -170,7 +170,7 @@ of the files and folders that Rails created by default: | File/Folder | Purpose | | ----------- | ------- | |app/|Contains the controllers, models, views, helpers, mailers, channels, jobs and assets for your application. You'll focus on this folder for the remainder of this guide.| -|bin/|Contains the rails script that starts your app and can contain other scripts you use to setup, update, deploy or run your application.| +|bin/|Contains the rails script that starts your app and can contain other scripts you use to setup, update, deploy, or run your application.| |config/|Configure your application's routes, database, and more. This is covered in more detail in [Configuring Rails Applications](configuring.html).| |config.ru|Rack configuration for Rack based servers used to start the application. For more information about Rack, see the [Rack website](https://rack.github.io/).| |db/|Contains your current database schema, as well as the database migrations.| @@ -346,9 +346,9 @@ Now that you've seen how to create a controller, an action and a view, let's create something with a bit more substance. In the Blog application, you will now create a new _resource_. A resource is the -term used for a collection of similar objects, such as articles, people or +term used for a collection of similar objects, such as articles, people, or animals. -You can create, read, update and destroy items for a resource and these +You can create, read, update, and destroy items for a resource and these operations are referred to as _CRUD_ operations. Rails provides a `resources` method which can be used to declare a standard REST @@ -504,7 +504,7 @@ write this content in it: ``` When you refresh you'll now see that the -page has a title. The route, controller, action and view are now working +page has a title. The route, controller, action, and view are now working harmoniously! It's time to create the form for a new article. ### The first form @@ -1122,7 +1122,7 @@ that otherwise `@article` would be `nil` in our view, and calling `@article.errors.any?` would throw an error. TIP: Rails automatically wraps fields that contain an error with a div -with class `field_with_errors`. You can define a css rule to make them +with class `field_with_errors`. You can define a CSS rule to make them standout. Now you'll get a nice error message when saving an article without title when @@ -1204,10 +1204,10 @@ it look as follows: This time we point the form to the `update` action, which is not defined yet but will be very soon. -Passing the article object to the method, will automagically create url for submitting the edited article form. -This option tells Rails that we want this form to be submitted -via the `PATCH` HTTP method which is the HTTP method you're expected to use to -**update** resources according to the REST protocol. +Passing the article object to the method will automatically set the URL for +submitting the edited article form. This option tells Rails that we want this +form to be submitted via the `PATCH` HTTP method, which is the HTTP method you're +expected to use to **update** resources according to the REST protocol. The arguments to `form_with` could be model objects, say, `model: @article` which would cause the helper to fill in the form with the fields of the object. Passing in a @@ -1506,7 +1506,7 @@ appear. TIP: Learn more about Unobtrusive JavaScript on [Working With JavaScript in Rails](working_with_javascript_in_rails.html) guide. -Congratulations, you can now create, show, list, update and destroy +Congratulations, you can now create, show, list, update, and destroy articles. TIP: In general, Rails encourages using resources objects instead of @@ -2065,8 +2065,8 @@ getting up and running with Rails, feel free to consult these support resources: * The [Ruby on Rails Guides](index.html) -* The [Ruby on Rails Tutorial](http://railstutorial.org/book) -* The [Ruby on Rails mailing list](http://groups.google.com/group/rubyonrails-talk) +* The [Ruby on Rails Tutorial](https://www.railstutorial.org/book) +* The [Ruby on Rails mailing list](https://groups.google.com/group/rubyonrails-talk) * The [#rubyonrails](irc://irc.freenode.net/#rubyonrails) channel on irc.freenode.net -- cgit v1.2.3 From 27e5c76a77cbca90836ad4fc3a861d9c47cf8588 Mon Sep 17 00:00:00 2001 From: Yauheni Dakuka Date: Mon, 12 Feb 2018 09:15:12 +0300 Subject: Remove parentheses [ci skip] --- guides/source/autoloading_and_reloading_constants.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/autoloading_and_reloading_constants.md b/guides/source/autoloading_and_reloading_constants.md index 6d30910ce8..5428b16edc 100644 --- a/guides/source/autoloading_and_reloading_constants.md +++ b/guides/source/autoloading_and_reloading_constants.md @@ -476,7 +476,7 @@ How files are autoloaded depends on `eager_load` and `cache_classes` config sett 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). +See also [Autoloading in the Test Environment](#autoloading-in-the-test-environment). `config.autoload_paths` is not changeable from environment-specific configuration files. -- cgit v1.2.3 From a7b97454f8dc481a9f6725d22b56ee62f69a3417 Mon Sep 17 00:00:00 2001 From: Yauheni Dakuka Date: Mon, 12 Feb 2018 23:29:34 +0300 Subject: Change structure of AS core extensions [ci skip] --- guides/source/active_support_core_extensions.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) (limited to 'guides/source') diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md index 8e2826bb85..6c980fb0e9 100644 --- a/guides/source/active_support_core_extensions.md +++ b/guides/source/active_support_core_extensions.md @@ -925,6 +925,15 @@ The macros `cattr_reader`, `cattr_writer`, and `cattr_accessor` are analogous to ```ruby class MysqlAdapter < AbstractAdapter # Generates class methods to access @@emulate_booleans. + cattr_accessor :emulate_booleans +end +``` + +Also, you can pass a block to `cattr_*` to set up the attribute with a default value: + +```ruby +class MysqlAdapter < AbstractAdapter + # Generates class methods to access @@emulate_booleans with default value of true. cattr_accessor :emulate_booleans, default: true end ``` @@ -941,15 +950,6 @@ end we can access `field_error_proc` in views. -Also, you can pass a block to `cattr_*` to set up the attribute with a default value: - -```ruby -class MysqlAdapter < AbstractAdapter - # Generates class methods to access @@emulate_booleans with default value of true. - cattr_accessor :emulate_booleans, default: true -end -``` - The generation of the reader instance method can be prevented by setting `:instance_reader` to `false` and the generation of the writer instance method can be prevented by setting `:instance_writer` to `false`. Generation of both methods can be prevented by setting `:instance_accessor` to `false`. In all cases, the value must be exactly `false` and not any false value. ```ruby -- cgit v1.2.3 From e360ac12315ed6b9eadca5bcc0d95dc766ba8523 Mon Sep 17 00:00:00 2001 From: Evgenii Pecherkin Date: Tue, 17 Oct 2017 16:05:05 +0400 Subject: Introduce serializers to ActiveJob --- guides/source/active_job_basics.md | 65 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 63 insertions(+), 2 deletions(-) (limited to 'guides/source') diff --git a/guides/source/active_job_basics.md b/guides/source/active_job_basics.md index 914ef2c327..a7067cb97d 100644 --- a/guides/source/active_job_basics.md +++ b/guides/source/active_job_basics.md @@ -339,8 +339,21 @@ UserMailer.welcome(@user).deliver_later # Email will be localized to Esperanto. ``` -GlobalID --------- +Supported types for arguments +---------------------------- + +ActiveJob supports the following types of arguments by default: + + - Basic types (`NilClass`, `String`, `Integer`, `Fixnum`, `Bignum`, `Float`, `BigDecimal`, `TrueClass`, `FalseClass`) + - `Symbol` (`:foo`, `:bar`, ...) + - `ActiveSupport::Duration` (`1.day`, `2.weeks`, ...) + - Classes constants (`ActiveRecord::Base`, `MySpecialService`, ...) + - Struct instances (`Struct.new('Rectangle', :width, :height).new(12, 20)`, ...) + - `Hash`. Keys should be of `String` or `Symbol` type + - `ActiveSupport::HashWithIndifferentAccess` + - `Array` + +### GlobalID Active Job supports GlobalID for parameters. This makes it possible to pass live Active Record objects to your job instead of class/id pairs, which you then have @@ -368,6 +381,54 @@ end This works with any class that mixes in `GlobalID::Identification`, which by default has been mixed into Active Record classes. +### Serializers + +You can extend list of supported types for arguments. You just need to define your own serializer. + +```ruby +class MySpecialSerializer + class << self + # Check if this object should be serialized using this serializer + def serialize?(argument) + argument.is_a? MySpecialValueObject + end + + # Convert an object to a simpler representative using supported object types. + # The recommended representative is a Hash with a specific key. Keys can be of basic types only + def serialize(object) + { + key => ActiveJob::Serializers.serialize(object.value) + 'another_attribute' => ActiveJob::Serializers.serialize(object.another_attribute) + } + end + + # Check if this serialized value be deserialized using this serializer + def deserialize?(argument) + argument.is_a?(Hash) && argument.keys == [key, 'another_attribute'] + end + + # Convert serialized value into a proper object + def deserialize(object) + value = ActiveJob::Serializers.deserialize(object[key]) + another_attribute = ActiveJob::Serializers.deserialize(object['another_attribute']) + MySpecialValueObject.new value, another_attribute + end + + # Define this method if you are using a hash as a representative. + # This key will be added to a list of restricted keys for hashes. Use basic types only + def key + "_aj_custom_dummy_value_object" + end + end +end +``` + +And now you just need to add this serializer to a list: + +```ruby +ActiveJob::Base.add_serializers(MySpecialSerializer) +``` + Exceptions ---------- -- cgit v1.2.3 From 3785a5729959a838bb13f2d298a59e12e1844f74 Mon Sep 17 00:00:00 2001 From: Evgenii Pecherkin Date: Mon, 23 Oct 2017 17:29:28 +0400 Subject: Remove non-default serializers --- guides/source/active_job_basics.md | 4 ---- 1 file changed, 4 deletions(-) (limited to 'guides/source') diff --git a/guides/source/active_job_basics.md b/guides/source/active_job_basics.md index a7067cb97d..eea64f9367 100644 --- a/guides/source/active_job_basics.md +++ b/guides/source/active_job_basics.md @@ -345,10 +345,6 @@ Supported types for arguments ActiveJob supports the following types of arguments by default: - Basic types (`NilClass`, `String`, `Integer`, `Fixnum`, `Bignum`, `Float`, `BigDecimal`, `TrueClass`, `FalseClass`) - - `Symbol` (`:foo`, `:bar`, ...) - - `ActiveSupport::Duration` (`1.day`, `2.weeks`, ...) - - Classes constants (`ActiveRecord::Base`, `MySpecialService`, ...) - - Struct instances (`Struct.new('Rectangle', :width, :height).new(12, 20)`, ...) - `Hash`. Keys should be of `String` or `Symbol` type - `ActiveSupport::HashWithIndifferentAccess` - `Array` -- cgit v1.2.3 From a5f7357a3dff2617ba13a274feb8d8ac2492f26a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Fri, 9 Feb 2018 17:27:01 -0500 Subject: Add configuration to set custom serializers --- guides/source/configuring.md | 2 ++ 1 file changed, 2 insertions(+) (limited to 'guides/source') diff --git a/guides/source/configuring.md b/guides/source/configuring.md index b0f39e7ab5..fd747c1686 100644 --- a/guides/source/configuring.md +++ b/guides/source/configuring.md @@ -741,6 +741,8 @@ There are a few configuration options available in Active Support: * `config.active_job.logger` accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then used to log information from Active Job. You can retrieve this logger by calling `logger` on either an Active Job class or an Active Job instance. Set to `nil` to disable logging. +* `config.active_job.custom_serializers` allows to set custom argument serializers. Defaults to `[]`. + ### Configuring Action Cable * `config.action_cable.url` accepts a string for the URL for where -- cgit v1.2.3 From 71721dc1c9b769d3c06317122dc88cad4a346580 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Fri, 9 Feb 2018 17:27:39 -0500 Subject: Improve documentation on custom serializers --- guides/source/active_job_basics.md | 43 +++++++++++++++++++------------------- 1 file changed, 21 insertions(+), 22 deletions(-) (limited to 'guides/source') diff --git a/guides/source/active_job_basics.md b/guides/source/active_job_basics.md index eea64f9367..0ee522e23d 100644 --- a/guides/source/active_job_basics.md +++ b/guides/source/active_job_basics.md @@ -345,6 +345,12 @@ Supported types for arguments ActiveJob supports the following types of arguments by default: - Basic types (`NilClass`, `String`, `Integer`, `Fixnum`, `Bignum`, `Float`, `BigDecimal`, `TrueClass`, `FalseClass`) + - `Symbol + - `ActiveSupport::Duration` + - `Date` + - `Time` + - `DateTime` + - `ActiveSupport::TimeWithZone` - `Hash`. Keys should be of `String` or `Symbol` type - `ActiveSupport::HashWithIndifferentAccess` - `Array` @@ -382,38 +388,31 @@ by default has been mixed into Active Record classes. You can extend list of supported types for arguments. You just need to define your own serializer. ```ruby -class MySpecialSerializer - class << self - # Check if this object should be serialized using this serializer +class MoneySerializer < ActiveJob::Serializers::ObjectSerializer + # Check if this object should be serialized using this serializer. def serialize?(argument) - argument.is_a? MySpecialValueObject + argument.is_a? Money end # Convert an object to a simpler representative using supported object types. - # The recommended representative is a Hash with a specific key. Keys can be of basic types only + # The recommended representative is a Hash with a specific key. Keys can be of basic types only. + # You should call `super` to add the custom serializer type to the hash def serialize(object) - { - key => ActiveJob::Serializers.serialize(object.value) - 'another_attribute' => ActiveJob::Serializers.serialize(object.another_attribute) - } + super( + "cents" => object.cents, + "currency" => object.currency + ) end - # Check if this serialized value be deserialized using this serializer + # Check if this serialized value be deserialized using this serializer. + # ActiveJob::Serializers::ObjectSerializer#deserialize? already take care of this. def deserialize?(argument) - argument.is_a?(Hash) && argument.keys == [key, 'another_attribute'] + super end # Convert serialized value into a proper object - def deserialize(object) - value = ActiveJob::Serializers.deserialize(object[key]) - another_attribute = ActiveJob::Serializers.deserialize(object['another_attribute']) - MySpecialValueObject.new value, another_attribute - end - - # Define this method if you are using a hash as a representative. - # This key will be added to a list of restricted keys for hashes. Use basic types only - def key - "_aj_custom_dummy_value_object" + def deserialize(hash) + Money.new hash["cents"], hash["currency"] end end end @@ -422,7 +421,7 @@ end And now you just need to add this serializer to a list: ```ruby -ActiveJob::Base.add_serializers(MySpecialSerializer) +Rails.application.config.active_job.custom_serializers << MySpecialSerializer ``` -- cgit v1.2.3 From 69645cba727dfa1c18c666d2a2f1c0dedffde938 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Mon, 12 Feb 2018 14:16:41 -0500 Subject: Simplify the implementation of custom argument serializers We can speed up things for the supported types by keeping the code in the way it was. We can also avoid to loop trough all serializers in the deserialization by trying to access the class already in the Hash. We could also speed up the custom serialization if we define the class that is going to be serialized when registering the serializers, but that will remove the possibility of defining a serialzer for a superclass and have the subclass serialized using it. --- guides/source/active_job_basics.md | 6 ------ 1 file changed, 6 deletions(-) (limited to 'guides/source') diff --git a/guides/source/active_job_basics.md b/guides/source/active_job_basics.md index 0ee522e23d..92a04c585f 100644 --- a/guides/source/active_job_basics.md +++ b/guides/source/active_job_basics.md @@ -404,12 +404,6 @@ class MoneySerializer < ActiveJob::Serializers::ObjectSerializer ) end - # Check if this serialized value be deserialized using this serializer. - # ActiveJob::Serializers::ObjectSerializer#deserialize? already take care of this. - def deserialize?(argument) - super - end - # Convert serialized value into a proper object def deserialize(hash) Money.new hash["cents"], hash["currency"] -- cgit v1.2.3 From 007c7914ff919913461a1e8285d8db07707051e3 Mon Sep 17 00:00:00 2001 From: Yauheni Dakuka Date: Thu, 15 Feb 2018 07:55:01 +0300 Subject: Missing backquote, extra end keyword [ci skip] --- guides/source/active_job_basics.md | 35 +++++++++++++++++------------------ 1 file changed, 17 insertions(+), 18 deletions(-) (limited to 'guides/source') diff --git a/guides/source/active_job_basics.md b/guides/source/active_job_basics.md index 92a04c585f..9b738e8cdd 100644 --- a/guides/source/active_job_basics.md +++ b/guides/source/active_job_basics.md @@ -345,7 +345,7 @@ Supported types for arguments ActiveJob supports the following types of arguments by default: - Basic types (`NilClass`, `String`, `Integer`, `Fixnum`, `Bignum`, `Float`, `BigDecimal`, `TrueClass`, `FalseClass`) - - `Symbol + - `Symbol` - `ActiveSupport::Duration` - `Date` - `Time` @@ -389,25 +389,24 @@ You can extend list of supported types for arguments. You just need to define yo ```ruby class MoneySerializer < ActiveJob::Serializers::ObjectSerializer - # Check if this object should be serialized using this serializer. - def serialize?(argument) - argument.is_a? Money - end + # Check if this object should be serialized using this serializer. + def serialize?(argument) + argument.is_a? Money + end - # Convert an object to a simpler representative using supported object types. - # The recommended representative is a Hash with a specific key. Keys can be of basic types only. - # You should call `super` to add the custom serializer type to the hash - def serialize(object) - super( - "cents" => object.cents, - "currency" => object.currency - ) - end + # Convert an object to a simpler representative using supported object types. + # The recommended representative is a Hash with a specific key. Keys can be of basic types only. + # You should call `super` to add the custom serializer type to the hash + def serialize(object) + super( + "cents" => object.cents, + "currency" => object.currency + ) + end - # Convert serialized value into a proper object - def deserialize(hash) - Money.new hash["cents"], hash["currency"] - end + # Convert serialized value into a proper object + def deserialize(hash) + Money.new hash["cents"], hash["currency"] end end ``` -- cgit v1.2.3 From b6bbedf1a8f12fdc8814acb547a36640814f22ca Mon Sep 17 00:00:00 2001 From: Jeremy Prevost Date: Thu, 15 Feb 2018 16:30:15 -0500 Subject: ActiveStorage file cleanup in Integration Tests Documents ActiveStorage file cleanup in Integration Tests which is similar but slightly different than the existing docs for System Tests. --- guides/source/active_storage_overview.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) (limited to 'guides/source') diff --git a/guides/source/active_storage_overview.md b/guides/source/active_storage_overview.md index 97c56dfd93..c72a38b1de 100644 --- a/guides/source/active_storage_overview.md +++ b/guides/source/active_storage_overview.md @@ -556,6 +556,30 @@ config.active_job.queue_adapter = :inline config.active_storage.service = :local_test ``` +Discarding Files Stored During Integration Tests +------------------------------------------- + +Similarly to System Tests, files uploaded during Integration Tests will not be +automatically cleaned up. If you want to clear the files, you can do it in an +`after_teardown` callback. Doing it here ensures that all connections created +during the test are complete and you won't receive an error from Active Storage +saying it can't find a file. + +```ruby +module ActionDispatch + class IntegrationTest + def remove_uploaded_files + FileUtils.rm_rf(Rails.root.join('tmp', 'storage')) + end + + def after_teardown + super + remove_uploaded_files + end + end +end +``` + Implementing Support for Other Cloud Services --------------------------------------------- -- cgit v1.2.3 From 26821d9b572815a39c8ecb2e19375b2abff68730 Mon Sep 17 00:00:00 2001 From: eileencodes Date: Wed, 20 Dec 2017 16:59:41 -0500 Subject: Add test parallelization to Rails Provides both a forked process and threaded parallelization options. To use add `parallelize` to your test suite. Takes a `workers` argument that controls how many times the process is forked. For each process a new database will be created suffixed with the worker number; test-database-0 and test-database-1 respectively. If `ENV["PARALLEL_WORKERS"]` is set the workers argument will be ignored and the environment variable will be used instead. This is useful for CI environments, or other environments where you may need more workers than you do for local testing. If the number of workers is set to `1` or fewer, the tests will not be parallelized. The default parallelization method is to fork processes. If you'd like to use threads instead you can pass `with: :threads` to the `parallelize` method. Note the threaded parallelization does not create multiple database and will not work with system tests at this time. parallelize(workers: 2, with: :threads) The threaded parallelization uses Minitest's parallel exector directly. The processes paralleliztion uses a Ruby Drb server. For parallelization via threads a setup hook and cleanup hook are provided. ``` class ActiveSupport::TestCase parallelize_setup do |worker| # setup databases end parallelize_teardown do |worker| # cleanup database end parallelize(workers: 2) end ``` [Eileen M. Uchitelle, Aaron Patterson] --- guides/source/testing.md | 83 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) (limited to 'guides/source') diff --git a/guides/source/testing.md b/guides/source/testing.md index af6127f4a5..5d2b8bc5d6 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -462,6 +462,89 @@ Rails options: -c, --[no-]color Enable color in the output ``` +Parallel Testing +---------------- + +Parallel testing allows you to parallelize your test suite. While forking processes is the +default method, threading is supported as well. Running tests in parallel reduces the time it +takes your entire test suite to run. + +## Parallel testing with processes + +The default parallelization method is to fork processes using Ruby's DRb system. The processes +are forked based on the number of workers provided. The default is 2, but can be changed by the +number passed to the parallelize method. Active Record automatically handles creating and +migrating a new database for each worker to use. + +To enable parallelization add the following to your `test_helper.rb`: + +``` +class ActiveSupport::TestCase + parallelize(workers: 2) +end +``` + +The number of workers passed is the number of times the process will be forked. You may want to +parallelize your local test suite differently from your CI, so an environment variable is provided +to be able to easily change the number of workers a test run should use: + +``` +PARALLEL_WORKERS=15 bin/rails test +``` + +When parallelizing tests, Active Record automatically handles creating and migrating a database for each +process. The databases will be suffixed with the number corresponding to the worker. For example, if you +have 2 workers the tests will create `test-database-0` and `test-database-1` respectively. + +If the number of workers passed is 1 or fewer the processes will not be forked and the tests will not +be parallelized and the tests will use the original `test-database` database. + +Two hooks are provided, one runs when the process is forked, and one runs before the processes are closed. +These can be useful if your app uses multiple databases or perform other tasks that depend on the number of +workers. + +The `parallelize_setup` method is called right after the processes are forked. The `parallelize_teardown` metod +is called right before the processes are closed. + +``` +class ActiveSupport::TestCase + parallelize_setup do |worker| + # setup databases + end + + parallelize_teardown do |worker| + # cleanup database + end + + parallelize(workers: 2) +end +``` + +These methods are not needed or available when using parallel testing with threads. + +## Parallel testing with threads + +If you prefer using threads or are using JRuby, a threaded parallelization option is provided. The threaded +parallelizer is backed by Minitest's `Parallel::Executor`. + +To change the parallelization method to use threads over forks put the following in your `test_helper.rb` + +``` +class ActiveSupport::TestCase + parallelize(workers: 2, with: :threads) +end +``` + +Rails applications generated from JRuby will automatically include the `with: :threads` option. + +The number of workers passed to `parallelize` determines the number of threads the tests will use. You may +want to parallelize your local test suite differently from your CI, so an environment variable is provided +to be able to easily change the number of workers a test run should use: + +``` +PARALLEL_WORKERS=15 bin/rails test +``` + The Test Database ----------------- -- cgit v1.2.3 From a713fdae4eb4f7ccd34932edc61561a96b8d9f35 Mon Sep 17 00:00:00 2001 From: "yuuji.yaginuma" Date: Sat, 17 Feb 2018 16:48:44 +0900 Subject: Merge descriptions related to parallel test into one section [ci skip] --- guides/source/testing.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'guides/source') diff --git a/guides/source/testing.md b/guides/source/testing.md index 5d2b8bc5d6..b9b310cbba 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -469,7 +469,7 @@ Parallel testing allows you to parallelize your test suite. While forking proces default method, threading is supported as well. Running tests in parallel reduces the time it takes your entire test suite to run. -## Parallel testing with processes +### Parallel testing with processes The default parallelization method is to fork processes using Ruby's DRb system. The processes are forked based on the number of workers provided. The default is 2, but can be changed by the @@ -522,7 +522,7 @@ end These methods are not needed or available when using parallel testing with threads. -## Parallel testing with threads +### Parallel testing with threads If you prefer using threads or are using JRuby, a threaded parallelization option is provided. The threaded parallelizer is backed by Minitest's `Parallel::Executor`. -- cgit v1.2.3 From 30528cda9e30e42915f3a0fa204d822ce013c168 Mon Sep 17 00:00:00 2001 From: bogdanvlviv Date: Sat, 17 Feb 2018 00:41:54 +0200 Subject: Fix docs of ActiveJob custom argument serializers Add `:nodoc:` to `ActiveJob::Serializers` Add `:doc:` to `ActiveJob::Serializers::ObjectSerializer#klass` Express `ActiveJob::Serializers::ObjectSerializer#klass` as private method --- guides/source/active_job_basics.md | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) (limited to 'guides/source') diff --git a/guides/source/active_job_basics.md b/guides/source/active_job_basics.md index 9b738e8cdd..6db7ce370f 100644 --- a/guides/source/active_job_basics.md +++ b/guides/source/active_job_basics.md @@ -346,12 +346,12 @@ ActiveJob supports the following types of arguments by default: - Basic types (`NilClass`, `String`, `Integer`, `Fixnum`, `Bignum`, `Float`, `BigDecimal`, `TrueClass`, `FalseClass`) - `Symbol` - - `ActiveSupport::Duration` - `Date` - `Time` - `DateTime` - `ActiveSupport::TimeWithZone` - - `Hash`. Keys should be of `String` or `Symbol` type + - `ActiveSupport::Duration` + - `Hash` (Keys should be of `String` or `Symbol` type) - `ActiveSupport::HashWithIndifferentAccess` - `Array` @@ -385,39 +385,38 @@ by default has been mixed into Active Record classes. ### Serializers -You can extend list of supported types for arguments. You just need to define your own serializer. +You can extend the list of supported argument types. You just need to define your own serializer: ```ruby class MoneySerializer < ActiveJob::Serializers::ObjectSerializer - # Check if this object should be serialized using this serializer. + # Checks if an argument should be serialized by this serializer. def serialize?(argument) argument.is_a? Money end - # Convert an object to a simpler representative using supported object types. + # Converts an object to a simpler representative using supported object types. # The recommended representative is a Hash with a specific key. Keys can be of basic types only. - # You should call `super` to add the custom serializer type to the hash - def serialize(object) + # You should call `super` to add the custom serializer type to the hash. + def serialize(money) super( - "cents" => object.cents, - "currency" => object.currency + "amount" => money.amount, + "currency" => money.currency ) end - # Convert serialized value into a proper object + # Converts serialized value into a proper object. def deserialize(hash) - Money.new hash["cents"], hash["currency"] + Money.new(hash["amount"], hash["currency"]) end end ``` -And now you just need to add this serializer to a list: +and add this serializer to the list: ```ruby -Rails.application.config.active_job.custom_serializers << MySpecialSerializer +Rails.application.config.active_job.custom_serializers << MoneySerializer ``` - Exceptions ---------- -- cgit v1.2.3 From 1e526788e6b1d3f42f4d8fdca20e588d42838c80 Mon Sep 17 00:00:00 2001 From: Jeremy Daer Date: Fri, 16 Feb 2018 17:14:27 -0800 Subject: Rails 6 requires Ruby 2.3+ --- guides/source/command_line.md | 2 +- guides/source/getting_started.md | 2 +- guides/source/upgrading_ruby_on_rails.md | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) (limited to 'guides/source') diff --git a/guides/source/command_line.md b/guides/source/command_line.md index 648645af7c..b574516392 100644 --- a/guides/source/command_line.md +++ b/guides/source/command_line.md @@ -432,7 +432,7 @@ INFO: You can also use `bin/rails -T` to get the list of tasks. $ bin/rails about About your application's environment Rails version 5.1.0 -Ruby version 2.2.2 (x86_64-linux) +Ruby version 2.5.0 (x86_64-linux) RubyGems version 2.4.6 Rack version 2.0.1 JavaScript Runtime Node.js (V8) diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md index ad587d6117..e90f6d0546 100644 --- a/guides/source/getting_started.md +++ b/guides/source/getting_started.md @@ -90,7 +90,7 @@ $ ruby -v ruby 2.3.1p112 ``` -Rails requires Ruby version 2.2.2 or later. If the version number returned is +Rails requires Ruby version 2.3.0 or later. If the version number returned is less than that number, you'll need to install a fresh copy of Ruby. TIP: A number of tools exist to help you quickly install Ruby and Ruby diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md index 51b284ff12..14e54db1f2 100644 --- a/guides/source/upgrading_ruby_on_rails.md +++ b/guides/source/upgrading_ruby_on_rails.md @@ -35,6 +35,7 @@ You can find a list of all released Rails versions [here](https://rubygems.org/g Rails generally stays close to the latest released Ruby version when it's released: +* Rails 6 requires Ruby 2.3.0 or newer. * Rails 5 requires Ruby 2.2.2 or newer. * Rails 4 prefers Ruby 2.0 and requires 1.9.3 or newer. * Rails 3.2.x is the last branch to support Ruby 1.8.7. -- cgit v1.2.3 From 5645149d3a27054450bd1130ff5715504638a5f5 Mon Sep 17 00:00:00 2001 From: Eddie Lebow Date: Wed, 14 Feb 2018 21:33:02 -0500 Subject: Deprecate update_attributes and update_attributes! Closes #31998 --- guides/source/active_record_callbacks.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/active_record_callbacks.md b/guides/source/active_record_callbacks.md index 630dafe632..4f54b4c206 100644 --- a/guides/source/active_record_callbacks.md +++ b/guides/source/active_record_callbacks.md @@ -264,7 +264,7 @@ The whole callback chain is wrapped in a transaction. If any callback raises an throw :abort ``` -WARNING. Any exception that is not `ActiveRecord::Rollback` or `ActiveRecord::RecordInvalid` will be re-raised by Rails after the callback chain is halted. Raising an exception other than `ActiveRecord::Rollback` or `ActiveRecord::RecordInvalid` may break code that does not expect methods like `save` and `update_attributes` (which normally try to return `true` or `false`) to raise an exception. +WARNING. Any exception that is not `ActiveRecord::Rollback` or `ActiveRecord::RecordInvalid` will be re-raised by Rails after the callback chain is halted. Raising an exception other than `ActiveRecord::Rollback` or `ActiveRecord::RecordInvalid` may break code that does not expect methods like `save` and `update` (which normally try to return `true` or `false`) to raise an exception. Relational Callbacks -------------------- -- cgit v1.2.3 From d4eb0dc89ee6b476e2e10869dc282a96f956c6c7 Mon Sep 17 00:00:00 2001 From: Jeremy Daer Date: Sat, 17 Feb 2018 13:02:18 -0800 Subject: Rails 6 requires Ruby 2.4.1+ Skipping over 2.4.0 to sidestep the `"symbol_from_string".to_sym.dup` bug. References #32028 --- guides/source/active_job_basics.md | 2 +- guides/source/active_support_core_extensions.md | 73 ++++--------------------- guides/source/command_line.md | 8 +-- guides/source/getting_started.md | 4 +- guides/source/upgrading_ruby_on_rails.md | 2 +- 5 files changed, 19 insertions(+), 70 deletions(-) (limited to 'guides/source') diff --git a/guides/source/active_job_basics.md b/guides/source/active_job_basics.md index 9b738e8cdd..4a29327d91 100644 --- a/guides/source/active_job_basics.md +++ b/guides/source/active_job_basics.md @@ -344,7 +344,7 @@ Supported types for arguments ActiveJob supports the following types of arguments by default: - - Basic types (`NilClass`, `String`, `Integer`, `Fixnum`, `Bignum`, `Float`, `BigDecimal`, `TrueClass`, `FalseClass`) + - Basic types (`NilClass`, `String`, `Integer`, `Float`, `BigDecimal`, `TrueClass`, `FalseClass`) - `Symbol` - `ActiveSupport::Duration` - `Date` diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md index 6c980fb0e9..73b24b900a 100644 --- a/guides/source/active_support_core_extensions.md +++ b/guides/source/active_support_core_extensions.md @@ -135,16 +135,14 @@ NOTE: Defined in `active_support/core_ext/object/blank.rb`. ### `duplicable?` -In Ruby 2.4 most objects can be duplicated via `dup` or `clone` except -methods and certain numbers. Though Ruby 2.2 and 2.3 can't duplicate `nil`, -`false`, `true`, and symbols as well as instances `Float`, `Fixnum`, -and `Bignum` instances. +As of Ruby 2.5, most objects can be duplicated via `dup` or `clone`: ```ruby "foo".dup # => "foo" "".dup # => "" -1.method(:+).dup # => TypeError: allocator undefined for Method -Complex(0).dup # => TypeError: can't copy Complex +Rational(1).dup # => (1/1) +Complex(0).dup # => (0+0i) +1.method(:+).dup # => TypeError (allocator undefined for Method) ``` Active Support provides `duplicable?` to query an object about this: @@ -152,35 +150,18 @@ Active Support provides `duplicable?` to query an object about this: ```ruby "foo".duplicable? # => true "".duplicable? # => true -Rational(1).duplicable? # => false -Complex(1).duplicable? # => false +Rational(1).duplicable? # => true +Complex(1).duplicable? # => true 1.method(:+).duplicable? # => false ``` -`duplicable?` matches Ruby's `dup` according to the Ruby version. - -So in 2.4: +`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 -nil.dup # => nil -:my_symbol.dup # => :my_symbol -1.dup # => 1 - -nil.duplicable? # => true -:my_symbol.duplicable? # => true -1.duplicable? # => true -``` - -Whereas in 2.2 and 2.3: - -```ruby -nil.dup # => TypeError: can't dup NilClass -:my_symbol.dup # => TypeError: can't dup Symbol -1.dup # => TypeError: can't dup Fixnum - -nil.duplicable? # => false -:my_symbol.duplicable? # => false -1.duplicable? # => false +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. @@ -2776,20 +2757,6 @@ Active Record does not accept unknown options when building associations, for ex NOTE: Defined in `active_support/core_ext/hash/keys.rb`. -### Working with Values - -#### `transform_values` && `transform_values!` - -The method `transform_values` accepts a block and returns a hash that has applied the block operations to each of the values in the receiver. - -```ruby -{ nil => nil, 1 => 1, :x => :a }.transform_values { |value| value.to_s.upcase } -# => {nil=>"", 1=>"1", :x=>"A"} -``` -There's also the bang variant `transform_values!` that applies the block operations to values in the very receiver. - -NOTE: Defined in `active_support/core_ext/hash/transform_values.rb`. - ### Slicing Ruby has built-in support for taking slices out of strings and arrays. Active Support extends slicing to hashes: @@ -2890,24 +2857,6 @@ end NOTE: Defined in `active_support/core_ext/regexp.rb`. -### `match?` - -Rails implements `Regexp#match?` for Ruby versions prior to 2.4: - -```ruby -/oo/.match?('foo') # => true -/oo/.match?('bar') # => false -/oo/.match?('foo', 1) # => true -``` - -The backport has the same interface and lack of side-effects in the caller like -not setting `$1` and friends, but it does not have the speed benefits. Its -purpose is to be able to write 2.4 compatible code. Rails itself uses this -predicate internally for example. - -Active Support defines `Regexp#match?` only if not present, so code running -under 2.4 or later does run the original one and gets the performance boost. - Extensions to `Range` --------------------- diff --git a/guides/source/command_line.md b/guides/source/command_line.md index b574516392..b41e8bbec6 100644 --- a/guides/source/command_line.md +++ b/guides/source/command_line.md @@ -431,16 +431,16 @@ INFO: You can also use `bin/rails -T` to get the list of tasks. ```bash $ bin/rails about About your application's environment -Rails version 5.1.0 +Rails version 6.0.0 Ruby version 2.5.0 (x86_64-linux) -RubyGems version 2.4.6 -Rack version 2.0.1 +RubyGems version 2.7.3 +Rack version 2.0.4 JavaScript Runtime Node.js (V8) Middleware: Rack::Sendfile, ActionDispatch::Static, ActionDispatch::Executor, ActiveSupport::Cache::Strategy::LocalCache::Middleware, Rack::Runtime, Rack::MethodOverride, ActionDispatch::RequestId, ActionDispatch::RemoteIp, Sprockets::Rails::QuietAssets, Rails::Rack::Logger, ActionDispatch::ShowExceptions, WebConsole::Middleware, ActionDispatch::DebugExceptions, ActionDispatch::Reloader, ActionDispatch::Callbacks, ActiveRecord::Migration::CheckPending, ActionDispatch::Cookies, ActionDispatch::Session::CookieStore, ActionDispatch::Flash, Rack::Head, Rack::ConditionalGet, Rack::ETag Application root /home/foobar/commandsapp Environment development Database adapter sqlite3 -Database schema version 20110805173523 +Database schema version 20180205173523 ``` ### `assets` diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md index e90f6d0546..f545b90103 100644 --- a/guides/source/getting_started.md +++ b/guides/source/getting_started.md @@ -87,10 +87,10 @@ current version of Ruby installed: ```bash $ ruby -v -ruby 2.3.1p112 +ruby 2.5.0 ``` -Rails requires Ruby version 2.3.0 or later. If the version number returned is +Rails requires Ruby version 2.4.1 or later. If the version number returned is less than that number, you'll need to install a fresh copy of Ruby. TIP: A number of tools exist to help you quickly install Ruby and Ruby diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md index 14e54db1f2..ff7ccfd47d 100644 --- a/guides/source/upgrading_ruby_on_rails.md +++ b/guides/source/upgrading_ruby_on_rails.md @@ -35,7 +35,7 @@ You can find a list of all released Rails versions [here](https://rubygems.org/g Rails generally stays close to the latest released Ruby version when it's released: -* Rails 6 requires Ruby 2.3.0 or newer. +* Rails 6 requires Ruby 2.4.1 or newer. * Rails 5 requires Ruby 2.2.2 or newer. * Rails 4 prefers Ruby 2.0 and requires 1.9.3 or newer. * Rails 3.2.x is the last branch to support Ruby 1.8.7. -- cgit v1.2.3 From 8f98054ef96f9335667071c70a7cf7d82ee92b07 Mon Sep 17 00:00:00 2001 From: Brian Kephart Date: Sat, 17 Feb 2018 22:29:25 -0600 Subject: Document :reconnect_attempts option for Redis Cache Store [ci skip] --- guides/source/caching_with_rails.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) (limited to 'guides/source') diff --git a/guides/source/caching_with_rails.md b/guides/source/caching_with_rails.md index cd9f4b4a68..5dde6f34fa 100644 --- a/guides/source/caching_with_rails.md +++ b/guides/source/caching_with_rails.md @@ -465,6 +465,10 @@ is often faster than waiting more than a second to retrieve it. Both read and write timeouts default to 1 second, but may be set lower if your network is consistently low latency. +By default, the cache store will not attempt to reconnect to Redis if the +connection fails during a request. If you experience frequent disconnects you +may wish to enable reconnect attempts. + Cache reads and writes never raise exceptions. They just return `nil` instead, behaving as if there was nothing in the cache. To gauge whether your cache is hitting exceptions, you may provide an `error_handler` to report to an @@ -480,9 +484,10 @@ like this: cache_servers = %w[ "redis://cache-01:6379/0", "redis://cache-02:6379/0", … ], config.cache_store = :redis_cache_store, url: cache_servers, - connect_timeout: 30, # Defaults to 20 seconds - read_timeout: 0.2, # Defaults to 1 second - write_timeout: 0.2, # Defaults to 1 second + connect_timeout: 30, # Defaults to 20 seconds + read_timeout: 0.2, # Defaults to 1 second + write_timeout: 0.2, # Defaults to 1 second + reconnect_attempts: 1, # Defaults to 0 error_handler: -> (method:, returning:, exception:) { # Report errors to Sentry as warnings -- cgit v1.2.3 From 3933e5bc9fc4c975b14941316e9119796fd558e0 Mon Sep 17 00:00:00 2001 From: fatkodima Date: Sun, 18 Feb 2018 16:07:43 +0200 Subject: Fix active_job_basics.md callbacks example [ci skip] --- guides/source/active_job_basics.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/active_job_basics.md b/guides/source/active_job_basics.md index 4a29327d91..f6bbdeccd6 100644 --- a/guides/source/active_job_basics.md +++ b/guides/source/active_job_basics.md @@ -276,7 +276,7 @@ class GuestsCleanupJob < ApplicationJob end private - def around_cleanup(job) + def around_cleanup # Do something before perform yield # Do something after perform -- cgit v1.2.3 From a966f225a94b0387368982ac0da2b49c8a9a77aa Mon Sep 17 00:00:00 2001 From: Andrew White Date: Wed, 21 Feb 2018 12:48:49 +0000 Subject: Add note to Active Storage guide about S3 permissions [ci skip] --- guides/source/active_storage_overview.md | 2 ++ 1 file changed, 2 insertions(+) (limited to 'guides/source') diff --git a/guides/source/active_storage_overview.md b/guides/source/active_storage_overview.md index c72a38b1de..a7cb14c52a 100644 --- a/guides/source/active_storage_overview.md +++ b/guides/source/active_storage_overview.md @@ -121,6 +121,8 @@ Add the [`aws-sdk-s3`](https://github.com/aws/aws-sdk-ruby) gem to your `Gemfile gem "aws-sdk-s3", require: false ``` +NOTE: The core features of Active Storage require the following permissions: `s3:ListBucket`, `s3:PutObject`, `s3:GetObject`, and `s3:DeleteObject`. If you have additional upload options configured such as setting ACLs then additional permissions may be required. + ### Microsoft Azure Storage Service Declare an Azure Storage service in `config/storage.yml`: -- cgit v1.2.3