aboutsummaryrefslogtreecommitdiffstats
path: root/actionpack/lib/action_view/dependency_tracker.rb
blob: 1e31185c260b9cde0986359595ea1bc0ba6d9892 (plain) (blame)
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
60
61
62
63
64
65
66
module ActionView
  class DependencyTracker
    def self.find_dependencies(name, template)
      ErbTracker.call(name, template)
    end

    class ErbTracker
      EXPLICIT_DEPENDENCY = /# Template Dependency: (\S+)/

      # Matches:
      #   render partial: "comments/comment", collection: commentable.comments
      #   render "comments/comments"
      #   render 'comments/comments'
      #   render('comments/comments')
      #
      #   render(@topic)         => render("topics/topic")
      #   render(topics)         => render("topics/topic")
      #   render(message.topics) => render("topics/topic")
      RENDER_DEPENDENCY = /
        render\s*                     # render, followed by optional whitespace
        \(?                           # start an optional parenthesis for the render call
        (partial:|:partial\s+=>)?\s*  # naming the partial, used with collection -- 1st capture
        ([@a-z"'][@a-z_\/\."']+)      # the template name itself -- 2nd capture
      /x

      def self.call(name, template)
        new(name, template).call
      end

      def initialize(name, template)
        @name, @template = name, template
      end

      def call
        render_dependencies + explicit_dependencies
      end

      private
        attr_reader :name, :template

        def directory
          name.split("/")[0..-2].join("/")
        end

        def render_dependencies
          template.source.scan(RENDER_DEPENDENCY).
            collect(&:second).uniq.

            # render(@topic)         => render("topics/topic")
            # render(topics)         => render("topics/topic")
            # render(message.topics) => render("topics/topic")
            collect { |name| name.sub(/\A@?([a-z]+\.)*([a-z_]+)\z/) { "#{$2.pluralize}/#{$2.singularize}" } }.

            # render("headline") => render("message/headline")
            collect { |name| name.include?("/") ? name : "#{directory}/#{name}" }.

            # replace quotes from string renders
            collect { |name| name.gsub(/["']/, "") }
        end

        def explicit_dependencies
          template.source.scan(EXPLICIT_DEPENDENCY).flatten.uniq
        end
    end
  end
end