Skip to content

Commit e683c8a

Browse files
committed
[Fix #870] Fix an error for Rails/RootPathnameMethods
Fixes #870. This PR fixes an error for `Rails/RootPathnameMethods` when using `Rails.env` argument within `Dir.glob`.
1 parent 363ed1e commit e683c8a

File tree

3 files changed

+27
-2
lines changed

3 files changed

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

lib/rubocop/cop/rails/root_pathname_methods.rb

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -214,8 +214,17 @@ def include_interpolation?(arguments)
214214
end
215215

216216
def join_arguments(arguments)
217-
quote = include_interpolation?(arguments) ? '"' : "'"
218-
joined_arguments = arguments.map(&:value).join('/')
217+
use_interpolation = false
218+
219+
joined_arguments = arguments.map do |arg|
220+
if arg.respond_to?(:value)
221+
arg.value
222+
else
223+
use_interpolation = true
224+
"\#{#{arg.source}}"
225+
end
226+
end.join('/')
227+
quote = include_interpolation?(arguments) || use_interpolation ? '"' : "'"
219228

220229
"#{quote}#{joined_arguments}#{quote}"
221230
end

spec/rubocop/cop/rails/root_pathname_methods_spec.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,21 @@
101101
Rails.root.glob("**/#{path}/*.rb")
102102
RUBY
103103
end
104+
105+
it 'registers an offense when using `Rails.env` argument within `Dir.glob`' do
106+
expect_offense(<<~'RUBY')
107+
Dir.glob(Rails.root.join("db", "seeds", Rails.env, "*.rb")).sort.each do |file|
108+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `Rails.root` is a `Pathname` so you can just append `#glob`.
109+
load file
110+
end
111+
RUBY
112+
113+
expect_correction(<<~'RUBY')
114+
Rails.root.glob("db/seeds/#{Rails.env}/*.rb").sort.each do |file|
115+
load file
116+
end
117+
RUBY
118+
end
104119
end
105120

106121
# This is handled by `Rails/RootJoinChain`

0 commit comments

Comments
 (0)