Class: Elected::Stats

Inherits:
Object show all
Defined in:
lib/elected/stats.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*names) ⇒ Stats

Returns a new instance of Stats.



9
10
11
12
# File 'lib/elected/stats.rb', line 9

def initialize(*names)
  @counters = Concurrent::Hash.new
  names.map { |x| get_or_set_counter x }
end

Instance Attribute Details

#countersObject (readonly)

Returns the value of attribute counters.



7
8
9
# File 'lib/elected/stats.rb', line 7

def counters
  @counters
end

Instance Method Details

#count(name) ⇒ Object



14
15
16
# File 'lib/elected/stats.rb', line 14

def count(name)
  get_or_set_counter(name).sum
end

#increment(name, value = 1) ⇒ Object



18
19
20
21
# File 'lib/elected/stats.rb', line 18

def increment(name, value = 1)
  get_or_set_counter(name).add value
  count name
end

#to_hashObject



23
24
25
# File 'lib/elected/stats.rb', line 23

def to_hash
  @counters.keys.sort.each_with_object({}) { |k, h| h[k] = count k }
end

#to_sObject Also known as: inspect



27
28
29
# File 'lib/elected/stats.rb', line 27

def to_s
  %{#<#{self.class.name} #{to_hash.map { |k, v| "#{k}=#{v}" }.join(' ')}>}
end