Class: MongoPersistedCollection

Inherits:
Object
  • Object
show all
Defined in:
lib/util/mongo_persisted_collection.rb

Overview

Collection of items that are automatically persisted to a MongoDB collection

Instance Method Summary collapse

Constructor Details

#initialize(hostname, db, collection) ⇒ MongoPersistedCollection

Creates a new MongoPersistedCollection

Parameters:

  • hostname (String)

    of the MongoDB server

  • db (String)

    the database where we want to persist the array

  • collection (String)

    the collection we are using to persist this collection



12
13
14
15
16
# File 'lib/util/mongo_persisted_collection.rb', line 12

def initialize( hostname, db, collection )
  Mongo::Logger.logger.level = ::Logger::INFO
  client = Mongo::Client.new([hostname], :database => db)
  @collection = client[collection]
end

Instance Method Details

#delete(item) ⇒ Hash

Deletes the first element from this persisted collection that is equal to item

Parameters:

  • item (Hash)

    the object we want to delete

Returns:

  • (Hash)

    the object we just deleted



33
34
35
# File 'lib/util/mongo_persisted_collection.rb', line 33

def delete( item )
  from_bson_to_hash @collection.find(item).find_one_and_delete
end

#lengthFixnum

Returns the length of the collection

Returns:

  • (Fixnum)

    the length of the collection



63
64
65
# File 'lib/util/mongo_persisted_collection.rb', line 63

def length
  @collection.find.count.to_i
end

#push(item) ⇒ MongoPersistedCollection

Pushes (appends) the given hash on to the end of this persisted collection

Parameters:

  • item (Hash)

    the object we want to append

Returns:



23
24
25
26
# File 'lib/util/mongo_persisted_collection.rb', line 23

def push( item )
  @collection.insert_one item
  self
end

#replace(item, replacement) ⇒ Hahs

Replaces the first element from this persisted array that matches item, with replacement

Parameters:

  • replacement (Hash)

    for the current element

Returns:

  • (Hahs)

    the item that was replaced, {} if the element wasn’t in the collection



42
43
44
45
46
# File 'lib/util/mongo_persisted_collection.rb', line 42

def replace( item, replacement )
  r = delete item
  push replacement
  r
end

#to_aArray<Hash>

Returns an array representation of this collection

Returns:

  • (Array<Hash>)

    array representation of this persisted collection



52
53
54
55
56
57
58
# File 'lib/util/mongo_persisted_collection.rb', line 52

def to_a
  ta = Array.new
  @collection.find.each do |doc|
    ta.push from_bson_to_hash(doc)
  end
  ta
end