Class: Rack::Grid

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

Defined Under Namespace

Classes: ConnectionError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Grid.



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

def initialize(app, options = {})
  options = {
    :hostname => 'localhost',
    :prefix   => 'grid',
    :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.



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

def database
  @database
end

#dbObject (readonly)

Returns the value of attribute db.



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

def db
  @db
end

#hostnameObject (readonly)

Returns the value of attribute hostname.



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

def hostname
  @hostname
end

#portObject (readonly)

Returns the value of attribute port.



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

def port
  @port
end

#prefixObject (readonly)

Returns the value of attribute prefix.



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

def prefix
  @prefix
end

Instance Method Details

#call(env) ⇒ Object

Strip the _id out of the path. This allows the user to send something like /grid/4ba69fde8c8f369a6e000003/filename.jpg to find the file with an id of 4ba69fde8c8f369a6e000003.



31
32
33
34
35
36
37
38
# File 'lib/rack/grid.rb', line 31

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

#grid_request(id) ⇒ Object

Get file from GridFS or return a 404



42
43
44
45
46
47
# File 'lib/rack/grid.rb', line 42

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