Showing 211 of 211 total issues
Favor modifier if
usage when having a single-line body. Another good alternative is the usage of control flow &&
/||
. Open
if (self.class.autoset)
- Read upRead up
- Exclude checks
Checks for if
and unless
statements that would fit on one line if
written as modifier if
/unless
. The cop also checks for modifier
if
/unless
lines that exceed the maximum line length.
The maximum line length is configured in the Layout/LineLength
cop. The tab size is configured in the IndentationWidth
of the
Layout/IndentationStyle
cop.
One-line pattern matching is always allowed. To ensure that there are few cases
where the match variable is not used, and to prevent oversights. The variable x
becomes undefined and raises NameError
when the following example is changed to
the modifier form:
if [42] in [x]
x # `x` is undefined when using modifier form.
end
NOTE: It is allowed when defined?
argument has an undefined value,
because using the modifier form causes the following incompatibility:
unless defined?(undefined_foo)
undefined_foo = 'default_value'
end
undefined_foo # => 'default_value'
undefined_bar = 'default_value' unless defined?(undefined_bar)
undefined_bar # => nil
Example:
# bad
if condition
do_stuff(bar)
end
unless qux.empty?
Foo.do_something
end
do_something_with_a_long_name(arg) if long_condition_that_prevents_code_fit_on_single_line
# good
do_stuff(bar) if condition
Foo.do_something unless qux.empty?
if long_condition_that_prevents_code_fit_on_single_line
do_something_with_a_long_name(arg)
end
if short_condition # a long comment that makes it too long if it were just a single line
do_something
end
Redundant single-element character class, [i]
can be replaced with i
. Open
if gsub_enclosure && header.scan(/^\/[\^]?([^(\$\/)]+)[\$]?\/[i]?$/i) && $1
- Read upRead up
- Exclude checks
Checks for unnecessary single-element Regexp character classes.
Example:
# bad
r = /[x]/
# good
r = /x/
# bad
r = /[\s]/
# good
r = /\s/
# bad
r = %r{/[b]}
# good
r = %r{/b}
# good
r = /[ab]/
Use safe navigation (&.
) instead of checking if an object exists before calling the method. Open
if header_found && header_found.is_a?(Hash)
- Read upRead up
- Exclude checks
Transforms usages of a method call safeguarded by a non nil
check for the variable whose method is being called to
safe navigation (&.
). If there is a method chain, all of the methods
in the chain need to be checked for safety, and all of the methods will
need to be changed to use safe navigation.
The default for ConvertCodeThatCanStartToReturnNil
is false
.
When configured to true
, this will
check for code in the format !foo.nil? && foo.bar
. As it is written,
the return of this code is limited to false
and whatever the return
of the method is. If this is converted to safe navigation,
foo&.bar
can start returning nil
as well as what the method
returns.
The default for MaxChainLength
is 2
We have limited the cop to not register an offense for method chains
that exceed this option is set.
Safety:
Autocorrection is unsafe because if a value is false
, the resulting
code will have different behavior or raise an error.
x = false
x && x.foo # return false
x&.foo # raises NoMethodError
Example:
# bad
foo.bar if foo
foo.bar.baz if foo
foo.bar(param1, param2) if foo
foo.bar { |e| e.something } if foo
foo.bar(param) { |e| e.something } if foo
foo.bar if !foo.nil?
foo.bar unless !foo
foo.bar unless foo.nil?
foo && foo.bar
foo && foo.bar.baz
foo && foo.bar(param1, param2)
foo && foo.bar { |e| e.something }
foo && foo.bar(param) { |e| e.something }
foo ? foo.bar : nil
foo.nil? ? nil : foo.bar
!foo.nil? ? foo.bar : nil
!foo ? nil : foo.bar
# good
foo&.bar
foo&.bar&.baz
foo&.bar(param1, param2)
foo&.bar { |e| e.something }
foo&.bar(param) { |e| e.something }
foo && foo.bar.baz.qux # method chain with more than 2 methods
foo && foo.nil? # method that `nil` responds to
# Method calls that do not use `.`
foo && foo < bar
foo < bar if foo
# When checking `foo&.empty?` in a conditional, `foo` being `nil` will actually
# do the opposite of what the author intends.
foo && foo.empty?
# This could start returning `nil` as well as the return of the method
foo.nil? || foo.bar
!foo || foo.bar
# Methods that are used on assignment, arithmetic operation or
# comparison should not be converted to use safe navigation
foo.baz = bar if foo
foo.baz + bar if foo
foo.bar > 2 if foo
Use (at % 5).zero?
instead of at % 5 == 0
. Open
progression_tracker.call(at) if at % 5 == 0 || index == content[:rows].length - 1
- Read upRead up
- Exclude checks
Checks for usage of comparison operators (==
,
>
, <
) to test numbers as zero, positive, or negative.
These can be replaced by their respective predicate methods.
This cop can also be configured to do the reverse.
This cop can be customized allowed methods with AllowedMethods
.
By default, there are no methods to allowed.
This cop disregards #nonzero?
as its value is truthy or falsey,
but not true
and false
, and thus not always interchangeable with
!= 0
.
This cop allows comparisons to global variables, since they are often
populated with objects which can be compared with integers, but are
not themselves Integer
polymorphic.
Safety:
This cop is unsafe because it cannot be guaranteed that the receiver defines the predicates or can be compared to a number, which may lead to a false positive for non-standard classes.
Example: EnforcedStyle: predicate (default)
# bad
foo == 0
0 > foo
bar.baz > 0
# good
foo.zero?
foo.negative?
bar.baz.positive?
Example: EnforcedStyle: comparison
# bad
foo.zero?
foo.negative?
bar.baz.positive?
# good
foo == 0
0 > foo
bar.baz > 0
Example: AllowedMethods: [] (default) with EnforcedStyle: predicate
# bad
foo == 0
0 > foo
bar.baz > 0
Example: AllowedMethods: [==] with EnforcedStyle: predicate
# good
foo == 0
# bad
0 > foo
bar.baz > 0
Example: AllowedPatterns: [] (default) with EnforcedStyle: comparison
# bad
foo.zero?
foo.negative?
bar.baz.positive?
Example: AllowedPatterns: ['zero'] with EnforcedStyle: predicate
# good
# bad
foo.zero?
# bad
foo.negative?
bar.baz.positive?
Use safe navigation (&.
) instead of checking if an object exists before calling the method. Open
return column[:width].call(context) if column[:width] && column[:width].is_a?(Proc)
- Read upRead up
- Exclude checks
Transforms usages of a method call safeguarded by a non nil
check for the variable whose method is being called to
safe navigation (&.
). If there is a method chain, all of the methods
in the chain need to be checked for safety, and all of the methods will
need to be changed to use safe navigation.
The default for ConvertCodeThatCanStartToReturnNil
is false
.
When configured to true
, this will
check for code in the format !foo.nil? && foo.bar
. As it is written,
the return of this code is limited to false
and whatever the return
of the method is. If this is converted to safe navigation,
foo&.bar
can start returning nil
as well as what the method
returns.
The default for MaxChainLength
is 2
We have limited the cop to not register an offense for method chains
that exceed this option is set.
Safety:
Autocorrection is unsafe because if a value is false
, the resulting
code will have different behavior or raise an error.
x = false
x && x.foo # return false
x&.foo # raises NoMethodError
Example:
# bad
foo.bar if foo
foo.bar.baz if foo
foo.bar(param1, param2) if foo
foo.bar { |e| e.something } if foo
foo.bar(param) { |e| e.something } if foo
foo.bar if !foo.nil?
foo.bar unless !foo
foo.bar unless foo.nil?
foo && foo.bar
foo && foo.bar.baz
foo && foo.bar(param1, param2)
foo && foo.bar { |e| e.something }
foo && foo.bar(param) { |e| e.something }
foo ? foo.bar : nil
foo.nil? ? nil : foo.bar
!foo.nil? ? foo.bar : nil
!foo ? nil : foo.bar
# good
foo&.bar
foo&.bar&.baz
foo&.bar(param1, param2)
foo&.bar { |e| e.something }
foo&.bar(param) { |e| e.something }
foo && foo.bar.baz.qux # method chain with more than 2 methods
foo && foo.nil? # method that `nil` responds to
# Method calls that do not use `.`
foo && foo < bar
foo < bar if foo
# When checking `foo&.empty?` in a conditional, `foo` being `nil` will actually
# do the opposite of what the author intends.
foo && foo.empty?
# This could start returning `nil` as well as the return of the method
foo.nil? || foo.bar
!foo || foo.bar
# Methods that are used on assignment, arithmetic operation or
# comparison should not be converted to use safe navigation
foo.baz = bar if foo
foo.baz + bar if foo
foo.bar > 2 if foo
Extra empty line detected at module body end. Open
end
- Read upRead up
- Exclude checks
Checks if empty lines around the bodies of modules match the configuration.
Example: EnforcedStyle: noemptylines (default)
# good
module Foo
def bar
# ...
end
end
Example: EnforcedStyle: empty_lines
# good
module Foo
def bar
# ...
end
end
Example: EnforcedStyle: emptylinesexcept_namespace
# good
module Foo
module Bar
# ...
end
end
Example: EnforcedStyle: emptylinesspecial
# good
module Foo
def bar; end
end
Trailing whitespace detected. Open
- Read upRead up
- Exclude checks
Looks for trailing whitespace in the source code.
Example:
# The line in this example contains spaces after the 0.
# bad
x = 0
# The line in this example ends directly after the 0.
# good
x = 0
Example: AllowInHeredoc: false (default)
# The line in this example contains spaces after the 0.
# bad
code = <<~RUBY
x = 0
RUBY
# ok
code = <<~RUBY
x = 0 #{}
RUBY
# good
trailing_whitespace = ' '
code = <<~RUBY
x = 0#{trailing_whitespace}
RUBY
Example: AllowInHeredoc: true
# The line in this example contains spaces after the 0.
# good
code = <<~RUBY
x = 0
RUBY
Redundant safe navigation detected, use .
instead. Open
if @status_tracker&.is_a?(Proc)
- Read upRead up
- Exclude checks
Checks for redundant safe navigation calls.
Use cases where a constant, named in camel case for classes and modules is nil
are rare,
and an offense is not detected when the receiver is a constant. The detection also applies
to literal receivers, except for nil
.
For all receivers, the instance_of?
, kind_of?
, is_a?
, eql?
, respond_to?
,
and equal?
methods are checked by default.
These are customizable with AllowedMethods
option.
The AllowedMethods
option specifies nil-safe methods,
in other words, it is a method that is allowed to skip safe navigation.
Note that the AllowedMethod
option is not an option that specifies methods
for which to suppress (allow) this cop's check.
In the example below, the safe navigation operator (&.
) is unnecessary
because NilClass
has methods like respond_to?
and is_a?
.
Safety:
This cop is unsafe, because autocorrection can change the return type of
the expression. An offending expression that previously could return nil
will be autocorrected to never return nil
.
Example:
# bad
CamelCaseConst&.do_something
# bad
do_something if attrs&.respond_to?(:[])
# good
do_something if attrs.respond_to?(:[])
# bad
while node&.is_a?(BeginNode)
node = node.parent
end
# good
CamelCaseConst.do_something
# good
while node.is_a?(BeginNode)
node = node.parent
end
# good - without `&.` this will always return `true`
foo&.respond_to?(:to_a)
# bad - for `nil`s conversion methods return default values for the type
foo&.to_h || {}
foo&.to_h { |k, v| [k, v] } || {}
foo&.to_a || []
foo&.to_i || 0
foo&.to_f || 0.0
foo&.to_s || ''
# good
foo.to_h
foo.to_h { |k, v| [k, v] }
foo.to_a
foo.to_i
foo.to_f
foo.to_s
Example: AllowedMethods: [nilsafemethod]
# bad
do_something if attrs&.nil_safe_method(:[])
# good
do_something if attrs.nil_safe_method(:[])
do_something if attrs&.not_nil_safe_method(:[])
Use each_key
instead of each
and remove the unused _value
block argument. Open
l.each do |parsed_header, _value|
next unless parsed_header
next unless (header.is_a?(Regexp) && parsed_header && parsed_header.match?(header)) || header.is_a?(String) && parsed_header == header
- Read upRead up
- Exclude checks
Checks for uses of each_key
and each_value
Hash methods.
NOTE: If you have an array of two-element arrays, you can put parentheses around the block arguments to indicate that you're not working with a hash, and suppress RuboCop offenses.
Safety:
This cop is unsafe because it cannot be guaranteed that the receiver
is a Hash
. The AllowedReceivers
configuration can mitigate,
but not fully resolve, this safety issue.
Example:
# bad
hash.keys.each { |k| p k }
hash.each { |k, unused_value| p k }
# good
hash.each_key { |k| p k }
# bad
hash.values.each { |v| p v }
hash.each { |unused_key, v| p v }
# good
hash.each_value { |v| p v }
Example: AllowedReceivers: ['execute']
# good
execute(sql).keys.each { |v| p v }
execute(sql).values.each { |v| p v }
Modifier form of unless
makes the line too long. Open
next unless (header.is_a?(Regexp) && parsed_header && parsed_header.match?(header)) || header.is_a?(String) && parsed_header == header
- Read upRead up
- Exclude checks
Checks for if
and unless
statements that would fit on one line if
written as modifier if
/unless
. The cop also checks for modifier
if
/unless
lines that exceed the maximum line length.
The maximum line length is configured in the Layout/LineLength
cop. The tab size is configured in the IndentationWidth
of the
Layout/IndentationStyle
cop.
One-line pattern matching is always allowed. To ensure that there are few cases
where the match variable is not used, and to prevent oversights. The variable x
becomes undefined and raises NameError
when the following example is changed to
the modifier form:
if [42] in [x]
x # `x` is undefined when using modifier form.
end
NOTE: It is allowed when defined?
argument has an undefined value,
because using the modifier form causes the following incompatibility:
unless defined?(undefined_foo)
undefined_foo = 'default_value'
end
undefined_foo # => 'default_value'
undefined_bar = 'default_value' unless defined?(undefined_bar)
undefined_bar # => nil
Example:
# bad
if condition
do_stuff(bar)
end
unless qux.empty?
Foo.do_something
end
do_something_with_a_long_name(arg) if long_condition_that_prevents_code_fit_on_single_line
# good
do_stuff(bar) if condition
Foo.do_something unless qux.empty?
if long_condition_that_prevents_code_fit_on_single_line
do_something_with_a_long_name(arg)
end
if short_condition # a long comment that makes it too long if it were just a single line
do_something
end
Use !empty?
instead of size > 0
. Open
raise 'File is inconsistent, please check you have data in it or check for invalid characters in headers like , / ; etc...' unless spreadsheet_data.size > 0
- Read upRead up
- Exclude checks
Checks for numeric comparisons that can be replaced
by a predicate method, such as receiver.length == 0
,
receiver.length > 0
, and receiver.length != 0
,
receiver.length < 1
and receiver.size == 0
that can be
replaced by receiver.empty?
and !receiver.empty?
.
NOTE: File
, Tempfile
, and StringIO
do not have empty?
so allow size == 0
and size.zero?
.
Safety:
This cop is unsafe because it cannot be guaranteed that the receiver
has an empty?
method that is defined in terms of length
. If there
is a non-standard class that redefines length
or empty?
, the cop
may register a false positive.
Example:
# bad
[1, 2, 3].length == 0
0 == "foobar".length
array.length < 1
{a: 1, b: 2}.length != 0
string.length > 0
hash.size > 0
# good
[1, 2, 3].empty?
"foobar".empty?
array.empty?
!{a: 1, b: 2}.empty?
!string.empty?
!hash.empty?
Trailing whitespace detected. Open
- Read upRead up
- Exclude checks
Looks for trailing whitespace in the source code.
Example:
# The line in this example contains spaces after the 0.
# bad
x = 0
# The line in this example ends directly after the 0.
# good
x = 0
Example: AllowInHeredoc: false (default)
# The line in this example contains spaces after the 0.
# bad
code = <<~RUBY
x = 0
RUBY
# ok
code = <<~RUBY
x = 0 #{}
RUBY
# good
trailing_whitespace = ' '
code = <<~RUBY
x = 0#{trailing_whitespace}
RUBY
Example: AllowInHeredoc: true
# The line in this example contains spaces after the 0.
# good
code = <<~RUBY
x = 0
RUBY
Trailing whitespace detected. Open
number_of_children = number_of_headers_row(column[:children], count += 1)
- Read upRead up
- Exclude checks
Looks for trailing whitespace in the source code.
Example:
# The line in this example contains spaces after the 0.
# bad
x = 0
# The line in this example ends directly after the 0.
# good
x = 0
Example: AllowInHeredoc: false (default)
# The line in this example contains spaces after the 0.
# bad
code = <<~RUBY
x = 0
RUBY
# ok
code = <<~RUBY
x = 0 #{}
RUBY
# good
trailing_whitespace = ' '
code = <<~RUBY
x = 0#{trailing_whitespace}
RUBY
Example: AllowInHeredoc: true
# The line in this example contains spaces after the 0.
# good
code = <<~RUBY
x = 0
RUBY
Redundant safe navigation detected, use .
instead. Open
if progression_tracker&.is_a?(Proc)
- Read upRead up
- Exclude checks
Checks for redundant safe navigation calls.
Use cases where a constant, named in camel case for classes and modules is nil
are rare,
and an offense is not detected when the receiver is a constant. The detection also applies
to literal receivers, except for nil
.
For all receivers, the instance_of?
, kind_of?
, is_a?
, eql?
, respond_to?
,
and equal?
methods are checked by default.
These are customizable with AllowedMethods
option.
The AllowedMethods
option specifies nil-safe methods,
in other words, it is a method that is allowed to skip safe navigation.
Note that the AllowedMethod
option is not an option that specifies methods
for which to suppress (allow) this cop's check.
In the example below, the safe navigation operator (&.
) is unnecessary
because NilClass
has methods like respond_to?
and is_a?
.
Safety:
This cop is unsafe, because autocorrection can change the return type of
the expression. An offending expression that previously could return nil
will be autocorrected to never return nil
.
Example:
# bad
CamelCaseConst&.do_something
# bad
do_something if attrs&.respond_to?(:[])
# good
do_something if attrs.respond_to?(:[])
# bad
while node&.is_a?(BeginNode)
node = node.parent
end
# good
CamelCaseConst.do_something
# good
while node.is_a?(BeginNode)
node = node.parent
end
# good - without `&.` this will always return `true`
foo&.respond_to?(:to_a)
# bad - for `nil`s conversion methods return default values for the type
foo&.to_h || {}
foo&.to_h { |k, v| [k, v] } || {}
foo&.to_a || []
foo&.to_i || 0
foo&.to_f || 0.0
foo&.to_s || ''
# good
foo.to_h
foo.to_h { |k, v| [k, v] }
foo.to_a
foo.to_i
foo.to_f
foo.to_s
Example: AllowedMethods: [nilsafemethod]
# bad
do_something if attrs&.nil_safe_method(:[])
# good
do_something if attrs.nil_safe_method(:[])
do_something if attrs&.not_nil_safe_method(:[])
Useless assignment to variable - columns
. Open
columns = schema[:columns]
- Read upRead up
- Exclude checks
Checks for every useless assignment to local variable in every
scope.
The basic idea for this cop was from the warning of ruby -cw
:
assigned but unused variable - foo
Currently this cop has advanced logic that detects unreferenced reassignments and properly handles varied cases such as branch, loop, rescue, ensure, etc.
NOTE: Given the assignment foo = 1, bar = 2
, removing unused variables
can lead to a syntax error, so this case is not autocorrected.
Safety:
This cop's autocorrection is unsafe because removing assignment from
operator assignment can cause NameError if this assignment has been used to declare
local variable. For example, replacing a ||= 1
to a || 1
may cause
"undefined local variable or method `a' for main:Object (NameError)".
Example:
# bad
def some_method
some_var = 1
do_something
end
Example:
# good
def some_method
some_var = 1
do_something(some_var)
end
Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping. Open
config[:errorTitle] = list_config[:error_title] || ''
- Read upRead up
- Exclude checks
Checks if uses of quotes match the configured preference.
Example: EnforcedStyle: single_quotes (default)
# bad
"No special symbols"
"No string interpolation"
"Just text"
# good
'No special symbols'
'No string interpolation'
'Just text'
"Wait! What's #{this}!"
Example: EnforcedStyle: double_quotes
# bad
'Just some text'
'No special chars or interpolation'
# good
"Just some text"
"No special chars or interpolation"
"Every string in #{project} uses double_quotes"
Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping. Open
config[:promptTitle] = list_config[:prompt_title] || ''
- Read upRead up
- Exclude checks
Checks if uses of quotes match the configured preference.
Example: EnforcedStyle: single_quotes (default)
# bad
"No special symbols"
"No string interpolation"
"Just text"
# good
'No special symbols'
'No string interpolation'
'Just text'
"Wait! What's #{this}!"
Example: EnforcedStyle: double_quotes
# bad
'Just some text'
'No special chars or interpolation'
# good
"Just some text"
"No special chars or interpolation"
"Every string in #{project} uses double_quotes"
Extra empty line detected at class body end. Open
end
- Read upRead up
- Exclude checks
Checks if empty lines around the bodies of classes match the configuration.
Example: EnforcedStyle: noemptylines (default)
# good
class Foo
def bar
# ...
end
end
Example: EnforcedStyle: empty_lines
# good
class Foo
def bar
# ...
end
end
Example: EnforcedStyle: emptylinesexcept_namespace
# good
class Foo
class Bar
# ...
end
end
Example: EnforcedStyle: emptylinesspecial
# good
class Foo
def bar; end
end
Example: EnforcedStyle: beginning_only
# good
class Foo
def bar
# ...
end
end
Example: EnforcedStyle: ending_only
# good
class Foo
def bar
# ...
end
end
Trailing whitespace detected. Open
- Read upRead up
- Exclude checks
Looks for trailing whitespace in the source code.
Example:
# The line in this example contains spaces after the 0.
# bad
x = 0
# The line in this example ends directly after the 0.
# good
x = 0
Example: AllowInHeredoc: false (default)
# The line in this example contains spaces after the 0.
# bad
code = <<~RUBY
x = 0
RUBY
# ok
code = <<~RUBY
x = 0 #{}
RUBY
# good
trailing_whitespace = ' '
code = <<~RUBY
x = 0#{trailing_whitespace}
RUBY
Example: AllowInHeredoc: true
# The line in this example contains spaces after the 0.
# good
code = <<~RUBY
x = 0
RUBY
Don't use parentheses around the condition of an if
. Open
if (self.class.autosave.nil? || self.class.autosave)
- Read upRead up
- Exclude checks
Checks for the presence of superfluous parentheses around the condition of if/unless/while/until.
AllowSafeAssignment
option for safe assignment.
By safe assignment we mean putting parentheses around
an assignment to indicate "I know I'm using an assignment
as a condition. It's not a mistake."
Example:
# bad
x += 1 while (x < 10)
foo unless (bar || baz)
if (x > 10)
elsif (x < 3)
end
# good
x += 1 while x < 10
foo unless bar || baz
if x > 10
elsif x < 3
end
Example: AllowSafeAssignment: true (default)
# good
foo unless (bar = baz)
Example: AllowSafeAssignment: false
# bad
foo unless (bar = baz)
Example: AllowInMultilineConditions: false (default)
# bad
if (x > 10 &&
y > 10)
end
# good
if x > 10 &&
y > 10
end
Example: AllowInMultilineConditions: true
# good
if (x > 10 &&
y > 10)
end