diff --git a/CHANGELOG.md b/CHANGELOG.md index 867b78a7b426..c743d428fd9b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,7 @@ * [#3039](https://github.com/bbatsov/rubocop/issues/3039): Accept `match` without a receiver in `Performance/EndWith`. ([@lumeet][]) * [#3039](https://github.com/bbatsov/rubocop/issues/3039): Accept `match` without a receiver in `Performance/StartWith`. ([@lumeet][]) * [#3048](https://github.com/bbatsov/rubocop/issues/3048): `Lint/NestedMethodDefinition` shouldn't flag methods defined on Structs. ([@owst][]) +* [#2912](https://github.com/bbatsov/rubocop/issues/2912): Check whether a line is aligned with the following line if the preceding line is not an assignment. ([@akihiro17][]) ### Changes @@ -2126,3 +2127,4 @@ [@bolshakov]: https://github.com/bolshakov [@jastkand]: https://github.com/jastkand [@graemeboy]: https://github.com/graemeboy +[@akihiro17]: https://github.com/akihiro17 diff --git a/lib/rubocop/cop/style/extra_spacing.rb b/lib/rubocop/cop/style/extra_spacing.rb index 2ca29cd0d5ad..5c26b477bb07 100644 --- a/lib/rubocop/cop/style/extra_spacing.rb +++ b/lib/rubocop/cop/style/extra_spacing.rb @@ -67,16 +67,31 @@ def check_tokens(ast, t1, t2) end def check_assignment(token) - # minus 2 is because pos.line is zero-based - line = processed_source.lines[token.pos.line - 2] - return if aligned_assignment?(token.pos, line) - - preceding = @asgn_lines.include?(token.pos.line - 1) - align_with = preceding ? 'preceding' : 'following' - message = format(MSG_UNALIGNED_ASGN, align_with) + assignment_line = '' + message = '' + if should_aligned_with_preceding_line?(token) + assignment_line = preceding_line(token) + message = format(MSG_UNALIGNED_ASGN, 'preceding') + else + assignment_line = following_line(token) + message = format(MSG_UNALIGNED_ASGN, 'following') + end + return if aligned_assignment?(token.pos, assignment_line) add_offense(token.pos, token.pos, message) end + def should_aligned_with_preceding_line?(token) + @asgn_lines.include?(token.pos.line - 1) + end + + def preceding_line(token) + processed_source.lines[token.pos.line - 2] + end + + def following_line(token) + 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 diff --git a/spec/rubocop/cop/style/extra_spacing_spec.rb b/spec/rubocop/cop/style/extra_spacing_spec.rb index e33667674d97..00603f9db3a3 100644 --- a/spec/rubocop/cop/style/extra_spacing_spec.rb +++ b/spec/rubocop/cop/style/extra_spacing_spec.rb @@ -253,6 +253,13 @@ expect(cop.offenses.size).to eq(0) end + it 'aligns the first assignment with the following assingment' do + inspect_source(cop, ['# comment', + 'a = 1', + 'bb = 2']) + expect(cop.offenses.size).to eq(0) + end + it 'autocorrects consecutive assignments which are not aligned' do new_source = autocorrect_source(cop, ['a = 1', 'bb = 2',