Class: Meangirls::GCounter

Inherits:
Counter show all
Defined in:
lib/meangirls/g_counter.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Counter

#-, #===, #to_i

Methods inherited from CRDT

merge, #to_json

Constructor Details

#initialize(hash = nil) ⇒ GCounter

Returns a new instance of GCounter.



3
4
5
6
7
8
9
10
# File 'lib/meangirls/g_counter.rb', line 3

def initialize(hash = nil)
  @e = {}

  if hash
    raise ArgumentError, 'hash must contain e' unless hash['e']
    @e = hash['e']
  end
end

Instance Attribute Details

#eObject

Returns the value of attribute e.



2
3
4
# File 'lib/meangirls/g_counter.rb', line 2

def e
  @e
end

Instance Method Details

#+(delta) ⇒ Object

Adds delta to this counter, using the current Meangirls node ID.



41
42
43
# File 'lib/meangirls/g_counter.rb', line 41

def +(delta)
  increment Meangirls.node, delta
end

#==(other) ⇒ Object

Strict equality: all actor counts match.



13
14
15
16
# File 'lib/meangirls/g_counter.rb', line 13

def ==(other)
  other.kind_of? self.class and
  @e == other.e
end

#as_jsonObject



18
19
20
21
22
23
# File 'lib/meangirls/g_counter.rb', line 18

def as_json
  {
    'type' => type,
    'e' => @e
  }
end

#cloneObject



45
46
47
48
# File 'lib/meangirls/g_counter.rb', line 45

def clone
  c = super
  c.e = @e.clone
end

#float?Boolean

Are any sums floating-point?

Returns:

  • (Boolean)


51
52
53
54
55
# File 'lib/meangirls/g_counter.rb', line 51

def float?
  @e.any? do |k, v|
    v.is_a? Float
  end
end

#increment(node = 1, delta = 1) ⇒ Object

Adds delta to this counter, as tracked by node. Returns self.



26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/meangirls/g_counter.rb', line 26

def increment(node = 1, delta = 1)
  if delta < 0
    raise ArgumentError, "Can't decrement a GCounter"
  end

  if @e[node]
    @e[node] += delta
  else
    @e[node] = delta
  end

  self
end

#merge(other) ⇒ Object

Merge with another GCounter and return the merged copy.



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/meangirls/g_counter.rb', line 58

def merge(other)
  unless other.kind_of? self.class
    raise ArgumentErrornew, "other must be a #{self.class}"
  end

  copy = clone
  @e.each do |k, v|
    if existing = copy.e[k]
      copy.e[k] = v if v > existing
    else
      copy.e[k] = v
    end
  end

  copy
end

#to_fObject



75
76
77
# File 'lib/meangirls/g_counter.rb', line 75

def to_f
  @e.values.inject(&:+) || 0.0
end

#typeObject



79
80
81
# File 'lib/meangirls/g_counter.rb', line 79

def type
  'g-counter'
end