Skip to content

Commit

Permalink
Fix an incorrect autocorrect for Rails/FilePath when File.join with…
Browse files Browse the repository at this point in the history
… Rails.root and path starting with `/`
  • Loading branch information
ydah committed Jul 20, 2023
1 parent b040d84 commit 3b60cb8
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#1049](https://github.com/rubocop/rubocop-rails/pull/1049): Fix an incorrect autocorrect for `Rails/FilePath` when File.join with Rails.root and path starting with `/`. ([@ydah][])
3 changes: 3 additions & 0 deletions lib/rubocop/cop/rails/file_path.rb
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,9 @@ def autocorrect_file_join(corrector, node)
side: :right
)
)
node.arguments.filter(&:str_type?).each do |argument|
corrector.replace(argument, argument.value.delete_prefix('/').inspect)
end
corrector.insert_after(node, '.to_s')
end

Expand Down
28 changes: 27 additions & 1 deletion spec/rubocop/cop/rails/file_path_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,19 @@
end
end

context 'when using File.join with Rails.root and path starting with `/`' do
it 'registers an offense' do
expect_offense(<<~RUBY)
File.join(Rails.root, '/app/models', '/user.rb')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `Rails.root.join('path/to').to_s`.
RUBY

expect_correction(<<~RUBY)
Rails.root.join("app/models/user.rb").to_s
RUBY
end
end

context 'when using ::Rails.root.join with some path strings' do
it 'registers an offense' do
expect_offense(<<~RUBY)
Expand Down Expand Up @@ -246,7 +259,20 @@
RUBY

expect_correction(<<~RUBY)
Rails.root.join('app', 'models').to_s
Rails.root.join("app", "models").to_s
RUBY
end
end

context 'when using File.join with Rails.root and path starting with `/`' do
it 'registers an offense' do
expect_offense(<<~RUBY)
File.join(Rails.root, '/app/models', '/user.rb')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `Rails.root.join('path', 'to').to_s`.
RUBY

expect_correction(<<~RUBY)
Rails.root.join("app", "models", "user.rb").to_s
RUBY
end
end
Expand Down

0 comments on commit 3b60cb8

Please sign in to comment.