Skip to content

Commit

Permalink
Make Rails/RootPathnameMethods aware of enforced style of `Style/St…
Browse files Browse the repository at this point in the history
…ringLiterals`

Follow up #872 (comment).

This PR makes `Rails/RootPathnameMethods` aware of enforced style of `Style/StringLiterals`.
  • Loading branch information
koic committed Nov 25, 2022
1 parent c88a51d commit 57544c7
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#875](https://github.com/rubocop/rubocop/pull/875): Make `Rails/RootPathnameMethods` aware of enforced style of `Style/StringLiterals`. ([@koic][])
16 changes: 10 additions & 6 deletions lib/rubocop/cop/rails/root_pathname_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -186,11 +186,7 @@ def evidence(node)
def build_path_glob_replacement(path, method)
receiver = range_between(path.loc.expression.begin_pos, path.children.first.loc.selector.end_pos).source

argument = if path.arguments.one?
path.first_argument.source
else
join_arguments(path.arguments)
end
argument = path.arguments.one? ? path.first_argument.source : join_arguments(path.arguments)

"#{receiver}.#{method}(#{argument})"
end
Expand Down Expand Up @@ -224,10 +220,18 @@ def join_arguments(arguments)
"\#{#{arg.source}}"
end
end.join('/')
quote = include_interpolation?(arguments) || use_interpolation ? '"' : "'"
quote = enforce_double_quotes? || include_interpolation?(arguments) || use_interpolation ? '"' : "'"

"#{quote}#{joined_arguments}#{quote}"
end

def enforce_double_quotes?
string_literals_config['EnforcedStyle'] == 'double_quotes'
end

def string_literals_config
config.for_cop('Style/StringLiterals')
end
end
end
end
Expand Down
17 changes: 17 additions & 0 deletions spec/rubocop/cop/rails/root_pathname_methods_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,23 @@
RUBY
end

context 'when double-quoted string literals are preferred' do
let(:other_cops) do
super().merge('Style/StringLiterals' => { 'EnforcedStyle' => 'double_quotes' })
end

it "registers an offense when using `Dir.glob(Rails.root.join('**', '*.rb'))`" do
expect_offense(<<~RUBY)
Dir.glob(Rails.root.join('**', '*.rb'))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `Rails.root` is a `Pathname` so you can just append `#glob`.
RUBY

expect_correction(<<~RUBY)
Rails.root.glob("**/*.rb")
RUBY
end
end

it "registers an offense when using `Dir.glob(Rails.root.join('**', \"\#{path}\", '*.rb'))`" do
expect_offense(<<~'RUBY')
Dir.glob(Rails.root.join('**', "#{path}", '*.rb'))
Expand Down

0 comments on commit 57544c7

Please sign in to comment.