Skip to content

Commit 2096b18

Browse files
committed
Fix Rails/FilePath to detect offenses from complex string interpolation
1 parent 92f433c commit 2096b18

File tree

3 files changed

+28
-5
lines changed

3 files changed

+28
-5
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#989](https://github.com/rubocop/rubocop-rails/pull/989): Fix `Rails/FilePath` to detect offenses from complex string interpolation. ([@r7kamura][])

lib/rubocop/cop/rails/file_path.rb

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -56,11 +56,8 @@ class FilePath < Base
5656

5757
def on_dstr(node)
5858
return unless rails_root_nodes?(node)
59-
return unless node.children.last.str_type?
60-
61-
last_child_source = node.children.last.source
62-
return unless last_child_source.start_with?('.') || last_child_source.include?(File::SEPARATOR)
63-
return if last_child_source.start_with?(':')
59+
return if dstr_separated_by_colon?(node)
60+
return unless dstr_ending_with_file_extension?(node) || dstr_including_file_separator?(node)
6461

6562
register_offense(node, require_to_s: true)
6663
end
@@ -119,6 +116,22 @@ def build_message(require_to_s)
119116

120117
format(message_template, to_s: to_s)
121118
end
119+
120+
def dstr_ending_with_file_extension?(node)
121+
node.children.last.str_type? && node.children.last.source.start_with?('.')
122+
end
123+
124+
def dstr_including_file_separator?(node)
125+
node.children.any? do |child|
126+
child.str_type? && child.source.include?(File::SEPARATOR)
127+
end
128+
end
129+
130+
def dstr_separated_by_colon?(node)
131+
node.children[1..].any? do |child|
132+
child.str_type? && child.source.start_with?(':')
133+
end
134+
end
122135
end
123136
end
124137
end

spec/rubocop/cop/rails/file_path_spec.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,15 @@
8888
end
8989
end
9090

91+
context 'when using Rails.root called by double quoted string that ends with string interpolation' do
92+
it 'registers an offense' do
93+
expect_offense(<<~'RUBY')
94+
"#{Rails.root}/a/#{b}"
95+
^^^^^^^^^^^^^^^^^^^^^^ Prefer `Rails.root.join('path/to')`.
96+
RUBY
97+
end
98+
end
99+
91100
context 'when concat Rails.root and file separator using string interpolation' do
92101
it 'registers an offense' do
93102
expect_offense(<<~'RUBY')

0 commit comments

Comments
 (0)