Skip to content

Commit

Permalink
Style/HashTransform*: Fix incorrect auto-correction when inside block…
Browse files Browse the repository at this point in the history
… body

The special case was checking for a block *being passed to* our
matched `node` (i.e. the `to_h` call), without excluding the case
of the `node` being *wrapped by* a block.
  • Loading branch information
franzliedke committed Oct 7, 2021
1 parent 29d104e commit 4c5f485
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 3 deletions.
3 changes: 3 additions & 0 deletions changelog/fix_stylehashtransform_fix_incorrect.md
@@ -0,0 +1,3 @@
* [#10171](https://github.com/rubocop/rubocop/pull/10171): Fix `Style/HashTransformKeys` and `Style/HashTransformValues` incorrect auto-correction when inside block body. ([@franzliedke][])

[@franzliedke]: https://github.com/franzliedke
6 changes: 3 additions & 3 deletions lib/rubocop/cop/mixin/hash_transform_method.rb
Expand Up @@ -139,9 +139,9 @@ def self.from_hash_brackets_map(node, match)
end

def self.from_map_to_h(node, match)
strip_trailing_chars = 0

unless node.parent&.block_type?
if node.parent&.block_type? && node.parent.send_node == node
strip_trailing_chars = 0
else
map_range = node.children.first.source_range
node_range = node.source_range
strip_trailing_chars = node_range.end_pos - map_range.end_pos
Expand Down
19 changes: 19 additions & 0 deletions spec/rubocop/cop/style/hash_transform_keys_spec.rb
Expand Up @@ -117,6 +117,25 @@
RUBY
end

it 'flags _.map {...}.to_h when transform_keys could be used when wrapped in another block' do
expect_offense(<<~RUBY)
wrapping do
x.map do |k, v|
^^^^^^^^^^^^^^^ Prefer `transform_keys` over `map {...}.to_h`.
[k.to_sym, v]
end.to_h
end
RUBY

expect_correction(<<~RUBY)
wrapping do
x.transform_keys do |k|
k.to_sym
end
end
RUBY
end

it 'does not flag _.map{...}.to_h when both key & value are transformed' do
expect_no_offenses('x.map {|k, v| [k.to_sym, foo(v)]}.to_h')
end
Expand Down
19 changes: 19 additions & 0 deletions spec/rubocop/cop/style/hash_transform_values_spec.rb
Expand Up @@ -117,6 +117,25 @@
RUBY
end

it 'flags _.map {...}.to_h when transform_values could be used when wrapped in another block' do
expect_offense(<<~RUBY)
wrapping do
x.map do |k, v|
^^^^^^^^^^^^^^^ Prefer `transform_values` over `map {...}.to_h`.
[k, v.to_s]
end.to_h
end
RUBY

expect_correction(<<~RUBY)
wrapping do
x.transform_values do |v|
v.to_s
end
end
RUBY
end

it 'does not flag _.map{...}.to_h when both key & value are transformed' do
expect_no_offenses('x.map {|k, v| [k.to_sym, foo(v)]}.to_h')
end
Expand Down

0 comments on commit 4c5f485

Please sign in to comment.