Class: RuboCop::Cop::Rails::FilePath

Inherits:
Base
  • Object
show all
Includes:
ConfigurableEnforcedStyle, RangeHelp
Defined in:
lib/rubocop/cop/rails/file_path.rb

Overview

Identifies usages of file path joining process to use ‘Rails.root.join` clause. It is used to add uniformity when joining paths.

Examples:

EnforcedStyle: slashes (default)

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

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

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

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

EnforcedStyle: arguments

# bad
Rails.root.join('app/models/goober')

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

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

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

Constant Summary collapse

MSG_SLASHES =
'Prefer `Rails.root.join(\'path/to\')%<to_s>s`.'
MSG_ARGUMENTS =
'Prefer `Rails.root.join(\'path\', \'to\')%<to_s>s`.'
RESTRICT_ON_SEND =
%i[join].freeze

Instance Method Summary collapse

Instance Method Details

#on_dstr(node) ⇒ Object



57
58
59
60
61
62
63
64
65
66
# File 'lib/rubocop/cop/rails/file_path.rb', line 57

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?(':')

  register_offense(node, require_to_s: true)
end

#on_send(node) ⇒ Object



68
69
70
71
72
# File 'lib/rubocop/cop/rails/file_path.rb', line 68

def on_send(node)
  check_for_file_join_with_rails_root(node)
  check_for_rails_root_join_with_slash_separated_path(node)
  check_for_rails_root_join_with_string_arguments(node)
end