Class: RuboCop::Cop::Rails::RootPublicPath

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/rails/root_public_path.rb

Overview

Favor ‘Rails.public_path` over `Rails.root` with `’public’‘

Examples:

# bad
Rails.root.join('public')
Rails.root.join('public/file.pdf')
Rails.root.join('public', 'file.pdf')

# good
Rails.public_path
Rails.public_path.join('file.pdf')
Rails.public_path.join('file.pdf')

Constant Summary collapse

MSG =
'Use `Rails.public_path`.'
RESTRICT_ON_SEND =
%i[join].to_set.freeze
PATTERN =
%r{\Apublic(/|\z)}.freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/rubocop/cop/rails/root_public_path.rb', line 35

def on_send(node)
  return unless (rails, maybe_public_path, other_args = rails_root_public(node))

  add_offense(node) do |corrector|
    first_args = maybe_public_path.gsub(PATTERN, '')

    args = other_args.map(&:source)
    args.unshift("'#{first_args}'") unless first_args.empty?

    replacement = "#{rails.source}.public_path"
    replacement += ".join(#{args.join(', ')})" unless args.empty?

    corrector.replace(node, replacement)
  end
end