Currently only Action Mailbox and Active Storage use initialized apps, so at least in those cases we can ensure the correct defaults are used by bug reporters.
Add documentation for `ActionText::RichText#to_s` and
`ActionText::Content#to_s` that demonstrates Action Text's ability to
sanitize and scrub its content.
Co-authored-by: Mike Dalessio <mike.dalessio@gmail.com>
Co-authored-by: Petrik de Heus <petrik@deheus.net>
* Update ActiveRecord::StrictLoadingViolationError API docs to
reference the guide to help beginners learn how to resolve the error.
* Update Active Record Query Interface guide to cover configuration and
the association option.
Apply suggestions from code review
Co-authored-by: Eileen M. Uchitelle <eileencodes@users.noreply.github.com>
Update the text for config.public_file_server.enabled in the configuring guide as PR #47137 turned on static file server by default for all environments.
Co-authored-by: Jonathan Hefner <jonathan@hefner.pro>
For better or worse, the Rails guide settled on double quotes
and a large part of the community also use rubocop which enforce
them by default.
So we might as well try to follow that style when providing code
snippets in the documentation or error messages.
Fix: https://github.com/rails/rails/issues/49822
I certainly didn't get them all, but consistency should be significantly
improved.
Co-Authored-By: Akhil G Krishnan <akhilgkrishnan4u@gmail.com>
Add link providing more details about ERB in the 'Getting Started' documentation [ci skip]
Co-Authored-By: Akhil G Krishnan <akhilgkrishnan4u@gmail.com>
Fix link to point to html [ci skip]
Co-authored-by: Rafael Mendonça França <rafael@franca.dev>
Revert "Merge branch 'branch_new' of https://github.com/mguan2020/rails into pr/49640"
This reverts commit 94b8c7d579a74c528c4a85f3ce0f0853c4883fd1, reversing
changes made to 1353ca902f260dfb9bbe7680ede2650a670f659f.
Revert "Revert "Merge branch 'branch_new' of https://github.com/mguan2020/rails into pr/49640""
This reverts commit e9ced85c8f6afe0bc057bc6d8d4387718a7c3916.
If there's a column named `disabled`, we'll still raise
`ActiveRecord::SubclassNotFound`. Setting `inheritance_column` to `nil`
works though.
I had mistakenly thought `:disabled` was the correct way to disable STI,
since this is what is done in [some tests][].
```ruby
Schema: cogs[ id, type, disabled, created_at, updated_at ]
class Cog < ApplicationRecord
self.inheritance_column = nil
end
Cog.create! type: "Sprocket", disabled: true
=> #<Cog type: "Sprocket", disabled: "t">
```
[some tests]: a4751751bc/activerecord/test/models/post.rb (L231)
The docs already talk about how to set up deferrable constraints, but
then rely on the user crafting custom SQL to actually use the feature.
The helper makes it easier to handle juggling multiple specific
constraints and quoting issues.
Since 74264f4 improved the secure_password length validation to match bcrypt limit, this validation can be described more accurately in the ActiveModel basics guide.
* Update broken links in testing.md
The HTTP headers and CGI variables section had broken links. Updated these to direct to the correct locations on datatracker.ietf.org.
* Update to Point to correct section 4.1
ActiveStorage::Attachment records are not directly maintained by
ActiveStorage and it may not be feasible or desired to update the record
when its attachment is saved.
We never explained how migrations paths work for shards. This fixes that
and also adds the appropriate class setup. You no longer need to set a
`default` shard as of #48353. In addition, `ApplicationRecord` should be
used for the non-sharded db that also serves as the tenant/shard router.
Then shards should get their own connection class since the schema
differs.
Otherwise they are considered separate lists instead of a sequence
within the same list. This also renders the code block with extra
indent, as part of the item they belong to.
Also use `Active Record Encryption` with capital letters consistently.
[ci skip]
Detail:
This Pull Request modifies the documentation of Action Text so that all instances of 'contenteditable' and 'execCommand' are now in a code block. This makes the documentation more readable for users.
Follow-up to #47782.
These examples merely illustrate the order of execution when using `up`
and `down`, so we only need one operation before and after.
Follow-up to #48221.
The Active Support Instrumentation guide is about the
`ActiveSupport::Notifications` API. Therefore, move the information
about `config.server_timing` and the `ActionDispatch::ServerTiming`
middleware to the existing sections in the Configuration guide.
These examples show RDoc in the form of Ruby comments, and should
therefore use the `ruby` code fence (which matches the other examples in
this guide).
- This should make it easier for apps or libraries that were
previously relying on the private API.
Also took the opportunity to tweak the doc of the BroadcastLogger
to mention what happens when calling a non-standard method.
Fix#49494
Link to `Rails::Generators::Testing::Behavior` instead of
`Rails::Generators::Testing::Behaviour` in an effort to ensure the Edge
Guides link to the correct API documentation.
* Conditionally print `$stdout` when invoking `run_generator`
In an effort to improve the developer experience when debugging
generator tests, we add the ability to conditionally print `$stdout`
instead of capturing it.
This allows for calls to `binding.irb` and `puts` work as expected.
```sh
PRINT_STDOUT=true ./bin/test test/generators/actions_test.rb
```
* Update railties/CHANGELOG.md
Co-authored-by: Rafael Mendonça França <rafael@franca.dev>
* Rename environment variable
* Update generators guides.
* Update guides
---------
Co-authored-by: Rafael Mendonça França <rafael@franca.dev>
* Add encryption.add_to_filter_parameters to configuring.md
encryption.add_to_filter_paramters has been merged by https://github.com/rails/rails/pull/46453.
(This PR is a second try of https://github.com/rails/rails/pull/49364 )
* Update entry for encryption.add_to_filter_parameters
Co-authored-by: Rafael Mendonça França <rafael@rubyonrails.org>
It's possible since Rails 6 (3ea2857943) to let the framework create Event objects, but the guides and docs weren't updated to lead with this example.
Manually instantiating an Event doesn't record CPU time and allocations, I've seen it more than once that people copy-pasting the example code get confused about these stats returning 0. The tests here show that - just like the apps I've worked on - the old pattern keeps getting copy-pasted.
- An oversight of #48615 is that it changes the `Rails.logger` to be
a broadcast logger after the app is booted. Anything referencing
`Rails.logger` during the boot process will get a simple logger and
ultimately resulting in logs not being broadcasted.
For example `ActionController::Base.logger.info("abc")` would
just output logs in the `development.log` file, not on STDOUT.
----
The only solution I could think of is to create a BroadcastLogger
earlier at boot, and add logger to that broadcast when needed (instead
of modiyfing the `Rails.logger` variable).
Register a callable to decode rendered content for a given MIME type
Each registered decoder will also define a `#rendered.$MIME` helper
method, where `$MIME` corresponds to the value of the `mime` argument.
=== Arguments
`mime` - Symbol the MIME Type name for the rendered content
`callable` - Callable to decode the String. Accepts the String
value as its only argument
`block` - Block serves as the decoder when the
`callable` is omitted
By default, ActionView::TestCase defines a decoder for:
* :html - returns an instance of Nokogiri::XML::Node
* :json - returns an instance of ActiveSupport::HashWithIndifferentAccess
Each pre-registered decoder also defines a corresponding helper:
* :html - defines `rendered.html`
* :json - defines `rendered.json`
=== Examples
To parse the rendered content into RSS, register a call to `RSS::Parser.parse`:
```ruby
register_decoder :rss, -> rendered { RSS::Parser.parse(rendered) }
test "renders RSS" do
article = Article.create!(title: "Hello, world")
render formats: :rss, partial: article
assert_equal "Hello, world", rendered.rss.items.last.title
end
```
To parse the rendered content into a Capybara::Simple::Node,
re-register an `:html` decoder with a call to
`Capybara.string`:
```ruby
register_decoder :html, -> rendered { Capybara.string(rendered) }
test "renders HTML" do
article = Article.create!(title: "Hello, world")
render partial: article
rendered.html.assert_css "h1", text: "Hello, world"
end
```
This change would force a lot of existing applications and libraries
to update their tests.
We included it in the beta to collect feedback from the community and
we had some comments about how negative this change would be.
Developers that care about the typography of their error messages
can easily change it in their applications using the translation
files, so there is no need to inflict pain in the upgrade process
by changing the default in the framework.
Revert "Merge PR #45463"
This reverts commit 9f60cd8dc7, reversing
changes made to 35d574dbfd.
As we (I and @yahonda) talked about the naming in person, naming unique
constraints as unique keys is very confusing to me.
All documents and descriptions says it's unique constraints, but naming
unique keys leads to misunderstanding it's a short-hand of unique
indexes.
Just naming it unique constraints is not misleading.
Expand examples by adding singular associations.
Expand the guides with `strict_loading!`.
Also add `to_a` to code examples as loading the associations is required
to raise the errors.
* Update 7_1_release_notes.md
For context see https://github.com/rails/rails/pull/45867
Include in release notes the deprecation of `true` and `false` values
for `config.action_dispatch.show_exceptions` in favor of `:all`,
`:rescuable` and `:none`.
* Update 7_1_release_notes.md
Co-authored-by: Hartley McGuire <skipkayhil@gmail.com>
---------
Co-authored-by: Hartley McGuire <skipkayhil@gmail.com>
Co-authored-by: Rafael Mendonça França <rafael@rubyonrails.org>
Change mentions of `app/views/shared` in the guides to be
`app/views/application` instead. View partials rely on the same
[Template Inheritance][] as their template counterparts, so the guides
should encourage end-users to benefit from that inheritance.
> This makes `app/views/application/` a great place for your shared
> partials, which can then be rendered in your ERB as such:
>
```html+erb
<%# app/views/admin/products/index.html.erb %>
<%= render @products || "empty_list" %>
<%# app/views/application/_empty_list.html.erb %>
There are no items in this list <em>yet</em>.
```
To enforce that template resolution, this commit also replaces
references to `shared/` with `application/` in the Rails test suite.
[Template Inheritance]: https://guides.rubyonrails.org/layouts_and_rendering.html#template-inheritance
Motivation / Background
---
While the `ActionView::TestCase` class isn't marked with a `:nodoc:`
comment to indicate that it's internal to Rails, there isn't much
content in the guides that explains how to test view partials.
Libraries like
[view_component](https://github.com/ViewComponent/view_component/) have
[built-in support for
testing](https://viewcomponent.org/guide/testing.html), including
Capybara integration.
While `ActionView::TestCase` already integrates with
`rails-dom-testing`, that integration could be better documented.
Additionally, it wouldn't take much for consuming applications to mimic
the ViewComponent testing experience for their Action View Partials.
Details
---
First, link to the "Testing Rails Applications" page from the
`ActionView::TestCase` class documentation.
Next, add a "Testing View Partials" section to the guides that expands
upon the variety of tooling available to tests that inherit from
`ActionView::TestCase`. In that section, cover topics like:
* the `render` helper method
* the `rendered` helper attribute reader
* calls to `assert_select` with attribute placeholders
* the `document_root_element` helper method
* integration with Ruby's Pattern Matching
* opportunities to integrate with Capybara
Additional Information
---
Additionally, add test coverage that exercise the examples shared in the
new section, including:
* Calls to `assert_select` that utilize attribute placeholders
* Ruby 3.0's Pattern Matching
* Integration with Capybara
* Add Bun support to `rails new -j` generator
* Add additional generation consideration for Bun
* Use development gems to test the whole workflow
* Remove custom gems from local testing
* Revert lock
* Revert errant custom gem declaration
* Fix linting errors
* Fix remnants of bad merge
* Always use latest bun
* Update actioncable/lib/rails/generators/channel/channel_generator.rb
Co-authored-by: Cadu Ribeiro <mail@cadu.dev>
* Update guides/source/working_with_javascript_in_rails.md
Co-authored-by: Rafael Mendonça França <rafael@franca.dev>
* Only use the latest bun if nothing is specified
* Hardcode known good version
---------
Co-authored-by: Cadu Ribeiro <mail@cadu.dev>
Co-authored-by: Rafael Mendonça França <rafael@franca.dev>
In #49105, `where` examples were added to the `normalizes` documentation
to demonstrate that normalizations are also applied for `where`.
However, as with the `exists?` examples, we should also demonstrate that
normalizations are only applied to keyword arguments, not positional
arguments. We can also address the original source of the confusion by
changing the wording of "finder methods" to "query methods".
This commit also removes the tests added in #49105. `normalizes` works
at the level of attribute types, so there is no need to test every query
method. Testing `find_by` is sufficient. (And, in point of fact,
`find_by` is implemented in terms of `where`.)
- Action Controller Overview: Add example of how a cpk record can be
found using a show action.
- Action View Form Helpers: Add example of what a form updating a cpk
record looks like.
- Action View Helpers: Add examples for url_for and link_to cpk record
urls.
Follow-up to [#47420][]
With the changes made in [#47420][], `has_secure_token` declarations can
be configured to execute in an `after_initialize` callback. This commit
proposed a new Rails 7.1 default: generate all `has_secure_token` values
when their corresponding models are initialized.
To preserve pre-7.1 behavior, applications can set
`config.active_record.generate_secure_token_on = :create`.
By default, generate the value when the model is initialized:
```ruby
class User < ApplicationRecord
has_secure_token
end
record = User.new
record.token # => "fwZcXX6SkJBJRogzMdciS7wf"
```
With `config.active_record.generate_secure_token_on = :create`, generate
the value when the model is created:
```ruby
# config/application.rb
config.active_record.generate_secure_token_on = :create
# app/models/user.rb
class User < ApplicationRecord
has_secure_token on: :create
end
record = User.new
record.token # => nil
record.save!
record.token # => "fwZcXX6SkJBJRogzMdciS7wf"
```
[#47420]: https://github.com/rails/rails/pull/47420
Co-authored-by: Hartley McGuire <skipkayhil@gmail.com>
* Replace list literals w/ Visible::VALID_STATUSES
In Getting Started guide, in the article and comment status dropdowns, use Visible::VALID_STATUSES instead of repeating the list of valid statuses. This makes the code DRYer and more expressive. This PR also adds a comment to that effect.
* Remove text changes, leave just code
Co-authored-by: Rafael Mendonça França <rafael@rubyonrails.org>
* select existing article status if any
In the Getting Started guide, in the dropdown for an article or comment's status, pre-selecting `public` will make _all_ articles seem `public` even if their status is really something else -- even `nil`. This was reported in issue #45028. Selecting `article.status || 'public'` instead will fix this, in _most_ cases. Pre-existing articles with `nil` status will show up as `public`, but if the form is submitted, they will indeed become `public`.
This commit makes that change, and adds text to explain why it is done.
* Simplify wording of changes to Getting Started
Co-authored-by: Rafael Mendonça França <rafael@rubyonrails.org>
Make the example complete so people can follow along insted of having
to understand the implicit context that you need an existing helper
called `text_field_with_label` to make the example work.
Fixes#49027.
To avoid accidental writing to the production database, I always start
rails console in sandbox mode. I only start rails console in non-sandbox
mode when I'm sure I want to write to the production database.
`sandbox_by_default` option is added to start rails console in sandbox
mode by default. With this option turned on, `--no-sandbox` must be
specified to start rails in non-sandbox mode.
Note that this option is ignored when rails environment is development
or test.
The current example test for jobs using `perform_now` to run the job inline. This is problematic for jobs that have retries configured, as any exception that is retried will be silently rescued. Ideally, the test will still fail because the job did not perform the work it was supposed to, but it makes finding the root cause a lot harder.
Testing with `perform_enqueued_jobs` and `perform_later` gets around this problem, as the retries are also performed immediately and, assuming that the exception happens consistently, it will bubble up after exhausting its retries.
Therefore, this PR updates the basic test guidance to suggest `perform_enqueued_jobs` and `perform_later` over `perform_now`.
Both described behaviours make it harder to test that a job raises a specific exception, so this requires special handling, which I added a paragraph on. I can pull that out to a separate PR if desired.
Follow-up to [#48857][]
Mention the recently introduced `file_fixture_upload` alias in the
Active Storage Overview guides to reinforce the symmetry with the
`file_fixture` test helper method.
[#48857]: https://github.com/rails/rails/pull/48857
Co-authored-by: Jonathan Hefner <jonathan@hefner.pro>
The naming difference between the test harness' [file_fixture][] helper
made available through Active Support (along with the
`file_fixture_path` configuration value) and the integration test
harness' [fixture_file_upload][] is a constant source of confusion and
surprise.
Since Active Support is more ubiquitous, this commit renames the
`fixture_file_upload` method to `file_fixture_upload` to match the order
of words in `file_fixture` and `file_fixture_path`.
To preserve backwards compatibility, declare a `fixture_file_upload`
alias to be preserved into the future (or removed at a future point in
time).
[file_fixture]: https://edgeapi.rubyonrails.org/classes/ActiveSupport/Testing/FileFixtures.html#method-i-file_fixture
[fixture_file_upload]: https://edgeapi.rubyonrails.org/classes/ActionDispatch/TestProcess/FixtureFile.html#method-i-fixture_file_upload
The SQL generated by this query (at 13.1.3.2):
```ruby
Author.joins(books: [{ reviews: { customer: :orders } }, :supplier] )
```
Is said to generate SQL whose select list is comprised of `*`, not
`authors.*`
which controls the HTML parser used by rails-dom-testing assertions.
The config parameter is set to :html5 in Rails 7.1 if the Nokogiri
HTML5 parser is supported.
As of Selenium 4.6, [the Selenium Manager is capable of managing Chrome
Driver installations and integrations][readme]. As of Selenium 4.11, the
Selenium Manager is capable of [capable of resolving the Chrome for
Testing installation][] path.
By omitting the `gem` declaration from the `Gemfile.tt`, newly generated
applications and applications updating their `Gemfile` in lockstep with
newer Rails versions can shed the dependency and avoid test failures
introduced by newly released Chrome versions (like, for example,
[titusfortner/webdrivers#247][]).
[readme]: 43f8ac436c (update-selenium-manager)
[titusfortner/webdrivers#247]: https://github.com/titusfortner/webdrivers/issues/247
[capable of resolving the Chrome for Testing installation]: https://github.com/rails/rails/pull/48847#issuecomment-1656756862
Co-authored-by: Titus Fortner <titusfortner@users.noreply.github.com>
This adds a cache optimization such that expired and version-mismatched
cache entries can be detected without deserializing their values. This
optimization is enabled when using cache format version >= 7.1 or a
custom serializer.
Co-authored-by: Jean Boussier <jean.boussier@gmail.com>
This commit adds support for replacing the compressor used for
serialized cache entries. Custom compressors must respond to `deflate`
and `inflate`. For example:
```ruby
module MyCompressor
def self.deflate(string)
# compression logic...
end
def self.inflate(compressed)
# decompression logic...
end
end
config.cache_store = :redis_cache_store, { compressor: MyCompressor }
```
As part of this work, cache stores now also support a `:serializer`
option. Similar to the `:coder` option, serializers must respond to
`dump` and `load`. However, serializers are only responsible for
serializing a cached value, whereas coders are responsible for
serializing the entire `ActiveSupport::Cache::Entry` instance.
Additionally, the output from serializers can be automatically
compressed, whereas coders are responsible for their own compression.
Specifying a serializer instead of a coder also enables performance
optimizations, including the bare string optimization introduced by cache
format version 7.1.
Currently the service specified here is `:s3` and it could be confused for the `Service::S3Service`. The modified code example shows more clarity to the reader that the service in this case here refers to the bucket name outlined in `storage.yml` rather than the adapter service.
* How to keep existing attachments on a has_many_attached when uploading new ones
* How to retain uploaded files when a form submission fails validation
[ci skip]
Fix: https://github.com/rails/rails/issues/45017
Ref: https://github.com/rails/rails/pull/29333
Ref: https://github.com/ruby/timeout/pull/30
Historically only raised errors would trigger a rollback, but in Ruby `2.3`, the `timeout` library
started using `throw` to interupt execution which had the adverse effect of committing open transactions.
To solve this, in Active Record 6.1 the behavior was changed to instead rollback the transaction as it was safer
than to potentially commit an incomplete transaction.
Using `return`, `break` or `throw` inside a `transaction` block was essentially deprecated from Rails 6.1 onwards.
However with the release of `timeout 0.4.0`, `Timeout.timeout` now raises an error again, and Active Record is able
to return to its original, less surprising, behavior.
ActiveRecord::Base has a dedicated ActiveSupport load hook. This adds an
additional hook for ActiveModel::Model, so that when ActiveModel is
being used without ActiveRecord, it can still be modified.
Fixes#48398
Prepared Statements and Query Logs are incompatible features due to query logs making every query unique.
Co-authored-by: Jean Boussier <jean.boussier@gmail.com>
This middleware has been logging at a FATAL level since the first
[commit][1] in Rails (the code originally lived in
actionpack/lib/action_controller/rescue.rb). However, FATAL is
documented in the Ruby Logger [docs][2] as being for "An unhandleable
error that results in a program crash.", which does not really apply to
this case since DebugExceptions is handling the error. A more
appropriate level would be ERROR, which the Ruby Logger docs describe as
"A handleable error condition."
This commit introduces a new configuration for the DebugExceptions log
level so that new apps will have it set to ERROR by default and ERROR
can eventually be made the default.
[1]: db045dbbf6
[2]: https://ruby-doc.org/3.2.1/stdlibs/logger/Logger/Severity.html
* Make sure active record encryption configuration happens after initializers have run
Co-authored-by: Cadu Ribeiro <mail@cadu.dev>
* Add a new option to support previous data encrypted non-deterministically with a hash digest of SHA1
There is currently a problem with Active Record encryption for users updating from 7.0 to 7.1 Before
#44873, data encrypted with non-deterministic encryption was always using SHA-1. The reason is that
`ActiveSupport::KeyGenerator.hash_digest_class` is set in an after_initialize block in the railtie config,
but encryption config was running before that, so it was effectively using the previous default SHA1. That
means that existing users are using SHA256 for non deterministic encryption, and SHA1 for deterministic
encryption.
This adds a new option `use_sha1_digest_for_non_deterministic_data` that
users can enable to support for SHA1 and SHA256 when decrypting existing data.
* Set a default value of true for `support_sha1_for_non_deterministic_encryption` and proper initializer values.
We want to enable the flag existing versions (< 7.1), and we want it to be false moving by
default moving forward.
* Make sure the system to auto-filter params supports different initialization orders
This reworks the system to auto-filter params so that it works when encrypted
attributes are declared before the encryption configuration logic runs.
Co-authored-by: Cadu Ribeiro <mail@cadu.dev>
---------
Co-authored-by: Cadu Ribeiro <mail@cadu.dev>
The testing guide for Active Job currently implies that when you queue a job it will be performed.
This isn't true; by default jobs are enqueued, not performed.
This PR fleshes out the docs a bit to show both examples, and adds a test to confirm the default behaviour.
Note that the most frequent change to the output are:
- attribute values, most often data-clipboard-text. libgumbo
entity-escapes fewer characters in attribute values than libxml2, and
wraps them in double-quotes. In particulary `>` and `<` are not
escaped per the HTML5 spec.
- linebreaks are different for some HTML elements, particularly lists.
In #48104, `:message_pack` was added as a supported value for the cache
format version because the format version essentially specifies the
default coder. However, as an API, the format version could potentially
be used to affect other aspects of serialization, such as the default
compression format.
This commit removes `:message_pack` as a supported value for the format
version, and, as a replacement, adds support for specifying
`coder: :message_pack`:
```ruby
# BEFORE
config.active_support.cache_format_version = :message_pack
# AFTER
config.cache_store = :redis_cache_store, { coder: :message_pack }
```
This Pull Request corrects one line in a code block.
In section _File Downloads_, the block that presents a solution against malicious file downloads expects that the path to a folder named 'file' (variable `basename`) matches the path to a folder which is 3 levels above, or else, it will raise an exception:
```ruby
raise if basename != File.expand_path(File.join(File.dirname(filename), '../../../'))
```
and that is impossible. It should instead be:
```ruby
raise if basename != File.expand_path(File.dirname(filename))
```
This bug goes as far back as v2.3 of the guide. I did not look further.
If an application is using sharding, they may not want to use `default`
as the `default_shard`. Unfortunately Rails expects there to be a shard
named `default` for certain actions internally. This leads to some
errors on boot and the application is left manually setting
`default_shard=` in their model or updating their shards in
`connects_to` to name `shard_one` to `default`. Neither are a great
solution, especially if Rails can do this for you. Changes to Active
Record are:
* Simplify `connects_to` by merging `database` into `shards` kwarg so we
can do a single loop through provided options.
* Set the `self.default_shard` to the first keys in the shards kwarg.
* Add a test for this behavior
* Update existing test that wasn't testing this to use `default`. I
could have left this test but it really messes with connections in the
other tests and since this isn't testing shard behavior specifically, I
updated it to use `default` as the default shard name.
This is a slight change in behavior from existing applications but
arguably this is fixing a bug because without this an application won't
boot. I originally thought that this would require a huge refactoring to
fix but realized that it makes a lot of sense to take the first shard as
they default. They should all have the same schema so we can assume it's
fine to take the first one.
Fixes: #45390
* new config value: action_view.sanitizer_vendor
* SanitizerHelper defaults to Rails::HTML4::Sanitizer
* 7.1 config defaults to Rails::HTML5::Sanitizer if it's supported
App templates may contain `after_bundle` blocks which should be run
after the template is executed, after running `bundle install`. For
example:
```ruby
gem "devise"
after_bundle do
generate "devise:install"
end
```
Prior to this commit, `bundle install` and `after_bundle` blocks were
run only when applying a template via `rails new`. This commit makes
`bin/rails app:template` run them as well.
Co-authored-by: "Gerard (Gerry) Caulfield" <git@caulfield.me>
This modifies the example application template to only use a single gem,
to run generator calls in an `after_bundle` block, and to include a
`db:migrate` call after running the generators.
This also simplifies the section's prose, and mentions
`bin/rails app:template` for running templates in existing apps.
This rewrites "Generators Fallbacks" section to remove the reference to
the Shoulda gem and provide a more explicit example. This also converts
the section into a subsection of "Overriding Rails Generators", since it
is a technique to override specific generators.
This replaces the "Customizing Your Workflow" section with an
"Overriding Rails Generators" section that is focused on simply
overriding a built-in generator. Detailed information about
`config.generators` has been delegated to the Configuration guide.
Outdated information about scaffold stylesheet generation has been
removed. Outdated information about helper test generation has been
updated. Detailed information about hooking generators together has
been delegated to the `hook_for` API documentation.
Reverts #47712.
Closes#44490.
This changes the section to focus on overriding a scaffold view
template, since that use case is more common than overriding the helper
template.
This also moves the section further up in the guide because overriding
generator templates is easier (and more likely) than overriding
generators themselves.
Adding a command line option is a natural follow-up to creating a
generator, and the example of specifying a command line option builds on
the example from the "Creating Generators with Generators" section.
Therefore, this commit puts the "Adding Command Line Options" section
right after the "Creating Generators with Generators" section.
This commit also tweaks the section to improve clarity.
Background
----------
During integration tests, it is desirable for the application to respond
as closely as possible to the way it would in production. This improves
confidence that the application behavior acts as it should.
In Rails tests, one major mismatch between the test and production
environments is that exceptions raised during an HTTP request (e.g.
`ActiveRecord::RecordNotFound`) are re-raised within the test rather
than rescued and then converted to a 404 response.
Setting `config.action_dispatch.show_exceptions` to `true` will make the
test environment act like production, however, when an unexpected
internal server error occurs, the test will be left with a opaque 500
response rather than presenting a useful stack trace. This makes
debugging more difficult.
This leaves the developer with choosing between higher quality
integration tests or an improved debugging experience on a failure.
I propose that we can achieve both.
Solution
--------
Change the configuration option `config.action_dispatch.show_exceptions`
from a boolean to one of 3 values: `:all`, `:rescuable`, `:none`. The
values `:all` and `:none` behaves the same as the previous `true` and
`false` respectively. What was previously `true` (now `:all`) continues
to be the default for non-test environments.
The new `:rescuable` value is the new default for the test environment.
It will show exceptions in the response only for rescuable exceptions as
defined by `ActionDispatch::ExceptionWrapper.rescue_responses`. In the
event of an unexpected internal server error, the exception that caused
the error will still be raised within the test so as to provide a useful
stack trace and a good debugging experience.
The description was mentioning broadcasting to a comment channel and
then the example broadcast to a post channel. In itself, not too
confusing, but because the example is broadcasting comments on the
post channel, it looks as if the order of parameters is reversed on
the `broadcast_to` call.
This organizes some related events into pseudo-subsections, such as
"Action Controller — Caching", for easier browsing. The
pseudo-subsections are at the same content level as their parent section
so that headings and event names are rendered consistently.
This PR does the following:
* Adds `trilogy` to lists of adapters where applicable
* Uses `MySQL` instead of adatper names where applicable
* Splits type information into adapters code so that the adapter is set
correctly.
* Fix tests that were using mysql2 when they should be abstract
* Add load hook for trilogy to match mysql2
This commit adds support for `:message_pack` and `:message_pack_allow_marshal`
as serializers for `config.action_dispatch.cookies_serializer`, just
like `config.active_support.message_serializer`.
The `:message_pack` serializer can fall back to deserializing with
`AS::JSON`, and the `:message_pack_allow_marshal` serializer can fall
back to deserializing with `AS::JSON` or `Marshal`. Additionally, the
`:marshal`, `:json`, and `:hybrid` / `:json_allow_marshal` serializers
can now fall back to deserializing with `AS::MessagePack`. These
behaviors make it easier to migrate between cookies serializers.
This commit adds support for `:message_pack` as a serializer for
`MessageEncryptor` and `MessageVerifier`, and, consequently, as an
option for `config.active_support.message_serializer`.
The `:message_pack` serializer is implemented via
`ActiveSupport::Messages::SerializerWithFallback` and can fall back to
deserializing with `AS::JSON`. Additionally, the `:marshal`, `:json`,
and `:json_allow_marshal` serializers can now fall back to deserializing
with `AS::MessagePack`.
This commit also adds support for `:message_pack_allow_marshal` as a
serializer, which can fall back to deserializing with `Marshal` as well
as `AS::JSON`.
Prior to this commit, `config.load_defaults 7.1` would cause old
messages (or messages from older apps) to become unreadable, and
developers were encouraged to manually set
`config.active_support.message_serializer = :json_allow_marshal` in
order to prevent this.
This commit changes the default message serializer set by
`config.load_defaults 7.1` from `:json` to `:json_allow_marshal` so that
upgraded apps can continue to read old messages without additional
configuration.
The intention is to eventually change the default to `:json` (with no
`Marshal` fallback) in Rails 7.2, after some time has passed with apps
generating JSON-serialized messages.
Apps can opt in to JSON-only serialization before Rails 7.2 by manually
setting `config.active_support.message_serializer = :json`.
Fixes#48118.
In #42843 and #42846, several config settings were added to control the
default serializer for `MessageEncryptor` and `MessageVerifier`, and to
provide a migration path from a default `Marshal` serializer to a
default `JSON` serializer:
* `config.active_support.default_message_encryptor_serializer`
* Supports `:marshal`, `:hybrid`, or `:json`.
* `config.active_support.default_message_verifier_serializer`
* Supports `:marshal`, `:hybrid`, or `:json`.
* `config.active_support.fallback_to_marshal_deserialization`
* Affects `:hybrid` for both `MessageEncryptor` and `MessageVerifier`.
* `config.active_support.use_marshal_serialization`
* Affects `:hybrid` for both `MessageEncryptor` and `MessageVerifier`.
This commit unifies those config settings into a single setting,
`config.active_support.message_serializer`, which supports `:marshal`,
`:json_allow_marshal`, and `:json` values. So, for example,
```ruby
config.active_support.default_message_encryptor_serializer = :hybrid
config.active_support.default_message_verifier_serializer = :hybrid
config.active_support.fallback_to_marshal_deserialization = true
config.active_support.use_marshal_serialization = false
```
becomes
```ruby
config.active_support.message_serializer = :json_allow_marshal
```
and
```ruby
config.active_support.default_message_encryptor_serializer = :hybrid
config.active_support.default_message_verifier_serializer = :hybrid
config.active_support.fallback_to_marshal_deserialization = false
config.active_support.use_marshal_serialization = false
```
becomes
```ruby
config.active_support.message_serializer = :json
```
This commit also replaces `ActiveSupport::JsonWithMarshalFallback` with
`ActiveSupport::Messages::SerializerWithFallback`, which implements a
generic mechanism for serializer fallback. The `:marshal` serializer
uses this mechanism too, so
```ruby
config.active_support.default_message_encryptor_serializer = :hybrid
config.active_support.default_message_verifier_serializer = :hybrid
config.active_support.fallback_to_marshal_deserialization = false
config.active_support.use_marshal_serialization = true
```
becomes
```ruby
config.active_support.message_serializer = :marshal
```
Additionally, the logging behavior of `JsonWithMarshalFallback` has been
replaced with notifications which include the names of the intended and
actual serializers, as well as the serialized and deserialized message
data. This provides a more targeted means of tracking serializer
fallback events. It also allows the user to "silence" such events, if
desired, without an additional config setting.
All of these changes make it easier to add migration paths for new
serializers such as `ActiveSupport::MessagePack`.
This updates two instances of custom initializer examples in the docs to
use the standard "library.name" format. Previously, one used just "name"
which can lead to hard to debug "cyclic dependency" errors, and the
other used "name.library" which is not the suggested format.
I don't know how prevalent this really is, but I heard several time
about users having memory exhaustion issues caused by the query cache
when dealing with long running jobs.
Overall it seems sensible for this cache not to be entirely unbounded.
This adds documentation for the `cache_read_multi.active_support`,
`cache_write_multi.active_support`, and `cache_delete_multi.active_support`
events to the Instrumentation guide.
This commit introduces a performance optimization for cache entries with
bare string values such as view fragments.
A new `7.1` cache format has been added which includes the optimization,
and the `:message_pack` cache format now includes the optimization as
well. (A new cache format is necessary because, during a rolling
deploy, unupgraded servers must be able to read cache entries from
upgraded servers, which means the optimization cannot be enabled for
existing apps by default.)
New apps will use the `7.1` cache format by default, and existing apps
can enable the format by setting `config.load_defaults 7.1`. Cache
entries written using the `6.1` or `7.0` cache formats can be read when
using the `7.1` format.
**Benchmark**
```ruby
# frozen_string_literal: true
require "benchmark/ips"
serializer_7_0 = ActiveSupport::Cache::SerializerWithFallback[:marshal_7_0]
serializer_7_1 = ActiveSupport::Cache::SerializerWithFallback[:marshal_7_1]
entry = ActiveSupport::Cache::Entry.new(Random.bytes(10_000), version: "123")
Benchmark.ips do |x|
x.report("dump 7.0") do
$dumped_7_0 = serializer_7_0.dump(entry)
end
x.report("dump 7.1") do
$dumped_7_1 = serializer_7_1.dump(entry)
end
x.compare!
end
Benchmark.ips do |x|
x.report("load 7.0") do
serializer_7_0.load($dumped_7_0)
end
x.report("load 7.1") do
serializer_7_1.load($dumped_7_1)
end
x.compare!
end
```
```
Warming up --------------------------------------
dump 7.0 5.482k i/100ms
dump 7.1 10.987k i/100ms
Calculating -------------------------------------
dump 7.0 73.966k (± 6.9%) i/s - 367.294k in 5.005176s
dump 7.1 127.193k (±17.8%) i/s - 615.272k in 5.081387s
Comparison:
dump 7.1: 127192.9 i/s
dump 7.0: 73966.5 i/s - 1.72x (± 0.00) slower
Warming up --------------------------------------
load 7.0 7.425k i/100ms
load 7.1 26.237k i/100ms
Calculating -------------------------------------
load 7.0 85.574k (± 1.7%) i/s - 430.650k in 5.034065s
load 7.1 264.877k (± 1.6%) i/s - 1.338M in 5.052976s
Comparison:
load 7.1: 264876.7 i/s
load 7.0: 85573.7 i/s - 3.10x (± 0.00) slower
```
Co-authored-by: Jean Boussier <jean.boussier@gmail.com>
This commit adds support for `:message_pack` as an option for
`config.active_support.cache_format_version`.
Cache entries written using the `6.1` or `7.0` formats can be read when
using the `:message_pack` format. Additionally, cache entries written
using the `:message_pack` format can now be read when using the `6.1` or
`7.0` format. These behaviors makes it easy to migrate between formats
without invalidating the entire cache.