Class: Trifle::Stats::Driver::Mongo

Inherits:
Object
  • Object
show all
Includes:
Mixins::Packer
Defined in:
lib/trifle/stats/driver/mongo.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Mixins::Packer

included

Constructor Details

#initialize(client, collection_name: 'trifle_stats') ⇒ Mongo

Returns a new instance of Mongo.



12
13
14
15
16
# File 'lib/trifle/stats/driver/mongo.rb', line 12

def initialize(client, collection_name: 'trifle_stats')
  @client = client
  @collection_name = collection_name
  @separator = '::'
end

Instance Attribute Details

#clientObject

Returns the value of attribute client.



10
11
12
# File 'lib/trifle/stats/driver/mongo.rb', line 10

def client
  @client
end

#collection_nameObject

Returns the value of attribute collection_name.



10
11
12
# File 'lib/trifle/stats/driver/mongo.rb', line 10

def collection_name
  @collection_name
end

#separatorObject

Returns the value of attribute separator.



10
11
12
# File 'lib/trifle/stats/driver/mongo.rb', line 10

def separator
  @separator
end

Class Method Details

.setup!(client, collection_name: 'trifle_stats') ⇒ Object



18
19
20
21
# File 'lib/trifle/stats/driver/mongo.rb', line 18

def self.setup!(client, collection_name: 'trifle_stats')
  client[collection_name].create
  client[collection_name].indexes.create_one({ key: 1 }, unique: true)
end

Instance Method Details

#get(keys:) ⇒ Object



53
54
55
56
57
58
59
# File 'lib/trifle/stats/driver/mongo.rb', line 53

def get(keys:)
  pkeys = keys.map { |key| key.join(separator) }
  data = collection.find(key: { '$in' => pkeys })
  map = data.inject({}) { |o, d| o.merge(d['key'] => d['data']) }

  pkeys.map { |pkey| map[pkey] || {} }
end

#inc(keys:, **values) ⇒ Object



23
24
25
26
27
28
29
30
31
# File 'lib/trifle/stats/driver/mongo.rb', line 23

def inc(keys:, **values)
  data = self.class.pack(hash: { data: values })

  collection.bulk_write(
    keys.map do |key|
      upsert_operation('$inc', pkey: key.join(separator), data: data)
    end
  )
end

#set(keys:, **values) ⇒ Object



33
34
35
36
37
38
39
40
41
# File 'lib/trifle/stats/driver/mongo.rb', line 33

def set(keys:, **values)
  data = self.class.pack(hash: { data: values })

  collection.bulk_write(
    keys.map do |key|
      upsert_operation('$set', pkey: key.join(separator), data: data)
    end
  )
end

#upsert_operation(operation, pkey:, data:) ⇒ Object



43
44
45
46
47
48
49
50
51
# File 'lib/trifle/stats/driver/mongo.rb', line 43

def upsert_operation(operation, pkey:, data:)
  {
    update_many: {
      filter: { key: pkey },
      update: { operation => data },
      upsert: true
    }
  }
end