Class: Dragonfly::DataStorage::MongoDataStore

Inherits:
Object
  • Object
show all
Defined in:
lib/dragonfly/data_storage/mongo_data_store.rb

Constant Summary collapse

OBJECT_ID =

Mongo gem deprecated ObjectID in favour of ObjectId

defined?(BSON::ObjectId) ? BSON::ObjectId : BSON::ObjectID
INVALID_OBJECT_ID =
defined?(BSON::InvalidObjectId) ? BSON::InvalidObjectId : BSON::InvalidObjectID

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ MongoDataStore

Returns a new instance of MongoDataStore.



20
21
22
23
24
25
26
# File 'lib/dragonfly/data_storage/mongo_data_store.rb', line 20

def initialize(opts={})
  self.host = opts[:host]
  self.port = opts[:port]
  self.database = opts[:database] if opts[:database]
  self.username = opts[:username]
  self.password = opts[:password]
end

Instance Method Details

#connectionObject



56
57
58
# File 'lib/dragonfly/data_storage/mongo_data_store.rb', line 56

def connection
  @connection ||= Mongo::Connection.new(host, port)
end

#dbObject



60
61
62
# File 'lib/dragonfly/data_storage/mongo_data_store.rb', line 60

def db
  @db ||= connection.db(database)
end

#destroy(uid) ⇒ Object

Raises:



49
50
51
52
53
54
# File 'lib/dragonfly/data_storage/mongo_data_store.rb', line 49

def destroy(uid)
  ensure_authenticated!
  grid.delete(bson_id(uid))
rescue Mongo::GridFileNotFound, INVALID_OBJECT_ID => e
  raise DataNotFound, "#{e} - #{uid}"
end

#gridObject



64
65
66
# File 'lib/dragonfly/data_storage/mongo_data_store.rb', line 64

def grid
  @grid ||= Mongo::Grid.new(db)
end

#retrieve(uid) ⇒ Object

Raises:



36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/dragonfly/data_storage/mongo_data_store.rb', line 36

def retrieve(uid)
  ensure_authenticated!
  grid_io = grid.get(bson_id(uid))
  extra = marshal_decode(grid_io.)
  extra[:meta].merge!(:stored_at => grid_io.upload_date)
  [
    grid_io.read,
    extra
  ]
rescue Mongo::GridFileNotFound, INVALID_OBJECT_ID => e
  raise DataNotFound, "#{e} - #{uid}"
end

#store(temp_object, opts = {}) ⇒ Object



28
29
30
31
32
33
34
# File 'lib/dragonfly/data_storage/mongo_data_store.rb', line 28

def store(temp_object, opts={})
  ensure_authenticated!
  temp_object.file do |f|
    mongo_id = grid.put(f, :metadata => marshal_encode(temp_object.attributes))
    mongo_id.to_s
  end
end