Class: Persistence::Adapters::Mongo

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

Overview

MongoDB database adapter.

Author:

Instance Attribute Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (Mongo) initialize(options = {})

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

- (Object) connection

Returns the value of attribute connection



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

def connection
  @connection
end

- (Object) database

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) collection(name = nil)

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

- (BSON::ObjectId?) destroy_resource(id)

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

- (Object) insert_resource(doc)

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

- (Hash) resource(id = nil)

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

- (Array) resources

Returns all persisted documents



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

def resources
  self.collection.find.to_a
end

- (Array) resources_with_keyword(keyword)

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

- (BSON::ObjectId?) update_resource(id, new_doc)

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