Class: MongoPersistedCollection
- Inherits:
-
Object
- Object
- MongoPersistedCollection
- Defined in:
- lib/util/mongo_persisted_collection.rb
Overview
Collection of items that are automatically persisted to a MongoDB collection
Instance Method Summary collapse
-
#delete(item) ⇒ Hash
Deletes the first element from this persisted collection that is equal to item.
-
#initialize(hostname, db, collection) ⇒ MongoPersistedCollection
constructor
Creates a new MongoPersistedCollection.
-
#length ⇒ Fixnum
Returns the length of the collection.
-
#push(item) ⇒ MongoPersistedCollection
Pushes (appends) the given hash on to the end of this persisted collection.
-
#replace(item, replacement) ⇒ Hahs
Replaces the first element from this persisted array that matches item, with replacement.
-
#to_a ⇒ Array<Hash>
Returns an array representation of this collection.
Constructor Details
#initialize(hostname, db, collection) ⇒ MongoPersistedCollection
Creates a new MongoPersistedCollection
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
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 |
#length ⇒ Fixnum
Returns 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
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
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_a ⇒ Array<Hash>
Returns an array representation of this 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 |