Class: Useless::Rack::Middleware::Assets

Inherits:
Object
  • Object
show all
Defined in:
lib/useless/rack/middleware/assets.rb

Overview

‘Assets` maps requests to files in the assets directory.

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Assets

Returns a new instance of Assets.



6
7
8
# File 'lib/useless/rack/middleware/assets.rb', line 6

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/useless/rack/middleware/assets.rb', line 10

def call(env)
  # If the path couldn't be a file in assets, just proxy the request.
  unless env['PATH_INFO'] =~ /\/\w+/
    return @app.call(env)
  end

  # The path is relative to the assets directory in the gem root
  path = File.expand_path("../../../../assets#{env['PATH_INFO']}", __FILE__)

  # If there's a corresponding file:
  if File.exists?(path) and !File.directory?(path)
    # Try to infer the type from the extension, resorting to 'plain'
    # if we can't.
    type = path[/\.(\w+)$/, 1] || 'plain'

    # Read the file,
    response = File.read(path)

    # and serve it up
    [200, {'Content-Type' => "text/#{type}"}, [response]]
  else
    # Otherwise, just pass the request along
    @app.call(env)
  end
end