lib/rubocop/cop/style/extra_spacing.rb in rubocop-0.40.0 vs lib/rubocop/cop/style/extra_spacing.rb in rubocop-0.41.0

- old
+ new

@@ -25,12 +25,19 @@ MSG_UNNECESSARY = 'Unnecessary spacing detected.'.freeze MSG_UNALIGNED_ASGN = '`=` is not aligned with the %s assignment.'.freeze def investigate(processed_source) + return if processed_source.ast.nil? + if force_equal_sign_alignment? @asgn_tokens = processed_source.tokens.select { |t| equal_sign?(t) } + # we don't want to operate on equals signs which are part of an + # optarg in a method definition + # e.g.: def method(optarg = default_val); end + @asgn_tokens = remove_optarg_equals(@asgn_tokens, processed_source) + # Only attempt to align the first = on each line @asgn_tokens = Set.new(@asgn_tokens.uniq { |t| t.pos.line }) @asgn_lines = @asgn_tokens.map { |t| t.pos.line } # Don't attempt to correct the same = more than once @corrected = Set.new @@ -92,17 +99,17 @@ processed_source.lines[token.pos.line] end def check_other(t1, t2, ast) return if t1.pos.line != t2.pos.line - return if t2.pos.begin_pos - 1 <= t1.pos.end_pos return if allow_for_alignment? && aligned_tok?(t2) start_pos = t1.pos.end_pos - return if ignored_ranges(ast).find { |r| r.include?(start_pos) } - end_pos = t2.pos.begin_pos - 1 + return if end_pos <= start_pos + return if ignored_range?(ast, start_pos) + range = Parser::Source::Range.new(processed_source.buffer, start_pos, end_pos) # Unary + doesn't appear as a token and needs special handling. return if unary_plus_non_offense?(range) @@ -115,10 +122,14 @@ else aligned_with_something?(token.pos) end end + def ignored_range?(ast, start_pos) + ignored_ranges(ast).any? { |r| r.include?(start_pos) } + end + def unary_plus_non_offense?(range) range.resize(range.size + 1).source =~ /^ ?\+$/ end # Returns an array of ranges that should not be reported. It's the @@ -198,9 +209,15 @@ # what column would it end from? line = processed_source.lines[asgn_token.pos.line - 1] leading = line[0...asgn_token.pos.column] spaces = leading.size - (leading =~ / *\Z/) asgn_token.pos.last_column - spaces + 1 + end + + def remove_optarg_equals(asgn_tokens, processed_source) + optargs = processed_source.ast.each_node(:optarg) + optarg_eql = optargs.map { |o| o.loc.operator.begin_pos }.to_set + asgn_tokens.reject { |t| optarg_eql.include?(t.pos.begin_pos) } end end end end end