Sha256: 0bcdd6a5d5e7183c7228e0436f7aa29cac456c9dec651d6875066f83e16e1e45

Contents?: true

Size: 1.19 KB

Versions: 11

Compression:

Stored size: 1.19 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # 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
      #   @good
      #   if condition_a
      #     action_a
      #   elsif condition_b
      #     action_b
      #   else
      #     action_c
      #   end
      #
      #   @bad
      #   if condition_a
      #     action_a
      #   else
      #     if condition_b
      #       action_b
      #     else
      #       action_c
      #     end
      #   end
      class IfInsideElse < Cop
        include IfNode

        MSG = 'Convert `if` nested inside `else` to `elsif`.'.freeze

        def on_if(node)
          _cond, _if_branch, else_branch = *node
          return unless else_branch
          return unless else_branch.if_type?
          return if ternary?(node) || ternary?(else_branch)
          return unless else_branch.loc.keyword.is?('if')
          return if node.loc.keyword.is?('unless')

          add_offense(else_branch, :keyword, MSG)
        end
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 2 rubygems

Version Path
dirwatch-0.0.9 vendor/bundle/ruby/2.5.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/if_inside_else.rb
dirwatch-0.0.8 vendor/bundle/ruby/2.5.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/if_inside_else.rb
dirwatch-0.0.6 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/if_inside_else.rb
dirwatch-0.0.5 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/if_inside_else.rb
dirwatch-0.0.4 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/if_inside_else.rb
dirwatch-0.0.3 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/if_inside_else.rb
dirwatch-0.0.2 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/if_inside_else.rb
rubocop-0.46.0 lib/rubocop/cop/style/if_inside_else.rb
rubocop-0.45.0 lib/rubocop/cop/style/if_inside_else.rb
rubocop-0.44.1 lib/rubocop/cop/style/if_inside_else.rb
rubocop-0.44.0 lib/rubocop/cop/style/if_inside_else.rb