Skip to content

Commit

Permalink
Merge pull request #239 from diogoosorio/index-by-multiple-lines
Browse files Browse the repository at this point in the history
Fixes Rails/IndexBy correction when .to_h is separated by a newline
  • Loading branch information
koic committed Apr 23, 2020
2 parents c36151c + 8307c6a commit 7e05a1f
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 1 deletion.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Expand Up @@ -9,6 +9,7 @@
### Bug fixes

* [#12](https://github.com/rubocop-hq/rubocop-rails/issues/12): Fix a false positive for `Rails/SkipsModelValidations` when passing a boolean literal to `touch`. ([@eugeneius][])
* [#238](https://github.com/rubocop-hq/rubocop-rails/issues/238): Fix auto correction for `Rails/IndexBy` when the `.to_h` invocation is separated in multiple lines. ([@diogoosorio][])

### Changes

Expand Down Expand Up @@ -183,3 +184,4 @@
[@sunny]: https://github.com/sunny
[@hoshinotsuyoshi]: https://github.com/hoshinotsuyoshi
[@tejasbubane]: https://github.com/tejasbubane
[@diogoosorio]: https://github.com/diogoosorio
9 changes: 8 additions & 1 deletion lib/rubocop/cop/mixin/index_method.rb
Expand Up @@ -112,7 +112,14 @@ def self.from_each_with_object(node, match)
end

def self.from_map_to_h(node, match)
strip_trailing_chars = node.parent&.block_type? ? 0 : '.to_h'.length
strip_trailing_chars = 0

unless node.parent&.block_type?
map_range = node.children.first.source_range
node_range = node.source_range
strip_trailing_chars = node_range.end_pos - map_range.end_pos
end

new(match, node.children.first, 0, strip_trailing_chars)
end

Expand Down
28 changes: 28 additions & 0 deletions spec/rubocop/cop/rails/index_by_spec.rb
Expand Up @@ -94,6 +94,34 @@
end
end

context 'when `to_h` is on a different line' do
it 'registers an offense for `map { ... }.to_h`' do
expect_offense(<<~RUBY)
x.map { |el| [el.to_sym, el] }.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `index_by` over `map { ... }.to_h`.
to_h
RUBY

expect_correction(<<~RUBY)
x.index_by { |el| el.to_sym }
RUBY
end
end

context 'when `.to_h` is on a different line' do
it 'registers an offense for `map { ... }.to_h`' do
expect_offense(<<~RUBY)
x.map { |el| [el.to_sym, el] }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `index_by` over `map { ... }.to_h`.
.to_h
RUBY

expect_correction(<<~RUBY)
x.index_by { |el| el.to_sym }
RUBY
end
end

context 'when to_h is not called on the result' do
it 'does not register an offense for `map { ... }.to_h`' do
expect_no_offenses('x.map { |el| [el.to_sym, el] }')
Expand Down

0 comments on commit 7e05a1f

Please sign in to comment.