Class: Mongo::GridFileSystem

Inherits:
Object
  • Object
show all
Includes:
Mongo::GridExt::InstanceMethods
Defined in:
lib/mongo/gridfs/grid_file_system.rb

Overview

A file store built on the GridFS specification featuring an API and behavior similar to that of a traditional file system.

Instance Method Summary collapse

Methods included from Mongo::GridExt::InstanceMethods

#exist?

Constructor Details

#initialize(db, fs_name = Grid::DEFAULT_FS_NAME) ⇒ GridFileSystem

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

Parameters:

  • db (Mongo::DB)

    a MongoDB database.

  • fs_name (String) (defaults to: Grid::DEFAULT_FS_NAME)

    A name for the file system. The default name, based on the specification, is ‘fs’.

Raises:



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/mongo/gridfs/grid_file_system.rb', line 32

def initialize(db, fs_name=Grid::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

  @default_query_opts = {:sort => [['filename', 1], ['uploadDate', -1]], :limit => 1}

  # Ensure indexes only if not connected to slave.
  unless db.connection.slave_ok?
    @files.create_index([['filename', 1], ['uploadDate', -1]])
    @chunks.create_index([['files_id', Mongo::ASCENDING], ['n', Mongo::ASCENDING]], :unique => true)
  end
end

Instance Method Details

#delete(filename = nil) { ... } ⇒ Boolean Also known as: unlink

Delete the file with the given filename. Note that this will delete all versions of the file.

Be careful with this. Deleting a GridFS file can result in read errors if another process is attempting to read a file while it’s being deleted. While the odds for this kind of race condition are small, it’s important to be aware of.

Parameters:

  • filename (String) (defaults to: nil)

Yields:

  • pass a block that returns an array of documents to be deleted.

Returns:

  • (Boolean)


127
128
129
130
131
132
133
134
135
136
137
# File 'lib/mongo/gridfs/grid_file_system.rb', line 127

def delete(filename=nil)
  if block_given?
    files = yield
  else
    files = @files.find({'filename' => filename}, :fields => ['_id'])
  end
  files.each do |file|
    @files.remove({'_id' => file['_id']})
    @chunks.remove({'files_id' => file['_id']})
  end
end

#open(filename, mode, opts = {}) ⇒ Object

Open a file for reading or writing. Note that the options for this method only apply when opening in ‘w’ mode.

Note that arbitary metadata attributes can be saved to the file by passing them is as options.

Examples:


# Store the text "Hello, world!" in the grid file system.
@grid = GridFileSystem.new(@db)
@grid.open('filename', 'w') do |f|
  f.write "Hello, world!"
end

# Output "Hello, world!"
@grid = GridFileSystem.new(@db)
@grid.open('filename', 'r') do |f|
  puts f.read
end

# Write a file on disk to the GridFileSystem
@file = File.open('image.jpg')
@grid = GridFileSystem.new(@db)
@grid.open('image.jpg, 'w') do |f|
  f.write @file
end

@return [Mongo::GridIO]

Parameters:

  • filename (String)

    the name of the file.

  • mode (String)

    either ‘r’ or ‘w’ for reading from or writing to the file.

  • opts (Hash) (defaults to: {})

    see GridIO#new

Options Hash (opts):

  • :metadata (Hash) — default: {}

    any additional data to store with the file.

  • :_id (ObjectId) — default: ObjectId

    a unique id for the file to be use in lieu of an automatically generated one.

  • :content_type (String) — default: 'binary/octet-stream'

    If no content type is specified, the content type will may be inferred from the filename extension if the mime-types gem can be loaded. Otherwise, the content type ‘binary/octet-stream’ will be used.

  • (262144) (Integer)

    :chunk_size size of file chunks in bytes.

  • :delete_old (Boolean) — default: false

    ensure that old versions of the file are deleted. This option only work in ‘w’ mode. Certain precautions must be taken when deleting GridFS files. See the notes under GridFileSystem#delete.

  • :safe (Boolean) — default: false

    When safe mode is enabled, the chunks sent to the server will be validated using an md5 hash. If validation fails, an exception will be raised.



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/mongo/gridfs/grid_file_system.rb', line 95

def open(filename, mode, opts={})
  opts = opts.dup
  opts.merge!(default_grid_io_opts(filename))
  del  = opts.delete(:delete_old) && mode == 'w'
  file = GridIO.new(@files, @chunks, filename, mode, opts)
  return file unless block_given?
  result = nil
  begin
    result = yield file
  ensure
    id = file.close
    if del
      self.delete do
        @files.find({'filename' => filename, '_id' => {'$ne' => id}}, :fields => ['_id'])
      end
    end
  end
  result
end