app/controllers/importers_controller.rb

Summary

Maintainability
D
2 days
Test Coverage

Unprotected mass assignment
Open

        @import_archive_file = ImportArchiveFile.create!(params.delete(:import_archive_file).merge(import_id: @import.id))

Mass assignment is a feature of Rails which allows an application to create a record from the values of a hash.

Example:

User.new(params[:user])

Unfortunately, if there is a user field called admin which controls administrator access, now any user can make themselves an administrator.

attr_accessible and attr_protected can be used to limit mass assignment. However, Brakeman will warn unless attr_accessible is used, or mass assignment is completely disabled.

There are two different mass assignment warnings which can arise. The first is when mass assignment actually occurs, such as the example above. This results in a warning like

Unprotected mass assignment near line 61: User.new(params[:user])

The other warning is raised whenever a model is found which does not use attr_accessible. This produces generic warnings like

Mass assignment is not restricted using attr_accessible

with a list of affected models.

In Rails 3.1 and newer, mass assignment can easily be disabled:

config.active_record.whitelist_attributes = true

Unfortunately, it can also easily be bypassed:

User.new(params[:user], :without_protection => true)

Brakeman will warn on uses of without_protection.

Unprotected mass assignment
Open

    @import = Import.new(params[:import])

Mass assignment is a feature of Rails which allows an application to create a record from the values of a hash.

Example:

User.new(params[:user])

Unfortunately, if there is a user field called admin which controls administrator access, now any user can make themselves an administrator.

attr_accessible and attr_protected can be used to limit mass assignment. However, Brakeman will warn unless attr_accessible is used, or mass assignment is completely disabled.

There are two different mass assignment warnings which can arise. The first is when mass assignment actually occurs, such as the example above. This results in a warning like

Unprotected mass assignment near line 61: User.new(params[:user])

The other warning is raised whenever a model is found which does not use attr_accessible. This produces generic warnings like

Mass assignment is not restricted using attr_accessible

with a list of affected models.

In Rails 3.1 and newer, mass assignment can easily be disabled:

config.active_record.whitelist_attributes = true

Unfortunately, it can also easily be bypassed:

User.new(params[:user], :without_protection => true)

Brakeman will warn on uses of without_protection.

Class has too many lines. [192/100]
Open

class ImportersController < ApplicationController
  include WorkerControllerHelpers

  # everything else is handled by application.rb
  before_filter :login_required, only: %i[list index new_related_set_from_archive_file]

This cop checks if the length a class exceeds some maximum value. Comment lines can optionally be ignored. The maximum allowed length is configurable.

Assignment Branch Condition size for get_progress is too high. [107.8/15]
Open

  def get_progress
    if !request.xhr?
      flash[:notice] = t('importers_controller.get_progress.import_failed')
      redirect_to action: 'list'
    else

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. [77/10]
Open

  def get_progress
    if !request.xhr?
      flash[:notice] = t('importers_controller.get_progress.import_failed')
      redirect_to action: 'list'
    else

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 create is too high. [70.26/15]
Open

  def create
    @import = Import.new(params[:import])
    @import.basket_id = @current_basket.id

    if importing_archive_file?

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 get_progress has a Cognitive Complexity of 49 (exceeds 5 allowed). Consider refactoring.
Open

  def get_progress
    if !request.xhr?
      flash[:notice] = t('importers_controller.get_progress.import_failed')
      redirect_to action: 'list'
    else
Severity: Minor
Found in app/controllers/importers_controller.rb - About 7 hrs to fix

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. [53/10]
Open

  def create
    @import = Import.new(params[:import])
    @import.basket_id = @current_basket.id

    if importing_archive_file?

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 has a Cognitive Complexity of 28 (exceeds 5 allowed). Consider refactoring.
Open

  def create
    @import = Import.new(params[:import])
    @import.basket_id = @current_basket.id

    if importing_archive_file?
