Skip to content

Commit ca58580

Browse files
authored
Merge pull request #1049 from ydah/fix-rails-file-path-autocorrect
Fix an incorrect autocorrect for `Rails/FilePath` when File.join with Rails.root and path starting with `/`
2 parents d81af27 + 3b60cb8 commit ca58580

File tree

3 files changed

+31
-1
lines changed

3 files changed

+31
-1
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
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][])

lib/rubocop/cop/rails/file_path.rb

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,9 @@ def autocorrect_file_join(corrector, node)
180180
side: :right
181181
)
182182
)
183+
node.arguments.filter(&:str_type?).each do |argument|
184+
corrector.replace(argument, argument.value.delete_prefix('/').inspect)
185+
end
183186
corrector.insert_after(node, '.to_s')
184187
end
185188

spec/rubocop/cop/rails/file_path_spec.rb

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,19 @@
1717
end
1818
end
1919

20+
context 'when using File.join with Rails.root and path starting with `/`' do
21+
it 'registers an offense' do
22+
expect_offense(<<~RUBY)
23+
File.join(Rails.root, '/app/models', '/user.rb')
24+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `Rails.root.join('path/to').to_s`.
25+
RUBY
26+
27+
expect_correction(<<~RUBY)
28+
Rails.root.join("app/models/user.rb").to_s
29+
RUBY
30+
end
31+
end
32+
2033
context 'when using ::Rails.root.join with some path strings' do
2134
it 'registers an offense' do
2235
expect_offense(<<~RUBY)
@@ -246,7 +259,20 @@
246259
RUBY
247260

248261
expect_correction(<<~RUBY)
249-
Rails.root.join('app', 'models').to_s
262+
Rails.root.join("app", "models").to_s
263+
RUBY
264+
end
265+
end
266+
267+
context 'when using File.join with Rails.root and path starting with `/`' do
268+
it 'registers an offense' do
269+
expect_offense(<<~RUBY)
270+
File.join(Rails.root, '/app/models', '/user.rb')
271+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `Rails.root.join('path', 'to').to_s`.
272+
RUBY
273+
274+
expect_correction(<<~RUBY)
275+
Rails.root.join("app", "models", "user.rb").to_s
250276
RUBY
251277
end
252278
end

0 commit comments

Comments
 (0)