Class: Rack::GridFS

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ GridFS

Returns a new instance of GridFS.



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

def initialize(app, options = {})
  options = {
    :hostname => 'localhost',
    :prefix   => 'gridfs',
    :port     => Mongo::Connection::DEFAULT_PORT,
  }.merge(options)

  @app        = app
  @hostname   = options[:hostname]
  @port       = options[:port]
  @database   = options[:database]
  @prefix     = options[:prefix]
  @db         = nil

  connect!
end

Instance Attribute Details

#databaseObject (readonly)

Returns the value of attribute database.



7
8
9
# File 'lib/rack/gridfs.rb', line 7

def database
  @database
end

#dbObject (readonly)

Returns the value of attribute db.



7
8
9
# File 'lib/rack/gridfs.rb', line 7

def db
  @db
end

#hostnameObject (readonly)

Returns the value of attribute hostname.



7
8
9
# File 'lib/rack/gridfs.rb', line 7

def hostname
  @hostname
end

#portObject (readonly)

Returns the value of attribute port.



7
8
9
# File 'lib/rack/gridfs.rb', line 7

def port
  @port
end

#prefixObject (readonly)

Returns the value of attribute prefix.



7
8
9
# File 'lib/rack/gridfs.rb', line 7

def prefix
  @prefix
end

Instance Method Details

#call(env) ⇒ Object



26
27
28
29
30
31
32
33
# File 'lib/rack/gridfs.rb', line 26

def call(env)
  request = Rack::Request.new(env)
  if request.path_info =~ /^\/#{prefix}\/(.+)$/
    gridfs_request($1)
  else
    @app.call(env)
  end
end

#gridfs_request(id) ⇒ Object



35
36
37
38
39
40
# File 'lib/rack/gridfs.rb', line 35

def gridfs_request(id)
  file = Mongo::Grid.new(db).get(Mongo::ObjectID.from_string(id))
  [200, {'Content-Type' => file.content_type}, [file.read]]
rescue Mongo::GridError, Mongo::InvalidObjectID
  [404, {'Content-Type' => 'text/plain'}, ['File not found.']]
end