Method build_search_query
has a Cognitive Complexity of 86 (exceeds 5 allowed). Consider refactoring. Open
def build_search_query
doc_query = self
search.query do
function_score do
- 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 build_search_query
has 93 lines of code (exceeds 25 allowed). Consider refactoring. Open
def build_search_query
doc_query = self
search.query do
function_score do
File document_query.rb
has 319 lines of code (exceeds 250 allowed). Consider refactoring. Open
class DocumentQuery
include Elasticsearch::DSL
HIGHLIGHT_OPTIONS = {
pre_tags: ["\ue000"],
Cyclomatic complexity for build_search_query is too high. [17/7] Open
def build_search_query
doc_query = self
search.query do
function_score do
- 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 build_search_query is too high. [18/8] Open
def build_search_query
doc_query = self
search.query do
function_score do
- 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
Class DocumentQuery
has 21 methods (exceeds 20 allowed). Consider refactoring. Open
class DocumentQuery
include Elasticsearch::DSL
HIGHLIGHT_OPTIONS = {
pre_tags: ["\ue000"],
Assignment Branch Condition size for build_search_query is too high. [<6, 118, 17> 119.4/17] Open
def build_search_query
doc_query = self
search.query do
function_score do
- 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 []
)
Use match?
instead of ===
when MatchData
is not used. Open
elsif /description/ === field
- Read upRead up
- Exclude checks
In Ruby 2.4, String#match?
, Regexp#match?
and Symbol#match?
have been added. The methods are faster than match
.
Because the methods avoid creating a MatchData
object or saving
backref.
So, when MatchData
is not used, use match?
instead of match
.
Example:
# bad
def foo
if x =~ /re/
do_something
end
end
# bad
def foo
if x.match(/re/)
do_something
end
end
# bad
def foo
if /re/ === x
do_something
end
end
# good
def foo
if x.match?(/re/)
do_something
end
end
# good
def foo
if x =~ /re/
do_something(Regexp.last_match)
end
end
# good
def foo
if x.match(/re/)
do_something($~)
end
end
# good
def foo
if /re/ === x
do_something($~)
end
end
Use match?
instead of match
when MatchData
is not used. Open
unless doc_query.query.match(/".*"/)
- Read upRead up
- Exclude checks
In Ruby 2.4, String#match?
, Regexp#match?
and Symbol#match?
have been added. The methods are faster than match
.
Because the methods avoid creating a MatchData
object or saving
backref.
So, when MatchData
is not used, use match?
instead of match
.
Example:
# bad
def foo
if x =~ /re/
do_something
end
end
# bad
def foo
if x.match(/re/)
do_something
end
end
# bad
def foo
if /re/ === x
do_something
end
end
# good
def foo
if x.match?(/re/)
do_something
end
end
# good
def foo
if x =~ /re/
do_something(Regexp.last_match)
end
end
# good
def foo
if x.match(/re/)
do_something($~)
end
end
# good
def foo
if /re/ === x
do_something($~)
end
end
Use =~
in places where the MatchData
returned by #match
will not be used. Open
unless doc_query.query.match(/".*"/)
- Read upRead up
- Exclude checks
This cop identifies the use of Regexp#match
or String#match
, which
returns #<MatchData>
/nil
. The return value of =~
is an integral
index/nil
and is more performant.
Example:
# bad
do_something if str.match(/regex/)
while regex.match('str')
do_something
end
# good
method(str =~ /regex/)
return value unless regex =~ 'str'
Use match?
instead of ===
when MatchData
is not used. Open
if /title/ === field
- Read upRead up
- Exclude checks
In Ruby 2.4, String#match?
, Regexp#match?
and Symbol#match?
have been added. The methods are faster than match
.
Because the methods avoid creating a MatchData
object or saving
backref.
So, when MatchData
is not used, use match?
instead of match
.
Example:
# bad
def foo
if x =~ /re/
do_something
end
end
# bad
def foo
if x.match(/re/)
do_something
end
end
# bad
def foo
if /re/ === x
do_something
end
end
# good
def foo
if x.match?(/re/)
do_something
end
end
# good
def foo
if x =~ /re/
do_something(Regexp.last_match)
end
end
# good
def foo
if x.match(/re/)
do_something($~)
end
end
# good
def foo
if /re/ === x
do_something($~)
end
end
Use each_value
instead of values.each
. Open
doc_query.full_text_fields.values.each do |field|
- 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.values.each { |v| p v }
# good
hash.each_key { |k| p k }
hash.each_value { |v| p v }
Example: AllowedReceivers: ['execute']
# good
execute(sql).keys.each { |v| p v }
execute(sql).values.each { |v| p v }
Redundant begin
block detected. Open
@full_text_fields ||= 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
Avoid the use of the case equality operator ===
. Open
if /title/ === field
- Read upRead up
- Exclude checks
Checks for uses of the case equality operator(===).
If AllowOnConstant
option is enabled, the cop will ignore violations when the receiver of
the case equality operator is a constant.
If AllowOnSelfClass
option is enabled, the cop will ignore violations when the receiver of
the case equality operator is self.class
. Note intermediate variables are not accepted.
Example:
# bad
(1..100) === 7
/something/ === some_string
# good
something.is_a?(Array)
(1..100).include?(7)
/something/.match?(some_string)
Example: AllowOnConstant: false (default)
# bad
Array === something
Example: AllowOnConstant: true
# good
Array === something
Example: AllowOnSelfClass: false (default)
# bad
self.class === something
Example: AllowOnSelfClass: true
# good
self.class === something
Redundant escape of / inside string literal. Open
must_not { regexp path: { value: "https?:\/\/#{site_filter.domain_name}#{site_filter.url_path}/.*" } }
- Read upRead up
- Exclude checks
Checks for redundant escapes in string literals.
Example:
# bad - no need to escape # without following {/$/@
"\#foo"
# bad - no need to escape single quotes inside double quoted string
"\'foo\'"
# bad - heredocs are also checked for unnecessary escapes
<<~STR
\#foo \"foo\"
STR
# good
"#foo"
# good
"\#{no_interpolation}"
# good
"'foo'"
# good
"foo\
bar"
# good
<<~STR
#foo "foo"
STR
Redundant escape of / inside string literal. Open
must_not { regexp path: { value: "https?:\/\/#{site_filter.domain_name}#{site_filter.url_path}/.*" } }
- Read upRead up
- Exclude checks
Checks for redundant escapes in string literals.
Example:
# bad - no need to escape # without following {/$/@
"\#foo"
# bad - no need to escape single quotes inside double quoted string
"\'foo\'"
# bad - heredocs are also checked for unnecessary escapes
<<~STR
\#foo \"foo\"
STR
# good
"#foo"
# good
"\#{no_interpolation}"
# good
"'foo'"
# good
"foo\
bar"
# good
<<~STR
#foo "foo"
STR
Avoid the use of the case equality operator ===
. Open
elsif /description/ === field
- Read upRead up
- Exclude checks
Checks for uses of the case equality operator(===).
If AllowOnConstant
option is enabled, the cop will ignore violations when the receiver of
the case equality operator is a constant.
If AllowOnSelfClass
option is enabled, the cop will ignore violations when the receiver of
the case equality operator is self.class
. Note intermediate variables are not accepted.
Example:
# bad
(1..100) === 7
/something/ === some_string
# good
something.is_a?(Array)
(1..100).include?(7)
/something/.match?(some_string)
Example: AllowOnConstant: false (default)
# bad
Array === something
Example: AllowOnConstant: true
# good
Array === something
Example: AllowOnSelfClass: false (default)
# bad
self.class === something
Example: AllowOnSelfClass: true
# good
self.class === something
sort
expects at least 2 positional arguments, got 0. Open
search.sort { by :changed, order: 'desc' } if @options[:sort_by_date]
- Read upRead up
- Exclude checks
Checks for a block that is known to need more positional
block arguments than are given (by default this is configured for
Enumerable
methods needing 2 arguments). Optional arguments are allowed,
although they don't generally make sense as the default value will
be used. Blocks that have no receiver, or take splatted arguments
(ie. *args
) are always accepted.
Keyword arguments (including **kwargs
) do not get counted towards
this, as they are not used by the methods in question.
Method names and their expected arity can be configured like this:
Methods:
inject: 2
reduce: 2
Safety:
This cop matches for method names only and hence cannot tell apart methods with same name in different classes, which may lead to a false positive.
Example:
# bad
values.reduce {}
values.min { |a| a }
values.sort { |a; b| a + b }
# good
values.reduce { |memo, obj| memo << obj }
values.min { |a, b| a <=> b }
values.sort { |*x| x[0] <=> x[1] }
Omit the hash value. Open
query: query,
- Read upRead up
- Exclude checks
Checks hash literal syntax.
It can enforce either the use of the class hash rocket syntax or the use of the newer Ruby 1.9 syntax (when applicable).
A separate offense is registered for each problematic pair.
The supported styles are:
- ruby19 - forces use of the 1.9 syntax (e.g.
{a: 1}
) when hashes have all symbols for keys - hash_rockets - forces use of hash rockets for all hashes
- nomixedkeys - simply checks for hashes with mixed syntaxes
- ruby19nomixed_keys - forces use of ruby 1.9 syntax and forbids mixed syntax hashes
This cop has EnforcedShorthandSyntax
option.
It can enforce either the use of the explicit hash value syntax or
the use of Ruby 3.1's hash value shorthand syntax.
The supported styles are:
- always - forces use of the 3.1 syntax (e.g. {foo:})
- never - forces use of explicit hash literal value
- either - accepts both shorthand and explicit use of hash literal value
- consistent - forces use of the 3.1 syntax only if all values can be omitted in the hash
Example: EnforcedStyle: ruby19 (default)
# bad
{:a => 2}
{b: 1, :c => 2}
# good
{a: 2, b: 1}
{:c => 2, 'd' => 2} # acceptable since 'd' isn't a symbol
{d: 1, 'e' => 2} # technically not forbidden
Example: EnforcedStyle: hash_rockets
# bad
{a: 1, b: 2}
{c: 1, 'd' => 5}
# good
{:a => 1, :b => 2}
Example: EnforcedStyle: nomixedkeys
# bad
{:a => 1, b: 2}
{c: 1, 'd' => 2}
# good
{:a => 1, :b => 2}
{c: 1, d: 2}
Example: EnforcedStyle: ruby19nomixed_keys
# bad
{:a => 1, :b => 2}
{c: 2, 'd' => 3} # should just use hash rockets
# good
{a: 1, b: 2}
{:c => 3, 'd' => 4}
Example: EnforcedShorthandSyntax: always (default)
# bad
{foo: foo, bar: bar}
# good
{foo:, bar:}
Example: EnforcedShorthandSyntax: never
# bad
{foo:, bar:}
# good
{foo: foo, bar: bar}
Example: EnforcedShorthandSyntax: either
# good
{foo: foo, bar: bar}
# good
{foo:, bar:}
Example: EnforcedShorthandSyntax: consistent
# bad - `foo` and `bar` values can be omitted
{foo: foo, bar: bar}
# bad - `bar` value can be omitted
{foo:, bar: bar}
# bad - mixed syntaxes
{foo:, bar: baz}
# good
{foo:, bar:}
# good - can't omit `baz`
{foo: foo, bar: baz}