Skip to content

Commit

Permalink
[Fix rubocop#2722] ExtraSpacing doesn't align optarg equals with assi…
Browse files Browse the repository at this point in the history
…gnment equals
  • Loading branch information
alexdowad authored and Neodelf committed Oct 15, 2016
1 parent ef84c2d commit e050d7c
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

### Bug fixes

* [#2722](https://github.com/bbatsov/rubocop/issues/2722): `Style/ExtraSpacing` does not attempt to align an equals sign in an argument list with one in an assignment statement. ([@alexdowad][])
* [#3133](https://github.com/bbatsov/rubocop/issues/3133): `Style/MultilineMethodCallBraceLayout` does not register offenses for single-line calls. ([@alexdowad][])
* [#3170](https://github.com/bbatsov/rubocop/issues/3170): `Style/MutableConstant` does not infinite-loop when correcting an array with no brackets. ([@alexdowad][])
* [#3150](https://github.com/bbatsov/rubocop/issues/3150): Fix auto-correct for Style/MultilineArrayBraceLayout. ([@jspanjers][])
Expand Down
13 changes: 13 additions & 0 deletions lib/rubocop/cop/style/extra_spacing.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,15 @@ class ExtraSpacing < Cop
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 }
Expand Down Expand Up @@ -205,6 +212,12 @@ def align_column(asgn_token)
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
Expand Down
8 changes: 8 additions & 0 deletions spec/rubocop/cop/style/extra_spacing_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -329,5 +329,13 @@
'a.attribute_name = 2',
'abc[1] = 3'].join("\n"))
end

it 'does not register an offense when optarg equals is not aligned with ' \
'assignment equals sign' do
inspect_source(cop, ['def method(arg = 1)',
' var = arg',
'end'])
expect(cop.offenses).to be_empty
end
end
end

0 comments on commit e050d7c

Please sign in to comment.