Class: Mongo::GridFileSystem

Inherits:
Object
  • Object
show all
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

Constructor Details

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

Initialize a new Grid 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:



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

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

  @files.create_index([['filename', 1], ['uploadDate', -1]])
  @default_query_opts = {:sort => [['filename', 1], ['uploadDate', -1]], :limit => 1}
end

Instance Method Details

#delete(filename) ⇒ Boolean Also known as: unlink

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

Parameters:

  • filename (String)

Returns:

  • (Boolean)


86
87
88
89
90
91
92
# File 'lib/mongo/gridfs/grid_file_system.rb', line 86

def delete(filename)
  files = @files.find({'filename' => filename}, :fields => ['_id'])
  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.

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

Parameters:

  • filename (String)

    the name of the file.

  • mode (String)

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



67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/mongo/gridfs/grid_file_system.rb', line 67

def open(filename, mode, opts={})
  opts.merge!(default_grid_io_opts(filename))
  file   = GridIO.new(@files, @chunks, filename, mode, opts)
  return file unless block_given?
  result = nil
  begin
    result = yield file
  ensure
    file.close
  end
  result
end