Sha256: c6869999346a1616c8c44eb156154ec103b00cb3448a21a5498f887c639b563a

Contents?: true

Size: 1.43 KB

Versions: 13

Compression:

Stored size: 1.43 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # 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
      class UnlessElse < Cop
        include RangeHelp

        MSG = 'Do not use `unless` with `else`. Rewrite these with the ' \
              'positive case first.'

        def on_if(node)
          return unless node.unless? && node.else?

          add_offense(node)
        end

        def autocorrect(node)
          body_range = range_between_condition_and_else(node, node.condition)
          else_range = range_between_else_and_end(node)

          lambda do |corrector|
            corrector.replace(node.loc.keyword, 'if')
            corrector.replace(body_range, else_range.source)
            corrector.replace(else_range, body_range.source)
          end
        end

        def range_between_condition_and_else(node, condition)
          range_between(condition.source_range.end_pos, node.loc.else.begin_pos)
        end

        def range_between_else_and_end(node)
          range_between(node.loc.else.end_pos, node.loc.end.begin_pos)
        end
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 3 rubygems

Version Path
rubocop-0.89.1 lib/rubocop/cop/style/unless_else.rb
rubocop-0.89.0 lib/rubocop/cop/style/unless_else.rb
rubocop-0.88.0 lib/rubocop/cop/style/unless_else.rb
rbhint-0.87.1.rc1 lib/rubocop/cop/style/unless_else.rb
rubocop-0.87.1 lib/rubocop/cop/style/unless_else.rb
rubocop-0.87.0 lib/rubocop/cop/style/unless_else.rb
rubocop-0.86.0 lib/rubocop/cop/style/unless_else.rb
files.com-1.0.1 vendor/bundle/ruby/2.5.0/gems/rubocop-0.85.1/lib/rubocop/cop/style/unless_else.rb
rbhint-0.85.1.rc2 lib/rubocop/cop/style/unless_else.rb
rbhint-0.85.1.rc1 lib/rubocop/cop/style/unless_else.rb
rubocop-0.85.1 lib/rubocop/cop/style/unless_else.rb
rbhint-0.8.5.rc1 lib/rubocop/cop/style/unless_else.rb
rubocop-0.85.0 lib/rubocop/cop/style/unless_else.rb