Class: Merb::Rack::Static

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

Instance Method Summary collapse

Methods included from DeferrableMiddleware

#deferred?

Constructor Details

#initialize(app, directory) ⇒ Static

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of Static



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

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

Instance Method Details

#call(env) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'merb-core/lib/merb-core/rack/middleware/static.rb', line 12

def call(env)
  path = if env[Merb::Const::PATH_INFO]
           env[Merb::Const::PATH_INFO].chomp(Merb::Const::SLASH)
         else
           Merb::Const::EMPTY_STRING
         end
  cached_path = (path.empty? ? 'index' : path) + '.html'

  if file_exist?(path) && env[Merb::Const::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[Merb::Const::REQUEST_METHOD] =~ /GET|HEAD/ # Serve the page cache if it's there and the request method is GET or HEAD
    env[Merb::Const::PATH_INFO] = cached_path
    serve_static(env)
  elsif path =~ /favicon\.ico/
    return [404, { Merb::Const::CONTENT_TYPE => Merb::Const::TEXT_SLASH_HTML }, "404 Not Found."]
  else
    @app.call(env)
  end
end

#file_exist?(path) ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

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

Parameters:

  • 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.



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

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

#serve_static(env) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • env (Hash)

    Environment variables to pass on to the server.



45
46
47
48
# File 'merb-core/lib/merb-core/rack/middleware/static.rb', line 45

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