Skip to content

Commit ece1454

Browse files
committed
Fix autocorrection for Rails/IndexBy and Rails/IndexWith when map { ... }.to_h is enclosed in another block
1 parent 1126163 commit ece1454

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
@@ -107,6 +107,27 @@
107107
end
108108
end
109109

110+
context 'when enclosed in another block' do
111+
it 'registers an offense for `map { ... }.to_h`' do
112+
expect_offense(<<~RUBY)
113+
wrapping do
114+
x.map do |el|
115+
^^^^^^^^^^^^^ Prefer `index_with` over `map { ... }.to_h`.
116+
[el, el.to_sym]
117+
end.to_h
118+
end
119+
RUBY
120+
121+
expect_correction(<<~RUBY)
122+
wrapping do
123+
x.index_with do |el|
124+
el.to_sym
125+
end
126+
end
127+
RUBY
128+
end
129+
end
130+
110131
it 'registers an offense for `Hash[map { ... }]`' do
111132
expect_offense(<<~RUBY)
112133
Hash[x.map { |el| [el, el.to_sym] }]

0 commit comments

Comments
 (0)