Skip to content

Commit 3d7228e

Browse files
authored
Merge pull request #867 from r7kamura/feature/index-method
Fix autocorrection bug when `::Hash` is used on `Rails/IndexBy` and `Rails/IndexWith`
2 parents 24b2e87 + 53bf6ab commit 3d7228e

File tree

4 files changed

+24
-1
lines changed

4 files changed

+24
-1
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#867](https://github.com/rubocop/rubocop-rails/pull/867): Fix autocorrection bug when `::Hash` is used on `Rails/IndexBy` and `Rails/IndexWith`. ([@r7kamura][])

lib/rubocop/cop/mixin/index_method.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ def self.from_map_to_h(node, match)
134134
end
135135

136136
def self.from_hash_brackets_map(node, match)
137-
new(match, node.children.last, 'Hash['.length, ']'.length)
137+
new(match, node.children.last, "#{node.receiver.source}[".length, ']'.length)
138138
end
139139

140140
def strip_prefix_and_suffix(node, corrector)

spec/rubocop/cop/rails/index_by_spec.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,17 @@
145145
RUBY
146146
end
147147

148+
it 'registers an offense for `::Hash[map { ... }]`' do
149+
expect_offense(<<~RUBY)
150+
::Hash[x.map { |el| [el.to_sym, el] }]
151+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `index_by` over `Hash[map { ... }]`.
152+
RUBY
153+
154+
expect_correction(<<~RUBY)
155+
x.index_by { |el| el.to_sym }
156+
RUBY
157+
end
158+
148159
context 'when using Ruby 2.6 or newer', :ruby26 do
149160
it 'registers an offense for `to_h { ... }`' do
150161
expect_offense(<<~RUBY)

spec/rubocop/cop/rails/index_with_spec.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,17 @@
118118
RUBY
119119
end
120120

121+
it 'registers an offense for `::Hash[map { ... }]`' do
122+
expect_offense(<<~RUBY)
123+
::Hash[x.map { |el| [el, el.to_sym] }]
124+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `index_with` over `Hash[map { ... }]`.
125+
RUBY
126+
127+
expect_correction(<<~RUBY)
128+
x.index_with { |el| el.to_sym }
129+
RUBY
130+
end
131+
121132
context 'when using Ruby 2.6 or newer', :ruby26 do
122133
it 'registers an offense for `to_h { ... }`' do
123134
expect_offense(<<~RUBY)

0 commit comments

Comments
 (0)