Sha256: ede507c1d415e2b6a2fb83025c4145aca8220b53fd5225a03afba1ac591aeb24

Contents?: true

Size: 1.38 KB

Versions: 31

Compression:

Stored size: 1.38 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

31 entries across 31 versions & 6 rubygems

Version Path
scrapbook-0.3.2 vendor/ruby/2.7.0/gems/rubocop-1.26.0/lib/rubocop/cop/style/unless_else.rb
scrapbook-0.3.1 vendor/ruby/2.7.0/gems/rubocop-1.26.0/lib/rubocop/cop/style/unless_else.rb
op_connect-0.1.2 vendor/bundle/ruby/3.1.0/gems/rubocop-1.26.0/lib/rubocop/cop/style/unless_else.rb
rubocop-1.26.0 lib/rubocop/cop/style/unless_else.rb
rubocop-1.25.1 lib/rubocop/cop/style/unless_else.rb
rubocop-1.25.0 lib/rubocop/cop/style/unless_else.rb
phillipug-foodie-0.1.0 .vendor/ruby/3.0.0/gems/rubocop-1.24.0/lib/rubocop/cop/style/unless_else.rb
rubocop-1.24.1 lib/rubocop/cop/style/unless_else.rb
rubocop-1.24.0 lib/rubocop/cop/style/unless_else.rb
rubocop-1.23.0 lib/rubocop/cop/style/unless_else.rb
rubocop-1.22.3 lib/rubocop/cop/style/unless_else.rb
rubocop-1.22.2 lib/rubocop/cop/style/unless_else.rb
rubocop-1.22.1 lib/rubocop/cop/style/unless_else.rb
rubocop-1.22.0 lib/rubocop/cop/style/unless_else.rb
rubocop-1.21.0 lib/rubocop/cop/style/unless_else.rb
rubocop-1.20.0 lib/rubocop/cop/style/unless_else.rb
rubocop-1.19.1 lib/rubocop/cop/style/unless_else.rb
rails_mini_profiler-0.2.0 vendor/bundle/ruby/3.0.0/gems/rubocop-1.18.3/lib/rubocop/cop/style/unless_else.rb
rubocop-1.19.0 lib/rubocop/cop/style/unless_else.rb
rubocop-1.18.4 lib/rubocop/cop/style/unless_else.rb