Skip to content

Commit 770e6bd

Browse files
authored
Merge pull request #875 from koic/make_rails_root_pathname_methods_aware_of_style_string_literals
Make `Rails/RootPathnameMethods` aware of enforced style of `Style/StringLiterals`
2 parents c88a51d + e8ffc7e commit 770e6bd

File tree

3 files changed

+28
-6
lines changed

3 files changed

+28
-6
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#875](https://github.com/rubocop/rubocop-rails/pull/875): Make `Rails/RootPathnameMethods` aware of enforced style of `Style/StringLiterals`. ([@koic][])

lib/rubocop/cop/rails/root_pathname_methods.rb

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -186,11 +186,7 @@ def evidence(node)
186186
def build_path_glob_replacement(path, method)
187187
receiver = range_between(path.loc.expression.begin_pos, path.children.first.loc.selector.end_pos).source
188188

189-
argument = if path.arguments.one?
190-
path.first_argument.source
191-
else
192-
join_arguments(path.arguments)
193-
end
189+
argument = path.arguments.one? ? path.first_argument.source : join_arguments(path.arguments)
194190

195191
"#{receiver}.#{method}(#{argument})"
196192
end
@@ -224,10 +220,18 @@ def join_arguments(arguments)
224220
"\#{#{arg.source}}"
225221
end
226222
end.join('/')
227-
quote = include_interpolation?(arguments) || use_interpolation ? '"' : "'"
223+
quote = enforce_double_quotes? || include_interpolation?(arguments) || use_interpolation ? '"' : "'"
228224

229225
"#{quote}#{joined_arguments}#{quote}"
230226
end
227+
228+
def enforce_double_quotes?
229+
string_literals_config['EnforcedStyle'] == 'double_quotes'
230+
end
231+
232+
def string_literals_config
233+
config.for_cop('Style/StringLiterals')
234+
end
231235
end
232236
end
233237
end

spec/rubocop/cop/rails/root_pathname_methods_spec.rb

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,23 @@
9191
RUBY
9292
end
9393

94+
context 'when double-quoted string literals are preferred' do
95+
let(:other_cops) do
96+
super().merge('Style/StringLiterals' => { 'EnforcedStyle' => 'double_quotes' })
97+
end
98+
99+
it "registers an offense when using `Dir.glob(Rails.root.join('**', '*.rb'))`" do
100+
expect_offense(<<~RUBY)
101+
Dir.glob(Rails.root.join('**', '*.rb'))
102+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `Rails.root` is a `Pathname` so you can just append `#glob`.
103+
RUBY
104+
105+
expect_correction(<<~RUBY)
106+
Rails.root.glob("**/*.rb")
107+
RUBY
108+
end
109+
end
110+
94111
it "registers an offense when using `Dir.glob(Rails.root.join('**', \"\#{path}\", '*.rb'))`" do
95112
expect_offense(<<~'RUBY')
96113
Dir.glob(Rails.root.join('**', "#{path}", '*.rb'))

0 commit comments

Comments
 (0)