Sha256: f5304fa31a30945a0593a19c8aed2bf52038f543803210b7d698c7fc3f3ff70f

Contents?: true

Size: 1.52 KB

Versions: 3

Compression:

Stored size: 1.52 KB

Contents

# encoding: utf-8

module Rubocop
  module Cop
    module Style
      # This cop checks for the presence of superfluous parentheses around the
      # condition of if/unless/while/until.
      class ParenthesesAroundCondition < Cop
        include IfNode
        include SafeAssignment

        def on_if(node)
          return if ternary_op?(node)
          process_control_op(node)
        end

        def on_while(node)
          process_control_op(node)
        end

        def on_until(node)
          process_control_op(node)
        end

        private

        def process_control_op(node)
          cond, _body = *node

          if cond.type == :begin
            return if parens_required?(node)
            # allow safe assignment
            return if safe_assignment?(cond) && safe_assignment_allowed?

            add_offense(cond, :expression, message(node))
          end
        end

        def parens_required?(node)
          exp = node.loc.expression
          kw = node.loc.keyword
          kw_offset = kw.begin_pos - exp.begin_pos

          exp.source[kw_offset..-1].start_with?(kw.source + '(')
        end

        def message(node)
          kw = node.loc.keyword.source
          article = kw == 'while' ? 'a' : 'an'
          "Don't use parentheses around the condition of #{article} `#{kw}`."
        end

        def autocorrect(node)
          @corrections << lambda do |corrector|
            corrector.remove(node.loc.begin)
            corrector.remove(node.loc.end)
          end
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
rubocop-0.21.0 lib/rubocop/cop/style/parentheses_around_condition.rb
rubocop-0.20.1 lib/rubocop/cop/style/parentheses_around_condition.rb
rubocop-0.20.0 lib/rubocop/cop/style/parentheses_around_condition.rb