Skip to content

Commit

Permalink
Merge pull request #989 from r7kamura/file-path-interpolation
Browse files Browse the repository at this point in the history
Fix `Rails/FilePath` to detect offenses from complex string interpolation
  • Loading branch information
koic committed Apr 25, 2023
2 parents 1b3c43d + 2096b18 commit 2235d8c
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#989](https://github.com/rubocop/rubocop-rails/pull/989): Fix `Rails/FilePath` to detect offenses from complex string interpolation. ([@r7kamura][])
23 changes: 18 additions & 5 deletions lib/rubocop/cop/rails/file_path.rb
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,8 @@ class FilePath < Base

def on_dstr(node)
return unless rails_root_nodes?(node)
return unless node.children.last.str_type?

last_child_source = node.children.last.source
return unless last_child_source.start_with?('.') || last_child_source.include?(File::SEPARATOR)
return if last_child_source.start_with?(':')
return if dstr_separated_by_colon?(node)
return unless dstr_ending_with_file_extension?(node) || dstr_including_file_separator?(node)

register_offense(node, require_to_s: false)
end
Expand Down Expand Up @@ -118,6 +115,22 @@ def build_message(require_to_s)

format(message_template, to_s: to_s)
end

def dstr_ending_with_file_extension?(node)
node.children.last.str_type? && node.children.last.source.start_with?('.')
end

def dstr_including_file_separator?(node)
node.children.any? do |child|
child.str_type? && child.source.include?(File::SEPARATOR)
end
end

def dstr_separated_by_colon?(node)
node.children[1..].any? do |child|
child.str_type? && child.source.start_with?(':')
end
end
end
end
end
Expand Down
9 changes: 9 additions & 0 deletions spec/rubocop/cop/rails/file_path_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,15 @@
end
end

context 'when using Rails.root called by double quoted string that ends with string interpolation' do
it 'registers an offense' do
expect_offense(<<~'RUBY')
"#{Rails.root}/a/#{b}"
^^^^^^^^^^^^^^^^^^^^^^ Prefer `Rails.root.join('path/to')`.
RUBY
end
end

context 'when concat Rails.root and file separator using string interpolation' do
it 'registers an offense' do
expect_offense(<<~'RUBY')
Expand Down

0 comments on commit 2235d8c

Please sign in to comment.