Skip to content

Rails/FilePath autocorrect shouldn't remove important trailing slash in dynamic string containing Rails.root #1177

Open
@henrahmagix

Description

@henrahmagix

I'm trying to use Rails.root to remove it from an absolute filepath to result in a filepath relative to Rails.root.

my_abs_path              = "/Users/me/rails_app/config/locales/text_en.yml"
expected_relative_result = "config/locales/text_en.yml"

my_abs_path.delete_prefix("#{Rails.root}/") == expected_relative_result
# => true

Expected behavior

# this should be allowed by Rails/FilePath cop because the last / in /Users/me/rails_app/ must be deleted, not just /Users/me/rails_app
my_abs_path.delete_prefix("#{Rails.root}/")

Actual behavior

my_abs_path.delete_prefix("#{Rails.root}/")
# raises Rails/FilePath, and is autocorrected to
my_abs_path.delete_prefix("#{Rails.root.join('')}")
# which raises Style/RedundantInterpolation, so we manually correct to
my_abs_path.delete_prefix(Rails.root.join('').to_s)
# which is wrong:
actual = my_abs_path.delete_prefix(Rails.root.join('').to_s)
actual == expected_relative_result
# => false
puts actual
# => "/config/locales/text_en.yml"

# so we try giving an argument to join, but still wrong because Rails.root.join never adds a trailing slash:
actual = my_abs_path.delete_prefix(Rails.root.join('./').to_s)
actual == expected_relative_result
# => false
puts actual
# => "/config/locales/text_en.yml"

Steps to reproduce the problem

Copy the below into a file, run RuboCop with autocorrect enabled and manually fix any other cops that are raised, then assert that the result is true.
rubocop-rails-filepath-test.rb

# where Rails.root is /Users/me/rails_app
my_abs_path = "/Users/me/rails_app/config/locales/text_en.yml"
expected_relative_result = "config/locales/text_en.yml"

actual = my_abs_path.delete_prefix("#{Rails.root}/")
if actual != expected_relative_result
  raise "Invalid autocorrection: #{actual.inspect} != #{expected_relative_result.inspect}"
end
rubocop -a rubocop-rails-filepath-test.rb
rubocop -A rubocop-rails-filepath-test.rb # autofix Style/RedundantInterpolation
bin/rails c < rubocop-rails-filepath-test.rb

RuboCop version

1.57.2 (using Parser 3.2.2.4, rubocop-ast 1.30.0, running on ruby 3.0.6) [arm64-darwin21]
  - rubocop-rails 2.22.1
  - rubocop-rspec 2.18.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions