Skip to content

Commit 6a05c6f

Browse files
committed
Fix autocorrection for Rails/IndexWith when the value is a hash literal without braces
1 parent 1126163 commit 6a05c6f

File tree

3 files changed

+31
-1
lines changed

3 files changed

+31
-1
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#1405](https://github.com/rubocop/rubocop-rails/pull/1405): Fix autocorrection for `Rails/IndexWith` when the value is a hash literal without braces. ([@koic][], [@eugeneius][])

lib/rubocop/cop/mixin/index_method.rb

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,10 @@ def set_new_arg_name(transformed_argname, corrector)
161161
end
162162

163163
def set_new_body_expression(transforming_body_expr, corrector)
164-
corrector.replace(block_node.body, transforming_body_expr.source)
164+
body_source = transforming_body_expr.source
165+
body_source = "{ #{body_source} }" if transforming_body_expr.hash_type? && !transforming_body_expr.braces?
166+
167+
corrector.replace(block_node.body, body_source)
165168
end
166169
end
167170
end

spec/rubocop/cop/rails/index_with_spec.rb

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,32 @@
101101
end
102102
end
103103

104+
context 'when the value is a hash literal with braces' do
105+
it 'registers an offense for `to_h { ... }`' do
106+
expect_offense(<<~RUBY)
107+
x.map { |el| [el, { value: el }] }.to_h
108+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `index_with` over `map { ... }.to_h`.
109+
RUBY
110+
111+
expect_correction(<<~RUBY)
112+
x.index_with { |el| { value: el } }
113+
RUBY
114+
end
115+
end
116+
117+
context 'when the value is a hash literal without braces' do
118+
it 'registers an offense for `to_h { ... }`' do
119+
expect_offense(<<~RUBY)
120+
x.map { |el| [el, value: el] }.to_h
121+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `index_with` over `map { ... }.to_h`.
122+
RUBY
123+
124+
expect_correction(<<~RUBY)
125+
x.index_with { |el| { value: el } }
126+
RUBY
127+
end
128+
end
129+
104130
context 'when to_h is not called on the result' do
105131
it 'does not register an offense for `map { ... }.to_h`' do
106132
expect_no_offenses('x.map { |el| [el, el.to_sym] }')

0 commit comments

Comments
 (0)