Sha256: 3425c09445b6988f6bf99f64b827c756fdfc176f392128cc8526f7001c8f4cc3

Contents?: true

Size: 1.4 KB

Versions: 35

Compression:

Stored size: 1.4 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 < Base
        include RangeHelp
        extend AutoCorrector

        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) do |corrector|
            body_range = range_between_condition_and_else(node, node.condition)
            else_range = range_between_else_and_end(node)

            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

35 entries across 35 versions & 3 rubygems

Version Path
plaid-14.13.0 vendor/bundle/ruby/3.0.0/gems/rubocop-0.91.1/lib/rubocop/cop/style/unless_else.rb
plaid-14.12.1 vendor/bundle/ruby/3.0.0/gems/rubocop-0.91.1/lib/rubocop/cop/style/unless_else.rb
plaid-14.12.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/style/unless_else.rb
plaid-14.11.1 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/style/unless_else.rb
plaid-14.10.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/style/unless_else.rb
plaid-14.7.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/style/unless_else.rb
rubocop-1.12.1 lib/rubocop/cop/style/unless_else.rb
rubocop-1.12.0 lib/rubocop/cop/style/unless_else.rb
rubocop-1.11.0 lib/rubocop/cop/style/unless_else.rb
rubocop-1.10.0 lib/rubocop/cop/style/unless_else.rb
rubocop-1.9.1 lib/rubocop/cop/style/unless_else.rb
rubocop-1.9.0 lib/rubocop/cop/style/unless_else.rb
rubocop-1.8.1 lib/rubocop/cop/style/unless_else.rb
rubocop-1.8.0 lib/rubocop/cop/style/unless_else.rb
rubocop-1.7.0 lib/rubocop/cop/style/unless_else.rb
rubocop-1.6.1 lib/rubocop/cop/style/unless_else.rb
rubocop-1.6.0 lib/rubocop/cop/style/unless_else.rb
rubocop-1.5.2 lib/rubocop/cop/style/unless_else.rb
rubocop-1.5.1 lib/rubocop/cop/style/unless_else.rb
rubocop-1.5.0 lib/rubocop/cop/style/unless_else.rb