Class: Persistence::Adapters::Mongo

Inherits:
Object
  • Object
show all
Defined in:
lib/persistence/adapters/mongo.rb

Overview

MongoDB database adapter.

Author:

  • Jiri Zajpt

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Mongo

Initializes adapter with given options.

Options Hash (options):

  • :host (String)

    Host

  • :database (String)

    Database name

  • :collection (String)

    Collection name



21
22
23
24
25
# File 'lib/persistence/adapters/mongo.rb', line 21

def initialize(options = {})
  @connection = ::Mongo::Connection.new(options[:host])
  @database = @connection.db(options[:database])
  self.collection(options[:collection]) if options[:collection]
end

Instance Attribute Details

#connectionObject

Returns the value of attribute connection



12
13
14
# File 'lib/persistence/adapters/mongo.rb', line 12

def connection
  @connection
end

#databaseObject

Returns the value of attribute database



13
14
15
# File 'lib/persistence/adapters/mongo.rb', line 13

def database
  @database
end

Instance Method Details

#collection(name = nil) ⇒ Collection

Uses given collection or returns the current one used.



90
91
92
# File 'lib/persistence/adapters/mongo.rb', line 90

def collection(name = nil)
  @_coll = name.present? ? self.database[name] : @_coll
end

#destroy_resource(id) ⇒ BSON::ObjectId?

Destroys existing object



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

def destroy_resource(id)
  id = self.to_id(id)
  result = self.collection.remove({ _id: id }, safe: true)
  if self.remove_result_ok?(result)
    id
  else
    nil
  end
end

#insert_resource(doc) ⇒ Object

Inserts a new object into collection



53
54
55
# File 'lib/persistence/adapters/mongo.rb', line 53

def insert_resource(doc)
  self.collection.insert(doc)
end

#resource(id = nil) ⇒ Hash

Returns a persisted hash of given document.



31
32
33
# File 'lib/persistence/adapters/mongo.rb', line 31

def resource(id = nil)
  collection.find_one(self.to_id(id))
end

#resourcesArray

Returns all persisted documents



38
39
40
# File 'lib/persistence/adapters/mongo.rb', line 38

def resources
  self.collection.find.to_a
end

#resources_with_keyword(keyword) ⇒ Array

Returns persisted documents with given keyword



45
46
47
48
# File 'lib/persistence/adapters/mongo.rb', line 45

def resources_with_keyword(keyword)
  escaped = Regexp.escape(keyword)
  self.collection.find(keywords: /#{escaped}/i)
end

#update_resource(id, new_doc) ⇒ BSON::ObjectId?

Updates existing object with new one



62
63
64
65
66
67
68
69
70
# File 'lib/persistence/adapters/mongo.rb', line 62

def update_resource(id, new_doc)
  id = self.to_id(id)
  result = self.collection.update({ _id: id }, new_doc, safe: true)
  if self.update_result_ok?(result)
    id
  else
    nil
  end
end