Sha256: 1718de85f3e75440238bdfa919d6a08854fdedb919abd3ea14683c3df3626378

Contents?: true

Size: 1.2 KB

Versions: 5

Compression:

Stored size: 1.2 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # Checks for if and unless statements used as modifiers of other if or
      # unless statements.
      #
      # @example
      #
      #  # bad
      #  tired? ? 'stop' : 'go faster' if running?
      #
      #  # bad
      #  if tired?
      #    "please stop"
      #  else
      #    "keep going"
      #  end if running?
      #
      #  # good
      #  if running?
      #    tired? ? 'stop' : 'go faster'
      #  end
      class IfUnlessModifierOfIfUnless < Cop
        include StatementModifier

        MSG = 'Avoid modifier `%<keyword>s` after another conditional.'

        def on_if(node)
          return unless node.modifier_form? && node.body.if_type?

          add_offense(node, location: :keyword,
                            message: format(MSG, keyword: node.keyword))
        end

        def autocorrect(node)
          lambda do |corrector|
            keyword = node.if? ? 'if' : 'unless'

            corrector.replace(node, <<~RUBY.chop)
              #{keyword} #{node.condition.source}
              #{node.if_branch.source}
              end
            RUBY
          end
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 2 rubygems

Version Path
rubocop-0.89.0 lib/rubocop/cop/style/if_unless_modifier_of_if_unless.rb
rubocop-0.88.0 lib/rubocop/cop/style/if_unless_modifier_of_if_unless.rb
rbhint-0.87.1.rc1 lib/rubocop/cop/style/if_unless_modifier_of_if_unless.rb
rubocop-0.87.1 lib/rubocop/cop/style/if_unless_modifier_of_if_unless.rb
rubocop-0.87.0 lib/rubocop/cop/style/if_unless_modifier_of_if_unless.rb