Class: DataMapper::Adapters::MongoDBAdapter

Inherits:
AbstractAdapter
  • Object
show all
Defined in:
lib/mongodb_adapter.rb

Instance Method Summary collapse

Constructor Details

#initialize(name, options) ⇒ MongoDBAdapter

Returns a new instance of MongoDBAdapter.



14
15
16
17
18
19
20
21
22
# File 'lib/mongodb_adapter.rb', line 14

def initialize(name, options)
  super
  
  @hostname   = @options[:hostname] || 'localhost'
  @port       = @options[:port]     || 27017
  @database   = @options[:database] || 'dm-mongodb-test'
  
  @db = Mongo::Connection.new(@hostname, @port).db(@database)
end

Instance Method Details

#create(resources) ⇒ Object

Create mongodb entry



25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/mongodb_adapter.rb', line 25

def create(resources)
  resources.each do |resource|
    collection = @db.collection(resource.model.storage_name)
    id_hash = {}
    Mongo::ObjectID.create_pk(id_hash)
    initialize_serial(resource, id_hash[:_id].to_s.to_i(16))
    doc = resource.attributes(:field)
    doc[:_id] = id_hash[:_id]
    doc = stringify_bignums(doc)
    doc = stringify_discriminators(doc)
    collection.insert(doc)
  end
end

#delete(resources) ⇒ Object



76
77
78
79
80
81
82
83
84
# File 'lib/mongodb_adapter.rb', line 76

def delete(resources)
  collection = @db.collection(resources[0].model.storage_name)
  ids = []
  resources.each do |resource|
    serial = resource.model.serial(name).get(resource)
    ids << Mongo::ObjectID.from_string(serial.to_s(16))
  end
  collection.remove(:_id => {'$in' => ids})
end

#read(query) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/mongodb_adapter.rb', line 39

def read(query)
  collection = @db.collection(query.model.storage_name)
  criteria = conditions_to_hash(query.conditions)

  result = []

  cur = collection.find(criteria)
  cur = cur.limit(query.limit) if query.limit
  cur.each do |document|
    # __bignums array contains keys for Bignum properties (MongoDB doesn't support Bignum)
    document['__bignums'].each do |key|
      document[key] = document[key].to_i
    end
    # __discriminators array contains keys for Discriminator properties
    (document['__discriminators'] || []).each do |key|
      # Class from String
      document[key] = eval(document[key])
    end
    result << document
  end

  result
end

#update(attributes, resources) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/mongodb_adapter.rb', line 63

def update(attributes,resources)
  collection = @db.collection(resources[0].model.storage_name)
  resources.each do |resource|
    doc = resource.attributes(:field)
    serial = resource.model.serial(name).get(resource)
    doc[:_id] = Mongo::ObjectID.from_string(serial.to_s(16))
    doc = stringify_bignums(doc)
    doc = stringify_discriminators(doc)
    collection.save(doc)
  end
  resources.length
end