Class has too many lines. [209/100] Open
class Importer
attr_accessor :file, :check, :lines, :options, :status_tracker, :success
attr_accessor :context
class << self
- Read upRead up
- Exclude checks
Checks if the length of a class exceeds some maximum value. Comment lines can optionally be ignored. The maximum allowed length is configurable.
You can set constructs you want to fold with CountAsOne
.
Available are: 'array', 'hash', 'heredoc', and 'method_call'. Each construct
will be counted as one line regardless of its actual size.
NOTE: This cop also applies for Struct
definitions.
Example: CountAsOne: ['array', 'heredoc', 'method_call']
class Foo
ARRAY = [ # +1
1,
2
]
HASH = { # +3
key: 'value'
}
MSG = <<~HEREDOC # +1
Heredoc
content.
HEREDOC
foo( # +1
1,
2
)
end # 6 points
Method has too many lines. [27/10] Open
def import(save: true, status_tracker: nil)
self.class.before.call(@context, options) if self.class.before.is_a?(Proc)
at = 0
errors_lines = []
success_count = 0
- Read upRead up
- Exclude checks
Checks if the length of a method exceeds some maximum value. Comment lines can optionally be allowed. The maximum allowed length is configurable.
You can set constructs you want to fold with CountAsOne
.
Available are: 'array', 'hash', 'heredoc', and 'method_call'. Each construct
will be counted as one line regardless of its actual size.
NOTE: The ExcludedMethods
and IgnoredMethods
configuration is
deprecated and only kept for backwards compatibility.
Please use AllowedMethods
and AllowedPatterns
instead.
By default, there are no methods to allowed.
Example: CountAsOne: ['array', 'heredoc', 'method_call']
def m
array = [ # +1
1,
2
]
hash = { # +3
key: 'value'
}
<<~HEREDOC # +1
Heredoc
content.
HEREDOC
foo( # +1
1,
2
)
end # 6 points
Method has too many lines. [25/10] Open
def spreadsheet_data
begin
spreadsheet_data = spreadsheet.sheet(spreadsheet.sheets[0]).parse(header_search: required_headers)
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 if the length of a method exceeds some maximum value. Comment lines can optionally be allowed. The maximum allowed length is configurable.
You can set constructs you want to fold with CountAsOne
.
Available are: 'array', 'hash', 'heredoc', and 'method_call'. Each construct
will be counted as one line regardless of its actual size.
NOTE: The ExcludedMethods
and IgnoredMethods
configuration is
deprecated and only kept for backwards compatibility.
Please use AllowedMethods
and AllowedPatterns
instead.
By default, there are no methods to allowed.
Example: CountAsOne: ['array', 'heredoc', 'method_call']
def m
array = [ # +1
1,
2
]
hash = { # +3
key: 'value'
}
<<~HEREDOC # +1
Heredoc
content.
HEREDOC
foo( # +1
1,
2
)
end # 6 points
Class Importer
has 27 methods (exceeds 20 allowed). Consider refactoring. Open
class Importer
attr_accessor :file, :check, :lines, :options, :status_tracker, :success
attr_accessor :context
class << self
Method has too many lines. [20/10] Open
def import_line(line, save: true)
record = find_or_initialize_record(line)
return { status: :not_found } unless record
@success = false
- Read upRead up
- Exclude checks
Checks if the length of a method exceeds some maximum value. Comment lines can optionally be allowed. The maximum allowed length is configurable.
You can set constructs you want to fold with CountAsOne
.
Available are: 'array', 'hash', 'heredoc', and 'method_call'. Each construct
will be counted as one line regardless of its actual size.
NOTE: The ExcludedMethods
and IgnoredMethods
configuration is
deprecated and only kept for backwards compatibility.
Please use AllowedMethods
and AllowedPatterns
instead.
By default, there are no methods to allowed.
Example: CountAsOne: ['array', 'heredoc', 'method_call']
def m
array = [ # +1
1,
2
]
hash = { # +3
key: 'value'
}
<<~HEREDOC # +1
Heredoc
content.
HEREDOC
foo( # +1
1,
2
)
end # 6 points
Method detect_header_scheme
has a Cognitive Complexity of 19 (exceeds 5 allowed). Consider refactoring. Open
def detect_header_scheme
return @header_scheme if @header_scheme
@header_scheme = {}
# Read the first line of file (not header)
- Read upRead up
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Cyclomatic complexity for detect_header_scheme is too high. [14/7] Open
def detect_header_scheme
return @header_scheme if @header_scheme
@header_scheme = {}
# Read the first line of file (not header)
- Read upRead up
- Exclude checks
Checks that the cyclomatic complexity of methods is not higher than the configured maximum. The cyclomatic complexity is the number of linearly independent paths through a method. The algorithm counts decision points and adds one.
An if statement (or unless or ?:) increases the complexity by one. An else branch does not, since it doesn't add a decision point. The && operator (or keyword and) can be converted to a nested if statement, and ||/or is shorthand for a sequence of ifs, so they also add one. Loops can be said to have an exit condition, so they add one. Blocks that are calls to builtin iteration methods (e.g. `ary.map{...}) also add one, others are ignored.
def each_child_node(*types) # count begins: 1
unless block_given? # unless: +1
return to_enum(__method__, *types)
children.each do |child| # each{}: +1
next unless child.is_a?(Node) # unless: +1
yield child if types.empty? || # if: +1, ||: +1
types.include?(child.type)
end
self
end # total: 6
Perceived complexity for detect_header_scheme is too high. [14/8] Open
def detect_header_scheme
return @header_scheme if @header_scheme
@header_scheme = {}
# Read the first line of file (not header)
- Read upRead up
- Exclude checks
Tries to produce a complexity score that's a measure of the
complexity the reader experiences when looking at a method. For that
reason it considers when
nodes as something that doesn't add as much
complexity as an if
or a &&
. Except if it's one of those special
case
/when
constructs where there's no expression after case
. Then
the cop treats it as an if
/elsif
/elsif
... and lets all the when
nodes count. In contrast to the CyclomaticComplexity cop, this cop
considers else
nodes as adding complexity.
Example:
def my_method # 1
if cond # 1
case var # 2 (0.8 + 4 * 0.2, rounded)
when 1 then func_one
when 2 then func_two
when 3 then func_three
when 4..10 then func_other
end
else # 1
do_something until a && b # 2
end # ===
end # 7 complexity points
Perceived complexity for spreadsheet_data is too high. [14/8] Open
def spreadsheet_data
begin
spreadsheet_data = spreadsheet.sheet(spreadsheet.sheets[0]).parse(header_search: required_headers)
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
Tries to produce a complexity score that's a measure of the
complexity the reader experiences when looking at a method. For that
reason it considers when
nodes as something that doesn't add as much
complexity as an if
or a &&
. Except if it's one of those special
case
/when
constructs where there's no expression after case
. Then
the cop treats it as an if
/elsif
/elsif
... and lets all the when
nodes count. In contrast to the CyclomaticComplexity cop, this cop
considers else
nodes as adding complexity.
Example:
def my_method # 1
if cond # 1
case var # 2 (0.8 + 4 * 0.2, rounded)
when 1 then func_one
when 2 then func_two
when 3 then func_three
when 4..10 then func_other
end
else # 1
do_something until a && b # 2
end # ===
end # 7 complexity points
Cyclomatic complexity for spreadsheet_data is too high. [12/7] Open
def spreadsheet_data
begin
spreadsheet_data = spreadsheet.sheet(spreadsheet.sheets[0]).parse(header_search: required_headers)
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 that the cyclomatic complexity of methods is not higher than the configured maximum. The cyclomatic complexity is the number of linearly independent paths through a method. The algorithm counts decision points and adds one.
An if statement (or unless or ?:) increases the complexity by one. An else branch does not, since it doesn't add a decision point. The && operator (or keyword and) can be converted to a nested if statement, and ||/or is shorthand for a sequence of ifs, so they also add one. Loops can be said to have an exit condition, so they add one. Blocks that are calls to builtin iteration methods (e.g. `ary.map{...}) also add one, others are ignored.
def each_child_node(*types) # count begins: 1
unless block_given? # unless: +1
return to_enum(__method__, *types)
children.each do |child| # each{}: +1
next unless child.is_a?(Node) # unless: +1
yield child if types.empty? || # if: +1, ||: +1
types.include?(child.type)
end
self
end # total: 6
Cyclomatic complexity for import is too high. [12/7] Open
def import(save: true, status_tracker: nil)
self.class.before.call(@context, options) if self.class.before.is_a?(Proc)
at = 0
errors_lines = []
success_count = 0
- Read upRead up
- Exclude checks
Checks that the cyclomatic complexity of methods is not higher than the configured maximum. The cyclomatic complexity is the number of linearly independent paths through a method. The algorithm counts decision points and adds one.
An if statement (or unless or ?:) increases the complexity by one. An else branch does not, since it doesn't add a decision point. The && operator (or keyword and) can be converted to a nested if statement, and ||/or is shorthand for a sequence of ifs, so they also add one. Loops can be said to have an exit condition, so they add one. Blocks that are calls to builtin iteration methods (e.g. `ary.map{...}) also add one, others are ignored.
def each_child_node(*types) # count begins: 1
unless block_given? # unless: +1
return to_enum(__method__, *types)
children.each do |child| # each{}: +1
next unless child.is_a?(Node) # unless: +1
yield child if types.empty? || # if: +1, ||: +1
types.include?(child.type)
end
self
end # total: 6
Method has too many lines. [14/10] Open
def detect_header_scheme
return @header_scheme if @header_scheme
@header_scheme = {}
# Read the first line of file (not header)
- Read upRead up
- Exclude checks
Checks if the length of a method exceeds some maximum value. Comment lines can optionally be allowed. The maximum allowed length is configurable.
You can set constructs you want to fold with CountAsOne
.
Available are: 'array', 'hash', 'heredoc', and 'method_call'. Each construct
will be counted as one line regardless of its actual size.
NOTE: The ExcludedMethods
and IgnoredMethods
configuration is
deprecated and only kept for backwards compatibility.
Please use AllowedMethods
and AllowedPatterns
instead.
By default, there are no methods to allowed.
Example: CountAsOne: ['array', 'heredoc', 'method_call']
def m
array = [ # +1
1,
2
]
hash = { # +3
key: 'value'
}
<<~HEREDOC # +1
Heredoc
content.
HEREDOC
foo( # +1
1,
2
)
end # 6 points
Perceived complexity for import_line is too high. [11/8] Open
def import_line(line, save: true)
record = find_or_initialize_record(line)
return { status: :not_found } unless record
@success = false
- Read upRead up
- Exclude checks
Tries to produce a complexity score that's a measure of the
complexity the reader experiences when looking at a method. For that
reason it considers when
nodes as something that doesn't add as much
complexity as an if
or a &&
. Except if it's one of those special
case
/when
constructs where there's no expression after case
. Then
the cop treats it as an if
/elsif
/elsif
... and lets all the when
nodes count. In contrast to the CyclomaticComplexity cop, this cop
considers else
nodes as adding complexity.
Example:
def my_method # 1
if cond # 1
case var # 2 (0.8 + 4 * 0.2, rounded)
when 1 then func_one
when 2 then func_two
when 3 then func_three
when 4..10 then func_other
end
else # 1
do_something until a && b # 2
end # ===
end # 7 complexity points
Cyclomatic complexity for import_line is too high. [10/7] Open
def import_line(line, save: true)
record = find_or_initialize_record(line)
return { status: :not_found } unless record
@success = false
- Read upRead up
- Exclude checks
Checks that the cyclomatic complexity of methods is not higher than the configured maximum. The cyclomatic complexity is the number of linearly independent paths through a method. The algorithm counts decision points and adds one.
An if statement (or unless or ?:) increases the complexity by one. An else branch does not, since it doesn't add a decision point. The && operator (or keyword and) can be converted to a nested if statement, and ||/or is shorthand for a sequence of ifs, so they also add one. Loops can be said to have an exit condition, so they add one. Blocks that are calls to builtin iteration methods (e.g. `ary.map{...}) also add one, others are ignored.
def each_child_node(*types) # count begins: 1
unless block_given? # unless: +1
return to_enum(__method__, *types)
children.each do |child| # each{}: +1
next unless child.is_a?(Node) # unless: +1
yield child if types.empty? || # if: +1, ||: +1
types.include?(child.type)
end
self
end # total: 6
Method spreadsheet_data
has a Cognitive Complexity of 15 (exceeds 5 allowed). Consider refactoring. Open
def spreadsheet_data
begin
spreadsheet_data = spreadsheet.sheet(spreadsheet.sheets[0]).parse(header_search: required_headers)
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
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Method import_line
has a Cognitive Complexity of 15 (exceeds 5 allowed). Consider refactoring. Open
def import_line(line, save: true)
record = find_or_initialize_record(line)
return { status: :not_found } unless record
@success = false
- Read upRead up
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Cyclomatic complexity for required_headers is too high. [9/7] Open
def required_headers
return @required_headers if @required_headers
@required_columns = self.class.schema.select { |_field, column_config| !column_config.is_a?(Hash) || !column_config.key?(:required) || column_config[:required] }
@required_headers = @required_columns.values.map { |column| get_column_header(column) }.map { |header| transform_header_to_regexp(header) }
- Read upRead up
- Exclude checks
Checks that the cyclomatic complexity of methods is not higher than the configured maximum. The cyclomatic complexity is the number of linearly independent paths through a method. The algorithm counts decision points and adds one.
An if statement (or unless or ?:) increases the complexity by one. An else branch does not, since it doesn't add a decision point. The && operator (or keyword and) can be converted to a nested if statement, and ||/or is shorthand for a sequence of ifs, so they also add one. Loops can be said to have an exit condition, so they add one. Blocks that are calls to builtin iteration methods (e.g. `ary.map{...}) also add one, others are ignored.
def each_child_node(*types) # count begins: 1
unless block_given? # unless: +1
return to_enum(__method__, *types)
children.each do |child| # each{}: +1
next unless child.is_a?(Node) # unless: +1
yield child if types.empty? || # if: +1, ||: +1
types.include?(child.type)
end
self
end # total: 6
Perceived complexity for import is too high. [10/8] Open
def import(save: true, status_tracker: nil)
self.class.before.call(@context, options) if self.class.before.is_a?(Proc)
at = 0
errors_lines = []
success_count = 0
- Read upRead up
- Exclude checks
Tries to produce a complexity score that's a measure of the
complexity the reader experiences when looking at a method. For that
reason it considers when
nodes as something that doesn't add as much
complexity as an if
or a &&
. Except if it's one of those special
case
/when
constructs where there's no expression after case
. Then
the cop treats it as an if
/elsif
/elsif
... and lets all the when
nodes count. In contrast to the CyclomaticComplexity cop, this cop
considers else
nodes as adding complexity.
Example:
def my_method # 1
if cond # 1
case var # 2 (0.8 + 4 * 0.2, rounded)
when 1 then func_one
when 2 then func_two
when 3 then func_three
when 4..10 then func_other
end
else # 1
do_something until a && b # 2
end # ===
end # 7 complexity points
Method has too many lines. [12/10] Open
def parse_line(line)
parsed_line = {}
line.each do |header, value|
header_scheme = detect_header_scheme
if header.to_s == self.class.primary_key.to_s
- Read upRead up
- Exclude checks
Checks if the length of a method exceeds some maximum value. Comment lines can optionally be allowed. The maximum allowed length is configurable.
You can set constructs you want to fold with CountAsOne
.
Available are: 'array', 'hash', 'heredoc', and 'method_call'. Each construct
will be counted as one line regardless of its actual size.
NOTE: The ExcludedMethods
and IgnoredMethods
configuration is
deprecated and only kept for backwards compatibility.
Please use AllowedMethods
and AllowedPatterns
instead.
By default, there are no methods to allowed.
Example: CountAsOne: ['array', 'heredoc', 'method_call']
def m
array = [ # +1
1,
2
]
hash = { # +3
key: 'value'
}
<<~HEREDOC # +1
Heredoc
content.
HEREDOC
foo( # +1
1,
2
)
end # 6 points
Perceived complexity for required_headers is too high. [9/8] Open
def required_headers
return @required_headers if @required_headers
@required_columns = self.class.schema.select { |_field, column_config| !column_config.is_a?(Hash) || !column_config.key?(:required) || column_config[:required] }
@required_headers = @required_columns.values.map { |column| get_column_header(column) }.map { |header| transform_header_to_regexp(header) }
- Read upRead up
- Exclude checks
Tries to produce a complexity score that's a measure of the
complexity the reader experiences when looking at a method. For that
reason it considers when
nodes as something that doesn't add as much
complexity as an if
or a &&
. Except if it's one of those special
case
/when
constructs where there's no expression after case
. Then
the cop treats it as an if
/elsif
/elsif
... and lets all the when
nodes count. In contrast to the CyclomaticComplexity cop, this cop
considers else
nodes as adding complexity.
Example:
def my_method # 1
if cond # 1
case var # 2 (0.8 + 4 * 0.2, rounded)
when 1 then func_one
when 2 then func_two
when 3 then func_three
when 4..10 then func_other
end
else # 1
do_something until a && b # 2
end # ===
end # 7 complexity points
Method import
has a Cognitive Complexity of 10 (exceeds 5 allowed). Consider refactoring. Open
def import(save: true, status_tracker: nil)
self.class.before.call(@context, options) if self.class.before.is_a?(Proc)
at = 0
errors_lines = []
success_count = 0
- Read upRead up
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Method import
has 27 lines of code (exceeds 25 allowed). Consider refactoring. Open
def import(save: true, status_tracker: nil)
self.class.before.call(@context, options) if self.class.before.is_a?(Proc)
at = 0
errors_lines = []
success_count = 0
Method find_or_initialize_record
has a Cognitive Complexity of 9 (exceeds 5 allowed). Consider refactoring. Open
def find_or_initialize_record(line)
return nil unless self.class.primary_key && self.class.model_klass
if line[self.class.primary_key.to_sym].present?
if self.class.primary_key.to_sym == :id
- Read upRead up
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Assignment Branch Condition size for detect_header_scheme is too high. [<8, 30, 14> 34.06/17] Open
def detect_header_scheme
return @header_scheme if @header_scheme
@header_scheme = {}
# Read the first line of file (not header)
- Read upRead up
- Exclude checks
Checks that the ABC size of methods is not higher than the configured maximum. The ABC size is based on assignments, branches (method calls), and conditions. See http://c2.com/cgi/wiki?AbcMetric and https://en.wikipedia.org/wiki/ABC_Software_Metric.
Interpreting ABC size:
-
<= 17
satisfactory -
18..30
unsatisfactory -
>
30 dangerous
You can have repeated "attributes" calls count as a single "branch".
For this purpose, attributes are any method with no argument; no attempt
is meant to distinguish actual attr_reader
from other methods.
Example: CountRepeatedAttributes: false (default is true)
# `model` and `current_user`, referenced 3 times each,
# are each counted as only 1 branch each if
# `CountRepeatedAttributes` is set to 'false'
def search
@posts = model.active.visible_by(current_user)
.search(params[:q])
@posts = model.some_process(@posts, current_user)
@posts = model.another_process(@posts, current_user)
render 'pages/search/page'
end
This cop also takes into account AllowedMethods
(defaults to []
)
And AllowedPatterns
(defaults to []
)
Assignment Branch Condition size for find_or_initialize_record is too high. [<3, 34, 7> 34.84/17] Open
def find_or_initialize_record(line)
return nil unless self.class.primary_key && self.class.model_klass
if line[self.class.primary_key.to_sym].present?
if self.class.primary_key.to_sym == :id
- Read upRead up
- Exclude checks
Checks that the ABC size of methods is not higher than the configured maximum. The ABC size is based on assignments, branches (method calls), and conditions. See http://c2.com/cgi/wiki?AbcMetric and https://en.wikipedia.org/wiki/ABC_Software_Metric.
Interpreting ABC size:
-
<= 17
satisfactory -
18..30
unsatisfactory -
>
30 dangerous
You can have repeated "attributes" calls count as a single "branch".
For this purpose, attributes are any method with no argument; no attempt
is meant to distinguish actual attr_reader
from other methods.
Example: CountRepeatedAttributes: false (default is true)
# `model` and `current_user`, referenced 3 times each,
# are each counted as only 1 branch each if
# `CountRepeatedAttributes` is set to 'false'
def search
@posts = model.active.visible_by(current_user)
.search(params[:q])
@posts = model.some_process(@posts, current_user)
@posts = model.another_process(@posts, current_user)
render 'pages/search/page'
end
This cop also takes into account AllowedMethods
(defaults to []
)
And AllowedPatterns
(defaults to []
)
Assignment Branch Condition size for import_line is too high. [<9, 20, 10> 24.1/17] Open
def import_line(line, save: true)
record = find_or_initialize_record(line)
return { status: :not_found } unless record
@success = false
- Read upRead up
- Exclude checks
Checks that the ABC size of methods is not higher than the configured maximum. The ABC size is based on assignments, branches (method calls), and conditions. See http://c2.com/cgi/wiki?AbcMetric and https://en.wikipedia.org/wiki/ABC_Software_Metric.
Interpreting ABC size:
-
<= 17
satisfactory -
18..30
unsatisfactory -
>
30 dangerous
You can have repeated "attributes" calls count as a single "branch".
For this purpose, attributes are any method with no argument; no attempt
is meant to distinguish actual attr_reader
from other methods.
Example: CountRepeatedAttributes: false (default is true)
# `model` and `current_user`, referenced 3 times each,
# are each counted as only 1 branch each if
# `CountRepeatedAttributes` is set to 'false'
def search
@posts = model.active.visible_by(current_user)
.search(params[:q])
@posts = model.some_process(@posts, current_user)
@posts = model.another_process(@posts, current_user)
render 'pages/search/page'
end
This cop also takes into account AllowedMethods
(defaults to []
)
And AllowedPatterns
(defaults to []
)
Assignment Branch Condition size for required_headers is too high. [<5, 25, 8> 26.72/17] Open
def required_headers
return @required_headers if @required_headers
@required_columns = self.class.schema.select { |_field, column_config| !column_config.is_a?(Hash) || !column_config.key?(:required) || column_config[:required] }
@required_headers = @required_columns.values.map { |column| get_column_header(column) }.map { |header| transform_header_to_regexp(header) }
- Read upRead up
- Exclude checks
Checks that the ABC size of methods is not higher than the configured maximum. The ABC size is based on assignments, branches (method calls), and conditions. See http://c2.com/cgi/wiki?AbcMetric and https://en.wikipedia.org/wiki/ABC_Software_Metric.
Interpreting ABC size:
-
<= 17
satisfactory -
18..30
unsatisfactory -
>
30 dangerous
You can have repeated "attributes" calls count as a single "branch".
For this purpose, attributes are any method with no argument; no attempt
is meant to distinguish actual attr_reader
from other methods.
Example: CountRepeatedAttributes: false (default is true)
# `model` and `current_user`, referenced 3 times each,
# are each counted as only 1 branch each if
# `CountRepeatedAttributes` is set to 'false'
def search
@posts = model.active.visible_by(current_user)
.search(params[:q])
@posts = model.some_process(@posts, current_user)
@posts = model.another_process(@posts, current_user)
render 'pages/search/page'
end
This cop also takes into account AllowedMethods
(defaults to []
)
And AllowedPatterns
(defaults to []
)
Assignment Branch Condition size for spreadsheet_data is too high. [<7, 32, 15> 36.03/17] Open
def spreadsheet_data
begin
spreadsheet_data = spreadsheet.sheet(spreadsheet.sheets[0]).parse(header_search: required_headers)
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 that the ABC size of methods is not higher than the configured maximum. The ABC size is based on assignments, branches (method calls), and conditions. See http://c2.com/cgi/wiki?AbcMetric and https://en.wikipedia.org/wiki/ABC_Software_Metric.
Interpreting ABC size:
-
<= 17
satisfactory -
18..30
unsatisfactory -
>
30 dangerous
You can have repeated "attributes" calls count as a single "branch".
For this purpose, attributes are any method with no argument; no attempt
is meant to distinguish actual attr_reader
from other methods.
Example: CountRepeatedAttributes: false (default is true)
# `model` and `current_user`, referenced 3 times each,
# are each counted as only 1 branch each if
# `CountRepeatedAttributes` is set to 'false'
def search
@posts = model.active.visible_by(current_user)
.search(params[:q])
@posts = model.some_process(@posts, current_user)
@posts = model.another_process(@posts, current_user)
render 'pages/search/page'
end
This cop also takes into account AllowedMethods
(defaults to []
)
And AllowedPatterns
(defaults to []
)
Assignment Branch Condition size for import is too high. [<15, 37, 12> 41.69/17] Open
def import(save: true, status_tracker: nil)
self.class.before.call(@context, options) if self.class.before.is_a?(Proc)
at = 0
errors_lines = []
success_count = 0
- Read upRead up
- Exclude checks
Checks that the ABC size of methods is not higher than the configured maximum. The ABC size is based on assignments, branches (method calls), and conditions. See http://c2.com/cgi/wiki?AbcMetric and https://en.wikipedia.org/wiki/ABC_Software_Metric.
Interpreting ABC size:
-
<= 17
satisfactory -
18..30
unsatisfactory -
>
30 dangerous
You can have repeated "attributes" calls count as a single "branch".
For this purpose, attributes are any method with no argument; no attempt
is meant to distinguish actual attr_reader
from other methods.
Example: CountRepeatedAttributes: false (default is true)
# `model` and `current_user`, referenced 3 times each,
# are each counted as only 1 branch each if
# `CountRepeatedAttributes` is set to 'false'
def search
@posts = model.active.visible_by(current_user)
.search(params[:q])
@posts = model.some_process(@posts, current_user)
@posts = model.another_process(@posts, current_user)
render 'pages/search/page'
end
This cop also takes into account AllowedMethods
(defaults to []
)
And AllowedPatterns
(defaults to []
)
Line is too long. [167/120] Open
@required_columns = self.class.schema.select { |_field, column_config| !column_config.is_a?(Hash) || !column_config.key?(:required) || column_config[:required] }
- Read upRead up
- Exclude checks
Checks the length of lines in the source code.
The maximum length is configurable.
The tab size is configured in the IndentationWidth
of the Layout/IndentationStyle
cop.
It also ignores a shebang line by default.
This cop has some autocorrection capabilities. It can programmatically shorten certain long lines by inserting line breaks into expressions that can be safely split across lines. These include arrays, hashes, and method calls with argument lists.
If autocorrection is enabled, the following Layout cops are recommended to further format the broken lines. (Many of these are enabled by default.)
- ArgumentAlignment
- ArrayAlignment
- BlockAlignment
- BlockDelimiters
- BlockEndNewline
- ClosingParenthesisIndentation
- FirstArgumentIndentation
- FirstArrayElementIndentation
- FirstHashElementIndentation
- FirstParameterIndentation
- HashAlignment
- IndentationWidth
- MultilineArrayLineBreaks
- MultilineBlockLayout
- MultilineHashBraceLayout
- MultilineHashKeyLineBreaks
- MultilineMethodArgumentLineBreaks
- MultilineMethodParameterLineBreaks
- ParameterAlignment
Together, these cops will pretty print hashes, arrays, method calls, etc. For example, let's say the max columns is 25:
Example:
# bad
{foo: "0000000000", bar: "0000000000", baz: "0000000000"}
# good
{foo: "0000000000",
bar: "0000000000", baz: "0000000000"}
# good (with recommended cops enabled)
{
foo: "0000000000",
bar: "0000000000",
baz: "0000000000",
}
Line is too long. [164/120] 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 the length of lines in the source code.
The maximum length is configurable.
The tab size is configured in the IndentationWidth
of the Layout/IndentationStyle
cop.
It also ignores a shebang line by default.
This cop has some autocorrection capabilities. It can programmatically shorten certain long lines by inserting line breaks into expressions that can be safely split across lines. These include arrays, hashes, and method calls with argument lists.
If autocorrection is enabled, the following Layout cops are recommended to further format the broken lines. (Many of these are enabled by default.)
- ArgumentAlignment
- ArrayAlignment
- BlockAlignment
- BlockDelimiters
- BlockEndNewline
- ClosingParenthesisIndentation
- FirstArgumentIndentation
- FirstArrayElementIndentation
- FirstHashElementIndentation
- FirstParameterIndentation
- HashAlignment
- IndentationWidth
- MultilineArrayLineBreaks
- MultilineBlockLayout
- MultilineHashBraceLayout
- MultilineHashKeyLineBreaks
- MultilineMethodArgumentLineBreaks
- MultilineMethodParameterLineBreaks
- ParameterAlignment
Together, these cops will pretty print hashes, arrays, method calls, etc. For example, let's say the max columns is 25:
Example:
# bad
{foo: "0000000000", bar: "0000000000", baz: "0000000000"}
# good
{foo: "0000000000",
bar: "0000000000", baz: "0000000000"}
# good (with recommended cops enabled)
{
foo: "0000000000",
bar: "0000000000",
baz: "0000000000",
}
Line is too long. [158/120] Open
@header_scheme[self.class.primary_key.to_s] = self.class.primary_key.to_s if self.class.primary_key && !self.class.schema[self.class.primary_key.to_sym]
- Read upRead up
- Exclude checks
Checks the length of lines in the source code.
The maximum length is configurable.
The tab size is configured in the IndentationWidth
of the Layout/IndentationStyle
cop.
It also ignores a shebang line by default.
This cop has some autocorrection capabilities. It can programmatically shorten certain long lines by inserting line breaks into expressions that can be safely split across lines. These include arrays, hashes, and method calls with argument lists.
If autocorrection is enabled, the following Layout cops are recommended to further format the broken lines. (Many of these are enabled by default.)
- ArgumentAlignment
- ArrayAlignment
- BlockAlignment
- BlockDelimiters
- BlockEndNewline
- ClosingParenthesisIndentation
- FirstArgumentIndentation
- FirstArrayElementIndentation
- FirstHashElementIndentation
- FirstParameterIndentation
- HashAlignment
- IndentationWidth
- MultilineArrayLineBreaks
- MultilineBlockLayout
- MultilineHashBraceLayout
- MultilineHashKeyLineBreaks
- MultilineMethodArgumentLineBreaks
- MultilineMethodParameterLineBreaks
- ParameterAlignment
Together, these cops will pretty print hashes, arrays, method calls, etc. For example, let's say the max columns is 25:
Example:
# bad
{foo: "0000000000", bar: "0000000000", baz: "0000000000"}
# good
{foo: "0000000000",
bar: "0000000000", baz: "0000000000"}
# good (with recommended cops enabled)
{
foo: "0000000000",
bar: "0000000000",
baz: "0000000000",
}
Line is too long. [145/120] Open
@required_headers = @required_columns.values.map { |column| get_column_header(column) }.map { |header| transform_header_to_regexp(header) }
- Read upRead up
- Exclude checks
Checks the length of lines in the source code.
The maximum length is configurable.
The tab size is configured in the IndentationWidth
of the Layout/IndentationStyle
cop.
It also ignores a shebang line by default.
This cop has some autocorrection capabilities. It can programmatically shorten certain long lines by inserting line breaks into expressions that can be safely split across lines. These include arrays, hashes, and method calls with argument lists.
If autocorrection is enabled, the following Layout cops are recommended to further format the broken lines. (Many of these are enabled by default.)
- ArgumentAlignment
- ArrayAlignment
- BlockAlignment
- BlockDelimiters
- BlockEndNewline
- ClosingParenthesisIndentation
- FirstArgumentIndentation
- FirstArrayElementIndentation
- FirstHashElementIndentation
- FirstParameterIndentation
- HashAlignment
- IndentationWidth
- MultilineArrayLineBreaks
- MultilineBlockLayout
- MultilineHashBraceLayout
- MultilineHashKeyLineBreaks
- MultilineMethodArgumentLineBreaks
- MultilineMethodParameterLineBreaks
- ParameterAlignment
Together, these cops will pretty print hashes, arrays, method calls, etc. For example, let's say the max columns is 25:
Example:
# bad
{foo: "0000000000", bar: "0000000000", baz: "0000000000"}
# good
{foo: "0000000000",
bar: "0000000000", baz: "0000000000"}
# good (with recommended cops enabled)
{
foo: "0000000000",
bar: "0000000000",
baz: "0000000000",
}
Line is too long. [144/120] 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 the length of lines in the source code.
The maximum length is configurable.
The tab size is configured in the IndentationWidth
of the Layout/IndentationStyle
cop.
It also ignores a shebang line by default.
This cop has some autocorrection capabilities. It can programmatically shorten certain long lines by inserting line breaks into expressions that can be safely split across lines. These include arrays, hashes, and method calls with argument lists.
If autocorrection is enabled, the following Layout cops are recommended to further format the broken lines. (Many of these are enabled by default.)
- ArgumentAlignment
- ArrayAlignment
- BlockAlignment
- BlockDelimiters
- BlockEndNewline
- ClosingParenthesisIndentation
- FirstArgumentIndentation
- FirstArrayElementIndentation
- FirstHashElementIndentation
- FirstParameterIndentation
- HashAlignment
- IndentationWidth
- MultilineArrayLineBreaks
- MultilineBlockLayout
- MultilineHashBraceLayout
- MultilineHashKeyLineBreaks
- MultilineMethodArgumentLineBreaks
- MultilineMethodParameterLineBreaks
- ParameterAlignment
Together, these cops will pretty print hashes, arrays, method calls, etc. For example, let's say the max columns is 25:
Example:
# bad
{foo: "0000000000", bar: "0000000000", baz: "0000000000"}
# good
{foo: "0000000000",
bar: "0000000000", baz: "0000000000"}
# good (with recommended cops enabled)
{
foo: "0000000000",
bar: "0000000000",
baz: "0000000000",
}
Line is too long. [141/120] Open
record = self.class.model_klass.constantize.find_or_initialize_by("#{self.class.primary_key}": line[self.class.primary_key.to_sym])
- Read upRead up
- Exclude checks
Checks the length of lines in the source code.
The maximum length is configurable.
The tab size is configured in the IndentationWidth
of the Layout/IndentationStyle
cop.
It also ignores a shebang line by default.
This cop has some autocorrection capabilities. It can programmatically shorten certain long lines by inserting line breaks into expressions that can be safely split across lines. These include arrays, hashes, and method calls with argument lists.
If autocorrection is enabled, the following Layout cops are recommended to further format the broken lines. (Many of these are enabled by default.)
- ArgumentAlignment
- ArrayAlignment
- BlockAlignment
- BlockDelimiters
- BlockEndNewline
- ClosingParenthesisIndentation
- FirstArgumentIndentation
- FirstArrayElementIndentation
- FirstHashElementIndentation
- FirstParameterIndentation
- HashAlignment
- IndentationWidth
- MultilineArrayLineBreaks
- MultilineBlockLayout
- MultilineHashBraceLayout
- MultilineHashKeyLineBreaks
- MultilineMethodArgumentLineBreaks
- MultilineMethodParameterLineBreaks
- ParameterAlignment
Together, these cops will pretty print hashes, arrays, method calls, etc. For example, let's say the max columns is 25:
Example:
# bad
{foo: "0000000000", bar: "0000000000", baz: "0000000000"}
# good
{foo: "0000000000",
bar: "0000000000", baz: "0000000000"}
# good (with recommended cops enabled)
{
foo: "0000000000",
bar: "0000000000",
baz: "0000000000",
}
Unused block argument - k
. If it's necessary, use _
or _k
as an argument name to indicate that it won't be used. Open
error_line = line.map { |k, v| v }
- Read upRead up
- Exclude checks
Checks for unused block arguments.
Example:
# bad
do_something do |used, unused|
puts used
end
do_something do |bar|
puts :foo
end
define_method(:foo) do |bar|
puts :baz
end
# good
do_something do |used, _unused|
puts used
end
do_something do
puts :foo
end
define_method(:foo) do |_bar|
puts :baz
end
Example: IgnoreEmptyBlocks: true (default)
# good
do_something { |unused| }
Example: IgnoreEmptyBlocks: false
# bad
do_something { |unused| }
Example: AllowUnusedKeywordArguments: false (default)
# bad
do_something do |unused: 42|
foo
end
Example: AllowUnusedKeywordArguments: true
# good
do_something do |unused: 42|
foo
end
Unused method argument - status_tracker
. You can also write as import(*)
if you want the method to accept any arguments but don't care about them. Open
def import(save: true, status_tracker: nil)
- Read upRead up
- Exclude checks
Checks for unused method arguments.
Example:
# bad
def some_method(used, unused, _unused_but_allowed)
puts used
end
# good
def some_method(used, _unused, _unused_but_allowed)
puts used
end
Example: AllowUnusedKeywordArguments: false (default)
# bad
def do_something(used, unused: 42)
used
end
Example: AllowUnusedKeywordArguments: true
# good
def do_something(used, unused: 42)
used
end
Example: IgnoreEmptyMethods: true (default)
# good
def do_something(unused)
end
Example: IgnoreEmptyMethods: false
# bad
def do_something(unused)
end
Example: IgnoreNotImplementedMethods: true (default)
# good
def do_something(unused)
raise NotImplementedError
end
def do_something_else(unused)
fail "TODO"
end
Example: IgnoreNotImplementedMethods: false
# bad
def do_something(unused)
raise NotImplementedError
end
def do_something_else(unused)
fail "TODO"
end
Modifier form of if
makes the line too long. Open
@header_scheme[self.class.primary_key.to_s] = self.class.primary_key.to_s if self.class.primary_key && !self.class.schema[self.class.primary_key.to_sym]
- 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 spreadsheet_data.size.positive?
instead of spreadsheet_data.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 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?
Modifier form of unless
makes the line too long. 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 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
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
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
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?
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
Trailing whitespace detected. Open
errors_lines.push(error_line)
- 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
at = (((index + 1).to_d / lines.size) * 100.to_d)
- 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
Missing top-level documentation comment for class NtqExcelsior::Importer
. Open
class Importer
- Read upRead up
- Exclude checks
Checks for missing top-level documentation of classes and modules. Classes with no body are exempt from the check and so are namespace modules - modules that have nothing in their bodies except classes, other modules, constant definitions or constant visibility declarations.
The documentation requirement is annulled if the class or module has
a #:nodoc:
comment next to it. Likewise, #:nodoc: all
does the
same for all its children.
Example:
# bad
class Person
# ...
end
module Math
end
# good
# Description/Explanation of Person class
class Person
# ...
end
# allowed
# Class without body
class Person
end
# Namespace - A namespace can be a class or a module
# Containing a class
module Namespace
# Description/Explanation of Person class
class Person
# ...
end
end
# Containing constant visibility declaration
module Namespace
class Private
end
private_constant :Private
end
# Containing constant definition
module Namespace
Public = Class.new
end
# Macro calls
module Namespace
extend Foo
end
Example: AllowedConstants: ['ClassMethods']
# good
module A
module ClassMethods
# ...
end
end
Prefer ::Regexp.last_match(1)
over $1
. Open
header = $1
- Read upRead up
- Exclude checks
Looks for uses of Perl-style regexp match backreferences and their English versions like $1, $2, $&, &+, $MATCH, $PREMATCH, etc.
Example:
# bad
puts $1
# good
puts Regexp.last_match(1)
Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping. Open
e.message.delete_prefix('[').delete_suffix(']').split(",").map(&:strip).each do |header_missing|
- 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"
Method NtqExcelsior::Importer#lines
is defined at both lib/ntq_excelsior/importer.rb:6 and lib/ntq_excelsior/importer.rb:159. Open
def lines
- Read upRead up
- Exclude checks
Checks for duplicated instance (or singleton) method definitions.
Example:
# bad
def foo
1
end
def foo
2
end
Example:
# bad
def foo
1
end
alias foo bar
Example:
# good
def foo
1
end
def bar
2
end
Example:
# good
def foo
1
end
alias bar foo
Group together all attr_accessor
attributes. Open
attr_accessor :file, :check, :lines, :options, :status_tracker, :success
- Read upRead up
- Exclude checks
Checks for grouping of accessors in class
and module
bodies.
By default it enforces accessors to be placed in grouped declarations,
but it can be configured to enforce separating them in multiple declarations.
NOTE: If there is a method call before the accessor method it is always allowed as it might be intended like Sorbet.
Example: EnforcedStyle: grouped (default)
# bad
class Foo
attr_reader :bar
attr_reader :bax
attr_reader :baz
end
# good
class Foo
attr_reader :bar, :bax, :baz
end
# good
class Foo
# may be intended comment for bar.
attr_reader :bar
sig { returns(String) }
attr_reader :bax
may_be_intended_annotation :baz
attr_reader :baz
end
Example: EnforcedStyle: separated
# bad
class Foo
attr_reader :bar, :baz
end
# good
class Foo
attr_reader :bar
attr_reader :baz
end
Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping. Open
require 'ntq_excelsior/context'
- 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
raise 'File is missing' unless file.present?
- 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
e.message.delete_prefix('[').delete_suffix(']').split(",").map(&:strip).each do |header_missing|
- 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"
Use the return of the conditional for variable assignment and comparison. Open
if header_found[:header].is_a?(String)
missing_headers << header_found[:header]
else
missing_headers << (header_found[:humanized_header] || header_missing)
end
- Exclude checks
Indent access modifiers like private
. Open
private
- Read upRead up
- Exclude checks
Bare access modifiers (those not applying to specific methods) should be indented as deep as method definitions, or as deep as the class/module keyword, depending on configuration.
Example: EnforcedStyle: indent (default)
# bad
class Plumbus
private
def smooth; end
end
# good
class Plumbus
private
def smooth; end
end
Example: EnforcedStyle: outdent
# bad
class Plumbus
private
def smooth; end
end
# good
class Plumbus
private
def smooth; end
end
Unused method argument - save
. You can also write as import(*)
if you want the method to accept any arguments but don't care about them. Open
def import(save: true, status_tracker: nil)
- Read upRead up
- Exclude checks
Checks for unused method arguments.
Example:
# bad
def some_method(used, unused, _unused_but_allowed)
puts used
end
# good
def some_method(used, _unused, _unused_but_allowed)
puts used
end
Example: AllowUnusedKeywordArguments: false (default)
# bad
def do_something(used, unused: 42)
used
end
Example: AllowUnusedKeywordArguments: true
# good
def do_something(used, unused: 42)
used
end
Example: IgnoreEmptyMethods: true (default)
# good
def do_something(unused)
end
Example: IgnoreEmptyMethods: false
# bad
def do_something(unused)
end
Example: IgnoreNotImplementedMethods: true (default)
# good
def do_something(unused)
raise NotImplementedError
end
def do_something_else(unused)
fail "TODO"
end
Example: IgnoreNotImplementedMethods: false
# bad
def do_something(unused)
raise NotImplementedError
end
def do_something_else(unused)
fail "TODO"
end
Redundant escape inside regexp literal Open
if gsub_enclosure && header.scan(/^\/[\^]?([^(\$\/)]+)[\$]?\/[i]?$/i) && $1
- Read upRead up
- Exclude checks
Checks for redundant escapes inside Regexp literals.
Example:
# bad
%r{foo\/bar}
# good
%r{foo/bar}
# good
/foo\/bar/
# good
%r/foo\/bar/
# good
%r!foo\!bar!
# bad
/a\-b/
# good
/a-b/
# bad
/[\+\-]\d/
# good
/[+\-]\d/
Don't use parentheses around a method call. Open
if (self.class.autoset)
- Read upRead up
- Exclude checks
Checks for redundant parentheses.
Example:
# bad
(x) if ((y.z).nil?)
# good
x if y.z.nil?
Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping. Open
@action = record.persisted? ? 'update' : 'create'
- 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"
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.autoset)
- 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
Redundant escape inside regexp literal Open
if gsub_enclosure && header.scan(/^\/[\^]?([^(\$\/)]+)[\$]?\/[i]?$/i) && $1
- Read upRead up
- Exclude checks
Checks for redundant escapes inside Regexp literals.
Example:
# bad
%r{foo\/bar}
# good
%r{foo/bar}
# good
/foo\/bar/
# good
%r/foo\/bar/
# good
%r!foo\!bar!
# bad
/a\-b/
# good
/a-b/
# bad
/[\+\-]\d/
# good
/[+\-]\d/
Redundant return
detected. Open
return { status: :error, errors: @errors.join(", ") }
- Read upRead up
- Exclude checks
Checks for redundant return
expressions.
Example:
# These bad cases should be extended to handle methods whose body is
# if/else or a case expression with a default branch.
# bad
def test
return something
end
# bad
def test
one
two
three
return something
end
# bad
def test
return something if something_else
end
# good
def test
something if something_else
end
# good
def test
if x
elsif y
else
end
end
Example: AllowMultipleReturnValues: false (default)
# bad
def test
return x, y
end
Example: AllowMultipleReturnValues: true
# good
def test
return x, y
end
Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping. Open
require 'roo'
- 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"
Group together all attr_accessor
attributes. Open
attr_accessor :context
- Read upRead up
- Exclude checks
Checks for grouping of accessors in class
and module
bodies.
By default it enforces accessors to be placed in grouped declarations,
but it can be configured to enforce separating them in multiple declarations.
NOTE: If there is a method call before the accessor method it is always allowed as it might be intended like Sorbet.
Example: EnforcedStyle: grouped (default)
# bad
class Foo
attr_reader :bar
attr_reader :bax
attr_reader :baz
end
# good
class Foo
attr_reader :bar, :bax, :baz
end
# good
class Foo
# may be intended comment for bar.
attr_reader :bar
sig { returns(String) }
attr_reader :bax
may_be_intended_annotation :baz
attr_reader :baz
end
Example: EnforcedStyle: separated
# bad
class Foo
attr_reader :bar, :baz
end
# good
class Foo
attr_reader :bar
attr_reader :baz
end
Favor modifier if
usage when having a single-line body. Another good alternative is the usage of control flow &&
/||
. Open
if gsub_enclosure && header.scan(/^\/[\^]?([^(\$\/)]+)[\$]?\/[i]?$/i) && $1
- 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
Prefer ::Regexp.last_match(1)
over $1
. Open
if gsub_enclosure && header.scan(/^\/[\^]?([^(\$\/)]+)[\$]?\/[i]?$/i) && $1
- Read upRead up
- Exclude checks
Looks for uses of Perl-style regexp match backreferences and their English versions like $1, $2, $&, &+, $MATCH, $PREMATCH, etc.
Example:
# bad
puts $1
# good
puts Regexp.last_match(1)
Redundant begin
block detected. Open
begin
- Read upRead up
- Exclude checks
Checks for redundant begin
blocks.
Currently it checks for code like this:
Example:
# bad
def redundant
begin
ala
bala
rescue StandardError => e
something
end
end
# good
def preferred
ala
bala
rescue StandardError => e
something
end
# bad
begin
do_something
end
# good
do_something
# bad
# When using Ruby 2.5 or later.
do_something do
begin
something
rescue => ex
anything
end
end
# good
# In Ruby 2.5 or later, you can omit `begin` in `do-end` block.
do_something do
something
rescue => ex
anything
end
# good
# Stabby lambdas don't support implicit `begin` in `do-end` blocks.
-> do
begin
foo
rescue Bar
baz
end
end
Don't use parentheses around a logical expression. Open
if (self.class.autosave.nil? || self.class.autosave)
- Read upRead up
- Exclude checks
Checks for redundant parentheses.
Example:
# bad
(x) if ((y.z).nil?)
# good
x if y.z.nil?
Use %r
around regular expression. Open
if gsub_enclosure && header.scan(/^\/[\^]?([^(\$\/)]+)[\$]?\/[i]?$/i) && $1
- Read upRead up
- Exclude checks
Enforces using //
or %r
around regular expressions.
NOTE: The following %r
cases using a regexp starts with a blank or =
as a method argument allowed to prevent syntax errors.
do_something %r{ regexp} # `do_something / regexp/` is an invalid syntax.
do_something %r{=regexp} # `do_something /=regexp/` is an invalid syntax.
Example: EnforcedStyle: slashes (default)
# bad
snake_case = %r{^[\dA-Z_]+$}
# bad
regex = %r{
foo
(bar)
(baz)
}x
# good
snake_case = /^[\dA-Z_]+$/
# good
regex = /
foo
(bar)
(baz)
/x
Example: EnforcedStyle: percent_r
# bad
snake_case = /^[\dA-Z_]+$/
# bad
regex = /
foo
(bar)
(baz)
/x
# good
snake_case = %r{^[\dA-Z_]+$}
# good
regex = %r{
foo
(bar)
(baz)
}x
Example: EnforcedStyle: mixed
# bad
snake_case = %r{^[\dA-Z_]+$}
# bad
regex = /
foo
(bar)
(baz)
/x
# good
snake_case = /^[\dA-Z_]+$/
# good
regex = %r{
foo
(bar)
(baz)
}x
Example: AllowInnerSlashes: false (default)
# If `false`, the cop will always recommend using `%r` if one or more
# slashes are found in the regexp string.
# bad
x =~ /home\//
# good
x =~ %r{home/}
Example: AllowInnerSlashes: true
# good
x =~ /home\//
Missing frozen string literal comment. Open
require 'roo'
- Read upRead up
- Exclude checks
Helps you transition from mutable string literals
to frozen string literals.
It will add the # frozen_string_literal: true
magic comment to the top
of files to enable frozen string literals. Frozen string literals may be
default in future Ruby. The comment will be added below a shebang and
encoding comment. The frozen string literal comment is only valid in Ruby 2.3+.
Note that the cop will accept files where the comment exists but is set
to false
instead of true
.
To require a blank line after this comment, please see
Layout/EmptyLineAfterMagicComment
cop.
Safety:
This cop's autocorrection is unsafe since any strings mutations will
change from being accepted to raising FrozenError
, as all strings
will become frozen by default, and will need to be manually refactored.
Example: EnforcedStyle: always (default)
# The `always` style will always add the frozen string literal comment
# to a file, regardless of the Ruby version or if `freeze` or `<<` are
# called on a string literal.
# bad
module Bar
# ...
end
# good
# frozen_string_literal: true
module Bar
# ...
end
# good
# frozen_string_literal: false
module Bar
# ...
end
Example: EnforcedStyle: never
# The `never` will enforce that the frozen string literal comment does
# not exist in a file.
# bad
# frozen_string_literal: true
module Baz
# ...
end
# good
module Baz
# ...
end
Example: EnforcedStyle: always_true
# The `always_true` style enforces that the frozen string literal
# comment is set to `true`. This is a stricter option than `always`
# and forces projects to use frozen string literals.
# bad
# frozen_string_literal: false
module Baz
# ...
end
# bad
module Baz
# ...
end
# good
# frozen_string_literal: true
module Bar
# ...
end
Prefer keyword arguments for arguments with a boolean default value; use gsub_enclosure: false
instead of gsub_enclosure = false
. Open
def transform_header_to_regexp(header, gsub_enclosure = false)
- Read upRead up
- Exclude checks
Checks for places where keyword arguments can be used instead of
boolean arguments when defining methods. respond_to_missing?
method is allowed by default.
These are customizable with AllowedMethods
option.
Safety:
This cop is unsafe because changing a method signature will implicitly change behavior.
Example:
# bad
def some_method(bar = false)
puts bar
end
# bad - common hack before keyword args were introduced
def some_method(options = {})
bar = options.fetch(:bar, false)
puts bar
end
# good
def some_method(bar: false)
puts bar
end
Example: AllowedMethods: ['some_method']
# good
def some_method(bar = false)
puts bar
end
Redundant single-element character class, [\$]
can be replaced with \$
. 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]/
Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping. 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 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"
Shadowing outer local variable - header
. Open
header_scheme.each do |header, field|
- Read upRead up
- Exclude checks
Checks for the use of local variable names from an outer scope
in block arguments or block-local variables. This mirrors the warning
given by ruby -cw
prior to Ruby 2.6:
"shadowing outer local variable - foo".
NOTE: Shadowing of variables in block passed to Ractor.new
is allowed
because Ractor
should not access outer variables.
eg. following style is encouraged:
```ruby
worker_id, pipe = env
Ractor.new(worker_id, pipe) do |worker_id, pipe|
end
```
Example:
# bad
def some_method
foo = 1
2.times do |foo| # shadowing outer `foo`
do_something(foo)
end
end
Example:
# good
def some_method
foo = 1
2.times do |bar|
do_something(bar)
end
end
Use the double pipe equals operator ||=
instead. Open
record = self.class.model_klass.constantize.new unless record
- Read upRead up
- Exclude checks
Checks for potential usage of the ||=
operator.
Example:
# bad
name = name ? name : 'Bozhidar'
# bad
name = if name
name
else
'Bozhidar'
end
# bad
unless name
name = 'Bozhidar'
end
# bad
name = 'Bozhidar' unless name
# good - set name to 'Bozhidar', only if it's nil or false
name ||= 'Bozhidar'
Redundant single-element character class, [\^]
can be replaced with \^
. 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]/
Final newline missing. Open
end
- Read upRead up
- Exclude checks
Looks for trailing blank lines and a final newline in the source code.
Example: EnforcedStyle: final_newline (default)
# `final_newline` looks for one newline at the end of files.
# bad
class Foo; end
# EOF
# bad
class Foo; end # EOF
# good
class Foo; end
# EOF
Example: EnforcedStyle: finalblankline
# `final_blank_line` looks for one blank line followed by a new line
# at the end of files.
# bad
class Foo; end
# EOF
# bad
class Foo; end # EOF
# good
class Foo; end
# EOF
Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping. Open
@action = record.persisted? ? 'update' : 'create'
- 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"
Redundant safe navigation detected, use .
instead. Open
elsif header_found&.is_a?(String)
- 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 the return of the conditional for variable assignment and comparison. Open
if save
@success = record.save
else
@success = record.valid?
end
- Exclude checks