Skip to content

Commit

Permalink
[Fix rubocop#5534] remove empty line after Style/EachWithObject aut…
Browse files Browse the repository at this point in the history
…ocorrect
  • Loading branch information
flyerhzm committed Mar 2, 2018
1 parent 6c3ea47 commit e06f2ec
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -66,6 +66,7 @@
* [#5603](https://github.com/bbatsov/rubocop/pull/5603): Fix falsy offense for `Style/RedundantSelf` with pseudo variables. ([@pocke][])
* [#5547](https://github.com/bbatsov/rubocop/issues/5547): Fix auto-correction of of `Layout/BlockEndNewline` when there is top level code outside of a class. ([@rrosenblum][])
* [#5599](https://github.com/bbatsov/rubocop/issues/5599): Fix the suggestion being used by `Lint/NumberConversion` to use base 10 with Integer. ([@rrosenblum][])
* [#5534](https://github.com/bbatsov/rubocop/issues/5534): Fix `Style/EachWithObject` auto-correction leaves an empty line. ([@flyerhzm][])

### Changes

Expand Down
16 changes: 15 additions & 1 deletion lib/rubocop/cop/style/each_with_object.rb
Expand Up @@ -17,6 +17,8 @@ module Style
# # good
# [1, 2].each_with_object({}) { |e, a| a[e] = e }
class EachWithObject < Cop
include RangeHelp

MSG = 'Use `each_with_object` instead of `%<method>s`.'.freeze
METHODS = %i[inject reduce].freeze

Expand Down Expand Up @@ -51,7 +53,11 @@ def autocorrect(node)

return_value = return_value(node.body)

corrector.remove(return_value.loc.expression)
if return_value_occupies_whole_line?(return_value)
corrector.remove(whole_line_expression(return_value))
else
corrector.remove(return_value.loc.expression)
end
end
end
# rubocop:enable Metrics/AbcSize
Expand Down Expand Up @@ -90,6 +96,14 @@ def first_argument_returned?(args, return_value)

accumulator_var == return_var
end

def return_value_occupies_whole_line?(node)
whole_line_expression(node).source.strip == node.source
end

def whole_line_expression(node)
range_by_whole_lines(node.loc.expression, include_final_newline: true)
end
end
end
end
Expand Down
2 changes: 0 additions & 2 deletions spec/rubocop/cop/style/each_with_object_spec.rb
Expand Up @@ -27,7 +27,6 @@

expect(corrected).to eq(['[1, 2, 3].each_with_object({}) do |i, h|',
' h[i] = i',
' ',
'end',
''].join("\n"))
end
Expand All @@ -40,7 +39,6 @@
RUBY

expect(corrected).to eq(['[1, 2, 3].each_with_object({}) do |i, h|',
' ',
'end',
''].join("\n"))
end
Expand Down

0 comments on commit e06f2ec

Please sign in to comment.