Unsafe reflection method const_get called with parameter value Open
question = Object.const_get(params[:question][:type]).create(txt: '', questionnaire_id: questionnaire_id, seq: i, type: params[:question][:type], break_before: true)
- Read upRead up
- Exclude checks
Brakeman reports on several cases of remote code execution, in which a user is able to control and execute code in ways unintended by application authors.
The obvious form of this is the use of eval
with user input.
However, Brakeman also reports on dangerous uses of send
, constantize
, and other methods which allow creation of arbitrary objects or calling of arbitrary methods.
Unprotected mass assignment Open
Rails.logger.info(question.errors.messages.inspect) unless question.update_attributes(params[:question][question_key])
- 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
.
Unsafe reflection method const_get called with parameter value Open
@new_question = Object.const_get(params[:question_type][i.to_s][:type]).create(txt: '', type: params[:question_type][i.to_s][:type], break_before: true)
- Read upRead up
- Exclude checks
Brakeman reports on several cases of remote code execution, in which a user is able to control and execute code in ways unintended by application authors.
The obvious form of this is the use of eval
with user input.
However, Brakeman also reports on dangerous uses of send
, constantize
, and other methods which allow creation of arbitrary objects or calling of arbitrary methods.
Unprotected mass assignment Open
@questionnaire.update_attributes(questionnaire_params)
- 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
.
Unprotected mass assignment Open
@questionnaire.update_attributes(questionnaire_params)
- 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
.
Unsafe reflection method const_get called with parameter value Open
@questionnaire = Object.const_get(params[:questionnaire][:type]).new(questionnaire_params)
- Read upRead up
- Exclude checks
Brakeman reports on several cases of remote code execution, in which a user is able to control and execute code in ways unintended by application authors.
The obvious form of this is the use of eval
with user input.
However, Brakeman also reports on dangerous uses of send
, constantize
, and other methods which allow creation of arbitrary objects or calling of arbitrary methods.
Unsafe reflection method const_get called with parameter value Open
@questionnaire = Object.const_get(params[:model]).new
- Read upRead up
- Exclude checks
Brakeman reports on several cases of remote code execution, in which a user is able to control and execute code in ways unintended by application authors.
The obvious form of this is the use of eval
with user input.
However, Brakeman also reports on dangerous uses of send
, constantize
, and other methods which allow creation of arbitrary objects or calling of arbitrary methods.
Assignment Branch Condition size for update_quiz is too high. [124.7/15] Open
def update_quiz
@questionnaire = Questionnaire.find(params[:id])
if @questionnaire.nil?
redirect_to controller: 'submitted_content', action: 'view', id: params[:pid]
return
- 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
Assignment Branch Condition size for save_choices is too high. [107.1/15] Open
def save_choices(questionnaire_id)
return unless params[:new_question] or params[:new_choices]
questions = Question.where(questionnaire_id: questionnaire_id)
question_num = 1
- 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
File questionnaires_controller.rb
has 477 lines of code (exceeds 250 allowed). Consider refactoring. Open
class QuestionnairesController < ApplicationController
# Controller for Questionnaire objects
# A Questionnaire can be of several types (QuestionnaireType)
# Each Questionnaire contains zero or more questions (Question)
# Generally a questionnaire is associated with an assignment (Assignment)
Assignment Branch Condition size for create is too high. [63.61/15] Open
def create
if params[:questionnaire][:name].blank?
flash[:error] = 'A rubric or survey must have a title.'
redirect_to controller: 'questionnaires', action: 'new', model: params[:questionnaire][:type], private: params[:questionnaire][:private]
else
- 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
Method update_quiz
has a Cognitive Complexity of 41 (exceeds 5 allowed). Consider refactoring. Open
def update_quiz
@questionnaire = Questionnaire.find(params[:id])
if @questionnaire.nil?
redirect_to controller: 'submitted_content', action: 'view', id: params[:pid]
return
- 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 valid_quiz is too high. [54.09/15] Open
def valid_quiz
num_quiz_questions = Assignment.find(params[:aid]).num_quiz_questions
valid = "valid"
(1..num_quiz_questions).each do |i|
- 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
Assignment Branch Condition size for copy_questionnaire_details is too high. [36.4/15] Open
def copy_questionnaire_details(questions, orig_questionnaire)
@questionnaire.instructor_id = assign_instructor_id
@questionnaire.name = 'Copy of ' + orig_questionnaire.name
begin
@questionnaire.created_at = Time.now
- 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
Assignment Branch Condition size for add_new_questions is too high. [35.48/15] Open
def add_new_questions
questionnaire_id = params[:id] unless params[:id].nil?
num_of_existed_questions = Questionnaire.find(questionnaire_id).questions.size
((num_of_existed_questions + 1)..(num_of_existed_questions + params[:question][:total_num].to_i)).each do |i|
question = Object.const_get(params[:question][:type]).create(txt: '', questionnaire_id: questionnaire_id, seq: i, type: params[:question][:type], break_before: true)
- 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
Method save_choices
has a Cognitive Complexity of 27 (exceeds 5 allowed). Consider refactoring. Open
def save_choices(questionnaire_id)
return unless params[:new_question] or params[:new_choices]
questions = Question.where(questionnaire_id: questionnaire_id)
question_num = 1
- 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 save_all_questions is too high. [33/15] Open
def save_all_questions
questionnaire_id = params[:id]
begin
if params[:save]
params[:question].each_pair do |k, v|
- 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
Assignment Branch Condition size for new_quiz is too high. [33.2/15] Open
def new_quiz
valid_request = true
@assignment_id = params[:aid] # creating an instance variable to hold the assignment id
@participant_id = params[:pid] # creating an instance variable to hold the participant id
assignment = Assignment.find(@assignment_id)
- 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
Class QuestionnairesController
has 29 methods (exceeds 20 allowed). Consider refactoring. Open
class QuestionnairesController < ApplicationController
# Controller for Questionnaire objects
# A Questionnaire can be of several types (QuestionnaireType)
# Each Questionnaire contains zero or more questions (Question)
# Generally a questionnaire is associated with an assignment (Assignment)
Assignment Branch Condition size for create_questionnaire is too high. [30.51/15] Open
def create_questionnaire
@questionnaire = Object.const_get(params[:questionnaire][:type]).new(questionnaire_params)
# TODO: check for Quiz Questionnaire?
if @questionnaire.type == "QuizQuestionnaire" # checking if it is a quiz questionnaire
- 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
Assignment Branch Condition size for delete is too high. [27.22/15] Open
def delete
@questionnaire = Questionnaire.find(params[:id])
if @questionnaire
begin
name = @questionnaire.name
- 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
Assignment Branch Condition size for save_questions is too high. [25.2/15] Open
def save_questions(questionnaire_id)
delete_questions questionnaire_id
save_new_questions questionnaire_id
if params[:question]
- 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
Perceived complexity for update_quiz is too high. [17/7] Open
def update_quiz
@questionnaire = Questionnaire.find(params[:id])
if @questionnaire.nil?
redirect_to controller: 'submitted_content', action: 'view', id: params[:pid]
return
- 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
Assignment Branch Condition size for save_new_questions is too high. [22.05/15] Open
def save_new_questions(questionnaire_id)
if params[:new_question]
# The new_question array contains all the new questions
# that should be saved to the database
params[:new_question].keys.each do |question_key|
- 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
Perceived complexity for save_choices is too high. [14/7] Open
def save_choices(questionnaire_id)
return unless params[:new_question] or params[:new_choices]
questions = Question.where(questionnaire_id: questionnaire_id)
question_num = 1
- 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
Cyclomatic complexity for update_quiz is too high. [12/6] Open
def update_quiz
@questionnaire = Questionnaire.find(params[:id])
if @questionnaire.nil?
redirect_to controller: 'submitted_content', action: 'view', id: params[:pid]
return
- 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.
Method valid_quiz
has a Cognitive Complexity of 17 (exceeds 5 allowed). Consider refactoring. Open
def valid_quiz
num_quiz_questions = Assignment.find(params[:aid]).num_quiz_questions
valid = "valid"
(1..num_quiz_questions).each do |i|
- 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 action_allowed? is too high. [19.67/15] Open
def action_allowed?
if params[:action] == "edit"
@questionnaire = Questionnaire.find(params[:id])
(['Super-Administrator',
'Administrator'].include? current_role_name) ||
- 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
Cyclomatic complexity for create is too high. [10/6] Open
def create
if params[:questionnaire][:name].blank?
flash[:error] = 'A rubric or survey must have a title.'
redirect_to controller: 'questionnaires', action: 'new', model: params[:questionnaire][:type], private: params[:questionnaire][:private]
else
- 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.
Cyclomatic complexity for save_choices is too high. [9/6] Open
def save_choices(questionnaire_id)
return unless params[:new_question] or params[:new_choices]
questions = Question.where(questionnaire_id: questionnaire_id)
question_num = 1
- 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 new_quiz is too high. [10/7] Open
def new_quiz
valid_request = true
@assignment_id = params[:aid] # creating an instance variable to hold the assignment id
@participant_id = params[:pid] # creating an instance variable to hold the participant id
assignment = Assignment.find(@assignment_id)
- 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 update_quiz
has 48 lines of code (exceeds 25 allowed). Consider refactoring. Open
def update_quiz
@questionnaire = Questionnaire.find(params[:id])
if @questionnaire.nil?
redirect_to controller: 'submitted_content', action: 'view', id: params[:pid]
return
Cyclomatic complexity for save_all_questions is too high. [8/6] Open
def save_all_questions
questionnaire_id = params[:id]
begin
if params[:save]
params[:question].each_pair do |k, v|
- 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 save_all_questions is too high. [9/7] Open
def save_all_questions
questionnaire_id = params[:id]
begin
if params[:save]
params[:question].each_pair do |k, v|
- 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
Perceived complexity for valid_quiz is too high. [9/7] Open
def valid_quiz
num_quiz_questions = Assignment.find(params[:aid]).num_quiz_questions
valid = "valid"
(1..num_quiz_questions).each do |i|
- 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
Cyclomatic complexity for add_new_questions is too high. [8/6] Open
def add_new_questions
questionnaire_id = params[:id] unless params[:id].nil?
num_of_existed_questions = Questionnaire.find(questionnaire_id).questions.size
((num_of_existed_questions + 1)..(num_of_existed_questions + params[:question][:total_num].to_i)).each do |i|
question = Object.const_get(params[:question][:type]).create(txt: '', questionnaire_id: questionnaire_id, seq: i, type: params[:question][:type], break_before: true)
- 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.
Cyclomatic complexity for valid_quiz is too high. [7/6] Open
def valid_quiz
num_quiz_questions = Assignment.find(params[:aid]).num_quiz_questions
valid = "valid"
(1..num_quiz_questions).each do |i|
- 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.
Cyclomatic complexity for new_quiz is too high. [7/6] Open
def new_quiz
valid_request = true
@assignment_id = params[:aid] # creating an instance variable to hold the assignment id
@participant_id = params[:pid] # creating an instance variable to hold the participant id
assignment = Assignment.find(@assignment_id)
- 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.
Assignment Branch Condition size for save is too high. [16.4/15] Open
def save
@questionnaire.save!
save_questions @questionnaire.id if !@questionnaire.id.nil? and @questionnaire.id > 0
# We do not create node for quiz questionnaires
- 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
Perceived complexity for create is too high. [8/7] Open
def create
if params[:questionnaire][:name].blank?
flash[:error] = 'A rubric or survey must have a title.'
redirect_to controller: 'questionnaires', action: 'new', model: params[:questionnaire][:type], private: params[:questionnaire][:private]
else
- 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
Perceived complexity for add_new_questions is too high. [8/7] Open
def add_new_questions
questionnaire_id = params[:id] unless params[:id].nil?
num_of_existed_questions = Questionnaire.find(questionnaire_id).questions.size
((num_of_existed_questions + 1)..(num_of_existed_questions + params[:question][:total_num].to_i)).each do |i|
question = Object.const_get(params[:question][:type]).create(txt: '', questionnaire_id: questionnaire_id, seq: i, type: params[:question][:type], break_before: true)
- 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 add_new_questions
has a Cognitive Complexity of 14 (exceeds 5 allowed). Consider refactoring. Open
def add_new_questions
questionnaire_id = params[:id] unless params[:id].nil?
num_of_existed_questions = Questionnaire.find(questionnaire_id).questions.size
((num_of_existed_questions + 1)..(num_of_existed_questions + params[:question][:total_num].to_i)).each do |i|
question = Object.const_get(params[:question][:type]).create(txt: '', questionnaire_id: questionnaire_id, seq: i, type: params[:question][:type], break_before: true)
- 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 save_choices
has 42 lines of code (exceeds 25 allowed). Consider refactoring. Open
def save_choices(questionnaire_id)
return unless params[:new_question] or params[:new_choices]
questions = Question.where(questionnaire_id: questionnaire_id)
question_num = 1
Method create
has 42 lines of code (exceeds 25 allowed). Consider refactoring. Open
def create
if params[:questionnaire][:name].blank?
flash[:error] = 'A rubric or survey must have a title.'
redirect_to controller: 'questionnaires', action: 'new', model: params[:questionnaire][:type], private: params[:questionnaire][:private]
else
Assignment Branch Condition size for delete_questions is too high. [15.81/15] Open
def delete_questions(questionnaire_id)
# Deletes any questions that, as a result of the edit, are no longer in the questionnaire
questions = Question.where("questionnaire_id = ?", questionnaire_id)
@deleted_questions = []
questions.each do |question|
- 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
Block has too many lines. [37/25] Open
params[:question].keys.each do |qid|
@question = Question.find(qid)
@question.txt = params[:question][qid.to_sym][:txt]
@question.save
- Read upRead up
- Exclude checks
This cop checks if the length of a block exceeds some maximum value. Comment lines can optionally be ignored. The maximum allowed length is configurable. The cop can be configured to ignore blocks passed to certain methods.
Block has too many lines. [37/25] Open
questions.each do |question|
q_type = params[:question_type][question_num.to_s][:type]
params[:new_choices][question_num.to_s][q_type].keys.each do |choice_key|
score = if params[:new_choices][question_num.to_s][q_type][choice_key]["weight"] == 1.to_s
1
- Read upRead up
- Exclude checks
This cop checks if the length of a block exceeds some maximum value. Comment lines can optionally be ignored. The maximum allowed length is configurable. The cop can be configured to ignore blocks passed to certain methods.
Method delete_questions
has a Cognitive Complexity of 11 (exceeds 5 allowed). Consider refactoring. Open
def delete_questions(questionnaire_id)
# Deletes any questions that, as a result of the edit, are no longer in the questionnaire
questions = Question.where("questionnaire_id = ?", questionnaire_id)
@deleted_questions = []
questions.each do |question|
- 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 new_quiz
has 28 lines of code (exceeds 25 allowed). Consider refactoring. Open
def new_quiz
valid_request = true
@assignment_id = params[:aid] # creating an instance variable to hold the assignment id
@participant_id = params[:pid] # creating an instance variable to hold the participant id
assignment = Assignment.find(@assignment_id)
Method create
has a Cognitive Complexity of 10 (exceeds 5 allowed). Consider refactoring. Open
def create
if params[:questionnaire][:name].blank?
flash[:error] = 'A rubric or survey must have a title.'
redirect_to controller: 'questionnaires', action: 'new', model: params[:questionnaire][:type], private: params[:questionnaire][:private]
else
- 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 delete
has a Cognitive Complexity of 10 (exceeds 5 allowed). Consider refactoring. Open
def delete
@questionnaire = Questionnaire.find(params[:id])
if @questionnaire
begin
name = @questionnaire.name
- 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 save_questions
has a Cognitive Complexity of 10 (exceeds 5 allowed). Consider refactoring. Open
def save_questions(questionnaire_id)
delete_questions questionnaire_id
save_new_questions questionnaire_id
if params[:question]
- 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 save_all_questions
has a Cognitive Complexity of 10 (exceeds 5 allowed). Consider refactoring. Open
def save_all_questions
questionnaire_id = params[:id]
begin
if params[:save]
params[:question].each_pair do |k, v|
- 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 copy_questionnaire_details
has 27 lines of code (exceeds 25 allowed). Consider refactoring. Open
def copy_questionnaire_details(questions, orig_questionnaire)
@questionnaire.instructor_id = assign_instructor_id
@questionnaire.name = 'Copy of ' + orig_questionnaire.name
begin
@questionnaire.created_at = Time.now
Block has too many lines. [32/25] Open
params[:new_choices][question_num.to_s][q_type].keys.each do |choice_key|
score = if params[:new_choices][question_num.to_s][q_type][choice_key]["weight"] == 1.to_s
1
else
0
- Read upRead up
- Exclude checks
This cop checks if the length of a block exceeds some maximum value. Comment lines can optionally be ignored. The maximum allowed length is configurable. The cop can be configured to ignore blocks passed to certain methods.
Method save_new_questions
has a Cognitive Complexity of 8 (exceeds 5 allowed). Consider refactoring. Open
def save_new_questions(questionnaire_id)
if params[:new_question]
# The new_question array contains all the new questions
# that should be saved to the database
params[:new_question].keys.each do |question_key|
- 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 new_quiz
has a Cognitive Complexity of 8 (exceeds 5 allowed). Consider refactoring. Open
def new_quiz
valid_request = true
@assignment_id = params[:aid] # creating an instance variable to hold the assignment id
@participant_id = params[:pid] # creating an instance variable to hold the participant id
assignment = Assignment.find(@assignment_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
Method copy_questionnaire_details
has a Cognitive Complexity of 8 (exceeds 5 allowed). Consider refactoring. Open
def copy_questionnaire_details(questions, orig_questionnaire)
@questionnaire.instructor_id = assign_instructor_id
@questionnaire.name = 'Copy of ' + orig_questionnaire.name
begin
@questionnaire.created_at = Time.now
- 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
Block has too many lines. [30/25] Open
@quiz_question_choices.each do |quiz_question_choice|
if @question.type == "MultipleChoiceCheckbox"
if params[:quiz_question_choices][@question.id.to_s][@question.type][i.to_s]
quiz_question_choice.update_attributes(iscorrect: params[:quiz_question_choices][@question.id.to_s][@question.type][i.to_s][:iscorrect], txt: params[:quiz_question_choices][@question.id.to_s][@question.type][i.to_s][:txt])
else
- Read upRead up
- Exclude checks
This cop checks if the length of a block exceeds some maximum value. Comment lines can optionally be ignored. The maximum allowed length is configurable. The cop can be configured to ignore blocks passed to certain methods.
Method action_allowed?
has a Cognitive Complexity of 6 (exceeds 5 allowed). Consider refactoring. Open
def action_allowed?
if params[:action] == "edit"
@questionnaire = Questionnaire.find(params[:id])
(['Super-Administrator',
'Administrator'].include? current_role_name) ||
- 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 create_questionnaire
has a Cognitive Complexity of 6 (exceeds 5 allowed). Consider refactoring. Open
def create_questionnaire
@questionnaire = Object.const_get(params[:questionnaire][:type]).new(questionnaire_params)
# TODO: check for Quiz Questionnaire?
if @questionnaire.type == "QuizQuestionnaire" # checking if it is a quiz questionnaire
- 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
Avoid more than 3 levels of block nesting. Open
if quiz_question_choice.txt == "True"
quiz_question_choice.update_attributes(iscorrect: '1') # the statement is correct so "True" is the right answer
else
quiz_question_choice.update_attributes(iscorrect: '0')
end
- Read upRead up
- Exclude checks
This cop checks for excessive nesting of conditional and looping constructs.
You can configure if blocks are considered using the CountBlocks
option. When set to false
(the default) blocks are not counted
towards the nesting level. Set to true
to count blocks as well.
The maximum level of nesting allowed is configurable.
Avoid more than 3 levels of block nesting. Open
if quiz_question_choice.txt == "True"
quiz_question_choice.update_attributes(iscorrect: '0')
else
quiz_question_choice.update_attributes(iscorrect: '1') # the statement is not correct so "False" is the right answer
end
- Read upRead up
- Exclude checks
This cop checks for excessive nesting of conditional and looping constructs.
You can configure if blocks are considered using the CountBlocks
option. When set to false
(the default) blocks are not counted
towards the nesting level. Set to true
to count blocks as well.
The maximum level of nesting allowed is configurable.
Use each_key
instead of keys.each
. Open
params[:new_choices][question_num.to_s][q_type].keys.each do |choice_key|
- Read upRead up
- Exclude checks
This cop 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.
Example:
# bad
hash.keys.each { |k| p k }
hash.values.each { |v| p v }
hash.each { |k, _v| p k }
hash.each { |_k, v| p v }
# good
hash.each_key { |k| p k }
hash.each_value { |v| p v }
Use each_key
instead of keys.each
. Open
params[:question].keys.each do |qid|
- Read upRead up
- Exclude checks
This cop 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.
Example:
# bad
hash.keys.each { |k| p k }
hash.values.each { |v| p v }
hash.each { |k, _v| p k }
hash.each { |_k, v| p v }
# good
hash.each_key { |k| p k }
hash.each_value { |v| p v }
Use each_key
instead of keys.each
. Open
params[:new_question].keys.each do |question_key|
- Read upRead up
- Exclude checks
This cop 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.
Example:
# bad
hash.keys.each { |k| p k }
hash.values.each { |v| p v }
hash.each { |k, _v| p k }
hash.each { |_k, v| p v }
# good
hash.each_key { |k| p k }
hash.each_value { |v| p v }
Use each_key
instead of keys.each
. Open
params[:question].keys.each do |question_key|
- Read upRead up
- Exclude checks
This cop 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.
Example:
# bad
hash.keys.each { |k| p k }
hash.values.each { |v| p v }
hash.each { |k, _v| p k }
hash.each { |_k, v| p v }
# good
hash.each_key { |k| p k }
hash.each_value { |v| p v }
TODO found Open
# TODO: check for Quiz Questionnaire?
- Exclude checks
FIXME found Open
# FIXME: These private methods belong in the Questionnaire model
- Exclude checks
Similar blocks of code found in 2 locations. Consider refactoring. Open
q = QuizQuestionChoice.new(txt: "True", iscorrect: "false", question_id: question.id)
q.save
q = QuizQuestionChoice.new(txt: "False", iscorrect: "true", question_id: question.id)
q.save
- 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 27.
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 2 locations. Consider refactoring. Open
q = QuizQuestionChoice.new(txt: "True", iscorrect: "true", question_id: question.id)
q.save
q = QuizQuestionChoice.new(txt: "False", iscorrect: "false", question_id: question.id)
q.save
- 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 27.
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
Convert if
nested inside else
to elsif
. Open
if assignment.topics? && team.topic.nil? # flash error if this assignment has topic but current team does not have a topic
- Read upRead up
- Exclude checks
If the else
branch of a conditional consists solely of an if
node,
it can be combined with the else
to become an elsif
.
This helps to keep the nesting level from getting too deep.
Example:
# bad
if condition_a
action_a
else
if condition_b
action_b
else
action_c
end
end
# good
if condition_a
action_a
elsif condition_b
action_b
else
action_c
end
Useless assignment to variable - parent
. Open
parent = FolderNode.find_by(node_object_id: p_folder.id)
- Read upRead up
- Exclude checks
This cop checks for every useless assignment to local variable in every
scope.
The basic idea for this cop was from the warning of ruby -cw
:
assigned but unused variable - foo
Currently this cop has advanced logic that detects unreferenced reassignments and properly handles varied cases such as branch, loop, rescue, ensure, etc.
Example:
# bad
def some_method
some_var = 1
do_something
end
Example:
# good
def some_method
some_var = 1
do_something(some_var)
end
Move q.save
out of the conditional. Open
q.save
- Read upRead up
- Exclude checks
This cop checks for identical lines at the beginning or end of each branch of a conditional statement.
Example:
# bad
if condition
do_x
do_z
else
do_y
do_z
end
# good
if condition
do_x
else
do_y
end
do_z
# bad
if condition
do_z
do_x
else
do_z
do_y
end
# good
do_z
if condition
do_x
else
do_y
end
# bad
case foo
when 1
do_x
when 2
do_x
else
do_x
end
# good
case foo
when 1
do_x
do_y
when 2
# nothing
else
do_x
do_z
end
Useless assignment to variable - score
. Open
score = if params[:new_choices][question_num.to_s][q_type][choice_key]["weight"] == 1.to_s
- Read upRead up
- Exclude checks
This cop checks for every useless assignment to local variable in every
scope.
The basic idea for this cop was from the warning of ruby -cw
:
assigned but unused variable - foo
Currently this cop has advanced logic that detects unreferenced reassignments and properly handles varied cases such as branch, loop, rescue, ensure, etc.
Example:
# bad
def some_method
some_var = 1
do_something
end
Example:
# good
def some_method
some_var = 1
do_something(some_var)
end
Use a guard clause instead of wrapping the code inside a conditional expression. Open
if params[:question]
- 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
Move q.save
out of the conditional. Open
q.save
- Read upRead up
- Exclude checks
This cop checks for identical lines at the beginning or end of each branch of a conditional statement.
Example:
# bad
if condition
do_x
do_z
else
do_y
do_z
end
# good
if condition
do_x
else
do_y
end
do_z
# bad
if condition
do_z
do_x
else
do_z
do_y
end
# good
do_z
if condition
do_x
else
do_y
end
# bad
case foo
when 1
do_x
when 2
do_x
else
do_x
end
# good
case foo
when 1
do_x
do_y
when 2
# nothing
else
do_x
do_z
end
Line is too long. [171/160] Open
question = Object.const_get(params[:question][:type]).create(txt: '', questionnaire_id: questionnaire_id, seq: i, type: params[:question][:type], break_before: true)
- Exclude checks
Convert if
nested inside else
to elsif
. Open
if quiz_question_choice.txt == "True"
- Read upRead up
- Exclude checks
If the else
branch of a conditional consists solely of an if
node,
it can be combined with the else
to become an elsif
.
This helps to keep the nesting level from getting too deep.
Example:
# bad
if condition_a
action_a
else
if condition_b
action_b
else
action_c
end
end
# good
if condition_a
action_a
elsif condition_b
action_b
else
action_c
end
Line is too long. [236/160] Open
quiz_question_choice.update_attributes(iscorrect: params[:quiz_question_choices][@question.id.to_s][@question.type][i.to_s][:iscorrect], txt: params[:quiz_question_choices][@question.id.to_s][@question.type][i.to_s][:txt])
- Exclude checks
Use a guard clause instead of wrapping the code inside a conditional expression. Open
if params[:new_question]
- 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
Do not use Time.now
without zone. Use one of Time.zone.now
, Time.current
, Time.now.in_time_zone
, Time.now.utc
, Time.now.getlocal
, Time.now.iso8601
, Time.now.jisx0301
, Time.now.rfc3339
, Time.now.to_i
, Time.now.to_f
instead. Open
@questionnaire.created_at = Time.now
- Read upRead up
- Exclude checks
This cop checks for the use of Time methods without zone.
Built on top of Ruby on Rails style guide (https://github.com/bbatsov/rails-style-guide#time) and the article http://danilenko.org/2012/7/6/rails_timezones/ .
Two styles are supported for this cop. When EnforcedStyle is 'strict' then only use of Time.zone is allowed.
When EnforcedStyle is 'flexible' then it's also allowed to use Time.intimezone.
Example:
# always offense
Time.now
Time.parse('2015-03-02 19:05:37')
# no offense
Time.zone.now
Time.zone.parse('2015-03-02 19:05:37')
# no offense only if style is 'flexible'
Time.current
DateTime.strptime(str, "%Y-%m-%d %H:%M %Z").in_time_zone
Time.at(timestamp).in_time_zone