Commit Graph

79137 Commits

Author SHA1 Message Date
Carlos Antonio da Silva bd9d7804e0 Fix Rails version typo in upgrading guide [ci skip] 2021-02-04 13:41:30 -03:00
Rafael Mendonça França 6487836af8
Rails 7 requires Ruby 2.7 and prefer Ruby 3+
The code cleanup is comming in later commits but this
already remove support to Ruby < 2.7.
2021-02-04 16:34:53 +00:00
Eileen M. Uchitelle 5a477890c8
Merge pull request #41258 from eileencodes/primary-class
Expose `primary_abstract_class` public API
2021-02-04 09:47:34 -05:00
Abhay Nikam 3f96069ad9
Match the show action case in the new(updated) scaffold generator (#41331) 2021-02-04 14:03:17 +01:00
David Heinemeier Hansson dfebea447f Errantly removed during a merge 2021-02-04 13:36:09 +01:00
David Heinemeier Hansson 164c2f6257
Modernize scaffold generator (#41210)
* Slim down scaffold css

To prevent conflicts with utility frameworks that might also be resetting base elements.

* Use a box-style partial rather than a table

Shows the usage of partials right from the start. Better compatibility with upgrading to Turbo frames/stream updates.

* Correct use of quotes

* Use modern array-of-strings declaration

* Use double quotes for everything

* Fix syntax

* Remove outdated viewport declaration

This should be handled in app stylesheets.

* Use double quotes everywhere

* Use symbols not strings for before_action scoping

* Use human name to deal with double word records

* Grab test fixes from #41219

Thanks @abhaynikam 🙏

* Fix tests

* Use locar var not ivar

* Fix capitalization change

* Update railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt

Co-authored-by: Haroon Ahmed <haroon.ahmed25@gmail.com>

* Update railties/test/generators/scaffold_controller_generator_test.rb

Co-authored-by: Haroon Ahmed <haroon.ahmed25@gmail.com>

* Update railties/test/generators/scaffold_controller_generator_test.rb

Co-authored-by: Haroon Ahmed <haroon.ahmed25@gmail.com>

* Fix test

* Update railties/test/generators/scaffold_generator_test.rb

Co-authored-by: Jonathan Hefner <jonathan@hefner.pro>

* Correct logic warning about initializers

Defining initializer 4 to run before itself and after 3 is possible, but
not when the before constraint contradicts the after constraint via 2.

* Rename master to main in all code references

* Use length == 0 instead of empty in Preloader

Previously we were checking empty? on the association which would make a
query. Instead we can check length == 0 to ensure we are using the
length of the loaded records and not issuing extra queries.

Co-authored-by: Dinah Shi <dinahshi@github.com>

* Add regression tests for preloader query count

* ActionCable guides suggest test adapter for test env [ci skip]

* Changing 'rails new' --master to be --main

Renaming test containing flag

Updating other test referencing master branch

Add notice that --master is deprecated, but still working the same as --main

Only set @main if it's nil

Making warn wildcard

I think a hidden aliaes would be just as good

Improving description & fixing rubocop error

Forgot comma

Deprecation warning was kind of hard - so just doing alias for now

rubocop -a

* I think passing in the --master argument to run_generator is the way to go

* Removing .count to figure out why its failing

* Raise unknown type error on the definition time

If unknow type is given for attribute (`attribute :foo, :unknown`),
unknown type error isn't raised on the definition time but runtime.

It should be raised on the definition time.

* Refactor `attribute` not to reference `&block`

* Use major + minor AR versions in 'Directly inheriting' error message

* Raise error when passing passing a class to :source_type

Raise `ArgumentError` when `:source_type` is given as class
in `has_many :through` relation.

Closes #41092

* Adding badges and logo to README and CONTRIBUTING page

* switch references to main branch in docs

* Updating references to /rails/blob/master & raiks/tree/master to point to main

* Don't return query cache enabled pools in the query cache executor

Follow up #41046.

If query cache is enabled for all connection pools, `pools` always
matches to `all_connection_pools`, returning `pools` has become
redundant.

* Remove trailing commas in advanced route constraints example

* Search for yarn.cmd and yarn.ps1 in bin/yarn

Follow-up to #40950.

On Windows, Yarn actually uses `yarn.cmd` and `yarn.ps1` for PowerShell.

* Run bin/yarn via Ruby

Windows cannot directly run shebang scripts, such as `bin/yarn`.
Therefore, run `bin/yarn` via Ruby.

Actually fixes #40942.
Fixes #41123.

* Allow to opt-out of `strict_loading` mode on a per-record base.

This is useful when strict loading is enabled application wide or on a
model level.

* Fix granular connection swapping when there are multiple abstract classes

Some applications maybe have multiple abstract classes in the
inheritance chain but only one of those abstract classes is the one we
want to switch connections on. Previously, multiple abstract class
inhertance would break `connected_to` and not switch models to the
correct connection context.

To fix this we added a boolean that is set on the class when a
connection is established so we can check for whether it's identified as
a `connection_class?`. This allows us to delete the `abstract_class?`
check, since you cannot establish a connection on a non-abstract class.

The existing tests were changed because they were not calling
`connects_to` and granular swapping won't work on classes that didn't
establish the connection. The issue in these tests will be prevented
when #40965 is merged.

Co-authored-by: John Crepezzi <john.crepezzi@gmail.com>

* Avoid testing Thor internals

Thor's `apply` method is responsible for fetching a template when given
a URL.  Therefore, assume that `apply` behaves correctly, and simply
test that `apply` is called correctly.

This avoids errors like https://buildkite.com/rails/rails/builds/74245#540ecdf1-58ea-470a-a397-09f675520eb9/1100-1109
resulting from erikhuda/thor@4ce38c5478.

* Fix the benchmark script to point to the main branch

* Resolve default annotation tags after config loads

`Rails::SourceAnnotationExtractor::Annotation.tags` may be modified by
app configuration.  Therefore, resolve default annotation tags after
loading the app configuration.

This fixes errors like https://buildkite.com/rails/rails/builds/74268#240d60bc-baa7-4b6e-ad21-b3172095f939/1083-1092
resulting from erikhuda/thor@0222fe52ed.

* Upgrade all the gems to make sure we are testing with the latest versions locally

* Don't bother checking if strings respond to string methods

The respond_to? calls here are checking if the unsafe method names, in
this case "gsub" and "sub", respond to those same methods. This is
nonsensical and unnecessary.

* Update name of input to fix typo

* `connected_to` shouldn't be called on the abstract class that not established connection

Fixed: https://github.com/rails/rails/issues/40559#issuecomment-752056106

When abstract class hasn't own connections, calling `AbstractClass.connection`
returns parent class's connection. We call `AbstractClass.connection.preventing_writes?`
expecting abstract class's state to be returned, but actually it is parent's one.

I think that it isn't expected behavior so I prevents call `connected_to` on the abstract
class that not established the connection.

* Add Webpacker to Guides list

Adds a link to the Webpacker guide (added in https://github.com/rails/rails/pull/40817) to the [guides list](https://guides.rubyonrails.org/) and "Guides Index" dropdown menu.

* Update documents.yaml

* Fix unintialized instance variable connection_class

This was throwing a warning when the test suite is run. Adding an
reader fixes the issue.

* Webpacker guide: remove Basecamp reference [docs]

As a Rails user, if you *don't* know who Basecamp is or their relationship to the Rails framework, then this sentence is confusing. Reworded to instead just refer to Rails defaults.

cc @rossta

* fix broken link

* Update webpacker.md

* Added the unless-block for continuity

* Added :status for continuity

* Removed line for continuity

* Added a new line after the include statement

* Connection specification now passes the "url" key to the adapter

If the "url" protocol is "jdbc", "http", or "https" the url option will
be passed to the adapter. Previously only urls with the "jdbc" prefix
were passed to the Active Record Adapter, others are assumed to be
adapter specification urls.

Fixes #41137.

* Support hash config for `structure_dump_flags` and `structure_load_flags` flags

    Now that Active Record supports multiple databases configuration
    we need a way to pass specific flags for dump/load databases since
    the options are not the same for different adapters.
    We can use in the original way:
    ```ruby
    ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags = ['--no-defaults', '--skip-add-drop-table']
    #or
    ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags = '--no-defaults --skip-add-drop-table'
    ```
    And also use it passing a hash, with one or more keys, where the key
    is the adapter
    ```ruby
    ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags = {
      mysql2: ['--no-defaults', '--skip-add-drop-table'],
      postgres: '--no-tablespaces'
    }
    ```

* Update test docs in "contributing to Rails" guide

Updated guide to recommend `bin/test` and show examples of its use in different contexts.

Co-authored-by: Marivaldo Cavalheiro <marivaldo@gmail.com>

* Fix current_page? with kwargs on ruby3

Prevent raising an error when `options` are given as
kwargs, this is done by overriding `options` with kwargs
if `options` are `nil`; this implies that if both `options` and
kwargs are given, `options` takes precedence.

Fixes #41198

* `start_with?` allows multiple prefix values

* Fix code block in Webpacker Guide [ci skip]

Formatting fix: the example directory tree listing was bleeding into the
previous paragraph and had extraneous characters due to a missing
newline.

* Remove wrong usage for `arel_table` [ci skip]

This usage doesn't work properly (missing `where`, undefined `published`,
`arel_table` in the scope definition accidentally lose table alias).

* Restore ActiveStorage::Blob#find_signed

Rails 6.0 had a [public `find_signed` method][docs], but we changed it
to `find_signed!` in 31148cd6be.

This commit adds back `find_signed` alongside `find_signed!` to match
the corresponding [Active Record methods][].

[docs]: https://api.rubyonrails.org/v6.0.0/classes/ActiveStorage/Blob.html#method-c-find_signed
[Active Record methods]: https://github.com/rails/rails/blob/main/activerecord/lib/active_record/signed_id.rb#L42-L66

* Handle throwing in controller action in log subscriber

When throw was used in a controller action, and there is matching catch
around the request in a Rack middleware, then :exception won't be
present in the event payload.

This is because ActiveSupport::Notifications::Instrumenter.instrument
sets :exception in a rescue handler, but rescue is never called in a
throw/catch scenario:

  catch(:halt) do
    begin
      throw :halt
    rescue Exception => e
      puts "rescue" # never reached
    ensure
      puts "ensure"
    end
  end

Missing :exception was actually handled prior to Rails 6.1.0, but an
optimization updated the code to assume this was present. So this can be
considered a regression fix.

* Improve Fixture support for Active Storage (#41065)

* Improve Fixture support for Active Storage

Inspired by [76b33aa][], this commit extends the Active Storage
documentation to elaborate on how to declare fixtures.

In support of that, also introduce the `ActiveStorage::FixtureSet.blob`
method for injecting in-line [ActiveStorage::Blob][] attributes directly
into fixture YAML.

[76b33aa]: 76b33aa3d1
[ActiveStorage::Blob]: https://edgeapi.rubyonrails.org/classes/ActiveStorage/Blob.html

* Extra CR for style

* Two-space indention

* Explaining variable didn't explain, inline for style

Co-authored-by: David Heinemeier Hansson <david@loudthinking.com>

* Improve ActionText::FixtureSet documentation (#41062)

* Improve ActionText::FixtureSet documentation

Support for Action Text attachments in fixtures was added by [76b33aa][] and
released as part of [6.1.1][], but has not yet been documented.

This commit documents the `ActionText::FixtureSet` for the API
documentation, and mentions it in the Rails Guides pages.

[76b33aa]: 76b33aa3d1
[6.1.1]: https://github.com/rails/rails/releases/tag/v6.1.1

* Fix indention of comments

Co-authored-by: David Heinemeier Hansson <david@loudthinking.com>

* Fix Flaky ActiveStorage test (#41225)

Fixes a flaky Active Storage test introduced by [rails/rails#41065][],
and improves the documentation.

It seems that the test is covering the backwards compatibility of an
older interface for retrieving records through
`ActiveStorage::Record#find_signed!`. The test itself would pass
unpredictably. To isolate the failure and reproduce it consistently, a
see value was found after some trial and error:

```
SEED=59729 bin/test test/fixture_set_test.rb test/models/attachment_test.rb
```

This _used_ to pass consistently because [rails/rails][#41065]
introduced a call to `fixtures :all`, which introduces more variation in
the database's ID generation sequence. Without that line, `id` values
start at `1`, so the fact that calls to
`ActiveStorage::Attached::One#id` and `ActiveStorage::Blob#id` **both
return `1`** is purely coincidence.

The proposed resolution changes the test slightly. Prior to this change,
the identifier used during retrieval and verification fetched from
`@user.avatar.id`, where `@user.avatar` is an instance of
`ActiveStorage::Attached::One`. The verifier/retriever combination in
that test expected a signed identifier for an `ActiveStorage::Blob`
instance. The change involved retrieving an instance through
`@user.avatar.blob`.

To better emphasize how global the `fixtures :all` declaration is, move
it from the `test/fixture_set_test.rb` file to the `test/test_helper.rb`
file.

[rails/rails#41065]: https://github.com/rails/rails/pull/41065

* Fix doc: stylesheet_include_tag -> stylesheet_link_tag

* Remove reference to globalize gem

* Fix typo [ci skip]

* Add small improvements to the Webpacker guide

- fix typos like double spaces, accidental caps
- improve some HTML links by giving them a label
- etc

* Fixing delegated types example.

* Allow jobs to rescue all exceptions

Before this commit, only StandardError exceptions can be handled by
rescue_from handlers.

This changes the rescue clause to catch all Exception objects, allowing
rescue handlers to be defined for Exception classes not inheriting from
StandardError.

This means that rescue handlers that are rescuing Exceptions outside of
StandardError exceptions may rescue exceptions that were not being
rescued before this change.

Co-authored-by: Adrianna Chang <adrianna.chang@shopify.com>

* Guides: Missing erb tags for stylesheet_pack_tag [ci skip]

The section on needing to use `stylesheet_pack_tag` was lacking the erb
%'s.

I updated the markdown to actually show the helper being used with erb
as well as improve the wording of the sentence.

* Guides: Remove unneeded statement about stylesheet_pack_tag [ci skip]

* Update test names to match their behaviour

These tests were names `…creation_failure…` but there's no creation
failing in the tests themselves. Instead creation is succeeding, via
the `create_association` method which is added by the `has_one` relation.

I found these test names very confusing when reading this issue:
https://github.com/rails/rails/issues/13197
And the commit it links to: c6e10b0

The least we can do to make that issue less confusing is to start by
fixing these test names.
[ci skip]

* Remove SET NAMES, set collation using variable

Fixes malformed packet error that occurred with MariaDB client
connecting to RDS Aurora (MySQL 5.7) database.

* Update test helper to call parallelize according to fork support

* Show a warning when running no migration using SCOPE

When running a migration with `ENV["SCOPE"]` set returns a warning
if no migrations ran.
The message serves as a hint for the end-user to make sure he knows
that the migration have been filtered by `SCOPE`.

* Move ActiveStorage fixture hooks to on_load

In a test environment, rely on the loading of
`:active_support_test_case`.

Introduce the `:active_record_fixture_set` hook for the Active Storage
engine to listen for during the load process in a development
environment (like when running `db:fixtures:load`).

Since this commit moves the task-aware path resolution out of the block
that provided local variables, it recreates part of the fixture
directory path resolution logic.

* Improve ActiveRecord strict_loading documentation

Apply the same structure as the documentation of `validate` option by
starting the description with "when set to true". This implies, that
the value passed to the option should be a boolean.

* Remove legacy media=screen default from stylesheet_link_tag.

If the media attribute is omitted, the default for web browsers is "all", meaning that by default links apply to all media.

Before:

```ruby
> stylesheet_link_tag "style"
=> <link href="/assets/style.css" media="screen" rel="stylesheet" />
```

After:

```ruby
> stylesheet_link_tag "style"
=> <link href="/assets/style.css" rel="stylesheet" />

```

The current behavior is not going to change for existing applications.

For newly built applications, the media attribute is not going to be added by default. Which can be configured using the following:

```
Rails.application.config.action_view.stylesheet_media_default = false
```

* Do not eagerly load Request before initializers

Without those changes the configurations to ActionDispatch::Request
could not be applied in initializers.

* Change Request#media_type to return nil

When the request don't have a Content-Type header we were returning
an empty string instead of nil like Rack does.

* `ActionDispatch::Request#content_type` now returned Content-Type header as it is

* Disable rubocop suggestions

* Fix typo in the CHANGELOG

* Add config.action_view.stylesheet_media_default to baseline config

* Rename the config to make clear it is a boolean

* Add CHANGELOG entry for #41215

* Fix CI failure due to `app.config.action_view.delete(:apply_apply_stylesheet_media_default)`

https://buildkite.com/rails/rails/builds/74429#3de35026-a6dc-4f4c-b885-9b59e0c89b96/979-1036

* Fix deprecation message s/Rails 6.1 will return/Rails 7.0 will return/

`return_only_media_type_on_content_type` will be introduced in Rails 6.2
so the changing of returning Content-Type will happen in a future
version of Rails (probably 7.0).

* Revert "Merge pull request #41192 from kamipo/dont_return_pools"

This reverts commit 9d8ff32372, reversing
changes made to 9cde02ef5f.

Need to revert this so I can revert another PR.

* Revert "Merge pull request #41046 from eileencodes/dont-check-if-qc-is-enabled"

This reverts commit c97f1f195f, reversing
changes made to ac7851eb58.

We haven't quite tracked down why yet, but this change caused our API to
not use the query cache. Our API is Sinatra mixed with Rails. We install
the Exectutor in our API so it was installed. However, (some?)
production requests were showing 0 query cache hits.

jhawthorn found that we likely need this check because if we don't the
pools returned will be a different set. He'll send a test later today.

* Ensure test rake commands run immediately

Before this commit, Rails test Rake tasks only load the test files, and
the tests only run in an at_exit hook via minitest/autorun.

This prevents conditionally running tasks only when tests pass, or even
more simply in the right order. As a simple example, if you have:

task default: [:test, :rubocop]

The rubocop task will run after the test task loads the test files but
before the tests actually run.

This commit changes the test Rake tasks to shell out to the test runner
as a new process.

This diverges from previous behavior because now, any changes made in
the Rakefile or other code loaded by Rake won't be available to the
child process. However this brings the behavior of `rake test` closer to
the behavior of `rails test`.

Co-authored-by: Adrianna Chang <adrianna.chang@shopify.com>

* Fix typo

Co-authored-by: Haroon Ahmed <haroon.ahmed25@gmail.com>
Co-authored-by: Jonathan Hefner <jonathan@hefner.pro>
Co-authored-by: Gannon McGibbon <gannon.mcgibbon@gmail.com>
Co-authored-by: Rafael Mendonça França <rafael@franca.dev>
Co-authored-by: John Hawthorn <john@hawthorn.email>
Co-authored-by: Dinah Shi <dinahshi@github.com>
Co-authored-by: Santiago Bartesaghi <santib@hey.com>
Co-authored-by: Mike Rogers <me@mikerogers.io>
Co-authored-by: Ryuta Kamizono <kamipo@gmail.com>
Co-authored-by: Ryan Bigg <me@ryanbigg.com>
Co-authored-by: Jacopo <beschi.jacopo@gmail.com>
Co-authored-by: Guillaume Briday <guillaumebriday@gmail.com>
Co-authored-by: benhayehudi <bengreenberg@gmail.com>
Co-authored-by: wout@mick-wout.com <Wout>
Co-authored-by: Ayrton De Craene <hello@ayrton.be>
Co-authored-by: eileencodes <eileencodes@gmail.com>
Co-authored-by: John Crepezzi <john.crepezzi@gmail.com>
Co-authored-by: Chris Salzberg <chris@dejimata.com>
Co-authored-by: Tim Tilberg <ttilberg@gmail.com>
Co-authored-by: alpaca-tc <alpaca-tc@alpaca.tc>
Co-authored-by: Alex Ghiculescu <alex@tanda.co>
Co-authored-by: Xavier Noria <fxn@hashref.com>
Co-authored-by: ijlee2 <ijlee2@users.noreply.github.com>
Co-authored-by: Jon Bracy <jonbracy@gmail.com>
Co-authored-by: Gustavo Gonzalez <gustavo@gonzalez.guru>
Co-authored-by: Marivaldo Cavalheiro <marivaldo@gmail.com>
Co-authored-by: Chris Houhoulis <chris@chrishouhoulis.com>
Co-authored-by: Daniel Colson <daniel.colson@hey.com>
Co-authored-by: Janko Marohnić <janko.marohnic@gmail.com>
Co-authored-by: Sean Doyle <seanpdoyle@users.noreply.github.com>
Co-authored-by: André Luis Leal Cardoso Junior <andrehjr@gmail.com>
Co-authored-by: Youssef Boulkaid <yboulkaid@gmail.com>
Co-authored-by: Orhan Toy <toyorhan@gmail.com>
Co-authored-by: David Stosik <david.stosik+git-noreply@gmail.com>
Co-authored-by: Andrew Culver <andrew.culver@gmail.com>
Co-authored-by: Étienne Barrié <etienne.barrie@gmail.com>
Co-authored-by: Adrianna Chang <adrianna.chang@shopify.com>
Co-authored-by: Tony Drake <t27duck@gmail.com>
Co-authored-by: Sam Jewell <sam@bridge-u.com>
Co-authored-by: Robin Roestenburg <robin.roestenburg@4me.com>
Co-authored-by: Brandon Fish <brandon.j.fish@oracle.com>
Co-authored-by: Sean Doyle <sean.p.doyle24@gmail.com>
Co-authored-by: Cecile Veneziani <contact@cecilitse.org>
Co-authored-by: st0012 <stan001212@gmail.com>
2021-02-04 12:26:16 +01:00
Ryuta Kamizono 9c70d24e11 Refactor `enum` to extract the defining part for each `definitions` 2021-02-04 12:29:19 +09:00
Rafael França da418dc250
Merge pull request #41217 from Vin0uz/active-model-errors-add-doc
[ci-skip] Adding options example in ActiveModel::Errors doc
2021-02-03 16:18:26 -05:00
Eileen M. Uchitelle 72651119dd
Merge pull request #41324 from eileencodes/fix-timestamp-type-for-sqlite3
Fix timestamp type for sqlite3
2021-02-03 16:17:32 -05:00
Kevin Vinhas da0e869bd8 Adding options example in ActiveModel::Errors doc
Place errors with variable example under the `type is a symbol` block
Closes #41124
2021-02-03 21:55:10 +01:00
eileencodes 02bcf8912b
Fix timestamp type for sqlite3
According to the tests and code, sqlite3 converts the `timestamp` type
from `timestamp` to `datetime.` This can be seen in the change schema
tests.

This caused behavior to differ from `add_column` and `change_column`
because `change_column` wasn't calling `aliased_types`. The change here
fixes `change_column` so that it calls `aliased_types` the same way
`add_column` does.

Fixes #41310
2021-02-03 15:26:37 -05:00
Kasper Timm Hansen d30dad4bc1
Merge pull request #40229 from jonathanhefner/actioncable-client-reconnect-jitter
Prevent thundering herd of Action Cable clients
2021-02-03 07:21:36 +01:00
Ryuta Kamizono 8f1d110271 Remove unused code in FakeRecord 2021-02-03 11:12:45 +09:00
Rafael França 5268006e70
Merge pull request #41315 from etiennebarrie/cleanup-skipped-tests
Remove skipped TestRunner tests
2021-02-02 19:22:46 -05:00
Rafael Mendonça França 9ea15f1927
Improve performance of time type cast for ISO dates
Before this patch we were appeding a new date in front of
an already existing date what was making the fast path of the
type cast to not trigger.

The following benchmark was used to drive this implementation:

https://gist.github.com/rafaelfranca/0f71c00613f924fcbcdb14b95e6f7661

Closes #41316.
2021-02-03 00:10:15 +00:00
Rafael França ad36ceffcb
Merge pull request #41318 from ghiculescu/consistent-camelize-v2
Handle Symbol arguments in `ActiveSupport::Inflector.camelize` (v2)
2021-02-02 18:13:23 -05:00
Alex Ghiculescu 0e0c81e092 Handle Symbol arguments in `ActiveSupport::Inflector.camelize` (v2)
Better implementation of https://github.com/rails/rails/pull/41313

Now, only `false` and `:lower` as args will return a downcased first character (before https://github.com/rails/rails/pull/41313 only `false` did). Everything else returns an upcased first character, which is the default.

Update activesupport/lib/active_support/inflector/methods.rb

Co-authored-by: Ryuta Kamizono <kamipo@gmail.com>
2021-02-02 16:11:28 -07:00
Étienne Barrié 7ceaa002d6 Remove skipped TestRunner tests
Co-authored-by: Adrianna Chang <adrianna.chang@shopify.com>
2021-02-02 16:07:50 -05:00
Rafael França 0fa44051c8
Merge pull request #41292 from intrip/41156-fix-mysql-virtual-column-with-escapes
Fix Mysql schema for virtual column expressions with quotes
2021-02-02 14:04:54 -05:00
Rafael França 657238163e
Merge pull request #41313 from ghiculescu/consistent-camelize
Handle Symbol arguments in `ActiveSupport::Inflector.camelize`
2021-02-02 13:56:05 -05:00
Alex Ghiculescu cd3eac1df3 Accept a Symbol argument in `ActiveSupport::Inflector.camelize`
This was raised on the discussion forum: https://discuss.rubyonrails.org/t/inconsistency-between-string-camelize-and-activesupportinflector-camelize

`String#camelize` takes a symbol (`:upper` or `:lower`) as an argument. But `ActiveSupport::Inflector.camelize` takes a bool. This can result in surprising behavior if you assume the methods are interchangeable, and call `ActiveSupport::Inflector.camelize('active_support', :lower)` (the `:lower` argument is truthy so the return value is upcased).

This PR changes `ActiveSupport::Inflector.camelize` to match `String#camelize` behavior. It will now return an upcased string if you provide `true` or `:upper` as an argument, otherwise it will be downcased.
2021-02-02 11:24:41 -07:00
Jonathan Hefner cc9a9e8503 Prevent thundering herd of Action Cable clients
This commit makes a few changes to the Action Cable client to prevent a
"thundering herd" of client reconnects after server connectivity loss:

* The client will wait a random amount between 1x and 3x of the stale
  threshold after the server's last ping before making the first
  reconnection attempt.
* Subsequent reconnection attempts now use exponential backoff instead
  of logarithmic backoff.  To allow the delay between reconnection
  attempts to increase slowly at first, the default exponentiation base
  is < 2.
* Random jitter is applied to each delay between reconnection attempts.

Co-authored-by: John Williams <john@veloshots.com>
2021-02-02 10:43:05 -06:00
Ryuta Kamizono 9604fe334e
Merge pull request #41293 from yahonda/ruby_4070
Address `warning: Passing only keyword arguments to Struct#initialize`
2021-02-02 22:28:01 +09:00
Yasuo Honda 40db515e91 Address `warning: Passing only keyword arguments`
This pull request addresses the following warnings enabled since ruby/ruby#4070

* Warnings without this fix 1

```
% ruby -v
ruby 3.1.0dev (2021-02-01T10:54:21Z master 1cdae49d39) [x86_64-darwin20]
% bin/test test/cases/arel/visitors/sqlite_test.rb:36
... snip ...
/Users/yahonda/src/github.com/rails/rails/activerecord/test/cases/arel/support/fake_record.rb:98: warning: Passing only keyword arguments to Struct#initialize will behave differently from Ruby 3.2. Please use a Hash literal like .new({k: v}) instead of .new(k: v).
.

Finished in 0.003538s, 2261.1645 runs/s, 2543.8101 assertions/s.
8 runs, 9 assertions, 0 failures, 0 errors, 0 skips
%
```

* Warnings without this fix 2

```ruby
% ruby -v
ruby 3.1.0dev (2021-02-01T10:54:21Z master 1cdae49d39) [x86_64-darwin20]
% bin/test test/cases/type/adapter_specific_registry_test.rb
Using sqlite3
Run options: --seed 53175

......./Users/yahonda/src/github.com/rails/rails/activerecord/test/cases/type/adapter_specific_registry_test.rb:126: warning: Passing only keyword arguments to Struct#initialize will behave differently from Ruby 3.2. Please use a Hash literal like .new({k: v}) instead of .new(k: v).
/Users/yahonda/src/github.com/rails/rails/activemodel/lib/active_model/type/registry.rb:18: warning: Passing only keyword arguments to Struct#initialize will behave differently from Ruby 3.2. Please use a Hash literal like .new({k: v}) instead of .new(k: v).
/Users/yahonda/src/github.com/rails/rails/activerecord/test/cases/type/adapter_specific_registry_test.rb:130: warning: Passing only keyword arguments to Struct#initialize will behave differently from Ruby 3.2. Please use a Hash literal like .new({k: v}) instead of .new(k: v).
/Users/yahonda/src/github.com/rails/rails/activemodel/lib/active_model/type/registry.rb:18: warning: Passing only keyword arguments to Struct#initialize will behave differently from Ruby 3.2. Please use a Hash literal like .new({k: v}) instead of .new(k: v).
.../Users/yahonda/src/github.com/rails/rails/activerecord/test/cases/type/adapter_specific_registry_test.rb:85: warning: Passing only keyword arguments to Struct#initialize will behave differently from Ruby 3.2. Please use a Hash literal like .new({k: v}) instead of .new(k: v).
/Users/yahonda/src/github.com/rails/rails/activemodel/lib/active_model/type/registry.rb:18: warning: Passing only keyword arguments to Struct#initialize will behave differently from Ruby 3.2. Please use a Hash literal like .new({k: v}) instead of .new(k: v).
/Users/yahonda/src/github.com/rails/rails/activerecord/test/cases/type/adapter_specific_registry_test.rb:86: warning: Passing only keyword arguments to Struct#initialize will behave differently from Ruby 3.2. Please use a Hash literal like .new({k: v}) instead of .new(k: v).
/Users/yahonda/src/github.com/rails/rails/activemodel/lib/active_model/type/registry.rb:18: warning: Passing only keyword arguments to Struct#initialize will behave differently from Ruby 3.2. Please use a Hash literal like .new({k: v}) instead of .new(k: v).
.

Finished in 0.011424s, 962.8852 runs/s, 2450.9804 assertions/s.
11 runs, 28 assertions, 0 failures, 0 errors, 0 skips
%
```

* Warnings without this fix 3

```ruby
$ cd actionview
$ bin/test test/template/url_helper_test.rb
Run options: --seed 27105

........................../home/yahonda/src/github.com/rails/rails/actionview/test/template/url_helper_test.rb:88: warning: Passing only keyword arguments to Struct#initialize will behave differently from Ruby 3.2. Please use a Hash literal like .new({k: v}) instead of .new(k: v).
.............................../home/yahonda/src/github.com/rails/rails/actionview/test/template/url_helper_test.rb:94: warning: Passing only keyword arguments to Struct#initialize will behave differently from Ruby 3.2. Please use a Hash literal like .new({k: v}) instead of .new(k: v).
..................................................../home/yahonda/src/github.com/rails/rails/actionview/test/template/url_helper_test.rb:71: warning: Passing only keyword arguments to Struct#initialize will behave differently from Ruby 3.2. Please use a Hash literal like .new({k: v}) instead of .new(k: v).
......................

Finished in 0.305066s, 429.4159 runs/s, 580.2032 assertions/s.
131 runs, 177 assertions, 0 failures, 0 errors, 0 skips
$
```

Refer:
ruby/ruby#4070
https://bugs.ruby-lang.org/issues/16806

Co-authored-by: Ryuta Kamizono <kamipo@gmail.com>
2021-02-02 21:59:08 +09:00
Ryuta Kamizono 4b13727aea
Merge pull request #41306 from PChambino/active-job-test-helper-assertions
Add missing require to ActiveJob::TestHelper
2021-02-02 21:13:45 +09:00
Kasper Timm Hansen a2a5385b89
Merge pull request #41303 from Shopify/underscore-allocations
Optimize underscore inflector
2021-02-02 13:05:23 +01:00
Kasper Timm Hansen f43e701692
Merge pull request #41305 from Shopify/optimize-humanize
Optimize humanize inflector
2021-02-02 13:03:34 +01:00
Pedro Chambino d318af93c5
Add missing require to ActiveJob::TestHelper
Following PR #40780, it now fails after requiring active_job:

    irb(main):001:0> require 'active_job'
    => true
    irb(main):002:0> ActiveJob::VERSION::STRING
    => "6.1.1"
    irb(main):003:0> ActiveJob::TestHelper
    [redacted]
    NameError (uninitialized constant ActiveSupport::Testing)
2021-02-02 11:50:54 +00:00
Ryuta Kamizono a70680bb07
Merge pull request #41304 from yahonda/follow_up_84055130713
Address `Rails 7.0 will return Content-Type header without modification`
2021-02-02 20:44:29 +09:00
Yasuo Honda 51931f0bde Address `Rails 7.0 will return Content-Type header without modification`
This pull request addresses these warnings.

```ruby
$ cd actionmailbox
$ bin/test test/controllers/ingresses/relay/inbound_emails_controller_test.rb
Run options: --seed 32561

DEPRECATION WARNING: Rails 7.0 will return Content-Type header without modification. If you want just the MIME type, please use `#media_type` instead. (called from call at /home/yahonda/.rbenv/versions/3.0.0/lib/ruby/gems/3.0.0/gems/rack-2.2.3/lib/rack/tempfile_reaper.rb:15)
...DEPRECATION WARNING: Rails 7.0 will return Content-Type header without modification. If you want just the MIME type, please use `#media_type` instead. (called from call at /home/yahonda/.rbenv/versions/3.0.0/lib/ruby/gems/3.0.0/gems/rack-2.2.3/lib/rack/tempfile_reaper.rb:15)
..

Finished in 0.114883s, 43.5224 runs/s, 87.0447 assertions/s.
5 runs, 10 assertions, 0 failures, 0 errors, 0 skips
$
```

Follow-up https://github.com/rails/rails/commit/84055130713
related to https://github.com/rails/rails/pull/41251
2021-02-02 20:18:03 +09:00
Jean Boussier 8e0f88d558 Optimize humanize inflector
There a mixed bag of small optimizations here:

  - Since underscores are converted to spaces and that we remove all leading underscores. By changing the order of operations we can leverage the faster `.lstrip!`.
  - Corrected the gsub regexp to no longer match empty strings (`+` vs `*`).
  - Modify the matched strings in place to save on allocations

```ruby
require 'benchmark/ips'
require 'active_support/all'

module ActiveSupport
  module Inflector
    def humanize2(lower_case_and_underscored_word, capitalize: true, keep_id_suffix: false)
      result = lower_case_and_underscored_word.to_s.dup

      inflections.humans.each { |(rule, replacement)| break if result.sub!(rule, replacement) }

      result.tr!("_", " ")
      result.lstrip!
      unless keep_id_suffix
        result.delete_suffix!(" id")
      end

      result.gsub!(/([a-z\d]+)/i) do |match|
        match.downcase!
        inflections.acronyms[match] || match
      end

      if capitalize
        result.sub!(/\A\w/) do |match|
          match.upcase!
          match
        end
      end

      result
    end
  end
end

%w(foo foo_bar_id ____foo_bar).each do |str|
  puts "== Comparing with #{str.inspect} (#{RUBY_VERSION}) =="
  unless ActiveSupport::Inflector.humanize(str) == ActiveSupport::Inflector.humanize2(str)
    raise "#{ActiveSupport::Inflector.humanize2(str)} != #{ActiveSupport::Inflector.humanize(str)}"
  end

  Benchmark.ips do |x|
    x.report('humanize') { ActiveSupport::Inflector.humanize(str) }
    x.report('humanize2') { ActiveSupport::Inflector.humanize2(str) }
    x.compare!
  end
  puts
end
```

```
== Comparing with "foo" (2.7.2) ==
Warming up --------------------------------------
            humanize    25.593k i/100ms
           humanize2    29.256k i/100ms
Calculating -------------------------------------
            humanize    263.989k (± 1.9%) i/s -      1.331M in   5.043110s
           humanize2    299.883k (± 2.2%) i/s -      1.521M in   5.075478s

Comparison:
           humanize2:   299882.5 i/s
            humanize:   263989.1 i/s - 1.14x  (± 0.00) slower

== Comparing with "foo_bar_id" (2.7.2) ==
Warming up --------------------------------------
            humanize    18.187k i/100ms
           humanize2    25.678k i/100ms
Calculating -------------------------------------
            humanize    183.702k (± 1.5%) i/s -    927.537k in   5.050326s
           humanize2    250.470k (± 2.5%) i/s -      1.258M in   5.026682s

Comparison:
           humanize2:   250469.6 i/s
            humanize:   183702.3 i/s - 1.36x  (± 0.00) slower

== Comparing with "____foo_bar" (2.7.2) ==
Warming up --------------------------------------
            humanize    18.577k i/100ms
           humanize2    24.686k i/100ms
Calculating -------------------------------------
            humanize    188.868k (± 1.5%) i/s -    947.427k in   5.017524s
           humanize2    255.650k (± 1.8%) i/s -      1.284M in   5.022833s

Comparison:
           humanize2:   255649.8 i/s
```
2021-02-02 12:16:16 +01:00
Jean Boussier 58147cd2b4 Optimize underscore inflector
```ruby
require 'benchmark/ips'
require 'active_support/all'

ActiveSupport::Inflector.inflections do |inflect|
    inflect.acronym('RESTful')
end

module ActiveSupport
  module Inflector
    def underscore2(camel_cased_word)
      return camel_cased_word unless /[A-Z-]|::/.match?(camel_cased_word)
      word = camel_cased_word.to_s.gsub("::", "/")
      word.gsub!(inflections.acronyms_underscore_regex) { "#{$1 && '_' }#{$2.downcase}" }
      word.gsub!(/([A-Z\d]+)([A-Z][a-z])|([a-z\d])([A-Z])/) do
        if first_match = $1
          first_match << '_' << $2
        else
          $3 << '_' << $4
        end
      end
      word.tr!("-", "_")
      word.downcase!
      word
    end
  end
end

%w(RESTfulController Foo FooBar Foo::BarBaz FOOBar::EggSpam).each do |str|
  puts "== Comparing with #{str.inspect} (#{RUBY_VERSION}) =="
  unless ActiveSupport::Inflector.underscore(str) == ActiveSupport::Inflector.underscore2(str)
    raise "#{ActiveSupport::Inflector.underscore2(str)} != #{ActiveSupport::Inflector.underscore(str)}"
  end

  Benchmark.ips do |x|
    x.report('underscore') { ActiveSupport::Inflector.underscore(str) }
    x.report('underscore2') { ActiveSupport::Inflector.underscore2(str) }
    x.compare!
  end
  puts
end
```

```
== Comparing with "RESTfulController" (2.7.2) ==
Warming up --------------------------------------
          underscore    16.527k i/100ms
         underscore2    16.118k i/100ms
Calculating -------------------------------------
          underscore    165.223k (± 0.9%) i/s -    826.350k in   5.001882s
         underscore2    163.251k (± 0.9%) i/s -    822.018k in   5.035736s

Comparison:
          underscore:   165222.7 i/s
         underscore2:   163250.9 i/s - same-ish: difference falls within error

== Comparing with "Foo" (2.7.2) ==
Warming up --------------------------------------
          underscore    66.965k i/100ms
         underscore2    72.961k i/100ms
Calculating -------------------------------------
          underscore    669.221k (± 0.8%) i/s -      3.348M in   5.003557s
         underscore2    729.815k (± 1.1%) i/s -      3.721M in   5.099188s

Comparison:
         underscore2:   729815.0 i/s
          underscore:   669221.3 i/s - 1.09x  (± 0.00) slower

== Comparing with "FooBar" (2.7.2) ==
Warming up --------------------------------------
          underscore    26.869k i/100ms
         underscore2    26.446k i/100ms
Calculating -------------------------------------
          underscore    268.071k (± 0.7%) i/s -      1.343M in   5.011813s
         underscore2    264.400k (± 0.6%) i/s -      1.322M in   5.001317s

Comparison:
          underscore:   268071.4 i/s
         underscore2:   264400.1 i/s - 1.01x  (± 0.00) slower

== Comparing with "Foo::BarBaz" (2.7.2) ==
Warming up --------------------------------------
          underscore    20.611k i/100ms
         underscore2    20.609k i/100ms
Calculating -------------------------------------
          underscore    205.671k (± 1.3%) i/s -      1.031M in   5.011478s
         underscore2    204.304k (± 1.2%) i/s -      1.030M in   5.044446s

Comparison:
          underscore:   205670.8 i/s
         underscore2:   204304.1 i/s - same-ish: difference falls within error

== Comparing with "FOOBar::EggSpam" (2.7.2) ==
Warming up --------------------------------------
          underscore    15.348k i/100ms
         underscore2    18.932k i/100ms
Calculating -------------------------------------
          underscore    154.686k (± 0.9%) i/s -    782.748k in   5.060656s
         underscore2    188.706k (± 0.8%) i/s -    946.600k in   5.016580s

Comparison:
         underscore2:   188705.6 i/s
          underscore:   154685.7 i/s - 1.22x  (± 0.00) slower
```
2021-02-02 11:46:46 +01:00
Jacopo 3fe5e26dae Fix Mysql schema for virtual column expressions with quotes
Mysql automatically escapes quotes in generated columns expressions.
This leads into the generation of a double escape sequence when
using .inspect on the SQL result.
In order to fix this we remove the escape sequence from the SQL result.

Fixes #41156
2021-02-02 11:00:24 +01:00
Ryuta Kamizono beed933b9b
Merge pull request #41302 from kamipo/should_not_require_connection
`attribute` should not require a connection is established
2021-02-02 15:56:46 +09:00
Ryuta Kamizono 6d291aaa02 `attribute` should not require a connection is established
#41166 made `attribute` require a connection due to calling
`ActiveRecord::Type.adapter_name_from` immediately.

This fixes `adapter_name_from` to get the adapter name from the
connection db config to not retrieve a connection.
2021-02-02 15:04:23 +09:00
Ryuta Kamizono 24416e5df4 Fix enum predicate methods on object enum keys
Follow up #41278 to fix #41118.
2021-02-02 12:46:19 +09:00
Rafael França 56bcb839c4
Merge pull request #40927 from islue/skip-logging-rescuable-exceptions
Skip logging rescuable exceptions
2021-02-01 22:20:19 -05:00
Rafael Mendonça França bea721aa91
Merge remote-tracking branch 'origin/main' into skip-logging-rescuable-exceptions 2021-02-02 01:09:06 +00:00
Rafael Mendonça França efa64bb295
Refactor the code to keep instrumentation and log inside the modules
Use inheritance to keep the behavior in the right modules.

The order of Instrumentation and Logging had to change to be
flipped to keep the current behavior.
2021-02-02 01:07:24 +00:00
Rafael Mendonça França 739622b7d7
Merge PR #41218 branch 'add-strict-loading-doc' into main 2021-02-02 00:18:08 +00:00
Rafael França a04b301522
Merge pull request #41093 from gwincr11/action-job-transactions
Make destroy async transactional
2021-02-01 19:11:26 -05:00
Rafael França e5c1ba23f5
Merge pull request #41300 from CodingAnarchy/pg-adapter-fix
Pass binds on PostgreSQL exec_query even when prepared statements off globally
2021-02-01 19:09:35 -05:00
Matt Tanous 724b733c45 Pass binds through on PostgreSQL exec_query even when prepared statements are off globally 2021-02-01 18:30:14 -05:00
Rafael Mendonça França 48a7760823
Refactoring the code to not add methods to all models
Only models that need to use the `:destroy_async` feature
need those methods so it is better to not add to all models.
2021-02-01 23:26:04 +00:00
Rafael França fc96b3bf3e
Merge pull request #41298 from etiennebarrie/remove-setting-rails-env-at-require-time
Stop setting RAILS_ENV when test_unit railtie is loaded
2021-02-01 17:09:32 -05:00
Étienne Barrié da740d63b2 Stop setting RAILS_ENV when test_unit railtie is loaded
Because the TestUnit::Runner is used to run the tests from Rake test
tasks, we don't need to set the Rails environment based on the name of
the task anymore.

Co-authored-by: Adrianna Chang <adrianna.chang@shopify.com>
2021-02-01 16:00:05 -05:00
Kasper Timm Hansen 25028adae8
Merge pull request #41296 from Shopify/optimize-camelize
Reduce allocations in camelize inflector
2021-02-01 19:48:10 +01:00
Jean Boussier 73bc476cd0 Reduce allocations in camelize inflector
This method is the 4th biggest source of allocation during our application
boot (~300k allocations).

The goal of this PR was mostly to reduce allocations, but it also translate
to a 5-17% speedup.

The main change is leveraging `capitalize!` rather than `capitalize`.

The second important change is to merge the two `gsub!` together.

```ruby
require 'benchmark/ips'
require 'active_support/all'

module ActiveSupport
  module Inflector
    def camelize2(term, uppercase_first_letter = true)
      string = term.to_s
      if uppercase_first_letter
        string = string.sub(/^[a-z\d]*/) { |match| inflections.acronyms[match] || match.capitalize! || match }
      else
        string = string.sub(inflections.acronyms_camelize_regex) { |match| match.downcase! || match }
      end
      string.gsub!(/(?:_|(\/))([a-z\d]*)/i) do
        if $1
          "::#{inflections.acronyms[$2] || $2.capitalize! || $2}"
        else
          inflections.acronyms[$2] || $2.capitalize! || $2
        end
      end
      string
    end
  end
end

%w(foo foo_bar foo/bar_baz).each do |str|
  puts "== Comparing with #{str.inspect} (#{RUBY_VERSION}) =="
  Benchmark.ips do |x|
    x.report('camelize') { ActiveSupport::Inflector.camelize(str) }
    x.report('camelize2') { ActiveSupport::Inflector.camelize2(str) }
    x.compare!
  end
  puts
end
```

Results
```
== Comparing with "foo" (2.7.2) ==
Warming up --------------------------------------
            camelize    53.646k i/100ms
           camelize2    56.797k i/100ms
Calculating -------------------------------------
            camelize    532.012k (± 1.3%) i/s -      2.682M in   5.042620s
           camelize2    567.317k (± 1.3%) i/s -      2.840M in   5.006633s

Comparison:
           camelize2:   567317.4 i/s
            camelize:   532012.3 i/s - 1.07x  (± 0.00) slower

== Comparing with "foo_bar" (2.7.2) ==
Warming up --------------------------------------
            camelize    24.010k i/100ms
           camelize2    25.398k i/100ms
Calculating -------------------------------------
            camelize    239.036k (± 1.1%) i/s -      1.200M in   5.022811s
           camelize2    254.229k (± 1.3%) i/s -      1.295M in   5.095855s

Comparison:
           camelize2:   254228.8 i/s
            camelize:   239036.4 i/s - 1.06x  (± 0.00) slower

== Comparing with "foo/bar_baz" (2.7.2) ==
Warming up --------------------------------------
            camelize    17.116k i/100ms
           camelize2    19.628k i/100ms
Calculating -------------------------------------
            camelize    169.210k (± 1.0%) i/s -    855.800k in   5.058138s
           camelize2    199.385k (± 2.1%) i/s -      1.001M in   5.022935s

Comparison:
           camelize2:   199384.7 i/s
            camelize:   169210.0 i/s - 1.18x  (± 0.00) slower
```
2021-02-01 18:38:17 +01:00
Ryuta Kamizono e8d7181ad6
Merge pull request #41280 from kentakag/fix-raw-params-method-to-not-raise-an-exception
Fix raw params method to not raise an exception

Fixes #41279.
2021-02-01 22:35:54 +09:00
kentakag d7516f471a Fix exception in raw_params method
Prevent the raw_params method from throwing an exception
if the argument auth is blank.

Add tests for the raw_params method

Fix typo

Fix rubocop offenses
2021-02-01 16:22:42 +09:00