class RubbyCop::Cop::Rails::FilePath

This cop is used to identify usages of file path joining process to use `Rails.root.join` clause.

@example

# bad
Rails.root.join('app/models/goober')
File.join(Rails.root, 'app/models/goober')
"#{Rails.root}/app/models/goober"

# good
Rails.root.join('app', 'models', 'goober')

Constants

MSG

Public Instance Methods

on_dstr(node) click to toggle source
# File lib/rubbycop/cop/rails/file_path.rb, line 32
def on_dstr(node)
  return unless rails_root_nodes?(node)
  register_offense(node)
end
on_send(node) click to toggle source
# File lib/rubbycop/cop/rails/file_path.rb, line 37
def on_send(node)
  check_for_file_join_with_rails_root(node)
  check_for_rails_root_join_with_slash_separated_path(node)
end

Private Instance Methods

check_for_file_join_with_rails_root(node) click to toggle source
# File lib/rubbycop/cop/rails/file_path.rb, line 44
def check_for_file_join_with_rails_root(node)
  return unless file_join_nodes?(node)
  return unless node.method_args.any? { |e| rails_root_nodes?(e) }

  register_offense(node)
end
check_for_rails_root_join_with_slash_separated_path(node) click to toggle source
# File lib/rubbycop/cop/rails/file_path.rb, line 51
def check_for_rails_root_join_with_slash_separated_path(node)
  return unless rails_root_nodes?(node)
  return unless rails_root_join_nodes?(node)
  return unless node.method_args.any? { |arg| string_with_slash?(arg) }

  register_offense(node)
end
register_offense(node) click to toggle source
# File lib/rubbycop/cop/rails/file_path.rb, line 63
def register_offense(node)
  line_range = node.loc.column...node.loc.last_column

  add_offense(
    node,
    source_range(processed_source.buffer, node.loc.line, line_range),
    MSG
  )
end
string_with_slash?(node) click to toggle source
# File lib/rubbycop/cop/rails/file_path.rb, line 59
def string_with_slash?(node)
  node.type == :str && node.source =~ %r{/}
end