static.rb 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. module Rack
  2. # The Rack::Static middleware intercepts requests for static files
  3. # (javascript files, images, stylesheets, etc) based on the url prefixes or
  4. # route mappings passed in the options, and serves them using a Rack::File
  5. # object. This allows a Rack stack to serve both static and dynamic content.
  6. #
  7. # Examples:
  8. #
  9. # Serve all requests beginning with /media from the "media" folder located
  10. # in the current directory (ie media/*):
  11. #
  12. # use Rack::Static, :urls => ["/media"]
  13. #
  14. # Serve all requests beginning with /css or /images from the folder "public"
  15. # in the current directory (ie public/css/* and public/images/*):
  16. #
  17. # use Rack::Static, :urls => ["/css", "/images"], :root => "public"
  18. #
  19. # Serve all requests to / with "index.html" from the folder "public" in the
  20. # current directory (ie public/index.html):
  21. #
  22. # use Rack::Static, :urls => {"/" => 'index.html'}, :root => 'public'
  23. #
  24. # Serve all requests normally from the folder "public" in the current
  25. # directory but uses index.html as default route for "/"
  26. #
  27. # use Rack::Static, :urls => [""], :root => 'public', :index =>
  28. # 'public/index.html'
  29. #
  30. # Set a fixed Cache-Control header for all served files:
  31. #
  32. # use Rack::Static, :root => 'public', :cache_control => 'public'
  33. #
  34. class Static
  35. def initialize(app, options={})
  36. @app = app
  37. @urls = options[:urls] || ["/favicon.ico"]
  38. @index = options[:index]
  39. root = options[:root] || Dir.pwd
  40. cache_control = options[:cache_control]
  41. @file_server = Rack::File.new(root, cache_control)
  42. end
  43. def overwrite_file_path(path)
  44. @urls.kind_of?(Hash) && @urls.key?(path) || @index && path == '/'
  45. end
  46. def route_file(path)
  47. @urls.kind_of?(Array) && @urls.any? { |url| path.index(url) == 0 }
  48. end
  49. def can_serve(path)
  50. route_file(path) || overwrite_file_path(path)
  51. end
  52. def call(env)
  53. path = env["PATH_INFO"]
  54. if can_serve(path)
  55. env["PATH_INFO"] = (path == '/' ? @index : @urls[path]) if overwrite_file_path(path)
  56. @file_server.call(env)
  57. else
  58. @app.call(env)
  59. end
  60. end
  61. end
  62. end