Class: Grifizoid

Inherits:
Object
  • Object
show all
Defined in:
lib/grifizoid.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, &path_blk) ⇒ Grifizoid

Returns a new instance of Grifizoid.



2
3
4
5
# File 'lib/grifizoid.rb', line 2

def initialize(app, &path_blk)
  @app            = app
  @path_blk       = path_blk
end

Instance Method Details

#call(env) ⇒ Object

Get file from GridFileSystem or pass-thru



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/grifizoid.rb', line 8

def call(env)
  begin
    gfs_path = extract_gfs_path(env)
    file = Mongo::GridFileSystem.new(Mongoid.database).open(gfs_path, 'r')
    etag, last_modified = file.instance_variable_get(:@md5), Time.at( file.upload_date.to_i )
    
    headers = {
      'ETag'          => "\"#{etag}\"",
      'Last-Modified' => last_modified.httpdate,
    }
    if not_modified?(env, etag, last_modified )
      [304, headers, ['Not Modified']]
    else
      [200, headers.merge('Content-Type' => file.content_type, 'Content-Length' => file.file_length.to_s), file]
    end
  rescue Mongo::GridError, Mongo::GridFileNotFound
    @app.call(env)
  end
end

#extract_gfs_path(env) ⇒ Object

use raw path or path request to block to let user set a custom path



29
30
31
32
33
34
35
36
37
# File 'lib/grifizoid.rb', line 29

def extract_gfs_path(env)
  request   = Rack::Request.new(env)
  
  if @path_blk
    @path_blk.call(request)
  else
    request.path_info
  end
end