Class: Peplum::Application::Services::SharedHash

Inherits:
Object
  • Object
show all
Defined in:
lib/peplum/application/services/shared_hash.rb

Constant Summary collapse

CONCURRENCY =
20

Instance Method Summary collapse

Constructor Details

#initializeSharedHash

Returns a new instance of SharedHash.



9
10
11
12
13
14
15
16
# File 'lib/peplum/application/services/shared_hash.rb', line 9

def initialize(*)
  super

  @hash = {}

  @on_set_cb    = {}
  @on_delete_cb = {}
end

Instance Method Details

#delete(k, broadcast = true, &block) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/peplum/application/services/shared_hash.rb', line 41

def delete( k, broadcast = true, &block )
  if !@hash.include? k
    block.call if block_given?
    return
  end

  @hash.delete( k )
  call_on_delete( k )

  if broadcast
    each_peer do |peer, iterator|
      peer.send( name ).delete( k, false ) { iterator.next }
    end
  end

  block.call if block_given?
  nil
end

#get(k) ⇒ Object



18
19
20
# File 'lib/peplum/application/services/shared_hash.rb', line 18

def get( k )
  @hash[k]
end

#on_delete(k, &block) ⇒ Object



64
65
66
# File 'lib/peplum/application/services/shared_hash.rb', line 64

def on_delete( k, &block )
  (@on_delete_cb ||= []) << block
end

#on_set(k, &block) ⇒ Object



60
61
62
# File 'lib/peplum/application/services/shared_hash.rb', line 60

def on_set( k, &block )
  (@on_set_cb[k] ||= []) << block
end

#set(k, v, broadcast = true, &block) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/peplum/application/services/shared_hash.rb', line 22

def set( k, v, broadcast = true, &block )
  if @hash[k] == v
    block.call if block_given?
    return
  end

  @hash[k] = v
  call_on_set( k, v )

  if broadcast
    each_peer do |peer, iterator|
      peer.send( name ).set( k, v, false ) { iterator.next }
    end
  end

  block.call if block_given?
  nil
end

#to_hObject



68
69
70
# File 'lib/peplum/application/services/shared_hash.rb', line 68

def to_h
  @hash.dup
end