class Trifle::Stats::Driver::Mongo

Attributes

client[RW]
collection_name[RW]
separator[RW]

Public Class Methods

new(client, collection_name: 'trifle_stats') click to toggle source
# File lib/trifle/stats/driver/mongo.rb, line 13
def initialize(client, collection_name: 'trifle_stats')
  @client = client
  @collection_name = collection_name
  @separator = '::'
end

Public Instance Methods

get(key:) click to toggle source
# File lib/trifle/stats/driver/mongo.rb, line 46
def get(key:)
  pkey = key.join(separator)

  data = collection.find(key: pkey).limit(1).first
  return {} if data.nil? || data['data'].nil?

  data['data']
end
inc(key:, **values) click to toggle source
# File lib/trifle/stats/driver/mongo.rb, line 19
def inc(key:, **values)
  pkey = key.join(separator)

  collection.bulk_write(
    [upsert_operation('$inc', pkey: pkey, values: values)]
  )
end
set(key:, **values) click to toggle source
# File lib/trifle/stats/driver/mongo.rb, line 27
def set(key:, **values)
  pkey = key.join(separator)

  collection.bulk_write(
    [upsert_operation('$set', pkey: pkey, values: values)]
  )
end
upsert_operation(operation, pkey:, values:) click to toggle source
# File lib/trifle/stats/driver/mongo.rb, line 35
def upsert_operation(operation, pkey:, values:)
  data = self.class.pack(hash: { data: values })
  {
    update_many: {
      filter: { key: pkey },
      update: { operation => data },
      upsert: true
    }
  }
end

Private Instance Methods

collection() click to toggle source
# File lib/trifle/stats/driver/mongo.rb, line 57
def collection
  client[collection_name]
end