Class: Merb::Rack::Static

Inherits:
Middleware show all
Defined in:
lib/merb-core/rack/middleware/static.rb

Instance Method Summary collapse

Methods inherited from Middleware

#deferred?

Constructor Details

#initialize(app, directory) ⇒ Static

Returns a new instance of Static.



5
6
7
8
# File 'lib/merb-core/rack/middleware/static.rb', line 5

def initialize(app,directory)
  super(app)
  @static_server = ::Rack::File.new(directory)
end

Instance Method Details

#call(env) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/merb-core/rack/middleware/static.rb', line 10

def call(env)        
  path = env['PATH_INFO'] ? env['PATH_INFO'].chomp('/') : ""
  cached_path = (path.empty? ? 'index' : path) + '.html'
  
  if file_exist?(path) && env['REQUEST_METHOD'] =~ /GET|HEAD/ # Serve the file if it's there and the request method is GET or HEAD
    serve_static(env)
  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
    env['PATH_INFO'] = cached_path
    serve_static(env)
  elsif path =~ /favicon\.ico/
    return [404, {"Content-Type"=>"text/html"}, "404 Not Found."]
  else
    @app.call(env)
  end
end

#file_exist?(path) ⇒ Boolean

path<String>

The path to the file relative to the server root.

Returns

Boolean

True if file exists under the server root and is readable.

Returns:

  • (Boolean)


31
32
33
34
# File 'lib/merb-core/rack/middleware/static.rb', line 31

def file_exist?(path)
  full_path = ::File.join(@static_server.root, ::Merb::Request.unescape(path))
  ::File.file?(full_path) && ::File.readable?(full_path)
end

#serve_static(env) ⇒ Object

Parameters

env<Hash>

Environment variables to pass on to the server.



38
39
40
41
# File 'lib/merb-core/rack/middleware/static.rb', line 38

def serve_static(env)
  env["PATH_INFO"] = ::Merb::Request.unescape(env["PATH_INFO"])        
  @static_server.call(env)
end