1
0

public_file_server_middleware.rb 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. # frozen_string_literal: true
  2. require 'action_dispatch/middleware/static'
  3. class PublicFileServerMiddleware
  4. SERVICE_WORKER_TTL = 7.days.to_i
  5. CACHE_TTL = 28.days.to_i
  6. def initialize(app)
  7. @app = app
  8. @file_handler = ActionDispatch::FileHandler.new(Rails.application.paths['public'].first)
  9. end
  10. def call(env)
  11. file = @file_handler.attempt(env)
  12. # If the request is not a static file, move on!
  13. return @app.call(env) if file.nil?
  14. status, headers, response = file
  15. # Set cache headers on static files. Some paths require different cache headers
  16. headers['Cache-Control'] = begin
  17. request_path = env['REQUEST_PATH']
  18. if request_path.start_with?('/sw.js')
  19. "public, max-age=#{SERVICE_WORKER_TTL}, must-revalidate"
  20. elsif request_path.start_with?(paperclip_root_url)
  21. "public, max-age=#{CACHE_TTL}, immutable"
  22. else
  23. "public, max-age=#{CACHE_TTL}, must-revalidate"
  24. end
  25. end
  26. [status, headers, response]
  27. end
  28. private
  29. def paperclip_root_url
  30. ENV.fetch('PAPERCLIP_ROOT_URL', '/system')
  31. end
  32. end