7.1
- `config.active_job.use_big_decimal_serializer` was fixed to be `true`
in b4fffc3 but the documentation was not updated
- `config.active_record.run_commit_callbacks_on_first_saved_instances_in_transaction`
was added in 936a862
- `config.active_record.sqlite3_adapter_strict_strings_by_default` was
added in 21a6dbd but the documented default is incorrect
- `config.log_file_size` was initially set to `100.megabytes` but was
changed during review to be `100 * 1024 * 1024` for apps using
`config.active_support.bare` (cdce275)
7.0
- `config.active_support.isolation_level` was added in 540d2f4
6.1
- minor formatting fix
The changes were generated by a script:
5beae39bd8/bin/check-framework-defaults
The parentheses around `100 * 1024 * 1024` were removed from
railties/lib/rails/application/configuration.rb because the script
uses the values exactly.
This was added in 60f7d49, which didn't quite make the cutoff for the
7.0 release, so it doesn't belong under `7.0`.
In addition, the value being set is the same as the underlying
configuration's default. This is likely an oversight because the
`load_default` value was changed during review from `true` to be
`Rails.env` dependent, and later to `false`.
The PR #44931 fell off my radar a few months ago so I decided to add a
test myself to ensure this behavior change is tested. While doing that I
decided to refactor the changes from that PR to make the code a little
cleaner and easier to read.
Routes take a long time to draw. Over time, a Rails app can become slow
to boot simply because of how many routes it has. This script can be
used to detect routes that are drawn, but aren't actually valid.
Removing routes this script detects can help speed up your app and
remove dead code.
Example:
```
> bin/rails routes --unused
Found 2 unused routes:
Prefix Verb URI Pattern Controller#Action
one GET /one(.:format) action#one
two GET /two(.:format) action#two
```
The `Editor` command helper module was originally extracted from
`CredentialsCommand`, and still includes a help message mentioning
"credentials" and a `rescue` that is specific to encrypted files.
This commit removes those remnants, fully generalizing the `Editor`
module. Additionally, this commit changes `SecretsCommand` to make use
of the `Editor` module.
This commit enhances the `Rails::Command::Base.executable` method to
integrate a new `bin` class attribute and optional `subcommand` arg.
So, for example, `CredentialsCommand.executable(:edit)` will now return
"bin/rails credentials:edit".
Additionally, this commit replaces occurrences of "bin/rails COMMAND",
"rails COMMAND", and "COMMAND" in help messages with calls to
`executable`, for improved consistency.
In #44910, the `credentials:edit` command was fixed to support spaces in
the temporary file path on Windows. This commit applies the same fix to
the `encrypted:edit` command.
Previously configs of the form `config.active_job.X` were only forwarded to
`ActiveJob::Base`. This teaches Active Job to set them on `ActiveJob` directly
instead, if the setter exists.
For consistency, this more or less mirrors the way that Active Record does it.
Co-authored-by: Adrianna Chang <adrianna.chang@shopify.com>
Co-authored-by: Sam Bostock <sam.bostock@shopify.com>
---
Fix use_big_decimal_serializer Rails 7.1 default
This config should be enabled for new Rails 7.1 apps, or apps that have updated
their config to `load_defaults 7.1`, not disabled.
This also clarifies the config accessor comment.
---
Add contributor documentation comment to load_defaults
The process for introducing a change in behavior in Rails can be confusing to
new contributors, so a comment is added roughly explaining how to do so, and
what belongs in `load_defaults` and `new_framework_defaults`.
This comment is aimed at contributors, not consumers, so it is added within the
method, rather than above it.
Prior to this commit, the `credentials:edit` command would display a
save confirmation message even if it was aborted via interrupt:
```console
$ EDITOR='ruby -e "sleep 100"' bin/rails credentials:edit
<Ctrl+C>
Aborted changing file: nothing saved.
File encrypted and saved.
```
This commit fixes that behavior:
```console
$ EDITOR='ruby -e "sleep 100"' bin/rails credentials:edit
<Ctrl+C>
Aborted changing file: nothing saved.
```
This commit also applies the same fix to the `encrypted:edit` command.
In #30893, the `credentials:edit` command was changed to prevent saving
invalid YAML:
```yaml
# some_invalid_yaml.yml
secret_key_base: ...
- new_key: new value
```
```console
$ EDITOR='cp some_invalid_yaml.yml' bin/rails credentials:edit
ruby-3.1.2/lib/ruby/3.1.0/psych.rb:455:in `parse': (<unknown>): did not find expected key while parsing a block mapping at line 3 column 1 (Psych::SyntaxError)
$ bin/rails credentials:show
secret_key_base: ...
```
However, throwing away user input is not ideal. Such behavior can be
particularly troublesome when copying secrets from ephemeral sources.
This commit changes the `credentials:edit` command to always save user
input, and display a helpful warning when saving invalid YAML:
```console
$ EDITOR='cp some_invalid_yaml.yml' bin/rails credentials:edit
File encrypted and saved.
WARNING: Invalid YAML in '/path/to/app/config/credentials.yml.enc'.
(/path/to/app/config/credentials.yml.enc): did not find expected key while parsing a block mapping at line 3 column 1
Your application will not be able to load 'config/credentials.yml.enc' until the error has been fixed.
$ bin/rails credentials:show
# some_invalid_yaml.yml
secret_key_base: ...
- new_key: new value
```
This commit also applies the same fix to the `encrypted:edit` command.
Follow-up to #45501.
The Rack base class that `CookieStore` inherits from [always sets
`:same_site`][1]. Thus, `options.key?(:same_site)` always returns true
for session cookies, preventing a default value from being set.
It would be possible to change Rack to conditionally set `:same_site`,
but, from Rack's perspective, it has no reason to not set `:same_site`,
because it treats a `nil` value the same as no value.
Therefore, this commit specifies a default `:same_site` in `CookieStore`,
which simply defers to `request.cookies_same_site_protection` as
`CookieJar` does.
Fixes#45681.
[1]: https://github.com/rack/rack/blob/2.2.4/lib/rack/session/abstract/id.rb#L398-L402
Prior to this commit, if `config.require_master_key` was set to true in
`config/application.rb`, the `credentials:edit` command could not
automatically generate a master key file:
```ruby
# In config/application.rb
config.require_master_key = true
```
```console
# No previously existing credentials
$ rm config/master.key config/credentials.yml.enc
```
```console
$ bin/rails credentials:edit
activesupport/lib/active_support/encrypted_file.rb:118:in `handle_missing_key': Missing encryption key to decrypt file with. Ask your team for your master key and write it to config/master.key or put it in the ENV['RAILS_MASTER_KEY']. (ActiveSupport::EncryptedFile::MissingKeyError)
```
This commit adds a `EncryptedFile#key?` method that can be used to check
for the existence of a key without raising `MissingKeyError`, and the
`credentials:edit` command now uses this method:
```console
$ bin/rails credentials:edit
Adding config/master.key to store the encryption key: ...
Save this in a password manager your team can access.
If you lose the key, no one, including you, can access anything encrypted with it.
create config/master.key
```
This commit also applies the same fix to the `encrypted:edit` command.
Print default parent class for controller, job, and model generators.
Before:
[--parent=PARENT] # The parent class for the generated job
After:
[--parent=PARENT] # The parent class for the generated job
# Default: ApplicationJob
This refactors `EncryptedCommand` and its tests to more closely mirror
`CredentialsCommand`, in preparation for forthcoming shared fixes.
Specifically, `EncryptedCommand` now uses a central
`encrypted_configuration` instance instead of passing arguments around,
and the tests now use a default encrypted file path instead of passing
it around.
This commit also imports tests concerning key file generation from the
`CredentialsCommand` tests.
This pattern is useful in some cases, like moving the project folder
from myapp to myapp_moved, or testing generated behavior based on the
app name being hyphenated-app.
However, for the majority of cases this is not needed and adds
additional complexity to some assertion helpers. For example,
`assert_file` always expands paths relative to `destination_root`
instead of whatever the working directory is.
Prior to this commit, `EncryptedFile` would internally memoize when a
key file was non-existent. This meant that a key file generated after
checking `encrypted_file.key.nil?` would not be recognized, unless a new
`EncryptedFile` instance was used. (Though setting the key in a
designated environment variable instead would entirely bypass this
memoization.)
This commit changes `EncryptedFile` to only memoize when the key file
has been read. Consequently, this commit memoizes the `EncryptedFile`
(or, specifically, `EncryptedConfiguration`) instance used by
`CredentialsCommand`.
This commit also adds more test coverage around key file generation for
`CredentialsCommand`.
155b757 added some yarn commands to bin/setup for apps that are using
Node. However, the blank line between the added block and the
skip_active_record block results in an extraneous blank line added to
apps when running app:update.
Previously running app:update always would template an application.rb
file without the `config.generators.system_tests = nil` set, even for
applications that previously had it set.
Previously, BigDecimal was listed as not needing a serializer. However,
when used with an adapter storing the job arguments as JSON, it would get
serialized as a simple String, resulting in deserialization also producing
a String (instead of a BigDecimal).
By using a serializer, we ensure the round trip is safe.
During upgrade deployments of applications with multiple replicas making use of
BigDecimal job arguments with a queue adapter serializing to JSON, there exists
a possible race condition, whereby a "new" replica enqueues a job with an
argument serialized using `BigDecimalSerializer`, and an "old" replica fails to
deserialize it (as it does not have `BigDecimalSerializer`).
Therefore, to ensure safe upgrades, serialization will not use
`BigDecimalSerializer` until `config.active_job.use_big_decimal_serializer` is
enabled, which can be done safely after successful deployment of Rails 7.1.
This option will be removed in Rails 7.2, when it will become the default.
The default was changed in c2b96e3 but this test was not updated. Since
the assertion would pass even if the initializer failed, it needs to be
changed to something else.
In Psych >= 4.0.0, load defaults to safe_load. This commit
makes the ActiveRecord::Coders::YAMLColum class use Psych safe_load
as the Rails default.
This default is configurable via ActiveRecord.use_yaml_unsafe_load
We conditionally fallback to the correct unsafe load if use_yaml_unsafe_load
is set to true. unsafe_load was introduced in Psych 4.0.0
The list of safe_load permitted classes is configurable via
ActiveRecord.yaml_column_permitted_classes
[CVE-2022-32224]
This commit adds support for in-app custom credentials templates. When
a credentials file does not exist, `rails credentials:edit` will now try
to use `lib/templates/rails/credentials/credentials.yml.tt` to generate
the credentials file, before falling back to the default template.
This allows e.g. an open-source Rails app (which would not include
encrypted credentials files in its repo) to include a credentials
template, so that users who install the app will get a custom pre-filled
credentials file when they run `rails credentials:edit`.
Currently, when `config/credentials.yml.enc` is generated by
`CredentialsGenerator`, it includes a `secret_key_base` for convenience.
However, because `config/credentials/#{environment}.yml.enc` files are
generated by a different generator (`EncryptedFileGenerator`), they do
not include a `secret_key_base`.
This commit revises `CredentialsGenerator` to be more generator-like,
and changes `rails credentials:edit` to use it for generating both
`config/credentials.yml.enc` and `config/credentials/#{environment}.yml.enc`
files, thereby always including a `secret_key_base`.
https://github.com/rails/rails/pull/41395 added support for the `timestamptz` type on the Postgres adapter.
As we found [here](https://github.com/rails/rails/pull/41084#issuecomment-1056430921) this causes issues because in some scenarios the new type is not considered a time zone aware attribute, meaning values of this type in the DB are presented as a `Time`, not an `ActiveSupport::TimeWithZone`.
This PR fixes that by ensuring that `timestamptz` is always a time zone aware type, for Postgres users.
Building and linting are setup similar to other packages
Most of the changes are related to converting from sprockets requires to
ESM imports/export. However, there are a few notable changes as well:
- A few methods have been refactored to store the Rails object in a
closure so that properties on it can be overriden by applications (as
documented and tested). This also resulted in the "start" module
getting inlined so that it can use the resulting functions.
- The logic for running Rails.start() automatically had to change
because Rollup uses a slightly different module format than the
previous coffeescript bundle. The Rollup bundle does not set
window.Rails until the end up the bundle, so the condition had to be
updated and window.Rails had to be set manually to ensure backwards
compatability with scripts listening to the rails:attachBindings event
This commit improves handling of implied options for `AppGenerator` and
`PluginGenerator` in a few different ways.
Implied options are now reported:
```console
$ rails new my_cool_app --skip-active-job
Based on the specified options, the following options will also be activated:
--skip-action-mailer [due to --skip-active-job]
--skip-active-storage [due to --skip-active-job]
--skip-action-mailbox [due to --skip-active-storage]
--skip-action-text [due to --skip-active-storage]
...
```
Option conflicts raise an error:
```console
$ rails new my_cool_app --skip-active-job --no-skip-active-storage
Based on the specified options, the following options will also be activated:
--skip-action-mailer [due to --skip-active-job]
--skip-active-storage [due to --skip-active-job]
ERROR: Conflicts with --no-skip-active-storage
--skip-action-mailbox [due to --skip-active-storage]
--skip-action-text [due to --skip-active-storage]
railties/lib/rails/generators/app_base.rb:206:in `report_implied_options': Cannot proceed due to conflicting options (RuntimeError)
```
Meta option (e.g. `--minimal`) implications are also reported:
```console
$ rails new my_cool_app --minimal
Based on the specified options, the following options will also be activated:
--skip-active-job [due to --minimal]
--skip-action-mailer [due to --skip-active-job, --minimal]
--skip-active-storage [due to --skip-active-job, --minimal]
--skip-action-mailbox [due to --skip-active-storage, --minimal]
--skip-action-text [due to --skip-active-storage, --minimal]
--skip-javascript [due to --minimal]
--skip-hotwire [due to --skip-javascript, --minimal]
--skip-action-cable [due to --minimal]
--skip-bootsnap [due to --minimal]
--skip-dev-gems [due to --minimal]
--skip-system-test [due to --minimal]
...
```
`--no-*` options now work with meta options, and are both comprehensive
and precise:
```console
$ rails new my_cool_app --minimal --no-skip-active-storage
Based on the specified options, the following options will also be activated:
--skip-action-mailer [due to --minimal]
--skip-action-mailbox [due to --minimal]
--skip-action-text [due to --minimal]
--skip-javascript [due to --minimal]
--skip-hotwire [due to --skip-javascript, --minimal]
--skip-action-cable [due to --minimal]
--skip-bootsnap [due to --minimal]
--skip-dev-gems [due to --minimal]
--skip-system-test [due to --minimal]
...
```
Closes#45223.
Closes#45205.
Co-authored-by: Brad Trick <btrick@appacademy.io>
Previously Rails would always remove the connection if it found a
matching class in the pool manager. Therefore if
`ActiveRecord::Base.establish_connection` was called with the same
config, each time it was called it would be clobbered, even though the
config hasn't changed and the existing connection is prefectly fine. As
far as I can tell from conversations and reading the history this
functionality was added for ActiveRecord tests to be able to clobber the
connection and use a new config, then re-establish the old connection.
Essentially outside Rake tasks and AR tests, this functionality doesn't
have a ton of value.
On top of not adding a ton of value, this has resulted in a few bugs. In
Rails 6.0 I made it so that if you established a connection on
`ApplicationRecord` Rails would treat that connection the same as
`ActiveRecord::Base.` The reason for this is that the Railtie
establishes a connection on boot to the first database, but then if
you're using multiple databases you're calling `connects_to` in your
`ApplicationRecord` or primary abstract class which essentially doubles
your connections to the same database. To avoid opening 2 connections to
the same database, Rails treats them the same.
However, because we have this code that removes existing connections,
when an application boots, `ApplicationRecord` will clobber the
connection that the Railtie established even though the connection
configs are the same.
This removal of the connection caused bugs in migrations that load up a
model connected to `ApplicationRecord` (ex `Post.first`) and then calls
`execute("SELECT 1")` (obviously a simplified example). When `execute`
runs the connection is different from the one opened to run the
migration and essentially it is lost when the `remove_connection` code
is called.
To fix this I've updated the code to only remove the connection if the
database config is different. Ultimately I'd like to remove this code
altogether but to do that we first need to stop using
`Base.establish_connection` in the rake tasks and tests. This will fix
the major bugs until I come up with a solution for the areas that
currently need to call `establish_connection` on Base.
The added benefit of this change is that if your app is calling
`establish_connection` multiple times with the same config, it is now
3x faster than the previous implementation because we can return the
found pool instead of setting it up again. To benchmark this I
duplicated the `establish_connection` method to use the new behavior
with a new name.
Benchmark script:
```ruby
require "active_record"
require "logger"
require "benchmark/ips"
config_hash = { "development" => { "primary" => { "adapter" => "mysql2", "username" => "rails", "database" => "activerecord_unittest"}}}
ActiveRecord::Base.configurations = config_hash
db_config = ActiveRecord::Base.configurations.configs_for(env_name: "development", name: "primary")
p "Same model same config"
ActiveRecord::Base.connected_to(role: :writing, prevent_writes: true) do
Benchmark.ips do |x|
x.report "establish_connection with remove" do
ActiveRecord::Base.establish_connection(db_config)
end
x.report "establish_connection without remove" do
ActiveRecord::Base.establish_connection_no_remove(db_config)
end
x.compare!
end
end
```
Benchmark results:
```
Warming up --------------------------------------
establish_connection with remove
4.677k i/100ms
establish_connection without remove
19.501k i/100ms
Calculating -------------------------------------
establish_connection with remove
41.252k (±11.3%) i/s - 205.788k in 5.075525s
establish_connection without remove
179.205k (± 6.9%) i/s - 897.046k in 5.029742s
Comparison:
establish_connection without remove: 179205.1 i/s
establish_connection with remove: 41252.3 i/s - 4.34x (± 0.00) slower
```
Other changes:
1) sqlite3 now disconnects and reconnects the connection when `purge` is
called. This is necessary now that a new connection isn't created
everyt time `establish_connection` is called. Without this change to
purge the new database is left in an inaccessible state causing a
readonly error from the sqlite3 client. This wasn't happening in mysql
or postgres because they were already reconnecting the db connection.
2) I added `remove_connection` to tests that use `ApplicationRecord`.
This is required because `ApplicationRecord` or any class that is a
`primary_abstract_class` will be treated the same as
`ActiveRecord::Base`. This is fine in applications because they are
shared connections, but in the AR test environment, we don't want those
connnections to stick around (we want AR::Base back).
3) In the async tests I removed 2 calls to `establish_connection`. These
were causing sqlite3 tests to leak the state of async_executor because
it's stored on the connection. I'm not sure why these were calling
`establish_connection` but it's not necessary and was leaking state when
now that we are no longer removing the connection.
Fixes: #41855Fixes: #41876Fixes: #42873Fixes: #43004
Follow-up to #45344.
When using `config.load_default "7.1"`, the value is `false`, so the
value in `new_framework_defaults_7_1.rb` should be `false` as well.
This commit also adds configuration tests.
In minitest/minitest@6e06ac9 minitest changed such that it now accepts
`kwargs` instead of requiring kwargs to be shoved into the args array.
This is a good change but required some updates to our test code to get
the new version of minitest passing.
Changes are as follows:
1) Lock minitest to 5.15 for Ruby 2.7. We don't love this change but
it's pretty difficult to get 2.7 and 3.0 to play nicely together with
the new kwargs changes. Dropping 2.7 support isn't an option right
now for Rails. This is safe because all of the code changes here are
internal methods to Rails like assert_called_with. Applications
shouldn't be consuming them as they are no-doc'd.
2) Update the `assert_called_with` method to take any kwargs but also
the returns kwarg.
3) Update callers of `assert_called_with` to move the kwargs outside the
args array.
4) Update the message from marshaled exceptions. In 5.16 the exception
message is "result not reported" instead of "Wrapped undumpable
exception".
Co-authored-by: Matthew Draper <matthew@trebex.net>
activerecord-session_store was removed in 0ffe190, and has been
displaying a special error message when missing since Rails 4.0.
Replace the specific error message so that third party stores get nicer
error handling as well
This seems to be a pattern that was common around Rails 3 (for example,
it was last changed in 7ee5843). However, most of the usages were
removed in 36dd185 and this one looks like it was missed.
Some of the other files changed in 7ee5843 were later consolidated into
a root `load_paths.rb` file in 9f01dff which was later removed in
2abcdfd.
This removes the singularize from `where` which runs on all `expand_from_hash` keys which might be reflections or column names. This saves a lot of time by avoiding singularizing column names.
Previously in https://github.com/rails/rails/pull/45163 the singularize was removed entirely. after some reflection, I think it is better to at least give a warning for one release since `where` is a very popular API and the problems you can run into with incorrect relation could be hard to debug.
Configurable with `ActiveRecord::Base.allow_deprecated_singular_assocaitions_name = false` / `config.active_record.allow_deprecated_singular_assocaitions_name = false`
The `assert_called_with` helper allows passing a multi-dimensional array to
mock multiple calls to the same method for a given block. This works
fine now, but when adding support for real kwargs arguments to line up with
recent upgrades in Minitest, this approach is no longer workable because
we can't pass multiple sets of differing kwargs.
Rather than complicated this method further, this commit removes the
multi-call form of `assert_called_with` and modifies the tests that
currently make use of that functionality to just use the underlying
`Minitest::Mock` calls.
Co-authored-by: Eileen M. Uchitelle <eileencodes@gmail.com>
In #45162 it was discovered that the multi_db generator that was created
for 7.0 doesn't work correctly because that file is loaded _after_ the
initializer in active record is run. I tried moving everything to an
after_initialize but the middleware stack is frozen at that point. I
also attempted to fix this in #45353 but it just didn't feel right to
have to deprecate this behavior that _should_ work.
I then realized that most of the middleware in Rails is installed in the
middleware stack file in railties. If I move the middleware installation
to this file, everything works as necessary.
The only caveat is we need to check if `config` responds to
`active_record` but I think that should be fine - we already do that in
the framework defaults configuration.
Fixes#45162
If you use either of these frameworks, Active Job is used. That means
that only skipping Active Job will not really skip it, and whenever
app:update runs, Active Job will be added back.
In
f075be3dcb
did_you_mean and error_highlight now use `detailed_message` over
`message` to display errors.
For cases where we are testing `message`, in 3.2 and above we need to
test against `detailed_message` instead.
As far as I can tell in a Rails console when these errors are raised the
`detailed_message` is used so we shouldn't need to make other changes to
Rails. The only case where this isn't true is in the Railties changes -
we are explicitly formatting the did you mean message so we need to be
sure to call `detailed_message` here.
This fixes most of the failing tests for ruby-trunk.
Rails allows you to use a `shared` entry in the database yaml which gets
merged into other entries. This was broken when using a 3-tier config.
The change here ensures we're looping through all the configs. We know
we have a 3-tier config if the config is a hash and all the values
inside that config are a hash. If so we need to keep looping, otherwise
we have a standard 2-tier config.
Fixes #
Rails::Rack::Logger is one of the few (the only?) places where we aren't
able to use the preferred AS::N.instrument API with a block. This is
because we want to finish the event when the Rack body is closed, rather
than when the status and headers are first returned.
This switches to using the low-level `build_handle` API, which allows
safe interleaving of events and doesn't make use of thread or fiber
locals.
Since Puma 5.0 (puma/puma@05936689c8),
Puma will automatically set `workers` to `ENV["WEB_CONCURRENCY"] || 0`.
Additionally, if `ENV["WEB_CONCURRENCY"]` > 1, Puma will automatically
set `preload_app`.
This can lead to confusing scenarios for users who are unaware of this
behavior and have customized `config/puma.rb`. For example, if a user
uncomments the `workers` and `preload_app!` directives, it is clear that
Puma will preload the app, and the number of workers can be configured
by setting `ENV["WEB_CONCURRENCY"]`. If the user sets
`ENV["WEB_CONCURRENCY"]` > 1, but then changes their mind and removes
the `workers` or `preload_app!` directives *without* clearing
`ENV["WEB_CONCURRENCY"]`, Puma will still preload the app and launch
`ENV["WEB_CONCURRENCY"]` number of workers. Similarly, if a user
uncomments *only* the `workers` directive and sets
`ENV["WEB_CONCURRENCY"]` > 1, Puma will preload the app even though the
`preload_app!` directive is still commented out.
To avoid such scenarios, this commit removes the commented-out `workers`
and `preload_app!` directives from the default `config/puma.rb`.
Also, to improve discoverability of available configuration options,
this commit adds a link to the Puma DSL documentation at the top of the
file.
I was auditing which routes in my app do not actually a
have corresponding controller action. ActionMailbox's
inbound_mails has these 4 routes defined, which do not
actually work.
GET /rails/conductor/action_mailbox/inbound_emails/:id/edit
PATCH /rails/conductor/action_mailbox/inbound_emails/:id
PUT /rails/conductor/action_mailbox/inbound_emails/:id
DELETE /rails/conductor/action_mailbox/inbound_emails/:id
This avoids loading the Rakefile, which results in the app booting
twice, once in the development environment to load the Rake tasks, and
then another time in a fork to run the test runner in the test
environment.
Using Thor tasks with no parameters means passing arguments to the task
raises, whereas Rake accepts additional arguments that are not used:
$ bin/rake test:system SOMETHING=anything
Similarly, with Rake you can use --trace which won't work here.
If more than one test is using `use_postgresql` for it's tests and both
need to run `db:create` those tests will fail often due to them
running in parallel. I tried turning off parallelization for these tests
and they still ran in separate processes. Ultimately though, turning off
parallelization means we don't aren't testing parallelization. Instead I've
added `Process.pid` to the database name so it creates a database
specifically for that test. For cases where we need to set an explict
name a name can be passed in.
I also added an ensure to one of the tests so that the databases get
cleaned up and not left behind.
Fixes#45114Fixes#45158
Users, especially those who are creating an app for the first time,
might not be aware of the `rails credentials:diff --enroll` command.
This commit enrolls new apps in decrypted diffs by default so that users
benefit automatically. This behavior can be opted out of with the app
generator's `--skip-decrypted-diffs` flag.
This makes it possible to run a declarative-style test such as:
```ruby
class MyTest < ActiveSupport::TestCase
test "does something" do
# ...
end
end
```
Using its declared name:
```bash
$ bin/rails test test/my_test.rb -n "does something"
```
Instead of having to specify its expanded method name:
```bash
$ bin/rails test test/my_test.rb -n test_does_something
```
Co-authored-by: Eugene Kenny <elkenny@gmail.com>
Fix: https://github.com/rails/rails/issues/45092
Up until 3.0, `rails s` would always at least find webrick. But since it
was removed in Ruby 3.0, it's now possible to end up with no available server
at all.
In such case we should recommend adding puma to the Gemfile.
`--js` alias to `rails new --javascript ...`
Same as `-j`, e.g. `rails new --js esbuild ...`
`--skip-js` alias to `rails new --skip-javascript ...`
Same as `-J`, e.g. `rails new --skip-js ...`
Sdoc 2.4.0 supports a CSS badge that can be set by passing the version
as the HORO_BADGE_VERSION env variable.
The old badge image can be removed, as it no longer needs to be copied
by the docs server: https://github.com/rails/rails-docs-server/pull/28
In this commit, we are adding the option to set the name of the app
when generating a new one with `rails new`.
The option `--name` will override the application name to be different
from the folder name.
```
rails new my-app-folder --name=my-actual-app-name"
```
The command above will generate a
new Rails application in the folder `my-app-folder`, but the file
`config/application.rb` would have the following structure:
module MyActualAppName
class Application < Rails::Application
end
end
This option would be most useful when generating a Rails application in
the current folder:
```
rails new . --name=my-app
```
`Shellwords.escape` escapes unquoted spaces with a backslash, but
Windows does not treat backslash as an escape character. Escaping is
also a problem when paths are expressed in shortened 8.3 format (e.g.
`C:\Users\RubyOn~1\AppData\Local\Temp\...`) because a backslash will be
erroneously added before the `~`.
We can avoid the need to escape by using `system(command_name, *args)`
instead of `system(command_line)`, but we must still support
`ENV["EDITOR"]` values that embed command line arguments, such as
`subl -w`.
This commit changes to `system(command_name, *args)`, but uses
`Shellwords.split` to extract any embedded arguments from
`ENV["EDITOR"]`. This requires that Windows users put quotes around the
entire path of their editor if it contains spaces, such as:
```
SET EDITOR="C:\Program Files\Microsoft VS Code\Code.exe" -w
```
In other words, the following are **not** supported on Windows:
```
SET "EDITOR=C:\Program Files\Microsoft VS Code\Code.exe"
SET EDITOR=C:\Program Files\Microsoft VS Code\Code.exe
SET EDITOR=C:\"Program Files"\"Microsoft VS Code"\Code.exe -w
SET EDITOR=C:\Program^ Files\Microsoft^ VS^ Code\Code.exe -w
SET EDITOR=C:\Program` Files\Microsoft` VS` Code\Code.exe -w
```
Fixes#41617 (again).
Closes#44890.
If reloading is enabled, we need the interlock to synchronize reloads.
If reloading is disabled and so is eager loading, in the past you still needed
to synchronize autoloads because `classic` was not thread-safe. With Zeitwerk,
this is no longer needed.
Every time I write `config.cache_classes` I have to pause for a moment to make
sure I get it right. It makes you think.
On the other hand, if you read `config.enable_reloading = true`, does the
application reload? You do not need to spend 1 cycle of brain CPU to nod.
This functionality has been deprecated since Rails 6.1 and can now be
removed. I've deleted all code, docs, references, and tests related to
this feature.
Since `rails db:structure:{dump,load}` was deprecated there wasn't a simple way to dump a schema to both SQL and Ruby formats. This PR implements @jeremy suggestion @ https://github.com/rails/rails/pull/39470#pullrequestreview-483599714, so you can now do this with an environment variable. For example:
```
SCHEMA_FORMAT=sql rake db:schema:dump
```
After af7428c4ac the yarn install
instructions was dropped from bin/setup. This commmit adds it into
the setup script again if the user is not using importmap.
Rails 6.0 and Rails 6.1 didn't support the undocumented `before_remove_const` in
`zeitwerk` mode. I noticed this cleanup in AR was not being executed, and
restored the original code for Rails 7.
However, invoking `respond_to?` in an `on_unload` callback may have unexpected
side-effects, as seen in #44125. So, this patch reimplements the cleanup in a
more modern way.
Fixes#44125.
activerecord/lib/active_record/connection_adapters/postgresql/column.rb
- usage added in 64fd666
- unneeded because of active_support/rails: 8f58d6e
railties/lib/rails/rack/logger.rb
- usage added in c83d9a1
- usage removed in c131211
activesupport/lib/active_support/number_helper/number_converter.rb
- the NumberHelper was split into multiple classes in 2da9d67, however
the require was left in NumberConverter even though
NumberToPhoneConverter is the only class where it's used
activesupport/lib/active_support/duration/iso8601_serializer.rb
- usage added in 04c512d
- usage removed in 51e991f
This allows applications to specify the maximum number of records that
will be destroyed in a single background job by the `dependent:
:destroy_async` association option. By default, the current behavior
will remain the same: when a parent record is destroyed, all dependent
records will be destroyed in a single background job. If the number of
dependent records is greater than this configuration, the records will
be destroyed in multiple background jobs.
At GitHub, we have a custom method for destroying associated records
in the background that we'd like to replace with
`dependent: :destroy_async`. Some associations have a large number of
dependent records, and our infrastructure requires that background jobs
complete quickly, so we limit the maximum number of dependent records
destroyed in a single background job and enqueue additional jobs when
the number of records exceeds that limit.
ImageProcessingTransformer now offers a configurable allow-list for
transformation methods in addition to a configurable deny-list for arguments.
[CVE-2022-21831]
These classes are relatively small, however they include lots of
modules as helpers. And if any of the included module hold constants
including it cause the global constant cache to be invalidated
which is really bad for performance.
So when eager loading is enabled we create all the possible classes
as part of the application boot.
- ### Summary
The terminal output on a Rails application running ruby 3 will be
cluttered with thousands of lines if one inadventarly call a
unexisting method.
This happen in various places (IntegrationTest, when running a db
migration ...).
This is related to a change in ruby 3 when a NoMethodError is
raised.
### Simple reproduction
```
class A
def initialize(session)
@a = session
end
end
test = A.new("*" * 36)
test.dsad # undefined method `dsad' for #<A:0x00007f847d8494b0 @a="************************************"> (NoMethodError)
# Note that the "#<A:0x00007f847d8494b0 @a="************************************">" part
# is 65 chars long.
test = test = A.new("*" * 37)
test.dsad # undefined method `dsad' for #<A:0x00007fa8c38299c0> (NoMethodError)
```
On Ruby < 3, the NoMethodError message (everything starting from the
"#" char) could only be 65 characters long. If it was above that
ruby would only output the name of the class and its address.
On Ruby >= 3, that limitation has been removed and the message can
be any length long.
### On Rails
Anytime a method is called on a object that holds the entire
Rails::Application, the terminal would output the entire application
which is annoying be can be dangerous because it will leak
everything containing the credentials (stored inside the Application
object).
Calling `skip_forgery_protection` without first calling
`protect_from_forgery`--either manually or through default
settings--raises an `ArgumentError` because `verify_authenticity_token`
has not been defined as a callback.
Since Rails 7.0 adds `skip_forgery_protection` to the
`Rails::WelcomeController` (PR #42864), this behavior means that setting
`default_protect_from_forgery` to false and visiting the Rails Welcome
page (`/`) raises an error.
This behavior also created an issue for `ActionMailbox` that was
previously fixed in the Mailbox controller by running
`skip_forgery_protection` only if `default_protect_from_forgery` was
true (PR #35935).
This PR addresses the underlying issue by setting the `raise` option for
`skip_before_action` to default to false inside
`skip_forgery_protection`.
The fix is implemented in `request_forgery_protection.rb`. The change to
`ActionMailbox`'s `base_controller.rb` removes the now-unnecessary
check of `default_protect_from_forgery`.
The tests added in `request_forgery_protection_test.rb` and
`routing_test.rb` both raise an error when run against the current
codebase and pass with the changes noted above.
This has the benefit of hiding the warning message from git when
initialBranch configuration is unset, and was a recommendation on the
original commit adding main as the default branch for generators.
Ref: eb261937ac
I haven't yet identified why this particular test is causing issues when
other similarly-shaped ones seem fine, but if skipping it gets CI
working again, that's an improvement for now.
The `content_security_policy_report_only` config does not enable
violation reporting.
It makes sure the policy isn't enforced, only reported.
Also link to the guide instead of external documentation.
RDoc will automatically format and link API references as long as they
are not already marked up as inline code.
This commit removes markup from various API references so that those
references will link to the relevant API docs.
Rendering the list of boot steps as a code block confused the syntax
highlighter.
This commit changes the list to use RDoc's ordered list syntax, and adds
inline code markup as appropriate.
This almost never matters, but if the path-global 'rake' or 'rails'
points to a specific (and wrong) ruby version, (or, possible in CI,
there is no installed 'rails' executable), things get confused.
Instead, any time we mean "run a global 'rails', as for 'new'", use a
fully-qualified path to our in-tree copy. And any time we're working
inside an application, use the bin/rails script directly. It would be
equivalently valid to always use the one in exe/, because that handles
searching for bin/rails internally... but it's uglier to fully-qualify,
plus 'rake' would then be more complicated.
This ensures that the finish instrumenter is sent to the same
subscribers that the initial request was sent to.
This solves an issue where in a threaded environment the dynamic
subscriptions from ActionDispatch::ServerTiming would cause a mismatch
in the number of subscriptions to a topic, which would pop too many
values off of the thread-local stacks, leading to invalid events being
sent to subscribers.
Fixes#44167
`config.active_record.destroy_association_async_job` should allow applications
to specify the job that will be used to destroy associated records in the
background for `has_many` associations with the `dependent: :destroy_async`
option. That's being ignored, which means the default
`ActiveRecord::DestroyAssociationAsyncJob` always destroys records in the
background. This change stops ignoring the configuration.
These changes include adding a hybrid serializer class
named JsonWithMarshalFallback in order for existing apps
to have an upgrade path from Marshal to JSON.