Class: Rack::GridServe

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

Constant Summary collapse

VERSION =
'0.0.11'.freeze
DEFAULT_PREFIX =
'gridfs'.freeze
DEFAULT_CACHE_CONTROL =
'no-cache'.freeze
EDGE_SLASHES_RE =
/\A\/|\/\z/.freeze
EMPTY_STRING =
''.freeze
PATH_INFO =
'PATH_INFO'.freeze
CONTENT_TYPE =
'Content-Type'.freeze
CONTENT_LENGTH =
'Content-Length'.freeze
LAST_MODIFIED =
'Last-Modified'.freeze
CACHE_CONTROL =
'Cache-Control'.freeze
ETAG =
'ETag'.freeze
TEXT_PLAIN =
'text/plain'.freeze
NOT_FOUND =
'Not Found'.freeze
NOT_FOUND_RESPONSE =
[
  404, 
  {
    CONTENT_TYPE => TEXT_PLAIN
  }.freeze, 
  [NOT_FOUND].freeze
].freeze
UPLOAD_DATE_KEY =
'uploadDate'.freeze
CONTENT_TYPE_KEY =
'contentType'.freeze
ID_KEY =
'_id'.freeze
MD5_KEY =
'md5'.freeze

Instance Method Summary collapse

Constructor Details

#initialize(app, opts = {}) ⇒ GridServe

Returns a new instance of GridServe.



14
15
16
17
18
19
20
# File 'lib/rack/grid_serve.rb', line 14

def initialize app, opts={}
  @app = app
  @db = opts[:db]
  @prefix = (opts[:prefix] || DEFAULT_PREFIX).gsub(EDGE_SLASHES_RE, EMPTY_STRING)
  @prefix = "/#{@prefix}/".freeze
  @cache_control = opts[:cache_control] || DEFAULT_CACHE_CONTROL
end

Instance Method Details

#call(env) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/rack/grid_serve.rb', line 42

def call env
  path_info = env[PATH_INFO].to_s
  if under_prefix? path_info
    file = find_file path_info
    if file.nil?
      NOT_FOUND_RESPONSE
    else
      last_modified = Time.at file[UPLOAD_DATE_KEY].to_i
      headers = {
        CONTENT_TYPE => file[CONTENT_TYPE_KEY],
        ETAG => file[MD5_KEY],
        LAST_MODIFIED => last_modified.httpdate,
        CACHE_CONTROL => @cache_control
      }
      if can_use_cached?(env, file[MD5_KEY])
        headers.delete(CONTENT_TYPE)
        headers.delete(CONTENT_LENGTH)
        [304, headers, []]
      else
        [200, headers, @db.fs.open_download_stream(file[ID_KEY])]
      end
    end
  else
    @app.call env
  end
end