Class: Useless::Rack::Files

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

Overview

‘Rack::Files` retrieves files from Useless::FS and serves them up.

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Files

Returns a new instance of Files.



8
9
10
# File 'lib/useless/rack/files.rb', line 8

def initialize(app)
  @app = app
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
31
32
33
# File 'lib/useless/rack/files.rb', line 12

def call(env)
  if env['PATH_INFO'] =~ /^\/file/
    begin
      # The file ID is everything after the second '/' in the path
      id = env['PATH_INFO'].split('/')[2]

      # Retrieve the file from FS
      file = env['useless.fs'].get(BSON::ObjectId(id))

      # and serve it up with the associated content type
      return [200, {'Content-Type' => file.content_type}, file.read]

    # Two things can go wrong, and they'll both raise an error:
    #   * the specified ID is not a valid object ID
    #   * there is no file corresponding to the ID in the FS
    rescue BSON::InvalidObjectId, Useless::FS::FileNotFound
      [404, {'Content-Type' => 'text/plain'}, "File not found: #{id}"]
    end
  else
    @app.call(env)
  end
end