# #prepend_view_path leaks memory each time it is called with a new object. In
# order to prevent that, we prepare the resolver that it uses internally, and
# cache it.
#
# https://www.spacevatican.org/2019/5/4/debugging-a-memory-leak-in-a-rails-app/
# https://github.com/rails/rails/issues/14301#issuecomment-771651933
#
module ApplicationController::FixMemoryLeakInPrependViewPath

  RESOLVER_CACHE = Concurrent::Map.new

  def prepend_view_path(path)
    resolver = RESOLVER_CACHE.fetch_or_store(path) do
      ActionView::FileSystemResolver.new(path)
    end

    # https://github.com/rails/rails/issues/14301#issuecomment-771651933
    resolver.clear_cache unless ActionView::Resolver.caching?
    super(resolver)
  end

end