Severity: Minor
Found in app/controllers/importers_controller.rb - About 4 hrs to fix

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 create is too high. [20/7]
Open

  def create
    @import = Import.new(params[:import])
    @import.basket_id = @current_basket.id

    if importing_archive_file?

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 get_progress has 77 lines of code (exceeds 25 allowed). Consider refactoring.
Open

  def get_progress
    if !request.xhr?
      flash[:notice] = t('importers_controller.get_progress.import_failed')
      redirect_to action: 'list'
    else
Severity: Major
Found in app/controllers/importers_controller.rb - About 3 hrs to fix

    Perceived complexity for get_progress is too high. [19/7]
    Open

      def get_progress
        if !request.xhr?
          flash[:notice] = t('importers_controller.get_progress.import_failed')
          redirect_to action: 'list'
        else

    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 create is too high. [17/6]
    Open

      def create
        @import = Import.new(params[:import])
        @import.basket_id = @current_basket.id
    
        if importing_archive_file?

    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 get_progress is too high. [14/6]
    Open

      def get_progress
        if !request.xhr?
          flash[:notice] = t('importers_controller.get_progress.import_failed')
          redirect_to action: 'list'
        else

    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 create has 53 lines of code (exceeds 25 allowed). Consider refactoring.
    Open

      def create
        @import = Import.new(params[:import])
        @import.basket_id = @current_basket.id
    
        if importing_archive_file?
    Severity: Major
    Found in app/controllers/importers_controller.rb - About 2 hrs to fix

      Block has too many lines. [26/25]
      Open

                render :update do |page|
                  if records_processed > 0
                    page.replace_html 'report_records_processed', t(
                      'importers_controller.get_progress.amount_processed',
                      records_processed: records_processed

      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 more than 3 levels of block nesting.
      Open

                    if !status[:error].blank?
                      done_message = t('importers_controller.get_progress.error_message', error: status[:error].gsub("\n", '<br />'))
                    end

      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

                    unless params[:related_topic].blank?
                      page.replace_html(
                        'exit', '<p>' + link_to(
                          t('importers_controller.get_progress.back_to', item_title: related_topic.title),
                          action: 'show',

      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.

      Identical blocks of code found in 2 locations. Consider refactoring.
      Open

                render :update do |page|
                  page.hide('spinner')
                  unless params[:related_topic].blank?
                    page.replace_html 'done', '<p>' + message + ' ' + link_to(
                      t('importers_controller.get_progress.to_related_topics'),
      Severity: Major
      Found in app/controllers/importers_controller.rb and 1 other location - About 1 hr to fix
      app/controllers/importers_controller.rb on lines 195..205

      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 53.

      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

      Further Reading

      Identical blocks of code found in 2 locations. Consider refactoring.
      Open

              render :update do |page|
                page.hide('spinner')
                unless params[:related_topic].blank?
                  page.replace_html 'done', '<p>' + message + ' ' + link_to(
                    t('importers_controller.get_progress.to_related_topics'),
      Severity: Major
      Found in app/controllers/importers_controller.rb and 1 other location - About 1 hr to fix
      app/controllers/importers_controller.rb on lines 173..183

      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 53.

      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

      Further Reading

      end at 95, 27 is not aligned with case at 90, 8.
      Open

                                 end

      This cop checks whether the end keywords are aligned properly.

      Three modes are supported through the EnforcedStyleAlignWith configuration parameter:

      If it's set to keyword (which is the default), the end shall be aligned with the start of the keyword (if, class, etc.).

      If it's set to variable the end shall be aligned with the left-hand-side of the variable assignment, if there is one.

      If it's set to start_of_line, the end shall be aligned with the start of the line where the matching keyword appears.

      Example: EnforcedStyleAlignWith: keyword (default)

      # bad
      
      variable = if true
          end
      
      # good
      
      variable = if true
                 end

      Example: EnforcedStyleAlignWith: variable

      # bad
      
      variable = if true
          end
      
      # good
      
      variable = if true
      end

      Example: EnforcedStyleAlignWith: startofline

      # bad
      
      variable = if true
          end
      
      # good
      
      puts(if true
      end)

      Use parentheses in the method call to avoid confusion about precedence.
      Open

          @import.user_id = @site_admin && params[:contributing_user].present? ? User.find(params[:contributing_user]).id : current_user.id

      This cop checks for expressions where there is a call to a predicate method with at least one argument, where no parentheses are used around the parameter list, and a boolean operator, && or ||, is used in the last argument.

      The idea behind warning for these constructs is that the user might be under the impression that the return value from the method call is an operand of &&/||.

      Example:

      # bad
      
      if day.is? :tuesday && month == :jan
        # ...
      end

      Example:

      # good
      
      if day.is?(:tuesday) && month == :jan
        # ...
      end

      Use records_processed.positive? instead of records_processed > 0.
      Open

                  if records_processed > 0

      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

      Prefer $ERROR_INFO from the stdlib 'English' module (don't forget to require it) over $!.
      Open

              message += " - #{$!}" unless $!.blank?

      Use a guard clause instead of wrapping the code inside a conditional expression.
      Open

          unless user_is_authorized

      Use a guard clause instead of wrapping the code inside a conditional expression

      Example:

      # bad
      def test
        if something
          work
        end
      end
      
      # good
      def test
        return unless something
        work
      end
      
      # also good
      def test
        work if something
      end
      
      # bad
      if something
        raise 'exception'
      else
        ok
      end
      
      # good
      raise 'exception' if something
      ok

      Do not prefix reader method names with get_.
      Open

        def get_progress

      This cop makes sure that accessor methods are named properly.

      Example:

      # bad
      def set_attribute(value)
      end
      
      # good
      def attribute=(value)
      end
      
      # bad
      def get_attribute
      end
      
      # good
      def attribute
      end

      Favor unless over if for negative conditions.
      Open

                    if !status[:error].blank?
                      done_message = t('importers_controller.get_progress.error_message', error: status[:error].gsub("\n", '<br />'))
                    end

      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

      Do not use unless with else. Rewrite these with the positive case first.
      Open

            unless backgroundrb_is_running?(@worker_type)
              MiddleMan.new_worker(worker: @worker_type, worker_key: @worker_key)
              import_request = { host: request.host, protocol: request.protocol, request_uri: request.original_url }
              MiddleMan.worker(@worker_type, @worker_key).async_do_work(arg: {
                                                                          zoom_class: @zoom_class,

      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

      Convert if nested inside else to elsif.
      Open

            if importing_archive_file?

      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

      Do not use unless with else. Rewrite these with the positive case first.
      Open

                unless params[:related_topic].blank?
                  page.replace_html 'done', '<p>' + message + ' ' + link_to(
                    t('importers_controller.get_progress.to_related_topics'),
                    action: 'show',
                    controller: 'topics',

      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

      Use the return of the conditional for variable assignment and comparison.
      Open

          if params[:action] == 'create' && !importing_archive_file?
            # if we aren't creating an import for archive sets, the rules of who can access the 'new' action apply
            user_is_authorized = permit?('site_admin or admin of :current_basket or tech_admin of :site')
          else
            user_is_authorized = current_user_can_import_archive_sets?

      Do not use unless with else. Rewrite these with the positive case first.
      Open

                    unless params[:related_topic].blank?
                      page.replace_html(
                        'exit', '<p>' + link_to(
                          t('importers_controller.get_progress.back_to', item_title: related_topic.title),
                          action: 'show',

      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

      Avoid rescuing without specifying an error class.
      Open

            rescue

      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

      Prefer $ERROR_INFO from the stdlib 'English' module (don't forget to require it) over $!.
      Open

              message += " - #{$!}" unless $!.blank?

      Do not use unless with else. Rewrite these with the positive case first.
      Open

                  unless params[:related_topic].blank?
                    page.replace_html 'done', '<p>' + message + ' ' + link_to(
                      t('importers_controller.get_progress.to_related_topics'),
                      action: 'show',
                      controller: 'topics',

      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

      There are no issues that match your filters.

      Category
      Status