Skip to content

Commit

Permalink
Fix wrong autocorrect for Rails/FilePath when passing an array to `…
Browse files Browse the repository at this point in the history
…File.join`

`File.join` actually accepts nested arrays and will unflatten them as necessary.

Don't bother implementing autocorrect for these cases, seems complicated
and not worth the effort.

The current correction for these testcases look like this:
```rb
Rails.root.join().to_s
```
  • Loading branch information
Earlopain committed Aug 12, 2024
1 parent b8c4126 commit 4827792
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
1 change: 1 addition & 0 deletions changelog/fix_wrong_autocorrect_for_rails_file_path.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#1326](https://github.com/rubocop/rubocop-rails/pull/1326): Fix wrong autocorrect for `Rails/FilePath` when passing an array to `File.join`. ([@earlopain][])
2 changes: 1 addition & 1 deletion lib/rubocop/cop/rails/file_path.rb
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def check_for_file_join_with_rails_root(node)
return unless node.arguments.any? { |e| rails_root_nodes?(e) }

register_offense(node, require_to_s: true) do |corrector|
autocorrect_file_join(corrector, node)
autocorrect_file_join(corrector, node) unless node.first_argument.array_type?
end
end

Expand Down
20 changes: 20 additions & 0 deletions spec/rubocop/cop/rails/file_path_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,26 @@
end
end

context 'when using File.join with an array' do
it 'registers an offense' do
expect_offense(<<~RUBY)
File.join([Rails.root, 'foo'])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `Rails.root.join('path/to').to_s`.
RUBY

expect_no_corrections
end

it 'registers an offense for nested arrays' do
expect_offense(<<~RUBY)
File.join([Rails.root, 'foo', ['bar']])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `Rails.root.join('path/to').to_s`.
RUBY

expect_no_corrections
end
end

context 'when using Rails.root.join with slash separated path string' do
it 'does not register an offense' do
expect_no_offenses("Rails.root.join('app/models/goober')")
Expand Down

0 comments on commit 4827792

Please sign in to comment.