Sha256: 0868c6330352951516a9002448da3f1ebe707e51cf1286b89d9e1b11ae0245c8

Contents?: true

Size: 1.32 KB

Versions: 11

Compression:

Stored size: 1.32 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # This cop looks for *unless* expressions with *else* clauses.
      class UnlessElse < Cop
        MSG = 'Do not use `unless` with `else`. Rewrite these with the ' \
              'positive case first.'.freeze

        def on_if(node)
          loc = node.loc

          # discard ternary ops and modifier if/unless nodes
          return unless loc.respond_to?(:keyword) && loc.respond_to?(:else)
          return unless loc.keyword.is?('unless'.freeze) && loc.else

          add_offense(node, :expression)
        end

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

          lambda do |corrector|
            corrector.replace(node.loc.keyword, 'if'.freeze)
            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

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/unless_else.rb
dirwatch-0.0.8 vendor/bundle/ruby/2.5.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/unless_else.rb
dirwatch-0.0.6 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/unless_else.rb
dirwatch-0.0.5 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/unless_else.rb
dirwatch-0.0.4 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/unless_else.rb
dirwatch-0.0.3 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/unless_else.rb
dirwatch-0.0.2 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/unless_else.rb
rubocop-0.46.0 lib/rubocop/cop/style/unless_else.rb
rubocop-0.45.0 lib/rubocop/cop/style/unless_else.rb
rubocop-0.44.1 lib/rubocop/cop/style/unless_else.rb
rubocop-0.44.0 lib/rubocop/cop/style/unless_else.rb