Sha256: 02ba5f796a905d0ffdcf68a0349befff07f96e2f26c68b65858b76a24dec96e8

Contents?: true

Size: 1.21 KB

Versions: 6

Compression:

Stored size: 1.21 KB

Contents

# encoding: utf-8
# 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_op?(node) || ternary_op?(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

6 entries across 6 versions & 1 rubygems

Version Path
rubocop-0.39.0 lib/rubocop/cop/style/if_inside_else.rb
rubocop-0.38.0 lib/rubocop/cop/style/if_inside_else.rb
rubocop-0.37.2 lib/rubocop/cop/style/if_inside_else.rb
rubocop-0.37.1 lib/rubocop/cop/style/if_inside_else.rb
rubocop-0.37.0 lib/rubocop/cop/style/if_inside_else.rb
rubocop-0.36.0 lib/rubocop/cop/style/if_inside_else.rb