rubocop / rubocop-rails

A RuboCop extension focused on enforcing Rails best practices and coding conventions.
https://docs.rubocop.org/rubocop-rails
MIT License
821 stars 263 forks source link

The suggestions of the FilePath cop cause a TypeError if %w is used to specify the path #1389

Open cyclingzealot opened 2 days ago

cyclingzealot commented 2 days ago

Expected behavior

With a line like File.join(Rails.root, %w[test files migration]) with an array, it should be either A. be ignored or B. turned into Rails.root.join('test', 'files', 'migration').to_s

Personally, I prefer the notation with %w to minimize quotes. Thus I wouild choose option A, but I suspect gem author prefers B, which is acceptable.

Actual behavior

Running Rails/FilePath cop on File.join(Rails.root, %w[test files migration]) turns into Rails.root.join(%w[test files migration]).to_s, which Pathname.join can't handle array

Steps to reproduce the problem

  1. Steup test file
$ cat > tmp/test.rb
require File.expand_path("./config/environment")
File.join(Rails.root, %w[foo bar])
  1. Test and confirm clean execution
$ docker-compose exec web ruby tmp/test.rb
$ echo $?
0
  1. Run rubocop
docker-compose exec web rubocop --only Rails/FilePath  -a tmp/test.rb

tmp/test.rb:2:1: C: [Corrected] Rails/FilePath: Prefer Rails.root.join('path/to').to_s.
File.join(Rails.root, %w[foo bar])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1. Confirm change
$ cat tmp/test.rb 
require File.expand_path("./config/environment")
Rails.root.join(%w[foo bar]).to_s
  1. Attempt to execute file
$ docker-compose exec web ruby tmp/test.rb
/usr/local/lib/ruby/3.3.0/pathname.rb:419:in `initialize': no implicit conversion of Array into String (TypeError)

    result = Pathname.new(result) unless Pathname === result
                          ^^^^^^
    from /usr/local/lib/ruby/3.3.0/pathname.rb:419:in `new'
    from /usr/local/lib/ruby/3.3.0/pathname.rb:419:in `join'
    from tmp/test.rb:2:in `<main>'

RuboCop version

$ docker-compose exec web rubocop --verbose-version
1.69.0 (using Parser 3.3.6.0, rubocop-ast 1.36.2, analyzing as Ruby 3.3, running on ruby 3.3.6) [x86_64-linux-musl]
  - rubocop-performance 1.23.0
  - rubocop-rails 2.27.0

Reference

Similar to #472 but specific when using %w