Class: Microstat

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

Instance Method Summary collapse

Constructor Details

#initialize(redis: "redis://localhost:6379", namespace: 'mustat') ⇒ Microstat

Returns a new instance of Microstat.



4
5
6
7
# File 'lib/microstat.rb', line 4

def initialize(redis: "redis://localhost:6379", namespace: 'mustat')
  @redis = Redis.new(url: redis)
  @key_space = "#{namespace}:events"
end

Instance Method Details

#date(event_name, date_string) ⇒ Object

Returns a count for an arbitrary date string in the yyyymmdd format



40
41
42
# File 'lib/microstat.rb', line 40

def date(event_name, date_string)
  @redis.get "#{@key_space}:#{event_name}:#{date_string}"
end

#dates(event_name) ⇒ Object

Given an event type, return an array of dates where we have data



30
31
32
# File 'lib/microstat.rb', line 30

def dates(event_name)
  @redis.smembers "#{@key_space}:#{event_name}:dates"
end

#eventsObject

Lists the known event types



10
11
12
# File 'lib/microstat.rb', line 10

def events
  @redis.smembers @key_space
end

#history(event_name) ⇒ Object

Returns a hash with date:count tuples for a given event



45
46
47
48
49
50
51
52
53
# File 'lib/microstat.rb', line 45

def history(event_name)
  historical_counts = {}

  for date in dates(event_name)
    historical_counts[date] = date(event_name, date)
  end

  return historical_counts
end

#today(event_name) ⇒ Object

Return today’s count for an event



35
36
37
# File 'lib/microstat.rb', line 35

def today(event_name)
  @redis.get "#{@key_space}:#{event_name}:#{timestamp_today}"
end

#total(event_name) ⇒ Object

Return the total count for an event



56
57
58
# File 'lib/microstat.rb', line 56

def total(event_name)
  @redis.get "#{@key_space}:#{event_name}:total"
end

#track(event_name) ⇒ Object

Increments a specific event’s count, returns the total



15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/microstat.rb', line 15

def track(event_name)
  # Add the event to the known event space
  @redis.sadd @key_space, event_name

  # Add today as one of the tracked dates for this event
  @redis.sadd "#{@key_space}:#{event_name}:dates", timestamp_today

  # Increment event count for the current date
  @redis.incr "#{@key_space}:#{event_name}:#{timestamp_today}"

  # Increvent total event count, return it
  @redis.incr "#{@key_space}:#{event_name}:total"
end