From 482779255b43a01646a58569935fc2273b2f55f2 Mon Sep 17 00:00:00 2001 From: Earlopain <14981592+Earlopain@users.noreply.github.com> Date: Mon, 12 Aug 2024 13:32:52 +0200 Subject: [PATCH] Fix wrong autocorrect for `Rails/FilePath` when passing an array to `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 ``` --- ...x_wrong_autocorrect_for_rails_file_path.md | 1 + lib/rubocop/cop/rails/file_path.rb | 2 +- spec/rubocop/cop/rails/file_path_spec.rb | 20 +++++++++++++++++++ 3 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 changelog/fix_wrong_autocorrect_for_rails_file_path.md diff --git a/changelog/fix_wrong_autocorrect_for_rails_file_path.md b/changelog/fix_wrong_autocorrect_for_rails_file_path.md new file mode 100644 index 0000000000..10b2da3ae5 --- /dev/null +++ b/changelog/fix_wrong_autocorrect_for_rails_file_path.md @@ -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][]) diff --git a/lib/rubocop/cop/rails/file_path.rb b/lib/rubocop/cop/rails/file_path.rb index f98f37076f..02459031a9 100644 --- a/lib/rubocop/cop/rails/file_path.rb +++ b/lib/rubocop/cop/rails/file_path.rb @@ -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 diff --git a/spec/rubocop/cop/rails/file_path_spec.rb b/spec/rubocop/cop/rails/file_path_spec.rb index 1993e66ba4..3bec9ded2c 100644 --- a/spec/rubocop/cop/rails/file_path_spec.rb +++ b/spec/rubocop/cop/rails/file_path_spec.rb @@ -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')")