Class: Mongo::Grid

Inherits:
Object show all
Defined in:
lib/mongo/gridfs/grid.rb

Overview

Implementation of the MongoDB GridFS specification. A file store.

Constant Summary collapse

DEFAULT_FS_NAME =
'fs'

Instance Method Summary collapse

Constructor Details

#initialize(db, fs_name = DEFAULT_FS_NAME) ⇒ Grid

Initialize a new Grid instance, consisting of a MongoDB database and a filesystem prefix if not using the default.



28
29
30
31
32
33
34
35
36
37
# File 'lib/mongo/gridfs/grid.rb', line 28

def initialize(db, fs_name=DEFAULT_FS_NAME)
  raise MongoArgumentError, "db must be a Mongo::DB." unless db.is_a?(Mongo::DB)

  @db      = db
  @files   = @db["#{fs_name}.files"]
  @chunks  = @db["#{fs_name}.chunks"]
  @fs_name = fs_name

  @chunks.create_index([['files_id', Mongo::ASCENDING], ['n', Mongo::ASCENDING]])
end

Instance Method Details

#delete(id) ⇒ Boolean

Delete a file from the store.

Parameters:

  • []

    id

Returns:

  • (Boolean)


68
69
70
71
# File 'lib/mongo/gridfs/grid.rb', line 68

def delete(id)
  @files.remove({"_id" => id})
  @chunks.remove({"_id" => id})
end

#get(id) ⇒ Mongo::GridIO

Read a file from the file store.

Parameters:

  • []

    id the file’s unique id.

Returns:



58
59
60
61
# File 'lib/mongo/gridfs/grid.rb', line 58

def get(id)
  opts = {:query => {'_id' => id}}.merge!(default_grid_io_opts)
  GridIO.new(@files, @chunks, nil, 'r', opts)
end

#put(data, filename, opts = {}) ⇒ Mongo::ObjectID

Store a file in the file store.

Parameters:

  • data (String, #read)

    a string or io-like object to store.

  • filename (String)

    a name for the file.

Returns:



45
46
47
48
49
50
51
# File 'lib/mongo/gridfs/grid.rb', line 45

def put(data, filename, opts={})
  opts.merge!(default_grid_io_opts)
  file = GridIO.new(@files, @chunks, filename, 'w', opts=opts)
  file.write(data)
  file.close
  file.files_id
end