aboutsummaryrefslogtreecommitdiffstats
path: root/actionview/lib/action_view/cache_expiry.rb
blob: 7cdc2e99822950df81205fafea03ca60badf3749 (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
# frozen_string_literal: true

module ActionView
  class CacheExpiry
    class Executor
      def initialize(watcher:)
        @cache_expiry = CacheExpiry.new(watcher: watcher)
      end

      def before(target)
        @cache_expiry.clear_cache_if_necessary
      end
    end

    def initialize(watcher:)
      @watched_dirs = nil
      @watcher_class = watcher
      @watcher = nil
      @mutex = Mutex.new
    end

    def clear_cache_if_necessary
      @mutex.synchronize do
        watched_dirs = dirs_to_watch
        return if watched_dirs.empty?

        if watched_dirs != @watched_dirs
          @watched_dirs = watched_dirs
          @watcher = @watcher_class.new([], watched_dirs) do
            clear_cache
          end
          @watcher.execute
        else
          @watcher.execute_if_updated
        end
      end
    end

    def clear_cache
      ActionView::LookupContext::DetailsKey.clear
    end

    private

      def dirs_to_watch
        fs_paths = all_view_paths.grep(FileSystemResolver)
        fs_paths.map(&:path).sort.uniq
      end

      def all_view_paths
        ActionView::ViewPaths.all_view_paths.flat_map(&:paths)
      end
  end
end