Class: Hanover::GCounter
- Inherits:
-
Object
- Object
- Hanover::GCounter
- Defined in:
- lib/hanover/g_counter.rb
Instance Attribute Summary collapse
-
#counts ⇒ Object
Returns the value of attribute counts.
Class Method Summary collapse
Instance Method Summary collapse
- #increment ⇒ Object
-
#initialize ⇒ GCounter
constructor
A new instance of GCounter.
- #merge(other) ⇒ Object
- #tag ⇒ Object
- #to_json ⇒ Object
- #value ⇒ Object
Constructor Details
#initialize ⇒ GCounter
Returns a new instance of GCounter.
4 5 6 |
# File 'lib/hanover/g_counter.rb', line 4 def initialize self.counts = Hash.new{0} end |
Instance Attribute Details
#counts ⇒ Object
Returns the value of attribute counts.
3 4 5 |
# File 'lib/hanover/g_counter.rb', line 3 def counts @counts end |
Class Method Details
.from_json(json) ⇒ Object
15 16 17 18 19 20 21 22 23 |
# File 'lib/hanover/g_counter.rb', line 15 def self.from_json(json) # don't symbolize keys h = JSON.parse json raise ArgumentError.new 'unexpected type field in JSON' unless h['type'] == 'GCounter' gc = new gc.counts = h['c'] return gc end |
Instance Method Details
#increment ⇒ Object
25 26 27 |
# File 'lib/hanover/g_counter.rb', line 25 def increment counts[tag] += 1 end |
#merge(other) ⇒ Object
33 34 35 36 37 38 39 40 41 |
# File 'lib/hanover/g_counter.rb', line 33 def merge(other) new_keys = Set.new new_keys.merge counts.keys new_keys.merge other.counts.keys new_keys.each do |k| counts[k] = [counts[k], other.counts[k]].max end end |
#tag ⇒ Object
43 44 45 46 47 48 49 50 51 52 |
# File 'lib/hanover/g_counter.rb', line 43 def tag radix = 36 [ object_id.to_s(radix), Process.uid.to_s(radix), Process.gid.to_s(radix), Process.pid.to_s(radix), `hostname`.strip ].join end |
#to_json ⇒ Object
8 9 10 11 12 13 |
# File 'lib/hanover/g_counter.rb', line 8 def to_json { type: 'GCounter', c: counts }.to_json end |
#value ⇒ Object
29 30 31 |
# File 'lib/hanover/g_counter.rb', line 29 def value counts.values.inject(0, &:+) end |