Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes Rails/IndexBy correction when .to_h is separated by a newline #239

Merged
merged 1 commit into from Apr 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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