Parameters should be whitelisted for mass assignment Open
params.require(:event).permit!
- Read upRead up
- Exclude checks
Mass assignment is a feature of Rails which allows an application to create a record from the values of a hash.
Example:
User.new(params[:user])
Unfortunately, if there is a user field called admin
which controls administrator access, now any user can make themselves an administrator.
attr_accessible
and attr_protected
can be used to limit mass assignment. However, Brakeman will warn unless attr_accessible
is used, or mass assignment is completely disabled.
There are two different mass assignment warnings which can arise. The first is when mass assignment actually occurs, such as the example above. This results in a warning like
Unprotected mass assignment near line 61: User.new(params[:user])
The other warning is raised whenever a model is found which does not use attr_accessible
. This produces generic warnings like
Mass assignment is not restricted using attr_accessible
with a list of affected models.
In Rails 3.1 and newer, mass assignment can easily be disabled:
config.active_record.whitelist_attributes = true
Unfortunately, it can also easily be bypassed:
User.new(params[:user], :without_protection => true)
Brakeman will warn on uses of without_protection
.
Class has too many lines. [369/100] Open
class EventsController < ApplicationController
before_action :verify_current_user
before_action { verify_current_user_role("role_event_record") }
before_action :init_graphql_client
before_action :load_category_list, only: [:edit, :new, :create]
- Read upRead up
- Exclude checks
This cop checks if the length a class exceeds some maximum value. Comment lines can optionally be ignored. The maximum allowed length is configurable.
Method has too many lines. [159/10] Open
def edit
results = @smart_village.query <<~GRAPHQL
query {
eventRecord(
id: #{params[:id]}
- Read upRead up
- Exclude checks
This cop checks if the length of a method exceeds some maximum value. Comment lines can optionally be ignored. The maximum allowed length is configurable.
Method convert_params_for_graphql
has a Cognitive Complexity of 85 (exceeds 5 allowed). Consider refactoring. Open
def convert_params_for_graphql
# Convert has_many categories
if @event_params["categories"].present?
categories = []
@event_params["categories"].each do |_key, category|
- 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 convert_params_for_graphql is too high. [90.98/15] Open
def convert_params_for_graphql
# Convert has_many categories
if @event_params["categories"].present?
categories = []
@event_params["categories"].each do |_key, category|
- Read upRead up
- Exclude checks
This cop 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.
Complex method EventsController#convert_params_for_graphql (128.9) Open
def convert_params_for_graphql
# Convert has_many categories
if @event_params["categories"].present?
categories = []
@event_params["categories"].each do |_key, category|
- Read upRead up
- Exclude checks
Flog calculates the ABC score for methods. The ABC score is based on assignments, branches (method calls), and conditions.
You can read more about ABC metrics or the flog tool
Method has too many lines. [71/10] Open
def convert_params_for_graphql
# Convert has_many categories
if @event_params["categories"].present?
categories = []
@event_params["categories"].each do |_key, category|
- Read upRead up
- Exclude checks
This cop checks if the length of a method exceeds some maximum value. Comment lines can optionally be ignored. The maximum allowed length is configurable.
Method edit
has 159 lines of code (exceeds 25 allowed). Consider refactoring. Open
def edit
results = @smart_village.query <<~GRAPHQL
query {
eventRecord(
id: #{params[:id]}
File events_controller.rb
has 371 lines of code (exceeds 250 allowed). Consider refactoring. Open
class EventsController < ApplicationController
before_action :verify_current_user
before_action { verify_current_user_role("role_event_record") }
before_action :init_graphql_client
before_action :load_category_list, only: [:edit, :new, :create]
Cyclomatic complexity for convert_params_for_graphql is too high. [28/6] Open
def convert_params_for_graphql
# Convert has_many categories
if @event_params["categories"].present?
categories = []
@event_params["categories"].each do |_key, category|
- Read upRead up
- Exclude checks
This cop 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.
Perceived complexity for convert_params_for_graphql is too high. [28/7] Open
def convert_params_for_graphql
# Convert has_many categories
if @event_params["categories"].present?
categories = []
@event_params["categories"].each do |_key, category|
- Read upRead up
- Exclude checks
This cop 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. [24/10] Open
def copy_event_and_set_invisibility
query = create_update_or_copy_mutation(is_copy: true)
begin
results = @smart_village.query query
@smart_village.query <<~GRAPHQL
- Read upRead up
- Exclude checks
This cop checks if the length of a method exceeds some maximum value. Comment lines can optionally be ignored. The maximum allowed length is configurable.
Method has too many lines. [24/10] Open
def index
results = @smart_village.query <<~GRAPHQL
query {
eventRecords {
id
- Read upRead up
- Exclude checks
This cop checks if the length of a method exceeds some maximum value. Comment lines can optionally be ignored. The maximum allowed length is configurable.
Method convert_params_for_graphql
has 71 lines of code (exceeds 25 allowed). Consider refactoring. Open
def convert_params_for_graphql
# Convert has_many categories
if @event_params["categories"].present?
categories = []
@event_params["categories"].each do |_key, category|
Method has too many lines. [18/10] Open
def destroy
results = @smart_village.query <<~GRAPHQL
mutation {
destroyRecord(
id: #{params["id"]},
- Read upRead up
- Exclude checks
This cop checks if the length of a method exceeds some maximum value. Comment lines can optionally be ignored. The maximum allowed length is configurable.
Method has too many lines. [14/10] Open
def new_event_record
OpenStruct.new(
addresses: [OpenStruct.new],
dates: [OpenStruct.new],
contacts: [OpenStruct.new],
- Read upRead up
- Exclude checks
This cop checks if the length of a method exceeds some maximum value. Comment lines can optionally be ignored. The maximum allowed length is configurable.
Method has too many lines. [12/10] Open
def create
query = create_update_or_copy_mutation
begin
results = @smart_village.query query
rescue Graphlient::Errors::GraphQLError => e
- Read upRead up
- Exclude checks
This cop checks if the length of a method exceeds some maximum value. Comment lines can optionally be ignored. The maximum allowed length is configurable.
Assignment Branch Condition size for copy_event_and_set_invisibility is too high. [17.12/15] Open
def copy_event_and_set_invisibility
query = create_update_or_copy_mutation(is_copy: true)
begin
results = @smart_village.query query
@smart_village.query <<~GRAPHQL
- Read upRead up
- Exclude checks
This cop 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.
Assignment Branch Condition size for create is too high. [16.58/15] Open
def create
query = create_update_or_copy_mutation
begin
results = @smart_village.query query
rescue Graphlient::Errors::GraphQLError => e
- Read upRead up
- Exclude checks
This cop 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.
EventsController#create_update_or_copy_mutation has boolean parameter 'update' Open
def create_update_or_copy_mutation(update: false, is_copy: false)
- Read upRead up
- Exclude checks
Boolean Parameter
is a special case of Control Couple
, where a method parameter is defaulted to true or false. A Boolean Parameter effectively permits a method's caller to decide which execution path to take. This is a case of bad cohesion. You're creating a dependency between methods that is not really necessary, thus increasing coupling.
Example
Given
class Dummy
def hit_the_switch(switch = true)
if switch
puts 'Hitting the switch'
# do other things...
else
puts 'Not hitting the switch'
# do other things...
end
end
end
Reek would emit the following warning:
test.rb -- 3 warnings:
[1]:Dummy#hit_the_switch has boolean parameter 'switch' (BooleanParameter)
[2]:Dummy#hit_the_switch is controlled by argument switch (ControlParameter)
Note that both smells are reported, Boolean Parameter
and Control Parameter
.
Getting rid of the smell
This is highly dependent on your exact architecture, but looking at the example above what you could do is:
- Move everything in the
if
branch into a separate method - Move everything in the
else
branch into a separate method - Get rid of the
hit_the_switch
method alltogether - Make the decision what method to call in the initial caller of
hit_the_switch
EventsController#convert_params_for_graphql has approx 49 statements Open
def convert_params_for_graphql
- Read upRead up
- Exclude checks
A method with Too Many Statements
is any method that has a large number of lines.
Too Many Statements
warns about any method that has more than 5 statements. Reek's smell detector for Too Many Statements
counts +1 for every simple statement in a method and +1 for every statement within a control structure (if
, else
, case
, when
, for
, while
, until
, begin
, rescue
) but it doesn't count the control structure itself.
So the following method would score +6 in Reek's statement-counting algorithm:
def parse(arg, argv, &error)
if !(val = arg) and (argv.empty? or /\A-/ =~ (val = argv[0]))
return nil, block, nil # +1
end
opt = (val = parse_arg(val, &error))[1] # +2
val = conv_arg(*val) # +3
if opt and !arg
argv.shift # +4
else
val[0] = nil # +5
end
val # +6
end
(You might argue that the two assigments within the first @if@ should count as statements, and that perhaps the nested assignment should count as +2.)
EventsController#create has approx 10 statements Open
def create
- Read upRead up
- Exclude checks
A method with Too Many Statements
is any method that has a large number of lines.
Too Many Statements
warns about any method that has more than 5 statements. Reek's smell detector for Too Many Statements
counts +1 for every simple statement in a method and +1 for every statement within a control structure (if
, else
, case
, when
, for
, while
, until
, begin
, rescue
) but it doesn't count the control structure itself.
So the following method would score +6 in Reek's statement-counting algorithm:
def parse(arg, argv, &error)
if !(val = arg) and (argv.empty? or /\A-/ =~ (val = argv[0]))
return nil, block, nil # +1
end
opt = (val = parse_arg(val, &error))[1] # +2
val = conv_arg(*val) # +3
if opt and !arg
argv.shift # +4
else
val[0] = nil # +5
end
val # +6
end
(You might argue that the two assigments within the first @if@ should count as statements, and that perhaps the nested assignment should count as +2.)
EventsController#create_update_or_copy_mutation has boolean parameter 'is_copy' Open
def create_update_or_copy_mutation(update: false, is_copy: false)
- Read upRead up
- Exclude checks
Boolean Parameter
is a special case of Control Couple
, where a method parameter is defaulted to true or false. A Boolean Parameter effectively permits a method's caller to decide which execution path to take. This is a case of bad cohesion. You're creating a dependency between methods that is not really necessary, thus increasing coupling.
Example
Given
class Dummy
def hit_the_switch(switch = true)
if switch
puts 'Hitting the switch'
# do other things...
else
puts 'Not hitting the switch'
# do other things...
end
end
end
Reek would emit the following warning:
test.rb -- 3 warnings:
[1]:Dummy#hit_the_switch has boolean parameter 'switch' (BooleanParameter)
[2]:Dummy#hit_the_switch is controlled by argument switch (ControlParameter)
Note that both smells are reported, Boolean Parameter
and Control Parameter
.
Getting rid of the smell
This is highly dependent on your exact architecture, but looking at the example above what you could do is:
- Move everything in the
if
branch into a separate method - Move everything in the
else
branch into a separate method - Get rid of the
hit_the_switch
method alltogether - Make the decision what method to call in the initial caller of
hit_the_switch
EventsController#update has approx 7 statements Open
def update
- Read upRead up
- Exclude checks
A method with Too Many Statements
is any method that has a large number of lines.
Too Many Statements
warns about any method that has more than 5 statements. Reek's smell detector for Too Many Statements
counts +1 for every simple statement in a method and +1 for every statement within a control structure (if
, else
, case
, when
, for
, while
, until
, begin
, rescue
) but it doesn't count the control structure itself.
So the following method would score +6 in Reek's statement-counting algorithm:
def parse(arg, argv, &error)
if !(val = arg) and (argv.empty? or /\A-/ =~ (val = argv[0]))
return nil, block, nil # +1
end
opt = (val = parse_arg(val, &error))[1] # +2
val = conv_arg(*val) # +3
if opt and !arg
argv.shift # +4
else
val[0] = nil # +5
end
val # +6
end
(You might argue that the two assigments within the first @if@ should count as statements, and that perhaps the nested assignment should count as +2.)
EventsController#copy_event_and_set_invisibility has approx 10 statements Open
def copy_event_and_set_invisibility
- Read upRead up
- Exclude checks
A method with Too Many Statements
is any method that has a large number of lines.
Too Many Statements
warns about any method that has more than 5 statements. Reek's smell detector for Too Many Statements
counts +1 for every simple statement in a method and +1 for every statement within a control structure (if
, else
, case
, when
, for
, while
, until
, begin
, rescue
) but it doesn't count the control structure itself.
So the following method would score +6 in Reek's statement-counting algorithm:
def parse(arg, argv, &error)
if !(val = arg) and (argv.empty? or /\A-/ =~ (val = argv[0]))
return nil, block, nil # +1
end
opt = (val = parse_arg(val, &error))[1] # +2
val = conv_arg(*val) # +3
if opt and !arg
argv.shift # +4
else
val[0] = nil # +5
end
val # +6
end
(You might argue that the two assigments within the first @if@ should count as statements, and that perhaps the nested assignment should count as +2.)
EventsController#convert_params_for_graphql calls 'price_information["age_to"]' 2 times Open
price_information["age_to"] = price_information["age_to"].present? ? price_information["age_to"].to_f : nil
- Read upRead up
- Exclude checks
Duplication occurs when two fragments of code look nearly identical, or when two fragments of code have nearly identical effects at some conceptual level.
Reek implements a check for Duplicate Method Call.
Example
Here's a very much simplified and contrived example. The following method will report a warning:
def double_thing()
@other.thing + @other.thing
end
One quick approach to silence Reek would be to refactor the code thus:
def double_thing()
thing = @other.thing
thing + thing
end
A slightly different approach would be to replace all calls of double_thing
by calls to @other.double_thing
:
class Other
def double_thing()
thing + thing
end
end
The approach you take will depend on balancing other factors in your code.
EventsController#convert_params_for_graphql calls '@event_params["media_contents"]' 2 times Open
if @event_params["media_contents"].present?
media_contents = []
@event_params["media_contents"].each do |_key, media_content|
- Read upRead up
- Exclude checks
Duplication occurs when two fragments of code look nearly identical, or when two fragments of code have nearly identical effects at some conceptual level.
Reek implements a check for Duplicate Method Call.
Example
Here's a very much simplified and contrived example. The following method will report a warning:
def double_thing()
@other.thing + @other.thing
end
One quick approach to silence Reek would be to refactor the code thus:
def double_thing()
thing = @other.thing
thing + thing
end
A slightly different approach would be to replace all calls of double_thing
by calls to @other.double_thing
:
class Other
def double_thing()
thing + thing
end
end
The approach you take will depend on balancing other factors in your code.
EventsController#convert_params_for_graphql calls 'price_information["amount"]' 2 times Open
price_information["amount"] = price_information["amount"].to_f if price_information["amount"].present? || price_information["description"].present?
- Read upRead up
- Exclude checks
Duplication occurs when two fragments of code look nearly identical, or when two fragments of code have nearly identical effects at some conceptual level.
Reek implements a check for Duplicate Method Call.
Example
Here's a very much simplified and contrived example. The following method will report a warning:
def double_thing()
@other.thing + @other.thing
end
One quick approach to silence Reek would be to refactor the code thus:
def double_thing()
thing = @other.thing
thing + thing
end
A slightly different approach would be to replace all calls of double_thing
by calls to @other.double_thing
:
class Other
def double_thing()
thing + thing
end
end
The approach you take will depend on balancing other factors in your code.
EventsController has no descriptive comment Open
class EventsController < ApplicationController
- Read upRead up
- Exclude checks
Classes and modules are the units of reuse and release. It is therefore considered good practice to annotate every class and module with a brief comment outlining its responsibilities.
Example
Given
class Dummy
# Do things...
end
Reek would emit the following warning:
test.rb -- 1 warning:
[1]:Dummy has no descriptive comment (IrresponsibleModule)
Fixing this is simple - just an explaining comment:
# The Dummy class is responsible for ...
class Dummy
# Do things...
end
EventsController#convert_params_for_graphql calls '@event_params["organizer"]' 2 times Wontfix
if @event_params["organizer"].present?
unless nested_values?(@event_params["organizer"].to_h).include?(true)
- Read upRead up
- Exclude checks
Duplication occurs when two fragments of code look nearly identical, or when two fragments of code have nearly identical effects at some conceptual level.
Reek implements a check for Duplicate Method Call.
Example
Here's a very much simplified and contrived example. The following method will report a warning:
def double_thing()
@other.thing + @other.thing
end
One quick approach to silence Reek would be to refactor the code thus:
def double_thing()
thing = @other.thing
thing + thing
end
A slightly different approach would be to replace all calls of double_thing
by calls to @other.double_thing
:
class Other
def double_thing()
thing + thing
end
end
The approach you take will depend on balancing other factors in your code.
EventsController#convert_params_for_graphql calls '@event_params["price_informations"]' 2 times Open
if @event_params["price_informations"].present?
price_informations = []
@event_params["price_informations"].each do |_key, price_information|
- Read upRead up
- Exclude checks
Duplication occurs when two fragments of code look nearly identical, or when two fragments of code have nearly identical effects at some conceptual level.
Reek implements a check for Duplicate Method Call.
Example
Here's a very much simplified and contrived example. The following method will report a warning:
def double_thing()
@other.thing + @other.thing
end
One quick approach to silence Reek would be to refactor the code thus:
def double_thing()
thing = @other.thing
thing + thing
end
A slightly different approach would be to replace all calls of double_thing
by calls to @other.double_thing
:
class Other
def double_thing()
thing + thing
end
end
The approach you take will depend on balancing other factors in your code.
EventsController#convert_params_for_graphql calls '@event_params["contacts"]' 2 times Open
if @event_params["contacts"].present?
contacts = []
@event_params["contacts"].each do |_key, contact|
- Read upRead up
- Exclude checks
Duplication occurs when two fragments of code look nearly identical, or when two fragments of code have nearly identical effects at some conceptual level.
Reek implements a check for Duplicate Method Call.
Example
Here's a very much simplified and contrived example. The following method will report a warning:
def double_thing()
@other.thing + @other.thing
end
One quick approach to silence Reek would be to refactor the code thus:
def double_thing()
thing = @other.thing
thing + thing
end
A slightly different approach would be to replace all calls of double_thing
by calls to @other.double_thing
:
class Other
def double_thing()
thing + thing
end
end
The approach you take will depend on balancing other factors in your code.
EventsController#convert_params_for_graphql calls '@event_params["urls"]' 2 times Open
if @event_params["urls"].present?
urls = []
@event_params["urls"].each do |_key, url|
- Read upRead up
- Exclude checks
Duplication occurs when two fragments of code look nearly identical, or when two fragments of code have nearly identical effects at some conceptual level.
Reek implements a check for Duplicate Method Call.
Example
Here's a very much simplified and contrived example. The following method will report a warning:
def double_thing()
@other.thing + @other.thing
end
One quick approach to silence Reek would be to refactor the code thus:
def double_thing()
thing = @other.thing
thing + thing
end
A slightly different approach would be to replace all calls of double_thing
by calls to @other.double_thing
:
class Other
def double_thing()
thing + thing
end
end
The approach you take will depend on balancing other factors in your code.
EventsController assumes too much for instance variable '@smart_village' Open
class EventsController < ApplicationController
- Read upRead up
- Exclude checks
Classes should not assume that instance variables are set or present outside of the current class definition.
Good:
class Foo
def initialize
@bar = :foo
end
def foo?
@bar == :foo
end
end
Good as well:
class Foo
def foo?
bar == :foo
end
def bar
@bar ||= :foo
end
end
Bad:
class Foo
def go_foo!
@bar = :foo
end
def foo?
@bar == :foo
end
end
Example
Running Reek on:
class Dummy
def test
@ivar
end
end
would report:
[1]:InstanceVariableAssumption: Dummy assumes too much for instance variable @ivar
Note that this example would trigger this smell warning as well:
class Parent
def initialize(omg)
@omg = omg
end
end
class Child < Parent
def foo
@omg
end
end
The way to address the smell warning is that you should create an attr_reader
to use @omg
in the subclass and not access @omg
directly like this:
class Parent
attr_reader :omg
def initialize(omg)
@omg = omg
end
end
class Child < Parent
def foo
omg
end
end
Directly accessing instance variables is considered a smell because it breaks encapsulation and makes it harder to reason about code.
If you don't want to expose those methods as public API just make them private like this:
class Parent
def initialize(omg)
@omg = omg
end
private
attr_reader :omg
end
class Child < Parent
def foo
omg
end
end
Current Support in Reek
An instance variable must:
- be set in the constructor
- or be accessed through a method with lazy initialization / memoization.
If not, Instance Variable Assumption will be reported.
EventsController#convert_params_for_graphql calls '@event_params["categories"]' 2 times Open
if @event_params["categories"].present?
categories = []
@event_params["categories"].each do |_key, category|
- Read upRead up
- Exclude checks
Duplication occurs when two fragments of code look nearly identical, or when two fragments of code have nearly identical effects at some conceptual level.
Reek implements a check for Duplicate Method Call.
Example
Here's a very much simplified and contrived example. The following method will report a warning:
def double_thing()
@other.thing + @other.thing
end
One quick approach to silence Reek would be to refactor the code thus:
def double_thing()
thing = @other.thing
thing + thing
end
A slightly different approach would be to replace all calls of double_thing
by calls to @other.double_thing
:
class Other
def double_thing()
thing + thing
end
end
The approach you take will depend on balancing other factors in your code.
EventsController#convert_params_for_graphql calls '@event_params["dates"]' 2 times Open
if @event_params["dates"].present?
dates = []
@event_params["dates"].each do |_key, date|
- Read upRead up
- Exclude checks
Duplication occurs when two fragments of code look nearly identical, or when two fragments of code have nearly identical effects at some conceptual level.
Reek implements a check for Duplicate Method Call.
Example
Here's a very much simplified and contrived example. The following method will report a warning:
def double_thing()
@other.thing + @other.thing
end
One quick approach to silence Reek would be to refactor the code thus:
def double_thing()
thing = @other.thing
thing + thing
end
A slightly different approach would be to replace all calls of double_thing
by calls to @other.double_thing
:
class Other
def double_thing()
thing + thing
end
end
The approach you take will depend on balancing other factors in your code.
EventsController#convert_params_for_graphql calls '@event_params["addresses"]' 2 times Wontfix
if @event_params["addresses"].present?
addresses = []
@event_params["addresses"].each do |_key, address|
- Read upRead up
- Exclude checks
Duplication occurs when two fragments of code look nearly identical, or when two fragments of code have nearly identical effects at some conceptual level.
Reek implements a check for Duplicate Method Call.
Example
Here's a very much simplified and contrived example. The following method will report a warning:
def double_thing()
@other.thing + @other.thing
end
One quick approach to silence Reek would be to refactor the code thus:
def double_thing()
thing = @other.thing
thing + thing
end
A slightly different approach would be to replace all calls of double_thing
by calls to @other.double_thing
:
class Other
def double_thing()
thing + thing
end
end
The approach you take will depend on balancing other factors in your code.
EventsController#convert_params_for_graphql calls 'price_information["age_from"]' 2 times Open
price_information["age_from"] = price_information["age_from"].present? ? price_information["age_from"].to_f : nil
- Read upRead up
- Exclude checks
Duplication occurs when two fragments of code look nearly identical, or when two fragments of code have nearly identical effects at some conceptual level.
Reek implements a check for Duplicate Method Call.
Example
Here's a very much simplified and contrived example. The following method will report a warning:
def double_thing()
@other.thing + @other.thing
end
One quick approach to silence Reek would be to refactor the code thus:
def double_thing()
thing = @other.thing
thing + thing
end
A slightly different approach would be to replace all calls of double_thing
by calls to @other.double_thing
:
class Other
def double_thing()
thing + thing
end
end
The approach you take will depend on balancing other factors in your code.
EventsController assumes too much for instance variable '@event_params' Open
class EventsController < ApplicationController
- Read upRead up
- Exclude checks
Classes should not assume that instance variables are set or present outside of the current class definition.
Good:
class Foo
def initialize
@bar = :foo
end
def foo?
@bar == :foo
end
end
Good as well:
class Foo
def foo?
bar == :foo
end
def bar
@bar ||= :foo
end
end
Bad:
class Foo
def go_foo!
@bar = :foo
end
def foo?
@bar == :foo
end
end
Example
Running Reek on:
class Dummy
def test
@ivar
end
end
would report:
[1]:InstanceVariableAssumption: Dummy assumes too much for instance variable @ivar
Note that this example would trigger this smell warning as well:
class Parent
def initialize(omg)
@omg = omg
end
end
class Child < Parent
def foo
@omg
end
end
The way to address the smell warning is that you should create an attr_reader
to use @omg
in the subclass and not access @omg
directly like this:
class Parent
attr_reader :omg
def initialize(omg)
@omg = omg
end
end
class Child < Parent
def foo
omg
end
end
Directly accessing instance variables is considered a smell because it breaks encapsulation and makes it harder to reason about code.
If you don't want to expose those methods as public API just make them private like this:
class Parent
def initialize(omg)
@omg = omg
end
private
attr_reader :omg
end
class Child < Parent
def foo
omg
end
end
Current Support in Reek
An instance variable must:
- be set in the constructor
- or be accessed through a method with lazy initialization / memoization.
If not, Instance Variable Assumption will be reported.
Complex method EventsController#copy_event_and_set_invisibility (21.3) Open
def copy_event_and_set_invisibility
query = create_update_or_copy_mutation(is_copy: true)
begin
results = @smart_village.query query
@smart_village.query <<~GRAPHQL
- Read upRead up
- Exclude checks
Flog calculates the ABC score for methods. The ABC score is based on assignments, branches (method calls), and conditions.
You can read more about ABC metrics or the flog tool
EventsController#new_event_record doesn't depend on instance state (maybe move it to another class?) Open
def new_event_record
- Read upRead up
- Exclude checks
A Utility Function is any instance method that has no dependency on the state of the instance.
EventsController#create has the variable name 'e' Open
rescue Graphlient::Errors::GraphQLError => e
- Read upRead up
- Exclude checks
An Uncommunicative Variable Name
is a variable name that doesn't communicate its intent well enough.
Poor names make it hard for the reader to build a mental picture of what's going on in the code. They can also be mis-interpreted; and they hurt the flow of reading, because the reader must slow down to interpret the names.
EventsController#update has the variable name 'e' Open
rescue Graphlient::Errors::GraphQLError => e
- Read upRead up
- Exclude checks
An Uncommunicative Variable Name
is a variable name that doesn't communicate its intent well enough.
Poor names make it hard for the reader to build a mental picture of what's going on in the code. They can also be mis-interpreted; and they hurt the flow of reading, because the reader must slow down to interpret the names.
EventsController#copy_event_and_set_invisibility has the variable name 'e' Open
rescue Graphlient::Errors::GraphQLError => e
- Read upRead up
- Exclude checks
An Uncommunicative Variable Name
is a variable name that doesn't communicate its intent well enough.
Poor names make it hard for the reader to build a mental picture of what's going on in the code. They can also be mis-interpreted; and they hurt the flow of reading, because the reader must slow down to interpret the names.
Similar blocks of code found in 5 locations. Consider refactoring. Open
if @event_params["media_contents"].present?
media_contents = []
@event_params["media_contents"].each do |_key, media_content|
next if media_content.blank?
# content_type is always something (default: `image`), so we need to check all values
- Read upRead up
Duplicated Code
Duplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:
Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
When you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).
Tuning
This issue has a mass of 48.
We set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.
The threshold configuration represents the minimum mass a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.
If the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.
See codeclimate-duplication
's documentation for more information about tuning the mass threshold in your .codeclimate.yml
.
Refactorings
- Extract Method
- Extract Class
- Form Template Method
- Introduce Null Object
- Pull Up Method
- Pull Up Field
- Substitute Algorithm
Further Reading
- Don't Repeat Yourself on the C2 Wiki
- Duplicated Code on SourceMaking
- Refactoring: Improving the Design of Existing Code by Martin Fowler. Duplicated Code, p76
Similar blocks of code found in 7 locations. Consider refactoring. Open
def create
query = create_update_or_copy_mutation
begin
results = @smart_village.query query
rescue Graphlient::Errors::GraphQLError => e
- Read upRead up
Duplicated Code
Duplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:
Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
When you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).
Tuning
This issue has a mass of 42.
We set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.
The threshold configuration represents the minimum mass a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.
If the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.
See codeclimate-duplication
's documentation for more information about tuning the mass threshold in your .codeclimate.yml
.
Refactorings
- Extract Method
- Extract Class
- Form Template Method
- Introduce Null Object
- Pull Up Method
- Pull Up Field
- Substitute Algorithm
Further Reading
- Don't Repeat Yourself on the C2 Wiki
- Duplicated Code on SourceMaking
- Refactoring: Improving the Design of Existing Code by Martin Fowler. Duplicated Code, p76
Similar blocks of code found in 6 locations. Consider refactoring. Open
def destroy
results = @smart_village.query <<~GRAPHQL
mutation {
destroyRecord(
id: #{params["id"]},
- Read upRead up
Duplicated Code
Duplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:
Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
When you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).
Tuning
This issue has a mass of 35.
We set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.
The threshold configuration represents the minimum mass a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.
If the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.
See codeclimate-duplication
's documentation for more information about tuning the mass threshold in your .codeclimate.yml
.
Refactorings
- Extract Method
- Extract Class
- Form Template Method
- Introduce Null Object
- Pull Up Method
- Pull Up Field
- Substitute Algorithm
Further Reading
- Don't Repeat Yourself on the C2 Wiki
- Duplicated Code on SourceMaking
- Refactoring: Improving the Design of Existing Code by Martin Fowler. Duplicated Code, p76
Similar blocks of code found in 11 locations. Consider refactoring. Open
if @event_params["dates"].present?
dates = []
@event_params["dates"].each do |_key, date|
next if date.blank?
next unless nested_values?(date.to_h).include?(true)
- Read upRead up
Duplicated Code
Duplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:
Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
When you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).
Tuning
This issue has a mass of 33.
We set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.
The threshold configuration represents the minimum mass a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.
If the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.
See codeclimate-duplication
's documentation for more information about tuning the mass threshold in your .codeclimate.yml
.
Refactorings
- Extract Method
- Extract Class
- Form Template Method
- Introduce Null Object
- Pull Up Method
- Pull Up Field
- Substitute Algorithm
Further Reading
- Don't Repeat Yourself on the C2 Wiki
- Duplicated Code on SourceMaking
- Refactoring: Improving the Design of Existing Code by Martin Fowler. Duplicated Code, p76
Similar blocks of code found in 11 locations. Consider refactoring. Open
if @event_params["contacts"].present?
contacts = []
@event_params["contacts"].each do |_key, contact|
next if contact.blank?
next unless nested_values?(contact.to_h).include?(true)
- Read upRead up
Duplicated Code
Duplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:
Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
When you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).
Tuning
This issue has a mass of 33.
We set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.
The threshold configuration represents the minimum mass a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.
If the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.
See codeclimate-duplication
's documentation for more information about tuning the mass threshold in your .codeclimate.yml
.
Refactorings
- Extract Method
- Extract Class
- Form Template Method
- Introduce Null Object
- Pull Up Method
- Pull Up Field
- Substitute Algorithm
Further Reading
- Don't Repeat Yourself on the C2 Wiki
- Duplicated Code on SourceMaking
- Refactoring: Improving the Design of Existing Code by Martin Fowler. Duplicated Code, p76
Similar blocks of code found in 11 locations. Consider refactoring. Open
if @event_params["categories"].present?
categories = []
@event_params["categories"].each do |_key, category|
next if category.blank?
next unless nested_values?(category.to_h).include?(true)
- Read upRead up
Duplicated Code
Duplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:
Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
When you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).
Tuning
This issue has a mass of 33.
We set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.
The threshold configuration represents the minimum mass a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.
If the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.
See codeclimate-duplication
's documentation for more information about tuning the mass threshold in your .codeclimate.yml
.
Refactorings
- Extract Method
- Extract Class
- Form Template Method
- Introduce Null Object
- Pull Up Method
- Pull Up Field
- Substitute Algorithm
Further Reading
- Don't Repeat Yourself on the C2 Wiki
- Duplicated Code on SourceMaking
- Refactoring: Improving the Design of Existing Code by Martin Fowler. Duplicated Code, p76
Similar blocks of code found in 11 locations. Consider refactoring. Open
if @event_params["addresses"].present?
addresses = []
@event_params["addresses"].each do |_key, address|
next if address.blank?
next unless nested_values?(address.to_h).include?(true)
- Read upRead up
Duplicated Code
Duplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:
Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
When you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).
Tuning
This issue has a mass of 33.
We set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.
The threshold configuration represents the minimum mass a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.
If the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.
See codeclimate-duplication
's documentation for more information about tuning the mass threshold in your .codeclimate.yml
.
Refactorings
- Extract Method
- Extract Class
- Form Template Method
- Introduce Null Object
- Pull Up Method
- Pull Up Field
- Substitute Algorithm
Further Reading
- Don't Repeat Yourself on the C2 Wiki
- Duplicated Code on SourceMaking
- Refactoring: Improving the Design of Existing Code by Martin Fowler. Duplicated Code, p76
Similar blocks of code found in 7 locations. Consider refactoring. Open
def edit
results = @smart_village.query <<~GRAPHQL
query {
eventRecord(
id: #{params[:id]}
- Read upRead up
Duplicated Code
Duplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:
Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
When you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).
Tuning
This issue has a mass of 28.
We set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.
The threshold configuration represents the minimum mass a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.
If the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.
See codeclimate-duplication
's documentation for more information about tuning the mass threshold in your .codeclimate.yml
.
Refactorings
- Extract Method
- Extract Class
- Form Template Method
- Introduce Null Object
- Pull Up Method
- Pull Up Field
- Substitute Algorithm
Further Reading
- Don't Repeat Yourself on the C2 Wiki
- Duplicated Code on SourceMaking
- Refactoring: Improving the Design of Existing Code by Martin Fowler. Duplicated Code, p76
Similar blocks of code found in 7 locations. Consider refactoring. Open
if @event_params["urls"].present?
urls = []
@event_params["urls"].each do |_key, url|
next if url.blank?
- Read upRead up
Duplicated Code
Duplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:
Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
When you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).
Tuning
This issue has a mass of 26.
We set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.
The threshold configuration represents the minimum mass a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.
If the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.
See codeclimate-duplication
's documentation for more information about tuning the mass threshold in your .codeclimate.yml
.
Refactorings
- Extract Method
- Extract Class
- Form Template Method
- Introduce Null Object
- Pull Up Method
- Pull Up Field
- Substitute Algorithm
Further Reading
- Don't Repeat Yourself on the C2 Wiki
- Duplicated Code on SourceMaking
- Refactoring: Improving the Design of Existing Code by Martin Fowler. Duplicated Code, p76
Line is too long. [123/100] Wontfix
price_information["age_from"] = price_information["age_from"].present? ? price_information["age_from"].to_f : nil
- Exclude checks
Rename is_a_copy?
to a_copy?
. Open
def is_a_copy?
- Read upRead up
- Exclude checks
This cop makes sure that predicates are named properly.
Example:
# bad
def is_even(value)
end
def is_even?(value)
end
# good
def even?(value)
end
# bad
def has_value
end
def has_value?
end
# good
def value?
end
Line is too long. [157/100] Open
price_information["amount"] = price_information["amount"].to_f if price_information["amount"].present? || price_information["description"].present?
- Exclude checks
Missing top-level class documentation comment. Open
class EventsController < ApplicationController
- Read upRead up
- Exclude checks
This cop 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, or constant definitions.
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
# good
# Description/Explanation of Person class
class Person
# ...
end
Line is too long. [117/100] Wontfix
price_information["age_to"] = price_information["age_to"].present? ? price_information["age_to"].to_f : nil
- Exclude checks
Line is too long. [123/100] Wontfix
media_content["source_url"] = media_content.dig("source_url", "url").present? ? media_content["source_url"] : nil
- Exclude checks
Use the return of the conditional for variable assignment and comparison. Open
if results.try(:data).try(:destroy_record).try(:status_code) == 200
flash["notice"] = "Eintrag wurde gelöscht"
else
flash["notice"] = "Fehler: #{results.errors.inspect}"
end
- Exclude checks
Use a guard clause instead of wrapping the code inside a conditional expression. Open
if @event_params["organizer"].present?
- Read upRead up
- Exclude checks
Use a guard clause instead of wrapping the code inside a conditional expression
Example:
# bad
def test
if something
work
end
end
# good
def test
return unless something
work
end
# also good
def test
work if something
end
# bad
if something
raise 'exception'
else
ok
end
# good
raise 'exception' if something
ok
Use %i
or %I
for an array of symbols. Wontfix
before_action :load_category_list, only: [:edit, :new, :create]
- Read upRead up
- Exclude checks
This cop can check for array literals made up of symbols that are not using the %i() syntax.
Alternatively, it checks for symbol arrays using the %i() syntax on projects which do not want to use that syntax.
Configuration option: MinSize
If set, arrays with fewer elements than this value will not trigger the
cop. For example, a MinSize of
3` will not enforce a style on an array
of 2 or fewer elements.
Example: EnforcedStyle: percent (default)
# good
%i[foo bar baz]
# bad
[:foo, :bar, :baz]
Example: EnforcedStyle: brackets
# good
[:foo, :bar, :baz]
# bad
%i[foo bar baz]