Possible SQL injection Open
extended_fields = ExtendedField.all(conditions: "import_synonyms like \'%#{field}%\'")
- Read upRead up
- Exclude checks
Injection is #1 on the 2013 OWASP Top Ten web security risks. SQL injection is when a user is able to manipulate a value which is used unsafely inside a SQL query. This can lead to data leaks, data loss, elevation of privilege, and other unpleasant outcomes.
Brakeman focuses on ActiveRecord methods dealing with building SQL statements.
A basic (Rails 2.x) example looks like this:
User.first(:conditions => "username = '#{params[:username]}'")
Brakeman would produce a warning like this:
Possible SQL injection near line 30: User.first(:conditions => ("username = '#{params[:username]}'"))
The safe way to do this query is to use a parameterized query:
User.first(:conditions => ["username = ?", params[:username]])
Brakeman also understands the new Rails 3.x way of doing things (and local variables and concatenation):
username = params[:user][:name].downcase
password = params[:user][:password]
User.first.where("username = '" + username + "' AND password = '" + password + "'")
This results in this kind of warning:
Possible SQL injection near line 37:
User.first.where((((("username = '" + params[:user][:name].downcase) + "' AND password = '") + params[:user][:password]) + "'"))
See the Ruby Security Guide for more information and Rails-SQLi.org for many examples of SQL injection in Rails.
Unprotected mass assignment Open
new_image_file = ImageFile.new(params[:image_file])
- 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
.
Possible SQL injection Open
@current_basket.send(options[:item_type]).find(:all, conditions: conditions)
- Read upRead up
- Exclude checks
Injection is #1 on the 2013 OWASP Top Ten web security risks. SQL injection is when a user is able to manipulate a value which is used unsafely inside a SQL query. This can lead to data leaks, data loss, elevation of privilege, and other unpleasant outcomes.
Brakeman focuses on ActiveRecord methods dealing with building SQL statements.
A basic (Rails 2.x) example looks like this:
User.first(:conditions => "username = '#{params[:username]}'")
Brakeman would produce a warning like this:
Possible SQL injection near line 30: User.first(:conditions => ("username = '#{params[:username]}'"))
The safe way to do this query is to use a parameterized query:
User.first(:conditions => ["username = ?", params[:username]])
Brakeman also understands the new Rails 3.x way of doing things (and local variables and concatenation):
username = params[:user][:name].downcase
password = params[:user][:password]
User.first.where("username = '" + username + "' AND password = '" + password + "'")
This results in this kind of warning:
Possible SQL injection near line 37:
User.first.where((((("username = '" + params[:user][:name].downcase) + "' AND password = '") + params[:user][:password]) + "'"))
See the Ruby Security Guide for more information and Rails-SQLi.org for many examples of SQL injection in Rails.
Module has too many lines. [795/100] Open
module Importer
unless included_modules.include? Importer
def self.included(klass)
klass.send :include, KeteUrlFor
klass.send :include, OaiDcHelpers
- Read upRead up
- Exclude checks
This cop checks if the length a module exceeds some maximum value. Comment lines can optionally be ignored. The maximum allowed length is configurable.
Assignment Branch Condition size for create_new_item_from_record is too high. [203.3/15] Open
def create_new_item_from_record(record, zoom_class, options = {})
zoom_class_for_params = zoom_class.tableize.singularize
params = options[:params]
- 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 importer_prepare_extended_field is too high. [147.1/15] Open
def importer_prepare_extended_field(options = {})
params = options[:params]
field = options[:field]
value = options[:value]
zoom_class_for_params = options[:zoom_class_for_params]
- 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 create_new_item_from_record
has a Cognitive Complexity of 103 (exceeds 5 allowed). Consider refactoring. Open
def create_new_item_from_record(record, zoom_class, options = {})
zoom_class_for_params = zoom_class.tableize.singularize
params = options[:params]
- 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 has too many lines. [132/10] Open
def create_new_item_from_record(record, zoom_class, options = {})
zoom_class_for_params = zoom_class.tableize.singularize
params = options[:params]
- 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.
File importer.rb
has 806 lines of code (exceeds 250 allowed). Consider refactoring. Open
require 'tempfile'
require 'fileutils'
require 'mime/types'
require 'oai_dc_helpers'
require 'xml_helpers'
Method importer_prepare_extended_field
has a Cognitive Complexity of 87 (exceeds 5 allowed). Consider refactoring. Open
def importer_prepare_extended_field(options = {})
params = options[:params]
field = options[:field]
value = options[:value]
zoom_class_for_params = options[:zoom_class_for_params]
- 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 has too many lines. [95/10] Open
def importer_prepare_extended_field(options = {})
params = options[:params]
field = options[:field]
value = options[:value]
zoom_class_for_params = options[:zoom_class_for_params]
- 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 assign_value_to_appropriate_fields is too high. [74.14/15] Open
def assign_value_to_appropriate_fields(record_field, record_value, params, zoom_class)
return if SystemSetting.import_fields_to_ignore.include?(record_field)
logger.debug('record_field ' + record_field.inspect)
zoom_class_for_params = zoom_class.tableize.singularize
- 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 importer_process is too high. [67.68/15] Open
def importer_process(record, params)
current_record = @results[:records_processed] + 1
logger.info("starting record #{current_record}")
record_hash = {}
- 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 assign_value_to_appropriate_fields
has a Cognitive Complexity of 46 (exceeds 5 allowed). Consider refactoring. Open
def assign_value_to_appropriate_fields(record_field, record_value, params, zoom_class)
return if SystemSetting.import_fields_to_ignore.include?(record_field)
logger.debug('record_field ' + record_field.inspect)
zoom_class_for_params = zoom_class.tableize.singularize
- 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 importer_build_relations_to
has a Cognitive Complexity of 45 (exceeds 5 allowed). Consider refactoring. Open
def importer_build_relations_to(new_record, record_hash, params)
logger.info('building relations for new record')
if @related_topics_reference_in_record_xml_field.blank? && @related_topic.blank?
logger.info('no relations to be made for new record')
- 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 has too many lines. [52/10] Open
def importer_process(record, params)
current_record = @results[:records_processed] + 1
logger.info("starting record #{current_record}")
record_hash = {}
- 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.
Perceived complexity for create_new_item_from_record is too high. [49/7] Open
def create_new_item_from_record(record, zoom_class, options = {})
zoom_class_for_params = zoom_class.tableize.singularize
params = options[:params]
- 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. [49/10] Open
def assign_value_to_appropriate_fields(record_field, record_value, params, zoom_class)
return if SystemSetting.import_fields_to_ignore.include?(record_field)
logger.debug('record_field ' + record_field.inspect)
zoom_class_for_params = zoom_class.tableize.singularize
- 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 importer_locate_existing_items is too high. [53.15/15] Open
def importer_locate_existing_items(options = {})
# not applicable to related_topic imports, at least for the moment
return [] if @related_topic.present?
options = {
- 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 has too many lines. [45/10] Open
def importer_build_relations_to(new_record, record_hash, params)
logger.info('building relations for new record')
if @related_topics_reference_in_record_xml_field.blank? && @related_topic.blank?
logger.info('no relations to be made for new record')
- 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 importer_trim_fat_from_xml_import_file
has a Cognitive Complexity of 37 (exceeds 5 allowed). Consider refactoring. Open
def importer_trim_fat_from_xml_import_file(path_to_original_file, path_to_output, accession = nil)
fat_free_file = File.new(path_to_output, 'w+')
fatty_re = Regexp.new("\/\>.*")
- 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 importer_trim_fat_from_xml_import_file is too high. [48.77/15] Open
def importer_trim_fat_from_xml_import_file(path_to_original_file, path_to_output, accession = nil)
fat_free_file = File.new(path_to_output, 'w+')
fatty_re = Regexp.new("\/\>.*")
- 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 importer_prepare_path_to_image_file is too high. [47.34/15] Open
def importer_prepare_path_to_image_file(image_file)
image_path_array = image_file.split('\\')
# prep alternative versions of the filename
directories_up_to = @import_parent_dir_for_image_dirs + '/' + image_path_array[0] + '/'
- 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_new_item_from_record is too high. [38/6] Open
def create_new_item_from_record(record, zoom_class, options = {})
zoom_class_for_params = zoom_class.tableize.singularize
params = options[:params]
- 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 has too many lines. [41/10] Open
def importer_extended_fields_update_hash_for_item(options = {})
params = options[:params]
item_key = options[:item_key].to_sym
builder = Nokogiri::XML::Builder.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 create_new_item_from_record
has 132 lines of code (exceeds 25 allowed). Consider refactoring. Open
def create_new_item_from_record(record, zoom_class, options = {})
zoom_class_for_params = zoom_class.tableize.singularize
params = options[:params]
Method has too many lines. [39/10] Open
def importer_trim_fat_from_xml_import_file(path_to_original_file, path_to_output, accession = nil)
fat_free_file = File.new(path_to_output, 'w+')
fatty_re = Regexp.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. [39/10] Open
def importer_locate_existing_items(options = {})
# not applicable to related_topic imports, at least for the moment
return [] if @related_topic.present?
options = {
- 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 importer_build_relations_to is too high. [40.01/15] Open
def importer_build_relations_to(new_record, record_hash, params)
logger.info('building relations for new record')
if @related_topics_reference_in_record_xml_field.blank? && @related_topic.blank?
logger.info('no relations to be made for new record')
- 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 importer_extended_fields_update_hash_for_item is too high. [39.15/15] Open
def importer_extended_fields_update_hash_for_item(options = {})
params = options[:params]
item_key = options[:item_key].to_sym
builder = Nokogiri::XML::Builder.new
- 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 importer_prepare_extended_field is too high. [31/7] Open
def importer_prepare_extended_field(options = {})
params = options[:params]
field = options[:field]
value = options[:value]
zoom_class_for_params = options[:zoom_class_for_params]
- 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. [34/10] Open
def importer_prepare_path_to_image_file(image_file)
image_path_array = image_file.split('\\')
# prep alternative versions of the filename
directories_up_to = @import_parent_dir_for_image_dirs + '/' + image_path_array[0] + '/'
- 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 importer_create_related_topic is too high. [37.12/15] Open
def importer_create_related_topic(topic_params)
# clear any lingering values for @fields
# and instantiate it, in case we need it
@fields = nil
- 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 importer_trim_fat_from_xml_import_file is too high. [27/7] Open
def importer_trim_fat_from_xml_import_file(path_to_original_file, path_to_output, accession = nil)
fat_free_file = File.new(path_to_output, 'w+')
fatty_re = Regexp.new("\/\>.*")
- 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. [30/10] Open
def importer_create_related_topic(topic_params)
# clear any lingering values for @fields
# and instantiate it, in case we need it
@fields = nil
- 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 importer_setup_initial_instance_vars is too high. [34.73/15] Open
def importer_setup_initial_instance_vars(args)
@zoom_class = args[:zoom_class]
@import = Import.find(args[:import])
@import_type = @import.xml_type
@import_dir_path = ::Import::IMPORTS_DIR + @import.directory
- 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 has too many lines. [29/10] Open
def do_work(args = nil)
logger.info('in work')
begin
importer_setup_initial_instance_vars(args)
- 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 importer_prepare_extended_field
has 95 lines of code (exceeds 25 allowed). Consider refactoring. Open
def importer_prepare_extended_field(options = {})
params = options[:params]
field = options[:field]
value = options[:value]
zoom_class_for_params = options[:zoom_class_for_params]
Cyclomatic complexity for importer_trim_fat_from_xml_import_file is too high. [24/6] Open
def importer_trim_fat_from_xml_import_file(path_to_original_file, path_to_output, accession = nil)
fat_free_file = File.new(path_to_output, 'w+')
fatty_re = Regexp.new("\/\>.*")
- 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 importer_prepare_extended_field is too high. [24/6] Open
def importer_prepare_extended_field(options = {})
params = options[:params]
field = options[:field]
value = options[:value]
zoom_class_for_params = options[:zoom_class_for_params]
- 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 assign_value_to_appropriate_fields is too high. [24/7] Open
def assign_value_to_appropriate_fields(record_field, record_value, params, zoom_class)
return if SystemSetting.import_fields_to_ignore.include?(record_field)
logger.debug('record_field ' + record_field.inspect)
zoom_class_for_params = zoom_class.tableize.singularize
- 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 importer_locate_existing_items
has a Cognitive Complexity of 25 (exceeds 5 allowed). Consider refactoring. Open
def importer_locate_existing_items(options = {})
# not applicable to related_topic imports, at least for the moment
return [] if @related_topic.present?
options = {
- 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 do_work is too high. [30.02/15] Open
def do_work(args = nil)
logger.info('in work')
begin
importer_setup_initial_instance_vars(args)
- 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 assign_value_to_appropriate_fields is too high. [21/6] Open
def assign_value_to_appropriate_fields(record_field, record_value, params, zoom_class)
return if SystemSetting.import_fields_to_ignore.include?(record_field)
logger.debug('record_field ' + record_field.inspect)
zoom_class_for_params = zoom_class.tableize.singularize
- 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.
Consider simplifying this complex logical expression. Open
if line.include?('<ACCESSNO') || line.include?('<accessno') ||
line.include?('<DESCRIP') || line.include?('<descrip') ||
line.include?("<\/DESCRIP") || line.include?("<\/descrip") ||
line.include?("<\/Record") || line.include?("<\/export") ||
line.include?('<Information') || line.include?("<\/Information") ||
Assignment Branch Condition size for importer_fetch_related_topics is too high. [28.53/15] Open
def importer_fetch_related_topics(related_topic_identifier, params, options = {})
related_topics = []
related_topics += importer_locate_existing_items(options)
- 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 importer_process
has a Cognitive Complexity of 22 (exceeds 5 allowed). Consider refactoring. Open
def importer_process(record, params)
current_record = @results[:records_processed] + 1
logger.info("starting record #{current_record}")
record_hash = {}
- 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 importer_extended_fields_update_hash_for_item
has a Cognitive Complexity of 21 (exceeds 5 allowed). Consider refactoring. Open
def importer_extended_fields_update_hash_for_item(options = {})
params = options[:params]
item_key = options[:item_key].to_sym
builder = Nokogiri::XML::Builder.new
- 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
Perceived complexity for importer_process is too high. [17/7] Open
def importer_process(record, params)
current_record = @results[:records_processed] + 1
logger.info("starting record #{current_record}")
record_hash = {}
- 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 importer_fetch_related_topics
has a Cognitive Complexity of 20 (exceeds 5 allowed). Consider refactoring. Open
def importer_fetch_related_topics(related_topic_identifier, params, options = {})
related_topics = []
related_topics += importer_locate_existing_items(options)
- Read upRead up
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Cyclomatic complexity for importer_process is too high. [15/6] Open
def importer_process(record, params)
current_record = @results[:records_processed] + 1
logger.info("starting record #{current_record}")
record_hash = {}
- 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 has too many lines. [18/10] Open
def importer_setup_initial_instance_vars(args)
@zoom_class = args[:zoom_class]
@import = Import.find(args[:import])
@import_type = @import.xml_type
@import_dir_path = ::Import::IMPORTS_DIR + @import.directory
- 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. [18/10] Open
def importer_fetch_related_topics(related_topic_identifier, params, options = {})
related_topics = []
related_topics += importer_locate_existing_items(options)
- 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.
Perceived complexity for importer_build_relations_to is too high. [14/7] Open
def importer_build_relations_to(new_record, record_hash, params)
logger.info('building relations for new record')
if @related_topics_reference_in_record_xml_field.blank? && @related_topic.blank?
logger.info('no relations to be made for new record')
- 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 importer_build_relations_to is too high. [12/6] Open
def importer_build_relations_to(new_record, record_hash, params)
logger.info('building relations for new record')
if @related_topics_reference_in_record_xml_field.blank? && @related_topic.blank?
logger.info('no relations to be made for new record')
- 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 importer_prepare_path_to_image_file
has a Cognitive Complexity of 17 (exceeds 5 allowed). Consider refactoring. Open
def importer_prepare_path_to_image_file(image_file)
image_path_array = image_file.split('\\')
# prep alternative versions of the filename
directories_up_to = @import_parent_dir_for_image_dirs + '/' + image_path_array[0] + '/'
- Read upRead up
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Method do_work
has a Cognitive Complexity of 17 (exceeds 5 allowed). Consider refactoring. Open
def do_work(args = nil)
logger.info('in work')
begin
importer_setup_initial_instance_vars(args)
- Read upRead up
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Cyclomatic complexity for importer_locate_existing_items is too high. [11/6] Open
def importer_locate_existing_items(options = {})
# not applicable to related_topic imports, at least for the moment
return [] if @related_topic.present?
options = {
- 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 importer_locate_existing_items is too high. [12/7] Open
def importer_locate_existing_items(options = {})
# not applicable to related_topic imports, at least for the moment
return [] if @related_topic.present?
options = {
- 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. [15/10] Open
def importer_update_processing_vars_at_end
if @successful
@results[:notice] = I18n.t('importer_lib.importer_update_processing_vars_at_end.import_successful')
@results[:done_with_do_work] = true
@import.update_attributes(status: 'complete')
- 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. [15/10] Open
def importer_extended_fields_replacement_params_hash(options = {})
params = options[:params]
item_key = options[:item_key].to_sym
item_class = options[:item_class]
- 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 importer_xml_record_to_hash(record, upcase = false)
record_hash = Hash.from_xml(record.to_s)
# HACK: to go down one more level
record_hash.keys.each do |record_field|
- 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 importer_extended_fields_replacement_params_hash is too high. [19.54/15] Open
def importer_extended_fields_replacement_params_hash(options = {})
params = options[:params]
item_key = options[:item_key].to_sym
item_class = options[:item_class]
- 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 importer_process
has 52 lines of code (exceeds 25 allowed). Consider refactoring. Open
def importer_process(record, params)
current_record = @results[:records_processed] + 1
logger.info("starting record #{current_record}")
record_hash = {}
Perceived complexity for importer_prepare_path_to_image_file is too high. [10/7] Open
def importer_prepare_path_to_image_file(image_file)
image_path_array = image_file.split('\\')
# prep alternative versions of the filename
directories_up_to = @import_parent_dir_for_image_dirs + '/' + image_path_array[0] + '/'
- 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 assign_value_to_appropriate_fields
has 49 lines of code (exceeds 25 allowed). Consider refactoring. Open
def assign_value_to_appropriate_fields(record_field, record_value, params, zoom_class)
return if SystemSetting.import_fields_to_ignore.include?(record_field)
logger.debug('record_field ' + record_field.inspect)
zoom_class_for_params = zoom_class.tableize.singularize
Method has too many lines. [12/10] Open
def importer_records_from_directory_at(path, params)
# files or directories to ignore
not_wanted_patterns = ['Thumbs.db', 'ehthumbs.db', '__MACOSX']
Dir.foreach(path) do |record|
full_path_to_record = path + '/' + record
- 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.
Cyclomatic complexity for importer_prepare_path_to_image_file is too high. [8/6] Open
def importer_prepare_path_to_image_file(image_file)
image_path_array = image_file.split('\\')
# prep alternative versions of the filename
directories_up_to = @import_parent_dir_for_image_dirs + '/' + image_path_array[0] + '/'
- 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 importer_fetch_related_topics is too high. [8/6] Open
def importer_fetch_related_topics(related_topic_identifier, params, options = {})
related_topics = []
related_topics += importer_locate_existing_items(options)
- 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 do_work is too high. [9/7] Open
def do_work(args = nil)
logger.info('in work')
begin
importer_setup_initial_instance_vars(args)
- 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 importer_build_relations_to
has 45 lines of code (exceeds 25 allowed). Consider refactoring. Open
def importer_build_relations_to(new_record, record_hash, params)
logger.info('building relations for new record')
if @related_topics_reference_in_record_xml_field.blank? && @related_topic.blank?
logger.info('no relations to be made for new record')
Cyclomatic complexity for do_work is too high. [7/6] Open
def do_work(args = nil)
logger.info('in work')
begin
importer_setup_initial_instance_vars(args)
- 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 importer_fetch_related_topics is too high. [8/7] Open
def importer_fetch_related_topics(related_topic_identifier, params, options = {})
related_topics = []
related_topics += importer_locate_existing_items(options)
- 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 importer_update_processing_vars_at_end is too high. [16.28/15] Open
def importer_update_processing_vars_at_end
if @successful
@results[:notice] = I18n.t('importer_lib.importer_update_processing_vars_at_end.import_successful')
@results[:done_with_do_work] = true
@import.update_attributes(status: 'complete')
- 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 importer_extended_fields_update_hash_for_item
has 41 lines of code (exceeds 25 allowed). Consider refactoring. Open
def importer_extended_fields_update_hash_for_item(options = {})
params = options[:params]
item_key = options[:item_key].to_sym
builder = Nokogiri::XML::Builder.new
Method importer_trim_fat_from_xml_import_file
has 39 lines of code (exceeds 25 allowed). Consider refactoring. Open
def importer_trim_fat_from_xml_import_file(path_to_original_file, path_to_output, accession = nil)
fat_free_file = File.new(path_to_output, 'w+')
fatty_re = Regexp.new("\/\>.*")
Method importer_locate_existing_items
has 39 lines of code (exceeds 25 allowed). Consider refactoring. Open
def importer_locate_existing_items(options = {})
# not applicable to related_topic imports, at least for the moment
return [] if @related_topic.present?
options = {
Method importer_prepare_path_to_image_file
has 34 lines of code (exceeds 25 allowed). Consider refactoring. Open
def importer_prepare_path_to_image_file(image_file)
image_path_array = image_file.split('\\')
# prep alternative versions of the filename
directories_up_to = @import_parent_dir_for_image_dirs + '/' + image_path_array[0] + '/'
Method importer_create_related_topic
has 30 lines of code (exceeds 25 allowed). Consider refactoring. Open
def importer_create_related_topic(topic_params)
# clear any lingering values for @fields
# and instantiate it, in case we need it
@fields = nil
Method do_work
has 29 lines of code (exceeds 25 allowed). Consider refactoring. Open
def do_work(args = nil)
logger.info('in work')
begin
importer_setup_initial_instance_vars(args)
Block has too many lines. [34/25] Open
builder.root do |xml|
@fields.each do |field_to_xml|
field_name = field_to_xml.extended_field_label.downcase.tr(' ', '_')
if field_to_xml.extended_field_multiple
hash_of_values = params[item_key]['extended_content_values'][field_name] rescue nil
- 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. [32/25] Open
@fields.each do |field_to_xml|
field_name = field_to_xml.extended_field_label.downcase.tr(' ', '_')
if field_to_xml.extended_field_multiple
hash_of_values = params[item_key]['extended_content_values'][field_name] rescue nil
if !hash_of_values.nil?
- 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. [31/25] Open
IO.foreach(path_to_original_file) do |line|
line = remove_non_unix_new_lines(line)
# HACK: to seriously trim down accession records
# and make them in a form we can search easily
# only add non-fat to our fat_free_file
- 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.
Avoid deeply nested control flow statements. Open
elsif extended_field.ftype == 'topic_type' && @extended_field_that_contains_related_topics_reference.present?
logger.info 'dealing with topic_type extended field'
logger.info 'what is value? ' + value.inspect
unless value =~ /http:\/\//
logger.info 'value does not include http://'
Avoid deeply nested control flow statements. Open
args = field_modifier.arity == 2 ? [record_value, record_hash] : [record_value]
Avoid deeply nested control flow statements. Open
if !@root_element_name.nil? && @root_element_name == 'Root'
new_start_record_line += 'Record'
else
new_start_record_line += 'export'
end
Avoid deeply nested control flow statements. Open
accessno = !accessno_match_result.nil? && !accessno_match_result[1].nil? ? accessno_match_result[1] : nil
Avoid deeply nested control flow statements. Open
if zoom_class == 'StillImage'
logger.debug('in image')
params[:image_file] = upload_hash
else
logger.debug('in not image')
Avoid deeply nested control flow statements. Open
unless accessno.blank?
new_start_record_line += " ACCESSNO=\'#{accessno}\'"
end
Avoid deeply nested control flow statements. Open
additional_fields_derived_from_processing_values.merge!(parsed_value.last) if parsed_value.last.is_a?(Hash)
Method importer_create_related_topic
has a Cognitive Complexity of 8 (exceeds 5 allowed). Consider refactoring. Open
def importer_create_related_topic(topic_params)
# clear any lingering values for @fields
# and instantiate it, in case we need it
@fields = nil
- 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 deeply nested control flow statements. Open
if extended_field.multiple
value.split(',').each_with_index do |multiple_choice, multiple_index|
params[zoom_class_for_params]['extended_content_values'][extended_field.label_for_params][(multiple_index + 1).to_s] ||= {}
multiple_choice.strip.split('->').each_with_index do |choice, choice_index|
params[zoom_class_for_params]['extended_content_values'][extended_field.label_for_params][(multiple_index + 1).to_s][(choice_index + 1).to_s] = choice.strip
Block has too many lines. [29/25] Open
@related_topics_reference_in_record_xml_field.each do |related_topics_reference_in_record_xml_field|
next if related_topics_reference_in_record_xml_field.blank?
if record_hash[related_topics_reference_in_record_xml_field].blank?
logger.info("no relational field found with name of #{related_topics_reference_in_record_xml_field}")
next
- 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 remove_non_unix_new_lines
has a Cognitive Complexity of 7 (exceeds 5 allowed). Consider refactoring. Open
def remove_non_unix_new_lines(line)
line = line[0..-3] + line[-1..-1] if line[-2] == 0xD
line = line[0..-2] if line[-1] == 0xA
# add a unix newline if not already there
line = line + "\n" unless line.include?("\n")
- 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 importer_records_from_directory_at
has a Cognitive Complexity of 7 (exceeds 5 allowed). Consider refactoring. Open
def importer_records_from_directory_at(path, params)
# files or directories to ignore
not_wanted_patterns = ['Thumbs.db', 'ehthumbs.db', '__MACOSX']
Dir.foreach(path) do |record|
full_path_to_record = path + '/' + record
- 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 importer_xml_record_to_hash
has a Cognitive Complexity of 6 (exceeds 5 allowed). Consider refactoring. Open
def importer_xml_record_to_hash(record, upcase = false)
record_hash = Hash.from_xml(record.to_s)
# HACK: to go down one more level
record_hash.keys.each do |record_field|
- 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 importer_update_processing_vars_at_end
has a Cognitive Complexity of 6 (exceeds 5 allowed). Consider refactoring. Open
def importer_update_processing_vars_at_end
if @successful
@results[:notice] = I18n.t('importer_lib.importer_update_processing_vars_at_end.import_successful')
@results[:done_with_do_work] = true
@import.update_attributes(status: 'complete')
- 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 importer_setup_initial_instance_vars
has a Cognitive Complexity of 6 (exceeds 5 allowed). Consider refactoring. Open
def importer_setup_initial_instance_vars(args)
@zoom_class = args[:zoom_class]
@import = Import.find(args[:import])
@import_type = @import.xml_type
@import_dir_path = ::Import::IMPORTS_DIR + @import.directory
- 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
params[zoom_class_for_params]['extended_content_values'] = {} if \
params[zoom_class_for_params]['extended_content_values'].nil?
- 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 %w{choice autocomplete}.include?(extended_field.ftype)
params[zoom_class_for_params]['extended_content_values'][extended_field.label_for_params] ||= {}
if extended_field.multiple
value.split(',').each_with_index do |multiple_choice, multiple_index|
params[zoom_class_for_params]['extended_content_values'][extended_field.label_for_params][(multiple_index + 1).to_s] ||= {}
- 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 File.exist?(downer)
path_to_file_to_grab = downer
logger.debug('path_to_file_to_grab is downer: ' + path_to_file_to_grab)
elsif File.exist?(upper)
path_to_file_to_grab = upper
- 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 line.include?('<ACCESSNO') || line.include?('<accessno') ||
line.include?('<DESCRIP') || line.include?('<descrip') ||
line.include?("<\/DESCRIP") || line.include?("<\/descrip") ||
line.include?("<\/Record") || line.include?("<\/export") ||
line.include?('<Information') || line.include?("<\/Information") ||
- 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
related_topics = importer_fetch_related_topics(
related_topic_identifier, params, {
item_type: 'topics',
topic_type: @related_topic_type,
extended_field_data: {
- 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 params[zoom_class_for_params][:short_summary].nil?
params[zoom_class_for_params][:short_summary] = record_value
else
params[zoom_class_for_params][:short_summary] += "\n\n" + record_value
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 record_hash[record_field].present?
record_hash[record_field] += "\n\n" + record_value
else
record_hash[record_field] = record_value
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 extended_fields.present?
extended_field = extended_fields.select { |ext_field| (ext_field.import_synonyms || '').split.include?(field) }.first
@import_field_to_extended_field_map[field] = extended_field
else
logger.info('field in prepare: ' + field.inspect)
- 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 record_value.present? && importer_field_methods[record_field.downcase]
field_modifier = eval(importer_field_methods[record_field.downcase])
args = field_modifier.arity == 2 ? [record_value, record_hash] : [record_value]
parsed_value = Array(field_modifier.call(*args))
additional_fields_derived_from_processing_values.merge!(parsed_value.last) if parsed_value.last.is_a?(Hash)
- 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 @import_topic_type
extended_fields = @import_topic_type.mapped_fields
else
extended_fields = ExtendedField.all(conditions: "import_synonyms like \'%#{field}%\'")
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 params[zoom_class_for_params][:description].nil?
params[zoom_class_for_params][:description] = record_value
else
params[zoom_class_for_params][:description] += "\n\n" + record_value
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 ::Import::VALID_ARCHIVE_CLASSES.include?(zoom_class) && File.exist?(record_value)
# we do a check earlier in the script for imagefile
# so we should have something to work with here
upload_hash = { uploaded_data: copy_and_load_to_temp_file(record_value) }
if zoom_class == 'StillImage'
- 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
hash_of_values.keys.each do |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[item_key].keys.each do |field_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
record_hash.keys.each do |field_name|
- 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
record_hash.keys.each do |record_field|
- 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: it looks like this still needs multiple support?
- Exclude checks
HACK found Open
# HACK: to go down one more level
- Exclude checks
HACK found Open
# HACK, for horizons agency/series import, needs to be handled better
- Exclude checks
HACK found Open
# HACK: to seriously trim down accession records
- Exclude checks
HACK found Open
# HACK, for horizons agency/series import, needs to be handled better
- Exclude checks
HACK found Open
# HACK, conflict with symbol vs string for hash key
- Exclude checks
TODO found Open
# TODO: add support for zoom_classes that may have attachments
- Exclude checks
Identical blocks of code found in 2 locations. Consider refactoring. Open
if !@import.description_beginning_template.blank?
# append the citation to the description field
if !params[zoom_class_for_params][:description].nil?
params[zoom_class_for_params][:description] = @import.description_beginning_template + "\n\n" + params[zoom_class_for_params][:description]
else
- 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 70.
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
if zoom_class == 'Topic'
params[zoom_class_for_params][:topic_type_id] = @import_topic_type.id
@fields = @import_topic_type.topic_type_to_field_mappings
- 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
Identical blocks of code found in 2 locations. Consider refactoring. Open
if !options[:description_end_template].nil?
# append the description_end_template to the description field
if !params[zoom_class_for_params][:description].nil?
params[zoom_class_for_params][:description] += "\n\n" + options[:description_end_template]
else
- 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 2 locations. Consider refactoring. Open
if !SystemSetting.description_synonyms.blank? && SystemSetting.description_synonyms.include?(record_field)
if params[zoom_class_for_params][:description].nil?
params[zoom_class_for_params][:description] = record_value
else
params[zoom_class_for_params][:description] += "\n\n" + record_value
- 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 32.
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
if !SystemSetting.short_summary_synonyms.blank? && SystemSetting.short_summary_synonyms.include?(record_field)
if params[zoom_class_for_params][:short_summary].nil?
params[zoom_class_for_params][:short_summary] = record_value
else
params[zoom_class_for_params][:short_summary] += "\n\n" + record_value
- 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 32.
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
Useless assignment to variable - line
. Open
line = line + "\n" unless line.include?("\n")
- 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
Useless assignment to variable - description
. Open
description = ''
- 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
Redundant curly braces around a hash parameter. Open
related_topic_identifier, params, {
item_type: 'topics',
topic_type: @related_topic_type,
extended_field_data: {
label: @extended_field_that_contains_related_topics_reference.label_for_params,
- Read upRead up
- Exclude checks
This cop checks for braces around the last parameter in a method call
if the last parameter is a hash.
It supports braces
, no_braces
and context_dependent
styles.
Example: EnforcedStyle: braces
# The `braces` style enforces braces around all method
# parameters that are hashes.
# bad
some_method(x, y, a: 1, b: 2)
# good
some_method(x, y, {a: 1, b: 2})
Example: EnforcedStyle: no_braces (default)
# The `no_braces` style checks that the last parameter doesn't
# have braces around it.
# bad
some_method(x, y, {a: 1, b: 2})
# good
some_method(x, y, a: 1, b: 2)
Example: EnforcedStyle: context_dependent
# The `context_dependent` style checks that the last parameter
# doesn't have braces around it, but requires braces if the
# second to last parameter is also a hash literal.
# bad
some_method(x, y, {a: 1, b: 2})
some_method(x, y, {a: 1, b: 2}, a: 1, b: 2)
# good
some_method(x, y, a: 1, b: 2)
some_method(x, y, {a: 1, b: 2}, {a: 1, b: 2})
The use of eval
is a serious security risk. Open
field_modifier = eval(importer_field_methods[record_field.downcase])
- Read upRead up
- Exclude checks
This cop checks for the use of Kernel#eval
and Binding#eval
.
Example:
# bad
eval(something)
binding.eval(something)
Use only ascii symbols in comments. Open
# 'ü' => 'ū' }
- Read upRead up
- Exclude checks
This cop checks for non-ascii (non-English) characters in comments. You could set an array of allowed non-ascii chars in AllowedChars attribute (empty by default).
Example:
# bad
# Translates from English to 日本語。
# good
# Translates from English to Japanese
Use the return of the conditional for variable assignment and comparison. Open
if !params[zoom_class_for_params][:description].nil?
params[zoom_class_for_params][:description] = @import.description_beginning_template + "\n\n" + params[zoom_class_for_params][:description]
else
params[zoom_class_for_params][:description] = @import.description_beginning_template
end
- Exclude checks
Do not use parallel assignment. Open
@results[:error], @successful = $!.to_s, false
- Read upRead up
- Exclude checks
Checks for simple usages of parallel assignment. This will only complain when the number of variables being assigned matched the number of assigning variables.
Example:
# bad
a, b, c = 1, 2, 3
a, b, c = [1, 2, 3]
# good
one, two = *foo
a, b = foo()
a, b = b, a
a = 1
b = 2
c = 3
Useless assignment to variable - record
. Open
record = nil
- 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 the return of the conditional for variable assignment and comparison. Open
if !@import.license.blank?
topic_params[:topic][:license_id] = @import.license.id
else
topic_params[:topic][:license_id] = nil
end
- Exclude checks
Use self-assignment shorthand +=
. Open
line = line + "\n" unless line.include?("\n")
- Read upRead up
- Exclude checks
This cop enforces the use the shorthand for self-assignment.
Example:
# bad
x = x + 1
# good
x += 1
Use only ascii symbols in comments. Open
# 'ë' => 'ē',
- Read upRead up
- Exclude checks
This cop checks for non-ascii (non-English) characters in comments. You could set an array of allowed non-ascii chars in AllowedChars attribute (empty by default).
Example:
# bad
# Translates from English to 日本語。
# good
# Translates from English to Japanese
Redundant curly braces around a hash parameter. Open
new_record = create_new_item_from_record(record, @zoom_class, { params: params, record_hash: record_hash, description_end_template: description_end_template })
- Read upRead up
- Exclude checks
This cop checks for braces around the last parameter in a method call
if the last parameter is a hash.
It supports braces
, no_braces
and context_dependent
styles.
Example: EnforcedStyle: braces
# The `braces` style enforces braces around all method
# parameters that are hashes.
# bad
some_method(x, y, a: 1, b: 2)
# good
some_method(x, y, {a: 1, b: 2})
Example: EnforcedStyle: no_braces (default)
# The `no_braces` style checks that the last parameter doesn't
# have braces around it.
# bad
some_method(x, y, {a: 1, b: 2})
# good
some_method(x, y, a: 1, b: 2)
Example: EnforcedStyle: context_dependent
# The `context_dependent` style checks that the last parameter
# doesn't have braces around it, but requires braces if the
# second to last parameter is also a hash literal.
# bad
some_method(x, y, {a: 1, b: 2})
some_method(x, y, {a: 1, b: 2}, a: 1, b: 2)
# good
some_method(x, y, a: 1, b: 2)
some_method(x, y, {a: 1, b: 2}, {a: 1, b: 2})
Use a guard clause instead of wrapping the code inside a conditional expression. Open
if zoom_class == 'StillImage'
- 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
Favor unless
over if
for negative conditions. Open
params[zoom_class_for_params][:license_id] = @import.license.id if !@import.license.blank?
- Read upRead up
- Exclude checks
Checks for uses of if with a negated condition. Only ifs without else are considered. There are three different styles:
- both
- prefix
- postfix
Example: EnforcedStyle: both (default)
# enforces `unless` for `prefix` and `postfix` conditionals
# bad
if !foo
bar
end
# good
unless foo
bar
end
# bad
bar if !foo
# good
bar unless foo
Example: EnforcedStyle: prefix
# enforces `unless` for just `prefix` conditionals
# bad
if !foo
bar
end
# good
unless foo
bar
end
# good
bar if !foo
Example: EnforcedStyle: postfix
# enforces `unless` for just `postfix` conditionals
# bad
bar if !foo
# good
bar unless foo
# good
if !foo
bar
end
Use %r
around regular expression. Open
unless value =~ /http:\/\//
- Read upRead up
- Exclude checks
This cop enforces using // or %r around regular expressions.
Example: EnforcedStyle: slashes (default)
# bad
snake_case = %r{^[\dA-Z_]+$}
# bad
regex = %r{
foo
(bar)
(baz)
}x
# good
snake_case = /^[\dA-Z_]+$/
# good
regex = /
foo
(bar)
(baz)
/x
Example: EnforcedStyle: percent_r
# bad
snake_case = /^[\dA-Z_]+$/
# bad
regex = /
foo
(bar)
(baz)
/x
# good
snake_case = %r{^[\dA-Z_]+$}
# good
regex = %r{
foo
(bar)
(baz)
}x
Example: EnforcedStyle: mixed
# bad
snake_case = %r{^[\dA-Z_]+$}
# bad
regex = /
foo
(bar)
(baz)
/x
# good
snake_case = /^[\dA-Z_]+$/
# good
regex = %r{
foo
(bar)
(baz)
}x
Example: AllowInnerSlashes: false (default)
# If `false`, the cop will always recommend using `%r` if one or more
# slashes are found in the regexp string.
# bad
x =~ /home\//
# good
x =~ %r{home/}
Example: AllowInnerSlashes: true
# good
x =~ /home\//
Use only ascii symbols in comments. Open
# 'ï' => 'ī',
- Read upRead up
- Exclude checks
This cop checks for non-ascii (non-English) characters in comments. You could set an array of allowed non-ascii chars in AllowedChars attribute (empty by default).
Example:
# bad
# Translates from English to 日本語。
# good
# Translates from English to Japanese
Use the return of the conditional for variable assignment and comparison. Open
if options[:basket_id].nil?
params[zoom_class_for_params][:basket_id] = @current_basket.id
else
params[zoom_class_for_params][:basket_id] = options[:basket_id]
end
- Exclude checks
Favor unless
over if
for negative conditions. Open
if !value.blank?
# look up the synonym for the field
# check if it's been mapped locally
extended_field = ''
if @import_field_to_extended_field_map[field].present?
- Read upRead up
- Exclude checks
Checks for uses of if with a negated condition. Only ifs without else are considered. There are three different styles:
- both
- prefix
- postfix
Example: EnforcedStyle: both (default)
# enforces `unless` for `prefix` and `postfix` conditionals
# bad
if !foo
bar
end
# good
unless foo
bar
end
# bad
bar if !foo
# good
bar unless foo
Example: EnforcedStyle: prefix
# enforces `unless` for just `prefix` conditionals
# bad
if !foo
bar
end
# good
unless foo
bar
end
# good
bar if !foo
Example: EnforcedStyle: postfix
# enforces `unless` for just `postfix` conditionals
# bad
bar if !foo
# good
bar unless foo
# good
if !foo
bar
end
Favor unless
over if
for negative conditions. Open
if !@results[:error].nil?
logger.info("import error: #{@results[:error]}")
@results[:notice] += @results[:error]
end
- Read upRead up
- Exclude checks
Checks for uses of if with a negated condition. Only ifs without else are considered. There are three different styles:
- both
- prefix
- postfix
Example: EnforcedStyle: both (default)
# enforces `unless` for `prefix` and `postfix` conditionals
# bad
if !foo
bar
end
# good
unless foo
bar
end
# bad
bar if !foo
# good
bar unless foo
Example: EnforcedStyle: prefix
# enforces `unless` for just `prefix` conditionals
# bad
if !foo
bar
end
# good
unless foo
bar
end
# good
bar if !foo
Example: EnforcedStyle: postfix
# enforces `unless` for just `postfix` conditionals
# bad
bar if !foo
# good
bar unless foo
# good
if !foo
bar
end
Avoid the use of Perl-style backrefs. Open
m_field_value = (m_field_value =~ /(\d+)/ && $1) if circa
- Read upRead up
- Exclude checks
This cop looks for uses of Perl-style regexp match backreferences like $1, $2, etc.
Example:
# bad
puts $1
# good
puts Regexp.last_match(1)
Avoid rescuing without specifying an error class. Open
rescue
- Read upRead up
- Exclude checks
This cop checks for rescuing StandardError
. There are two supported
styles implicit
and explicit
. This cop will not register an offense
if any error other than StandardError
is specified.
Example: EnforcedStyle: implicit
# `implicit` will enforce using `rescue` instead of
# `rescue StandardError`.
# bad
begin
foo
rescue StandardError
bar
end
# good
begin
foo
rescue
bar
end
# good
begin
foo
rescue OtherError
bar
end
# good
begin
foo
rescue StandardError, SecurityError
bar
end
Example: EnforcedStyle: explicit (default)
# `explicit` will enforce using `rescue StandardError`
# instead of `rescue`.
# bad
begin
foo
rescue
bar
end
# good
begin
foo
rescue StandardError
bar
end
# good
begin
foo
rescue OtherError
bar
end
# good
begin
foo
rescue StandardError, SecurityError
bar
end
Use !empty?
instead of size > 0
. Open
if @fields.size > 0
- Read upRead up
- Exclude checks
This cop checks for numeric comparisons that can be replaced by a predicate method, such as receiver.length == 0, receiver.length > 0, receiver.length != 0, receiver.length < 1 and receiver.size == 0 that can be replaced by receiver.empty? and !receiver.empty.
Example:
# bad
[1, 2, 3].length == 0
0 == "foobar".length
array.length < 1
{a: 1, b: 2}.length != 0
string.length > 0
hash.size > 0
# good
[1, 2, 3].empty?
"foobar".empty?
array.empty?
!{a: 1, b: 2}.empty?
!string.empty?
!hash.empty?
Favor unless
over if
for negative conditions. Open
@tag_list_array = @import.base_tags.split(',').collect { |tag| tag.strip } if !@import.base_tags.blank?
- Read upRead up
- Exclude checks
Checks for uses of if with a negated condition. Only ifs without else are considered. There are three different styles:
- both
- prefix
- postfix
Example: EnforcedStyle: both (default)
# enforces `unless` for `prefix` and `postfix` conditionals
# bad
if !foo
bar
end
# good
unless foo
bar
end
# bad
bar if !foo
# good
bar unless foo
Example: EnforcedStyle: prefix
# enforces `unless` for just `prefix` conditionals
# bad
if !foo
bar
end
# good
unless foo
bar
end
# good
bar if !foo
Example: EnforcedStyle: postfix
# enforces `unless` for just `postfix` conditionals
# bad
bar if !foo
# good
bar unless foo
# good
if !foo
bar
end
Favor a normal if-statement over a modifier clause in a multiline statement. Open
related_topics = importer_fetch_related_topics(
related_topic_identifier, params, {
item_type: 'topics',
topic_type: @related_topic_type,
extended_field_data: {
- Read upRead up
- Exclude checks
Checks for uses of if/unless modifiers with multiple-lines bodies.
Example:
# bad
{
result: 'this should not happen'
} unless cond
# good
{ result: 'ok' } if cond
Use @fields.size.positive?
instead of @fields.size > 0
. Open
if @fields.size > 0
- Read upRead up
- Exclude checks
This cop checks for usage of comparison operators (==
,
>
, <
) to test numbers as zero, positive, or negative.
These can be replaced by their respective predicate methods.
The cop can also be configured to do the reverse.
The cop disregards #nonzero?
as it its value is truthy or falsey,
but not true
and false
, and thus not always interchangeable with
!= 0
.
The cop ignores comparisons to global variables, since they are often
populated with objects which can be compared with integers, but are
not themselves Interger
polymorphic.
Example: EnforcedStyle: predicate (default)
# bad
foo == 0
0 > foo
bar.baz > 0
# good
foo.zero?
foo.negative?
bar.baz.positive?
Example: EnforcedStyle: comparison
# bad
foo.zero?
foo.negative?
bar.baz.positive?
# good
foo == 0
0 > foo
bar.baz > 0
Pass &:remove
as an argument to each
instead of a block. Open
record.search('//agency.Predecessor').each do |node|
node.remove
end
- Read upRead up
- Exclude checks
Use symbols as procs when possible.
Example:
# bad
something.map { |s| s.upcase }
# good
something.map(&:upcase)
Use only ascii symbols in comments. Open
# replacements = { 'ä' => 'ā',
- Read upRead up
- Exclude checks
This cop checks for non-ascii (non-English) characters in comments. You could set an array of allowed non-ascii chars in AllowedChars attribute (empty by default).
Example:
# bad
# Translates from English to 日本語。
# good
# Translates from English to Japanese
Convert if
nested inside else
to elsif
. Open
if line.include?('<ACCESSNO') || line.include?('<accessno') ||
- 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
Avoid using rescue
in its modifier form. Open
hash_of_values = params[item_key]['extended_content_values'][field_name] rescue nil
- Read upRead up
- Exclude checks
This cop checks for uses of rescue in its modifier form.
Example:
# bad
some_method rescue handle_error
# good
begin
some_method
rescue
handle_error
end
Do not use unless
with else
. Rewrite these with the positive case first. Open
unless zoom_class == 'StillImage'
new_record_added = new_record.save
else
new_record_added = new_record.save unless new_image_file.nil?
end
- Read upRead up
- Exclude checks
This cop looks for unless expressions with else clauses.
Example:
# bad
unless foo_bar.nil?
# do something...
else
# do a different thing...
end
# good
if foo_bar.present?
# do something...
else
# do a different thing...
end
Redundant curly braces around a hash parameter. Open
value, params, {
item_type: 'topics',
topic_type: topic_type,
extended_field_data: {
label: @extended_field_that_contains_related_topics_reference.label_for_params,
- Read upRead up
- Exclude checks
This cop checks for braces around the last parameter in a method call
if the last parameter is a hash.
It supports braces
, no_braces
and context_dependent
styles.
Example: EnforcedStyle: braces
# The `braces` style enforces braces around all method
# parameters that are hashes.
# bad
some_method(x, y, a: 1, b: 2)
# good
some_method(x, y, {a: 1, b: 2})
Example: EnforcedStyle: no_braces (default)
# The `no_braces` style checks that the last parameter doesn't
# have braces around it.
# bad
some_method(x, y, {a: 1, b: 2})
# good
some_method(x, y, a: 1, b: 2)
Example: EnforcedStyle: context_dependent
# The `context_dependent` style checks that the last parameter
# doesn't have braces around it, but requires braces if the
# second to last parameter is also a hash literal.
# bad
some_method(x, y, {a: 1, b: 2})
some_method(x, y, {a: 1, b: 2}, a: 1, b: 2)
# good
some_method(x, y, a: 1, b: 2)
some_method(x, y, {a: 1, b: 2}, {a: 1, b: 2})
Use the return of the conditional for variable assignment and comparison. Open
if @skip_trimming
@path_to_trimmed_records = records_xml_path
else
@path_to_trimmed_records = importer_trim_fat_from_xml_import_file(records_xml_path, @path_to_trimmed_records)
end
- Exclude checks
Use the return of the conditional for variable assignment and comparison. Open
if @import_topic_type
extended_fields = @import_topic_type.mapped_fields
else
extended_fields = ExtendedField.all(conditions: "import_synonyms like \'%#{field}%\'")
end
- Exclude checks
Use the return of the conditional for variable assignment and comparison. Open
if SystemSetting.enable_embedded_support && zoom_class != 'StillImage' && ATTACHABLE_CLASSES.include?(zoom_class)
new_record.title = '-replace-' + record_hash['placeholder_title']
else
new_record.title = record_hash['placeholder_title']
end
- Exclude checks
Favor unless
over if
for negative conditions. Open
if !line.match(fatty_re)
if accession.nil?
# replace double dotted version of maori vowels
# with macrons
# replacements = { 'ä' => 'ā',
- Read upRead up
- Exclude checks
Checks for uses of if with a negated condition. Only ifs without else are considered. There are three different styles:
- both
- prefix
- postfix
Example: EnforcedStyle: both (default)
# enforces `unless` for `prefix` and `postfix` conditionals
# bad
if !foo
bar
end
# good
unless foo
bar
end
# bad
bar if !foo
# good
bar unless foo
Example: EnforcedStyle: prefix
# enforces `unless` for just `prefix` conditionals
# bad
if !foo
bar
end
# good
unless foo
bar
end
# good
bar if !foo
Example: EnforcedStyle: postfix
# enforces `unless` for just `postfix` conditionals
# bad
bar if !foo
# good
bar unless foo
# good
if !foo
bar
end
Use safe navigation (&.
) instead of checking if an object exists before calling the method. Open
title = record_hash[field_name].strip if field_name.casecmp('title').zero? || (SystemSetting.SystemSetting.title_synonyms && SystemSetting.SystemSetting.title_synonyms.include?(field_name))
- Read upRead up
- Exclude checks
This cop transforms usages of a method call safeguarded by a non nil
check for the variable whose method is being called to
safe navigation (&.
).
Configuration option: ConvertCodeThatCanStartToReturnNil
The default for this is false
. When configured to true
, this will
check for code in the format !foo.nil? && foo.bar
. As it is written,
the return of this code is limited to false
and whatever the return
of the method is. If this is converted to safe navigation,
foo&.bar
can start returning nil
as well as what the method
returns.
Example:
# bad
foo.bar if foo
foo.bar(param1, param2) if foo
foo.bar { |e| e.something } if foo
foo.bar(param) { |e| e.something } if foo
foo.bar if !foo.nil?
foo.bar unless !foo
foo.bar unless foo.nil?
foo && foo.bar
foo && foo.bar(param1, param2)
foo && foo.bar { |e| e.something }
foo && foo.bar(param) { |e| e.something }
# good
foo&.bar
foo&.bar(param1, param2)
foo&.bar { |e| e.something }
foo&.bar(param) { |e| e.something }
foo.nil? || foo.bar
!foo || foo.bar
# Methods that `nil` will `respond_to?` should not be converted to
# use safe navigation
foo.to_i if foo
Use self-assignment shorthand +=
. Open
@fields = @fields + ancestor.topic_type_to_field_mappings
- Read upRead up
- Exclude checks
This cop enforces the use the shorthand for self-assignment.
Example:
# bad
x = x + 1
# good
x += 1
Prefer $ERROR_INFO
from the stdlib 'English' module (don't forget to require it) over $!
. Open
@results[:error], @successful = $!.to_s, false
- Exclude checks
Favor unless
over if
for negative conditions. Open
if !params[zoom_class_for_params][:description].nil?
description = RedCloth.new params[zoom_class_for_params][:description]
params[zoom_class_for_params][:description] = description.to_html
end
- Read upRead up
- Exclude checks
Checks for uses of if with a negated condition. Only ifs without else are considered. There are three different styles:
- both
- prefix
- postfix
Example: EnforcedStyle: both (default)
# enforces `unless` for `prefix` and `postfix` conditionals
# bad
if !foo
bar
end
# good
unless foo
bar
end
# bad
bar if !foo
# good
bar unless foo
Example: EnforcedStyle: prefix
# enforces `unless` for just `prefix` conditionals
# bad
if !foo
bar
end
# good
unless foo
bar
end
# good
bar if !foo
Example: EnforcedStyle: postfix
# enforces `unless` for just `postfix` conditionals
# bad
bar if !foo
# good
bar unless foo
# good
if !foo
bar
end
Use ancestors.size.positive?
instead of ancestors.size > 0
. Open
if ancestors.size > 0
- Read upRead up
- Exclude checks
This cop checks for usage of comparison operators (==
,
>
, <
) to test numbers as zero, positive, or negative.
These can be replaced by their respective predicate methods.
The cop can also be configured to do the reverse.
The cop disregards #nonzero?
as it its value is truthy or falsey,
but not true
and false
, and thus not always interchangeable with
!= 0
.
The cop ignores comparisons to global variables, since they are often
populated with objects which can be compared with integers, but are
not themselves Interger
polymorphic.
Example: EnforcedStyle: predicate (default)
# bad
foo == 0
0 > foo
bar.baz > 0
# good
foo.zero?
foo.negative?
bar.baz.positive?
Example: EnforcedStyle: comparison
# bad
foo.zero?
foo.negative?
bar.baz.positive?
# good
foo == 0
0 > foo
bar.baz > 0
Pass &:strip
as an argument to collect
instead of a block. Open
@related_topics_reference_in_record_xml_field = @related_topics_reference_in_record_xml_field.split(',').collect { |r| r.strip }
- Read upRead up
- Exclude checks
Use symbols as procs when possible.
Example:
# bad
something.map { |s| s.upcase }
# good
something.map(&:upcase)
Unnecessary utf-8 encoding comment. Open
# -*- coding: utf-8 -*-
- Exclude checks
Favor unless
over if
for negative conditions. Open
if !reason_skipped.blank?
importer_log_to_skipped_records(title, reason_skipped)
end
- Read upRead up
- Exclude checks
Checks for uses of if with a negated condition. Only ifs without else are considered. There are three different styles:
- both
- prefix
- postfix
Example: EnforcedStyle: both (default)
# enforces `unless` for `prefix` and `postfix` conditionals
# bad
if !foo
bar
end
# good
unless foo
bar
end
# bad
bar if !foo
# good
bar unless foo
Example: EnforcedStyle: prefix
# enforces `unless` for just `prefix` conditionals
# bad
if !foo
bar
end
# good
unless foo
bar
end
# good
bar if !foo
Example: EnforcedStyle: postfix
# enforces `unless` for just `postfix` conditionals
# bad
bar if !foo
# good
bar unless foo
# good
if !foo
bar
end
%w
-literals should be delimited by [
and ]
. Open
if %w{choice autocomplete}.include?(extended_field.ftype)
- Read upRead up
- Exclude checks
This cop enforces the consistent usage of %
-literal delimiters.
Specify the 'default' key to set all preferred delimiters at once. You can continue to specify individual preferred delimiters to override the default.
Example:
# Style/PercentLiteralDelimiters:
# PreferredDelimiters:
# default: '[]'
# '%i': '()'
# good
%w[alpha beta] + %i(gamma delta)
# bad
%W(alpha #{beta})
# bad
%I(alpha beta)
Use a guard clause instead of wrapping the code inside a conditional expression. Open
if zoom_class == 'StillImage'
- 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
Favor unless
over if
for negative conditions. Open
if !File.exist?(new_file_path)
FileUtils.copy_file path_to_file_to_grab, new_file_path
end
- Read upRead up
- Exclude checks
Checks for uses of if with a negated condition. Only ifs without else are considered. There are three different styles:
- both
- prefix
- postfix
Example: EnforcedStyle: both (default)
# enforces `unless` for `prefix` and `postfix` conditionals
# bad
if !foo
bar
end
# good
unless foo
bar
end
# bad
bar if !foo
# good
bar unless foo
Example: EnforcedStyle: prefix
# enforces `unless` for just `prefix` conditionals
# bad
if !foo
bar
end
# good
unless foo
bar
end
# good
bar if !foo
Example: EnforcedStyle: postfix
# enforces `unless` for just `postfix` conditionals
# bad
bar if !foo
# good
bar unless foo
# good
if !foo
bar
end
Avoid the use of Perl-style backrefs. Open
value = (value =~ /(\d+)/ && $1) if circa
- Read upRead up
- Exclude checks
This cop looks for uses of Perl-style regexp match backreferences like $1, $2, etc.
Example:
# bad
puts $1
# good
puts Regexp.last_match(1)
Use the return of the conditional for variable assignment and comparison. Open
if !@root_element_name.nil? && @root_element_name == 'Root'
new_start_record_line += 'Record'
else
new_start_record_line += 'export'
end
- Exclude checks
Use the return of the conditional for variable assignment and comparison. Open
if options[:record_hash].nil?
record_hash = importer_xml_record_to_hash(record)
else
record_hash = options[:record_hash]
end
- Exclude checks
Use the return of the conditional for variable assignment and comparison. Open
if !params[zoom_class_for_params][:description].nil?
params[zoom_class_for_params][:description] = SystemSetting.description_template + "\n\n" + params[zoom_class_for_params][:description]
else
params[zoom_class_for_params][:description] = SystemSetting.description_template
end
- Exclude checks
Avoid using rescue
in its modifier form. Open
value = (params[item_key]['extended_content_values'][field_name] || '') rescue ''
- Read upRead up
- Exclude checks
This cop checks for uses of rescue in its modifier form.
Example:
# bad
some_method rescue handle_error
# good
begin
some_method
rescue
handle_error
end
Pass &:remove
as an argument to each
instead of a block. Open
record.search('//agency.Successor').each do |node|
node.remove
end
- Read upRead up
- Exclude checks
Use symbols as procs when possible.
Example:
# bad
something.map { |s| s.upcase }
# good
something.map(&:upcase)
Use next
to skip iteration. Open
if record_value.present? && importer_field_methods[record_field.downcase]
- Read upRead up
- Exclude checks
Use next
to skip iteration instead of a condition at the end.
Example: EnforcedStyle: skipmodifierifs (default)
# bad
[1, 2].each do |a|
if a == 1
puts a
end
end
# good
[1, 2].each do |a|
next unless a == 1
puts a
end
# good
[1, 2].each do |o|
puts o unless o == 1
end
Example: EnforcedStyle: always
# With `always` all conditions at the end of an iteration needs to be
# replaced by next - with `skip_modifier_ifs` the modifier if like
# this one are ignored: `[1, 2].each { |a| return 'yes' if a == 1 }`
# bad
[1, 2].each do |o|
puts o unless o == 1
end
# bad
[1, 2].each do |a|
if a == 1
puts a
end
end
# good
[1, 2].each do |a|
next unless a == 1
puts a
end
Use @record_interval.positive?
instead of @record_interval > 0
. Open
sleep(@record_interval) if @record_interval > 0
- Read upRead up
- Exclude checks
This cop checks for usage of comparison operators (==
,
>
, <
) to test numbers as zero, positive, or negative.
These can be replaced by their respective predicate methods.
The cop can also be configured to do the reverse.
The cop disregards #nonzero?
as it its value is truthy or falsey,
but not true
and false
, and thus not always interchangeable with
!= 0
.
The cop ignores comparisons to global variables, since they are often
populated with objects which can be compared with integers, but are
not themselves Interger
polymorphic.
Example: EnforcedStyle: predicate (default)
# bad
foo == 0
0 > foo
bar.baz > 0
# good
foo.zero?
foo.negative?
bar.baz.positive?
Example: EnforcedStyle: comparison
# bad
foo.zero?
foo.negative?
bar.baz.positive?
# good
foo == 0
0 > foo
bar.baz > 0
Use self-assignment shorthand +=
. Open
@fields = @fields + ancestor.topic_type_to_field_mappings
- Read upRead up
- Exclude checks
This cop enforces the use the shorthand for self-assignment.
Example:
# bad
x = x + 1
# good
x += 1
Use !empty?
instead of size > 0
. Open
if ancestors.size > 0
- Read upRead up
- Exclude checks
This cop checks for numeric comparisons that can be replaced by a predicate method, such as receiver.length == 0, receiver.length > 0, receiver.length != 0, receiver.length < 1 and receiver.size == 0 that can be replaced by receiver.empty? and !receiver.empty.
Example:
# bad
[1, 2, 3].length == 0
0 == "foobar".length
array.length < 1
{a: 1, b: 2}.length != 0
string.length > 0
hash.size > 0
# good
[1, 2, 3].empty?
"foobar".empty?
array.empty?
!{a: 1, b: 2}.empty?
!string.empty?
!hash.empty?
Prefer using YAML.safe_load
over YAML.load
. Open
importer_field_methods = (YAML.load(File.read(import_field_methods_file)) || {})[@import_type.to_s]
- Read upRead up
- Exclude checks
This cop checks for the use of YAML class methods which have potential security issues leading to remote code execution when loading from an untrusted source.
Example:
# bad
YAML.load("--- foo")
# good
YAML.safe_load("--- foo")
YAML.dump("foo")
Use only ascii symbols in comments. Open
# 'ö' => 'ō',
- Read upRead up
- Exclude checks
This cop checks for non-ascii (non-English) characters in comments. You could set an array of allowed non-ascii chars in AllowedChars attribute (empty by default).
Example:
# bad
# Translates from English to 日本語。
# good
# Translates from English to Japanese
Convert if
nested inside else
to elsif
. Open
if extended_field.multiple
- 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
Favor unless
over if
for negative conditions. Open
if !options[:description_end_template].nil?
# append the description_end_template to the description field
if !params[zoom_class_for_params][:description].nil?
params[zoom_class_for_params][:description] += "\n\n" + options[:description_end_template]
else
- Read upRead up
- Exclude checks
Checks for uses of if with a negated condition. Only ifs without else are considered. There are three different styles:
- both
- prefix
- postfix
Example: EnforcedStyle: both (default)
# enforces `unless` for `prefix` and `postfix` conditionals
# bad
if !foo
bar
end
# good
unless foo
bar
end
# bad
bar if !foo
# good
bar unless foo
Example: EnforcedStyle: prefix
# enforces `unless` for just `prefix` conditionals
# bad
if !foo
bar
end
# good
unless foo
bar
end
# good
bar if !foo
Example: EnforcedStyle: postfix
# enforces `unless` for just `postfix` conditionals
# bad
bar if !foo
# good
bar unless foo
# good
if !foo
bar
end
Pass &:strip
as an argument to collect
instead of a block. Open
@tag_list_array = @import.base_tags.split(',').collect { |tag| tag.strip } if !@import.base_tags.blank?
- Read upRead up
- Exclude checks
Use symbols as procs when possible.
Example:
# bad
something.map { |s| s.upcase }
# good
something.map(&:upcase)
Favor unless
over if
for negative conditions. Open
if !hash_of_values.nil?
xml.safe_send("#{field_name}_multiple") do
hash_of_values.keys.each do |key|
xml.safe_send(key.to_s) do
logger.debug('inside hash: key: ' + key.to_s)
- Read upRead up
- Exclude checks
Checks for uses of if with a negated condition. Only ifs without else are considered. There are three different styles:
- both
- prefix
- postfix
Example: EnforcedStyle: both (default)
# enforces `unless` for `prefix` and `postfix` conditionals
# bad
if !foo
bar
end
# good
unless foo
bar
end
# bad
bar if !foo
# good
bar unless foo
Example: EnforcedStyle: prefix
# enforces `unless` for just `prefix` conditionals
# bad
if !foo
bar
end
# good
unless foo
bar
end
# good
bar if !foo
Example: EnforcedStyle: postfix
# enforces `unless` for just `postfix` conditionals
# bad
bar if !foo
# good
bar unless foo
# good
if !foo
bar
end
Favor unless
over if
for negative conditions. Open
if !File.exist?(path_to_file_to_grab)
logger.debug('path_to_file_to_grab no match yet')
# Try case insensitive check
# this may not work on all systems, so falling back to only checking extensions after
- Read upRead up
- Exclude checks
Checks for uses of if with a negated condition. Only ifs without else are considered. There are three different styles:
- both
- prefix
- postfix
Example: EnforcedStyle: both (default)
# enforces `unless` for `prefix` and `postfix` conditionals
# bad
if !foo
bar
end
# good
unless foo
bar
end
# bad
bar if !foo
# good
bar unless foo
Example: EnforcedStyle: prefix
# enforces `unless` for just `prefix` conditionals
# bad
if !foo
bar
end
# good
unless foo
bar
end
# good
bar if !foo
Example: EnforcedStyle: postfix
# enforces `unless` for just `postfix` conditionals
# bad
bar if !foo
# good
bar unless foo
# good
if !foo
bar
end
Use safe navigation (&.
) instead of checking if an object exists before calling the method. Open
new_image_file.destroy unless new_image_file.nil?
- Read upRead up
- Exclude checks
This cop transforms usages of a method call safeguarded by a non nil
check for the variable whose method is being called to
safe navigation (&.
).
Configuration option: ConvertCodeThatCanStartToReturnNil
The default for this is false
. When configured to true
, this will
check for code in the format !foo.nil? && foo.bar
. As it is written,
the return of this code is limited to false
and whatever the return
of the method is. If this is converted to safe navigation,
foo&.bar
can start returning nil
as well as what the method
returns.
Example:
# bad
foo.bar if foo
foo.bar(param1, param2) if foo
foo.bar { |e| e.something } if foo
foo.bar(param) { |e| e.something } if foo
foo.bar if !foo.nil?
foo.bar unless !foo
foo.bar unless foo.nil?
foo && foo.bar
foo && foo.bar(param1, param2)
foo && foo.bar { |e| e.something }
foo && foo.bar(param) { |e| e.something }
# good
foo&.bar
foo&.bar(param1, param2)
foo&.bar { |e| e.something }
foo&.bar(param) { |e| e.something }
foo.nil? || foo.bar
!foo || foo.bar
# Methods that `nil` will `respond_to?` should not be converted to
# use safe navigation
foo.to_i if foo
Pass &:strip
as an argument to collect
instead of a block. Open
@tag_list_array += record_value.split(',').collect { |tag| tag.strip }
- Read upRead up
- Exclude checks
Use symbols as procs when possible.
Example:
# bad
something.map { |s| s.upcase }
# good
something.map(&:upcase)