Guest User

Untitled

a guest
Feb 21st, 2018
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. module Merb
  2. module Rack
  3. class Static < Merb::Rack::Middleware
  4.  
  5. def initialize(app,directory)
  6. super(app)
  7. @static_server = ::Rack::File.new(directory)
  8. end
  9.  
  10. def call(env)
  11. path = env['PATH_INFO'] ? env['PATH_INFO'].chomp('/') : ""
  12. cached_path = (path.empty? ? 'index' : path) + '.html'
  13.  
  14. if file_exist?(path) && env['REQUEST_METHOD'] =~ /GET|HEAD/ # Serve the file if it's there and the request method is GET or HEAD
  15. serve_static(env)
  16. elsif file_exist?(cached_path) && env['REQUEST_METHOD'] =~ /GET|HEAD/ # Serve the page cache if it's there and the request method is GET or HEAD
  17. env['PATH_INFO'] = cached_path
  18. serve_static(env)
  19. elsif path =~ /favicon\.ico/
  20. return [404, {"Content-Type"=>"text/html"}, "404 Not Found."]
  21. else
  22. @app.call(env)
  23. end
  24. end
  25.  
  26. # ==== Parameters
  27. # path<String>:: The path to the file relative to the server root.
  28. #
  29. # ==== Returns
  30. # Boolean:: True if file exists under the server root and is readable.
  31. def file_exist?(path)
  32. full_path = ::File.join(@static_server.root, ::Merb::Request.unescape(path))
  33. ::File.file?(full_path) && ::File.readable?(full_path)
  34. end
  35.  
  36. # ==== Parameters
  37. # env<Hash>:: Environment variables to pass on to the server.
  38. def serve_static(env)
  39. env["PATH_INFO"] = ::Merb::Request.unescape(env["PATH_INFO"])
  40. @static_server.call(env)
  41. end
  42.  
  43. end
  44. end
  45. end
Add Comment
Please, Sign In to add comment