Sha256: 9bb728c5ee3cb9655d5b7ef20bba312d1c3e4718d0741f7b072241333c2936a7

Contents?: true

Size: 1.63 KB

Versions: 2

Compression:

Stored size: 1.63 KB

Contents

# encoding: utf-8

module Rubocop
  module Cop
    module Lint
      # This cop checks for ambiguous operators in the first argument of a
      # method invocation without parentheses.
      #
      # @example
      #   array = [1, 2, 3]
      #
      #   # The `*` is interpreted as a splat operator but it could possibly be
      #   # a `*` method invocation (i.e. `do_something.*(array)`).
      #   do_something *array
      #
      #   # With parentheses, there's no ambiguity.
      #   do_something(*array)
      class AmbiguousOperator < Cop
        include ParserDiagnostic

        AMBIGUITIES = {
          '+'  => { actual: 'positive number', possible: 'addition' },
          '-'  => { actual: 'negative number', possible: 'subtraction' },
          '*'  => { actual: 'splat',           possible: 'multiplication' },
          '&'  => { actual: 'block',           possible: 'binary AND' },
          '**' => { actual: 'keyword splat',   possible: 'exponent' }
        }.each do |key, hash|
          hash[:operator] = key
        end

        MSG_FORMAT = 'Ambiguous %{actual} operator. Parenthesize the method ' \
                     "arguments if it's surely a %{actual} operator, or add " +
                     'a whitespace to the right of the %{operator} if it ' +
                     'should be a %{possible}.'

        private

        def relevant_diagnostic?(diagnostic)
          diagnostic.reason == :ambiguous_prefix
        end

        def alternative_message(diagnostic)
          operator = diagnostic.location.source
          hash = AMBIGUITIES[operator]
          format(MSG_FORMAT, hash)
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rubocop-0.18.1 lib/rubocop/cop/lint/ambiguous_operator.rb
rubocop-0.18.0 lib/rubocop/cop/lint/ambiguous_operator.rb