Skip to content

Commit

Permalink
[Fix rubocop#3750] Account for an assignment that spans multiple line…
Browse files Browse the repository at this point in the history
…s in ConditionalAssignment
  • Loading branch information
rrosenblum committed Dec 5, 2016
1 parent e37fa45 commit 04ef6f7
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 2 deletions.
2 changes: 1 addition & 1 deletion .rubocop_todo.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ Metrics/AbcSize:
# Offense count: 33
# Configuration parameters: CountComments.
Metrics/ClassLength:
Max: 173
Max: 176

# Offense count: 30
Metrics/CyclomaticComplexity:
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

* [#3751](https://github.com/bbatsov/rubocop/pull/3751): Avoid crash in `Rails/EnumUniqueness` cop. ([@pocke][])
* [#3766](https://github.com/bbatsov/rubocop/pull/3766): Avoid crash in `Style/ConditionalAssignment` cop with masgn. ([@pocke][])
* [#3750](https://github.com/bbatsov/rubocop/issues/3750): Register an offense in `Style/ConditionalAssignment` when the assignment spans multiple lines. ([@rrosenblum][])

## 0.46.0 (2016-11-30)

Expand Down
5 changes: 4 additions & 1 deletion lib/rubocop/cop/style/conditional_assignment.rb
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,10 @@ def longest_line(node, assignment)
end

def longest_rhs(branches)
branches.map { |branch| branch.children.last.source.length }.max
line_lengths = branches.flat_map do |branch|
branch.children.last.source.split("\n").map(&:length)
end
line_lengths.max
end

def line_length_cop_enabled?
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -588,6 +588,61 @@
expect(cop.messages).to eq([described_class::MSG])
end

it 'registers an offense for assignment in if else when the assignment ' \
'spans multiple lines' do
source = ['if foo',
' foo = {',
' a: 1,',
' b: 2,',
' c: 2,',
' d: 2,',
' e: 2,',
' f: 2,',
' g: 2,',
' h: 2',
' }',
'else',
' foo = { }',
'end']
inspect_source(cop, source)

expect(cop.messages).to eq([described_class::MSG])
end

it 'autocorrects assignment in if else when the assignment ' \
'spans multiple lines' do
source = ['if foo',
' foo = {',
' a: 1,',
' b: 2,',
' c: 2,',
' d: 2,',
' e: 2,',
' f: 2,',
' g: 2,',
' h: 2',
' }',
'else',
' foo = { }',
'end']
new_source = autocorrect_source(cop, source)

expect(new_source).to eq(['foo = if foo',
' {',
' a: 1,',
' b: 2,',
' c: 2,',
' d: 2,',
' e: 2,',
' f: 2,',
' g: 2,',
' h: 2',
' }',
'else',
' { }',
' end'].join("\n"))
end

context 'assignment as the last statement' do
it 'allows more than variable assignment in if else' do
source = ['if foo',
Expand Down

0 comments on commit 04ef6f7

Please sign in to comment.