Class: Bayesball::Persistence::Mongo

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/bayesball/persistence/mongo.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(uri, options = {}) ⇒ Mongo

Returns a new instance of Mongo.



7
8
9
10
11
# File 'lib/bayesball/persistence/mongo.rb', line 7

def initialize(uri, options={})
  collection_name = options.delete(:collection) || 'bayesball_categories'
  @db = build_db(uri, options)
  @collection = db.collection(collection_name)
end

Instance Attribute Details

#dbObject (readonly)

Returns the value of attribute db.



6
7
8
# File 'lib/bayesball/persistence/mongo.rb', line 6

def db
  @db
end

Instance Method Details

#[](key) ⇒ Object



17
18
19
20
# File 'lib/bayesball/persistence/mongo.rb', line 17

def [](key)
  doc = @collection.find_one(name: key)
  doc && doc['counts'] || {}
end

#[]=(key, value) ⇒ Object



22
23
24
# File 'lib/bayesball/persistence/mongo.rb', line 22

def []=(key, value)
  @collection.update({name: key}, {name: key, counts: value}, {upsert: true})
end

#eachObject



26
27
28
29
30
31
32
33
34
# File 'lib/bayesball/persistence/mongo.rb', line 26

def each
  if block_given?
    @collection.find.each do |item|
      yield [item['name'], item['counts']]
    end
  else
    Enumerator.new(self, :each)
  end
end

#empty?Boolean

Returns:

  • (Boolean)


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

def empty?
  @collection.count == 0
end