Skip to content

Commit

Permalink
[Fix #4418] Fix the check for the longest line when the longest line …
Browse files Browse the repository at this point in the history
…is the assignment
  • Loading branch information
rrosenblum authored and bbatsov committed Jun 7, 2017
1 parent e052e2b commit c800339
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 19 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -14,6 +14,7 @@
* [#4434](https://github.com/bbatsov/rubocop/issues/4434): Prevent bad auto-correct in `Style/Alias` for non-literal arguments. ([@drenmi][])
* [#4451](https://github.com/bbatsov/rubocop/issues/4451): Make `Style/AndOr` cop aware of comparison methods. ([@drenmi][])
* [#4457](https://github.com/bbatsov/rubocop/pull/4457): Fix false negative in `Lint/Void` with initialize and setter methods. ([@pocke][])
* [#4418](https://github.com/bbatsov/rubocop/issues/4418): Register an offense in `Style/ConditionalAssignment` when the assignment line is the longest line, and it does not exceed the max line length. ([@rrosenblum][])

### Changes

Expand Down
22 changes: 3 additions & 19 deletions lib/rubocop/cop/style/conditional_assignment.rb
Expand Up @@ -380,36 +380,20 @@ def correction_exceeds_line_limit?(node, branches)

assignment = lhs(tail(branches[0]))

longest_rhs_exceeds_line_limit?(branches, assignment) ||
longest_line_exceeds_line_limit?(node, assignment)
end

def longest_rhs_exceeds_line_limit?(branches, assignment)
longest_rhs_full_length(branches, assignment) > max_line_length
longest_line_exceeds_line_limit?(node, assignment)
end

def longest_line_exceeds_line_limit?(node, assignment)
longest_line(node, assignment).length > max_line_length
end

def longest_rhs_full_length(branches, assignment)
longest_rhs(branches) + indentation_width + assignment.length
end

def longest_line(node, assignment)
assignment_regex = /#{Regexp.escape(assignment).gsub(' ', '\s*')}/
assignment_regex = /\s*#{Regexp.escape(assignment).gsub('\ ', '\s*')}/
lines = node.source.lines.map do |line|
line.chomp.sub(assignment_regex, '')
end
longest_line = lines.max_by(&:length)
longest_line + assignment
end

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

def line_length_cop_enabled?
Expand Down
Expand Up @@ -344,6 +344,21 @@
RUBY
end

it 'registers an offense in an if else if the assignment is already ' \
'at the line length limit' do
source = <<-RUBY.strip_indent
if foo
bar = #{'a' * 72}
else
bar = #{'b' * 72}
end
RUBY

inspect_source(cop, source)

expect(cop.messages).to eq([message])
end

context 'correction would exceed max line length' do
it 'allows assignment to the same variable in if else if the correction ' \
'would create a line longer than the configured LineLength' do
Expand Down

0 comments on commit c800339

Please sign in to comment.