Skip to content

Commit

Permalink
Merge pull request #872 from koic/fix_an_error_for_rails_root_pathnam…
Browse files Browse the repository at this point in the history
…e_methods

[Fix #870] Fix an error for `Rails/RootPathnameMethods`
  • Loading branch information
koic authored Nov 24, 2022
2 parents 363ed1e + e683c8a commit c88a51d
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
1 change: 1 addition & 0 deletions changelog/fix_an_error_for_rails_root_pathname_methods.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#870](https://github.com/rubocop/rubocop-rails/issues/870): Fix an error for `Rails/RootPathnameMethods` when using `Rails.env` argument within `Dir.glob`. ([@koic][])
13 changes: 11 additions & 2 deletions lib/rubocop/cop/rails/root_pathname_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -214,8 +214,17 @@ def include_interpolation?(arguments)
end

def join_arguments(arguments)
quote = include_interpolation?(arguments) ? '"' : "'"
joined_arguments = arguments.map(&:value).join('/')
use_interpolation = false

joined_arguments = arguments.map do |arg|
if arg.respond_to?(:value)
arg.value
else
use_interpolation = true
"\#{#{arg.source}}"
end
end.join('/')
quote = include_interpolation?(arguments) || use_interpolation ? '"' : "'"

"#{quote}#{joined_arguments}#{quote}"
end
Expand Down
15 changes: 15 additions & 0 deletions spec/rubocop/cop/rails/root_pathname_methods_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,21 @@
Rails.root.glob("**/#{path}/*.rb")
RUBY
end

it 'registers an offense when using `Rails.env` argument within `Dir.glob`' do
expect_offense(<<~'RUBY')
Dir.glob(Rails.root.join("db", "seeds", Rails.env, "*.rb")).sort.each do |file|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `Rails.root` is a `Pathname` so you can just append `#glob`.
load file
end
RUBY

expect_correction(<<~'RUBY')
Rails.root.glob("db/seeds/#{Rails.env}/*.rb").sort.each do |file|
load file
end
RUBY
end
end

# This is handled by `Rails/RootJoinChain`
Expand Down

0 comments on commit c88a51d

Please sign in to comment.