Skip to content

Commit 88b9dc5

Browse files
authored
Merge pull request #1406 from eugeneius/index_by_index_with_enclosing_block
Fix autocorrection for `Rails/IndexBy` and `Rails/IndexWith` when `map { ... }.to_h` is enclosed in another block
2 parents 7edc744 + ece1454 commit 88b9dc5

File tree

4 files changed

+46
-3
lines changed

4 files changed

+46
-3
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#1406](https://github.com/rubocop/rubocop-rails/pull/1406): Fix autocorrection for `Rails/IndexBy` and `Rails/IndexWith` when `map { ... }.to_h` is enclosed in another block. ([@franzliedke][], [@eugeneius][])

lib/rubocop/cop/mixin/index_method.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -124,9 +124,9 @@ def self.from_to_h(node, match)
124124
end
125125

126126
def self.from_map_to_h(node, match)
127-
strip_trailing_chars = 0
128-
129-
unless node.parent&.block_type?
127+
if node.block_literal?
128+
strip_trailing_chars = 0
129+
else
130130
map_range = node.children.first.source_range
131131
node_range = node.source_range
132132
strip_trailing_chars = node_range.end_pos - map_range.end_pos

spec/rubocop/cop/rails/index_by_spec.rb

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,27 @@
134134
end
135135
end
136136

137+
context 'when enclosed in another block' do
138+
it 'registers an offense for `map { ... }.to_h`' do
139+
expect_offense(<<~RUBY)
140+
wrapping do
141+
x.map do |el|
142+
^^^^^^^^^^^^^ Prefer `index_by` over `map { ... }.to_h`.
143+
[el.to_sym, el]
144+
end.to_h
145+
end
146+
RUBY
147+
148+
expect_correction(<<~RUBY)
149+
wrapping do
150+
x.index_by do |el|
151+
el.to_sym
152+
end
153+
end
154+
RUBY
155+
end
156+
end
157+
137158
it 'registers an offense for `Hash[map { ... }]`' do
138159
expect_offense(<<~RUBY)
139160
Hash[x.map { |el| [el.to_sym, el] }]

spec/rubocop/cop/rails/index_with_spec.rb

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,27 @@
133133
end
134134
end
135135

136+
context 'when enclosed in another block' do
137+
it 'registers an offense for `map { ... }.to_h`' do
138+
expect_offense(<<~RUBY)
139+
wrapping do
140+
x.map do |el|
141+
^^^^^^^^^^^^^ Prefer `index_with` over `map { ... }.to_h`.
142+
[el, el.to_sym]
143+
end.to_h
144+
end
145+
RUBY
146+
147+
expect_correction(<<~RUBY)
148+
wrapping do
149+
x.index_with do |el|
150+
el.to_sym
151+
end
152+
end
153+
RUBY
154+
end
155+
end
156+
136157
it 'registers an offense for `Hash[map { ... }]`' do
137158
expect_offense(<<~RUBY)
138159
Hash[x.map { |el| [el, el.to_sym] }]

0 commit comments

Comments
 (0)