You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This cop looks for belongs_to associations where we control whether the
association is required via the deprecated required option instead.
Since Rails 5, belongs_to associations are required by default and this
can be controlled through the use of optional: true.
From the release notes:
belongs_to will now trigger a validation error by default if the
association is not present. You can turn this off on a
per-association basis with optional: true. Also deprecate required
option in favor of optional for belongs_to. (Pull Request)
In the case that the developer is doing required: false, we
definitely want to autocorrect to optional: true.
However, without knowing whether they've set overridden the default
value of config.active_record.belongs_to_required_by_default, we
can't say whether it's safe to remove required: true or whether we
should replace it with optional: false (or, similarly, remove a
superfluous optional: false). Therefore, in the cases we're using
required: true, we'll simply invert it to optional: false and the
user can remove depending on their defaults.
This cop checks for code that can be written with simpler conditionals
using Object#blank? defined by Active Support.
Interaction with Style/UnlessElse:
The configuration of NotPresent will not produce an offense in the
context of unless else if Style/UnlessElse is inabled. This is
to prevent interference between the auto-correction of the two cops.
Examples
NilOrEmpty: true (default)
# Converts usages of `nil? || empty?` to `blank?`# badfoo.nil? || foo.empty?foo == nil || foo.empty?# goodfoo.blank?
NotPresent: true (default)
# Converts usages of `!present?` to `blank?`# bad
!foo.present?# goodfoo.blank?
UnlessPresent: true (default)
# Converts usages of `unless present?` to `if blank?`# badsomethingunlessfoo.present?# goodsomethingiffoo.blank?# badunlessfoo.present?somethingend# goodiffoo.blank?somethingend# gooddefblank?
!present?end
Configurable attributes
Name
Default value
Configurable values
NilOrEmpty
true
Boolean
NotPresent
true
Boolean
UnlessPresent
true
Boolean
Rails/BulkChangeTable
Enabled by default
Safe
Supports autocorrection
VersionAdded
VersionChanged
Enabled
Yes
No
0.57
-
This Cop checks whether alter queries are combinable.
If combinable queries are detected, it suggests to you
to use change_table with bulk: true instead.
This option causes the migration to generate a single
ALTER TABLE statement combining multiple column alterations.
The bulk option is only supported on the MySQL and
the PostgreSQL (5.2 later) adapter; thus it will
automatically detect an adapter from development environment
in config/database.yml when the Database option is not set.
If the adapter is not mysql2 or postgresql,
this Cop ignores offenses.
Examples
# baddefchangeadd_column:users,:name,:string,null: falseadd_column:users,:nickname,:string# ALTER TABLE `users` ADD `name` varchar(255) NOT NULL# ALTER TABLE `users` ADD `nickname` varchar(255)end# gooddefchangechange_table:users,bulk: truedo |t|
t.string:name,null: falset.string:nicknameend# ALTER TABLE `users` ADD `name` varchar(255) NOT NULL,# ADD `nickname` varchar(255)end
# baddefchangechange_table:usersdo |t|
t.string:name,null: falset.string:nicknameendend# gooddefchangechange_table:users,bulk: truedo |t|
t.string:name,null: falset.string:nicknameendend# good# When you don't want to combine alter queries.defchangechange_table:users,bulk: falsedo |t|
t.string:name,null: falset.string:nicknameendend
Configurable attributes
Name
Default value
Configurable values
Database
<none>
mysql, postgresql
Include
db/migrate/*.rb
Array
Rails/CreateTableWithTimestamps
Enabled by default
Safe
Supports autocorrection
VersionAdded
VersionChanged
Enabled
Yes
No
0.52
-
This cop checks the migration for which timestamps are not included
when creating a new table.
In many cases, timestamps are useful information and should be added.
This cop checks for the correct use of Date methods,
such as Date.today, Date.current etc.
Using Date.today is dangerous, because it doesn't know anything about
Rails time zone. You must use Time.zone.today instead.
The cop also reports warnings when you are using to_time method,
because it doesn't know about Rails time zone either.
Two styles are supported for this cop. When EnforcedStyle is 'strict'
then the Date methods today, current, yesterday, and tomorrow
are prohibited and the usage of both to_time
and 'to_time_in_current_zone' are reported as warning.
When EnforcedStyle is 'flexible' then only Date.today is prohibited
and only to_time is reported as warning.
This cop looks for delegations that could have been created
automatically with the delegate method.
Safe navigation &. is ignored because Rails' allow_nil
option checks not just for nil but also delegates if nil
responds to the delegated method.
The EnforceForPrefixed option (defaulted to true) means that
using the target object as a prefix of the method name
without using the delegate method will be a violation.
When set to false, this case is legal.
This cop looks for delegations that pass :allow_blank as an option
instead of :allow_nil. :allow_blank is not a valid option to pass
to ActiveSupport#delegate.
This cop looks for enums written with array syntax.
When using array syntax, adding an element in a
position other than the last causes all previous
definitions to shift. Explicitly specifying the
value for each key prevents this from happening.
This cop enforces that exit calls are not used within a rails app.
Valid options are instead to raise an error, break, return, or some
other form of stopping execution of current request.
There are two obvious cases where exit is particularly harmful:
Usage in library code for your application. Even though Rails will
rescue from a SystemExit and continue on, unit testing that library
code will result in specs exiting (potentially silently if exit(0)
is used.)
Usage in application code outside of the web process could result in
the program exiting, which could result in the code failing to run and
do its job.
Examples
# badexit(0)# goodraise'a bad error has happened'
Configurable attributes
Name
Default value
Configurable values
Include
app/**/*.rb, config/**/*.rb, lib/**/*.rb
Array
Exclude
lib/**/*.rake
Array
Rails/FilePath
Enabled by default
Safe
Supports autocorrection
VersionAdded
VersionChanged
Enabled
Yes
No
0.47
0.57
This cop is used to identify usages of file path joining process
to use Rails.root.join clause. It is used to add uniformity when
joining paths.
This cop looks for has_many or has_one associations that don't
specify a :dependent option.
It doesn't register an offense if :through option was specified.
This cop checks for use of the helper methods which reference
instance variables.
Relying on instance variables makes it difficult to re-use helper
methods.
If it seems awkward to explicitly pass in each dependent
variable, consider moving the behaviour elsewhere, for
example to a model, decorator or presenter.
This cop is used to identify usages of http methods like get, post,
put, patch without the usage of keyword arguments in your tests and
change them to use keyword args. This cop only applies to Rails >= 5.
If you are running Rails < 5 you should disable the
Rails/HttpPositionalArguments cop or set your TargetRailsVersion in your
.rubocop.yml file to 4.0, etc.
This cop looks for has_(one|many) and belongs_to associations where
Active Record can't automatically determine the inverse association
because of a scope or the options used. Using the blog with order scope
example below, traversing the a Blog's association in both directions
with blog.posts.first.blog would cause the blog to be loaded from
the database twice.
:inverse_of must be manually specified for Active Record to use the
associated object in memory, or set to false to opt-out. Note that
setting nil does not stop Active Record from trying to determine the
inverse automatically, and is not considered a valid value for this.
# bad# However, RuboCop can not detect this pattern...classPhysician < ApplicationRecordhas_many:appointmentshas_many:patients,through: :appointmentsendclassAppointment < ApplicationRecordbelongs_to:physicianbelongs_to:patientendclassPatient < ApplicationRecordhas_many:appointmentshas_many:physicians,through: :appointmentsend# goodclassPhysician < ApplicationRecordhas_many:appointmentshas_many:patients,through: :appointmentsendclassAppointment < ApplicationRecordbelongs_to:physician,inverse_of: :appointmentsbelongs_to:patient,inverse_of: :appointmentsendclassPatient < ApplicationRecordhas_many:appointmentshas_many:physicians,through: :appointmentsend
Configurable attributes
Name
Default value
Configurable values
Include
app/models/**/*.rb
Array
Rails/LexicallyScopedActionFilter
Enabled by default
Safe
Supports autocorrection
VersionAdded
VersionChanged
Enabled
No
No
0.52
-
This cop checks that methods specified in the filter's only or
except options are defined within the same class or module.
You can technically specify methods of superclass or methods added by
mixins on the filter, but these can confuse developers. If you specify
methods that are defined in other classes or modules, you should
define the filter in that class or module.
If you rely on behaviour defined in the superclass actions, you must
remember to invoke super in the subclass actions.
classContentController < ApplicationControllerdefupdate@content.update(content_attributes)endendclassArticlesController < ContentControllerbefore_action:load_article,only: [:update]# the cop requires this method, but it relies on behaviour defined# in the superclass, so needs to invoke `super`defupdatesuperendprivatedefload_article@content=Article.find(params[:article_id])endend
This cop checks for calls to link_to that contain a
target: '_blank' but no rel: 'noopener'. This can be a security
risk as the loaded page will have control over the previous page
and could change its location for phishing purposes.
The option rel: 'noreferrer' also blocks this behavior
and removes the http-referrer header.
This cop checks for the use of output safety calls like html_safe,
raw, and safe_concat. These methods do not escape content. They
simply return a SafeBuffer containing the content as is. Instead,
use safe_join to join content and escape it and concat to
concatenate content and escape it, ensuring its safety.
Examples
user_content="<b>hi</b>"# bad"<p>#{user_content}</p>".html_safe# => ActiveSupport::SafeBuffer "<p><b>hi</b></p>"# goodcontent_tag(:p,user_content)# => ActiveSupport::SafeBuffer "<p><b>hi</b></p>"# badout=""out << "<li>#{user_content}</li>"out << "<li>#{user_content}</li>"out.html_safe# => ActiveSupport::SafeBuffer "<li><b>hi</b></li><li><b>hi</b></li>"# goodout=[]out << content_tag(:li,user_content)out << content_tag(:li,user_content)safe_join(out)# => ActiveSupport::SafeBuffer# "<li><b>hi</b></li><li><b>hi</b></li>"# badout="<h1>trusted content</h1>".html_safeout.safe_concat(user_content)# => ActiveSupport::SafeBuffer "<h1>trusted_content</h1><b>hi</b>"# goodout="<h1>trusted content</h1>".html_safeout.concat(user_content)# => ActiveSupport::SafeBuffer# "<h1>trusted_content</h1><b>hi</b>"# safe, though maybe not good styleout="trusted content"result=out.concat(user_content)# => String "trusted content<b>hi</b>"# because when rendered in ERB the String will be escaped:# <%= result %># => trusted content<b>hi</b># bad(user_content + " " + content_tag(:span,user_content)).html_safe# => ActiveSupport::SafeBuffer "<b>hi</b> <span><b>hi</b></span>"# goodsafe_join([user_content," ",content_tag(:span,user_content)])# => ActiveSupport::SafeBuffer# "<b>hi</b> <span><b>hi</b></span>"
Rails/PluralizationGrammar
Enabled by default
Safe
Supports autocorrection
VersionAdded
VersionChanged
Enabled
Yes
Yes
0.35
-
This cop checks for correct grammar when using ActiveSupport's
core extensions to the numeric classes.
This cop checks code that can be written more easily using
Object#presence defined by Active Support.
Examples
# bada.present? ? a : nil# bad
!a.present? ? nil : a# bada.blank? ? nil : a# bad
!a.blank? ? a : nil# gooda.presence
# bada.present? ? a : b# bad
!a.present? ? b : a# bada.blank? ? b : a# bad
!a.blank? ? a : b# gooda.presence || b
Rails/Present
Enabled by default
Safe
Supports autocorrection
VersionAdded
VersionChanged
Enabled
Yes
Yes
0.48
0.67
This cop checks for code that can be written with simpler conditionals
using Object#present? defined by Active Support.
Interaction with Style/UnlessElse:
The configuration of NotBlank will not produce an offense in the
context of unless else if Style/UnlessElse is inabled. This is
to prevent interference between the auto-correction of the two cops.
Examples
NotNilAndNotEmpty: true (default)
# Converts usages of `!nil? && !empty?` to `present?`# bad
!foo.nil? && !foo.empty?# badfoo != nil && !foo.empty?# goodfoo.present?
NotBlank: true (default)
# Converts usages of `!blank?` to `present?`# bad
!foo.blank?# bad
not foo.blank?# goodfoo.present?
UnlessBlank: true (default)
# Converts usages of `unless blank?` to `if present?`# badsomethingunlessfoo.blank?# goodsomethingiffoo.present?
Configurable attributes
Name
Default value
Configurable values
NotNilAndNotEmpty
true
Boolean
NotBlank
true
Boolean
UnlessBlank
true
Boolean
Rails/ReadWriteAttribute
Enabled by default
Safe
Supports autocorrection
VersionAdded
VersionChanged
Enabled
Yes
Yes
0.20
0.29
This cop checks for the use of the read_attribute or write_attribute
methods and recommends square brackets instead.
If an attribute is missing from the instance (for example, when
initialized by a partial select) then read_attribute
will return nil, but square brackets will raise
an ActiveModel::MissingAttributeError.
Explicitly raising an error in this situation is preferable, and that
is why rubocop recommends using square brackets.
# badwith_optionsoptions: falsedo |merger|
merger.invoke(merger.something)end# goodwith_optionsoptions: falsedoinvoke(something)end# goodclient=Client.newwith_optionsoptions: falsedo |merger|
client.invoke(merger.something,something)end# ok# When `with_options` includes a block, all scoping scenarios# cannot be evaluated. Thus, it is ok to include the explicit# receiver.with_optionsoptions: falsedo |merger|
merger.invokewith_another_methoddo |another_receiver|
merger.invoke(another_receiver)endend
Rails/ReflectionClassName
Enabled by default
Safe
Supports autocorrection
VersionAdded
VersionChanged
Enabled
Yes
No
0.64
-
This cop checks if the value of the option class_name, in
the definition of a reflection is a string.
This cop identifies possible cases where Active Record save! or related
should be used instead of save because the model might have failed to
save and an exception is better than unhandled failure.
This will allow:
update or save calls, assigned to a variable,
or used as a condition in an if/unless/case statement.
create calls, assigned to a variable that then has a
call to persisted?.
calls if the result is explicitly returned from methods and blocks,
or provided as arguments.
calls whose signature doesn't look like an ActiveRecord
persistence method.
By default it will also allow implicit returns from methods and blocks.
that behavior can be turned off with AllowImplicitReturn: false.
You can permit receivers that are giving false positives with
AllowedReceivers: []
Two styles are supported for this cop. When EnforcedStyle is 'strict'
then only use of Time.zone is allowed.
When EnforcedStyle is 'flexible' then it's also allowed
to use Time.in_time_zone.
Examples
EnforcedStyle: strict
# `strict` means that `Time` should be used with `zone`.# badTime.nowTime.parse('2015-03-02 19:05:37')# badTime.currentTime.at(timestamp).in_time_zone# goodTime.zone.nowTime.zone.parse('2015-03-02 19:05:37')
EnforcedStyle: flexible (default)
# `flexible` allows usage of `in_time_zone` instead of `zone`.# badTime.nowTime.parse('2015-03-02 19:05:37')# goodTime.zone.nowTime.zone.parse('2015-03-02 19:05:37')# goodTime.currentTime.at(timestamp).in_time_zone
Prefer the use of uniq (or distinct), before pluck instead of after.
The use of uniq before pluck is preferred because it executes within
the database.
This cop has two different enforcement modes. When the EnforcedStyle
is conservative (the default) then only calls to pluck on a constant
(i.e. a model class) before uniq are added as offenses.
When the EnforcedStyle is aggressive then all calls to pluck before
uniq are added as offenses. This may lead to false positives as the cop
cannot distinguish between calls to pluck on an ActiveRecord::Relation
vs a call to pluck on an ActiveRecord::Associations::CollectionProxy.
Autocorrect is disabled by default for this cop since it may generate
false positives.
# bad# this will return a Relation that pluck is called onModel.where(cond: true).pluck(:id).uniq# bad# an association on an instance will return a CollectionProxyinstance.assoc.pluck(:id).uniq# badModel.pluck(:id).uniq# goodModel.uniq.pluck(:id)
Configurable attributes
Name
Default value
Configurable values
EnforcedStyle
conservative
conservative, aggressive
AutoCorrect
false
Boolean
Rails/UnknownEnv
Enabled by default
Safe
Supports autocorrection
VersionAdded
VersionChanged
Enabled
Yes
No
0.51
-
This cop checks that environments called with Rails.env predicates
exist.