Skip to content

Commit

Permalink
Apply autocorrection by RuboCop to files generated by `bin/rails gene…
Browse files Browse the repository at this point in the history
…rate`

## Motivation / Background

RuboCop has now been included by default (rails#50456).
By adding the following tip to the default configuration, user can apply RuboCop's autocorrection to
code generated by `bin/rails generate` (e.g., migration file):

https://github.com/rubocop/rubocop-rails#rails-configuration-tip

This means that the generated files will be formatted according to user's .rubocop.yml custom configuration.

## Detail

Since `bin/rails generate` and `bin/rubocop` are used only in the development environment,
the target files are limited to only `config/environments/development.rb`.

## Additional information

This feature was introduced in Rails 6.1 by rails#38870.
  • Loading branch information
koic committed Dec 31, 2023
1 parent cbd8bd7 commit 85c1ca9
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,14 @@ Rails.application.configure do
<%- end -%>
# Raise error when a before_action's only/except options reference missing actions
config.action_controller.raise_on_missing_callback_actions = true
<%- unless skip_rubocop? -%>

config.generators.after_generate do |files|
# Apply autocorrection by RuboCop to files generated by `bin/rails generate`.
parsable_files = files.filter { |file| file.end_with?(".rb") }
unless parsable_files.empty?
system("bin/rubocop -A --fail-level=E #{parsable_files.shelljoin}", exception: true)
end
end
<%- end -%>
end
4 changes: 4 additions & 0 deletions railties/test/generators/app_generator_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -628,6 +628,7 @@ def test_inclusion_of_a_debugger
def test_inclusion_of_rubocop
run_generator
assert_gem "rubocop-rails-omakase"
assert_file "config/environments/development.rb", %r|# Apply autocorrection by RuboCop to files generated by `bin/rails generate`\.|
end

def test_rubocop_is_skipped_if_required
Expand All @@ -636,6 +637,9 @@ def test_rubocop_is_skipped_if_required
assert_no_gem "rubocop"
assert_no_file "bin/rubocop"
assert_no_file ".rubocop.yml"
assert_file "config/environments/development.rb" do |content|
assert_no_match(%r|# Apply autocorrection by RuboCop to files generated by `bin/rails generate`\.|, content)
end
end

def test_usage_read_from_file
Expand Down

0 comments on commit 85c1ca9

Please sign in to comment.