Class: Counterman

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/counterman.rb,
lib/counterman/time_span.rb,
lib/counterman/time_events.rb,
lib/counterman/time_spans/day.rb,
lib/counterman/hash_operations.rb,
lib/counterman/time_spans/hour.rb,
lib/counterman/time_spans/week.rb,
lib/counterman/time_spans/year.rb,
lib/counterman/time_spans/month.rb,
lib/counterman/time_spans/minute.rb

Overview

Public: Counterman core classs

Defined Under Namespace

Modules: HashOperations, TimeEvents Classes: Day, Hour, Minute, Month, TimeSpan, Week, Year

Constant Summary collapse

PREFIX =
"counterman"

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Counterman

Public: Initializes Counterman

options - An options hash to change how Counterman behaves


31
32
33
34
35
36
37
38
# File 'lib/counterman.rb', line 31

def initialize(options = {})

  self.options = default_options.merge!(options)
  self.redis   = options[:redis] || Redis.new

  spans = self.options.fetch(:time_spans, %w[year month week day hour minute])
  @time_spans = generate_spans(spans)
end

Class Attribute Details

.optionsObject

Returns the value of attribute options.



12
13
14
# File 'lib/counterman.rb', line 12

def options
  @options
end

.redisObject

Returns the value of attribute redis.



12
13
14
# File 'lib/counterman.rb', line 12

def redis
  @redis
end

Class Method Details

.safe(&block) ⇒ Object

Public: Prevents a fatal error if the options are set to silent



16
17
18
19
20
# File 'lib/counterman.rb', line 16

def safe(&block)
  yield if block
rescue Redis::BaseError => e
  raise e unless options[:silent]
end

Instance Method Details

#eventsObject

Public: List all the events given the counterman namespace



61
62
63
64
# File 'lib/counterman.rb', line 61

def events
  keys = safe { redis.keys([PREFIX, "*", "????"].join("_")) }
  keys.map { |key| key.split("_")[1] }
end

#reset_allObject

Public: Resets all the used keys



68
69
70
71
# File 'lib/counterman.rb', line 68

def reset_all
  keys = safe { redis.keys([PREFIX, "*"].join("_")) }
  safe { redis.del(keys) } if keys.any?
end

#track(event_name, ids, time = Time.now.utc) ⇒ Object

Public: Marks an id to a given event on a given time

event_name - The event name to be searched for
ids        - The ids to be tracked

Examples

analytics = Counterman.new
analytics.track("login", 1)
analytics.track("login", [2, 3, 4])


52
53
54
55
56
57
# File 'lib/counterman.rb', line 52

def track(event_name, ids, time = Time.now.utc)
  event_time = time.kind_of?(Time) ? time : Time.parse(time.to_s)
  time_events = TimeEvents.start(@time_spans, event_name, event_time)

  track_events(time_events, Array(ids))
end