Usage
You need to tell RuboCop to load the Rails extension. There are three ways to do this:
RuboCop configuration file
Put this into your .rubocop.yml
.
require: rubocop-rails
Now you can run rubocop
and it will automatically load the RuboCop Rails
cops together with the standard cops.
Rails configuration tip
In Rails 6.1+, add the following config.generators.after_generate
setting to
your config/environments/development.rb
to apply RuboCop autocorrection to code generated by bin/rails g
.
# config/environments/development.rb
Rails.application.configure do
config.generators.after_generate do |files|
parsable_files = files.filter { |file| file.end_with?('.rb') }
unless parsable_files.empty?
system("bundle exec rubocop -A --fail-level=E #{parsable_files.shelljoin}", exception: true)
end
end
end
It uses rubocop -A
to apply Style/FrozenStringLiteralComment
and other unsafe autocorrection cops.
rubocop -A
is unsafe autocorrection, but code generated by default is simple and less likely to
be incompatible with rubocop -A
. If you have problems you can replace it with rubocop -a
instead.
In Rails 7.2+, it is recommended to use config.generators.apply_rubocop_autocorrect_after_generate!
instead of the above setting:
# config/environments/development.rb
Rails.application.configure do
(snip)
# Apply autocorrection by RuboCop to files generated by `bin/rails generate`.
- # config.generators.apply_rubocop_autocorrect_after_generate!
+ config.generators.apply_rubocop_autocorrect_after_generate!
end
You only need to uncomment.