Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Style::HashTransformValues - incorrect autocorrection when wrapped in a block #10171

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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