Skip to content

Commit 2235d8c

Browse files
authored
Merge pull request #989 from r7kamura/file-path-interpolation
Fix `Rails/FilePath` to detect offenses from complex string interpolation
2 parents 1b3c43d + 2096b18 commit 2235d8c

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: false)
6663
end
@@ -118,6 +115,22 @@ def build_message(require_to_s)
118115

119116
format(message_template, to_s: to_s)
120117
end
118+
119+
def dstr_ending_with_file_extension?(node)
120+
node.children.last.str_type? && node.children.last.source.start_with?('.')
121+
end
122+
123+
def dstr_including_file_separator?(node)
124+
node.children.any? do |child|
125+
child.str_type? && child.source.include?(File::SEPARATOR)
126+
end
127+
end
128+
129+
def dstr_separated_by_colon?(node)
130+
node.children[1..].any? do |child|
131+
child.str_type? && child.source.start_with?(':')
132+
end
133+
end
121134
end
122135
end
123136
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)