class Refile::Gridfs::Backend

Constants

DEFAULT_PREFIX
INIT_CONNECTION_ARG_ERROR_MSG

Attributes

hasher[R]
max_size[R]
prefix[R]

Public Class Methods

new(connection_or_proc, max_size: nil, prefix: DEFAULT_PREFIX, hasher: Refile::RandomHasher.new) click to toggle source
# File lib/refile/gridfs/backend.rb, line 14
def initialize(connection_or_proc, max_size: nil, prefix: DEFAULT_PREFIX, hasher: Refile::RandomHasher.new)
  @connection_or_proc = connection_or_proc
  @max_size   = max_size
  @prefix     = prefix
  @hasher     = hasher
end

Public Instance Methods

clear!(confirm = nil) click to toggle source
# File lib/refile/gridfs/backend.rb, line 60
def clear!(confirm = nil)
  raise Refile::Confirm unless confirm == :confirm

  connection["#{@prefix}.files"].drop
  connection["#{@prefix}.chunks"].drop
end
delete(id) click to toggle source
# File lib/refile/gridfs/backend.rb, line 34
          def delete(id)
  file = gridfs.find_one(filename: id)
  gridfs.delete_one(file) if file
end
exists?(id) click to toggle source
# File lib/refile/gridfs/backend.rb, line 56
          def exists?(id)
  !! gridfs.find_one(filename: id)
end
get(id) click to toggle source
# File lib/refile/gridfs/backend.rb, line 30
          def get(id)
  Refile::File.new(self, id)
end
open(id) click to toggle source
# File lib/refile/gridfs/backend.rb, line 39
          def open(id)
  StringIO.new(read(id))
end
read(id) click to toggle source
# File lib/refile/gridfs/backend.rb, line 43
          def read(id)
  if exists?(id)
    gridfs.find_one(filename: id).data
  else
    nil
  end
end
size(id) click to toggle source
# File lib/refile/gridfs/backend.rb, line 51
          def size(id)
  file = gridfs.find_one(filename: id)
  file.data.length if file
end
upload(uploadable) click to toggle source
# File lib/refile/gridfs/backend.rb, line 21
                  def upload(uploadable)
  filename = @hasher.hash(uploadable)

  file = Mongo::Grid::File.new(uploadable.read, filename: filename)
  gridfs.insert_one(file)

  Refile::File.new(self, filename)
end

Private Instance Methods

connection() click to toggle source
# File lib/refile/gridfs/backend.rb, line 77
def connection
  @connection || obtain_new_connection
end
gridfs() click to toggle source
# File lib/refile/gridfs/backend.rb, line 81
def gridfs
  connection.database.fs(fs_name: @prefix)
end
obtain_new_connection() click to toggle source
# File lib/refile/gridfs/backend.rb, line 69
def obtain_new_connection
  candidate = @connection_or_proc.is_a?(Proc) ? @connection_or_proc.call : @connection_or_proc
  unless candidate.is_a?(Mongo::Client)
    raise ArgumentError.new(INIT_CONNECTION_ARG_ERROR_MSG)
  end
  @connection = candidate
end