|
| 1 | +class Jbuilder::DependencyTracker |
| 2 | + EXPLICIT_DEPENDENCY = /# Template Dependency: (\S+)/ |
| 3 | + |
| 4 | + # Matches: |
| 5 | + # json.partial! "messages/message" |
| 6 | + # json.partial!('messages/message') |
| 7 | + # |
| 8 | + DIRECT_RENDERS = / |
| 9 | + \w+\.partial! # json.partial! |
| 10 | + \(?\s* # optional parenthesis |
| 11 | + (['"])([^'"]+)\1 # quoted value |
| 12 | + /x |
| 13 | + |
| 14 | + # Matches: |
| 15 | + # json.partial! partial: "comments/comment" |
| 16 | + # json.comments @post.comments, partial: "comments/comment", as: :comment |
| 17 | + # json.array! @posts, partial: "posts/post", as: :post |
| 18 | + # = render partial: "account" |
| 19 | + # |
| 20 | + INDIRECT_RENDERS = / |
| 21 | + (?::partial\s*=>|partial:) # partial: or :partial => |
| 22 | + \s* # optional whitespace |
| 23 | + (['"])([^'"]+)\1 # quoted value |
| 24 | + /x |
| 25 | + |
| 26 | + def self.call(name, template, view_paths = nil) |
| 27 | + new(name, template, view_paths).dependencies |
| 28 | + end |
| 29 | + |
| 30 | + def initialize(name, template, view_paths = nil) |
| 31 | + @name, @template, @view_paths = name, template, view_paths |
| 32 | + end |
| 33 | + |
| 34 | + def dependencies |
| 35 | + direct_dependencies + indirect_dependencies + explicit_dependencies |
| 36 | + end |
| 37 | + |
| 38 | + private |
| 39 | + |
| 40 | + attr_reader :name, :template |
| 41 | + |
| 42 | + def direct_dependencies |
| 43 | + source.scan(DIRECT_RENDERS).map(&:second) |
| 44 | + end |
| 45 | + |
| 46 | + def indirect_dependencies |
| 47 | + source.scan(INDIRECT_RENDERS).map(&:second) |
| 48 | + end |
| 49 | + |
| 50 | + def explicit_dependencies |
| 51 | + dependencies = source.scan(EXPLICIT_DEPENDENCY).flatten.uniq |
| 52 | + |
| 53 | + wildcards, explicits = dependencies.partition { |dependency| dependency.end_with?("/*") } |
| 54 | + |
| 55 | + (explicits + resolve_directories(wildcards)).uniq |
| 56 | + end |
| 57 | + |
| 58 | + def resolve_directories(wildcard_dependencies) |
| 59 | + return [] unless @view_paths |
| 60 | + return [] if wildcard_dependencies.empty? |
| 61 | + |
| 62 | + # Remove trailing "/*" |
| 63 | + prefixes = wildcard_dependencies.map { |query| query[0..-3] } |
| 64 | + |
| 65 | + @view_paths.flat_map(&:all_template_paths).uniq.filter_map { |path| |
| 66 | + path.to_s if prefixes.include?(path.prefix) |
| 67 | + }.sort |
| 68 | + end |
| 69 | + |
| 70 | + def source |
| 71 | + template.source |
| 72 | + end |
| 73 | +end |
0 commit comments