forked from rubocop/rubocop-rails
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroot_public_path.rb
59 lines (47 loc) · 1.5 KB
/
root_public_path.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# frozen_string_literal: true
module RuboCop
module Cop
module Rails
# Favor `Rails.public_path` over `Rails.root` with `'public'`
#
# @example
# # 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')
#
class RootPublicPath < Base
extend AutoCorrector
MSG = 'Use `Rails.public_path`.'
RESTRICT_ON_SEND = %i[join].to_set.freeze
PATTERN = %r{\Apublic(/|\z)}.freeze
def_node_matcher :rails_root_public, <<~PATTERN
(send
(send
$(const {nil? cbase} :Rails) :root) :join
(str $#public_path?) $...)
PATTERN
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
private
def public_path?(string)
PATTERN.match?(string)
end
end
end
end
end