Class: Garcon::CopyOnWriteObserverSet

Inherits:
Object
  • Object
show all
Defined in:
lib/garcon/task/copy_on_write_observer_set.rb

Overview

A thread safe observer set implemented using copy-on-write approach: every time an observer is added or removed the whole internal data structure is duplicated and replaced with a new one.

Instance Method Summary collapse

Constructor Details

#initializeCopyOnWriteObserverSet



28
29
30
31
# File 'lib/garcon/task/copy_on_write_observer_set.rb', line 28

def initialize
  @mutex = Mutex.new
  @observers = {}
end

Instance Method Details

#add_observer(observer = nil, func = :update, &block) ⇒ Object

Adds an observer to this set. If a block is passed, the observer will be created by this method and no other params should be passed



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/garcon/task/copy_on_write_observer_set.rb', line 45

def add_observer(observer=nil, func=:update, &block)
  if observer.nil? && block.nil?
    raise ArgumentError, 'should pass observer as a first argument or block'
  elsif observer && block
    raise ArgumentError.new('cannot provide both an observer and a block')
  end

  if block
    observer = block
    func = :call
  end

  begin
    @mutex.lock
    new_observers = @observers.dup
    new_observers[observer] = func
    @observers = new_observers
    observer
  ensure
    @mutex.unlock
  end
end

#count_observersInteger



91
92
93
# File 'lib/garcon/task/copy_on_write_observer_set.rb', line 91

def count_observers
  observers.count
end

#delete_observer(observer) ⇒ Object



72
73
74
75
76
77
78
79
80
# File 'lib/garcon/task/copy_on_write_observer_set.rb', line 72

def delete_observer(observer)
  @mutex.lock
  new_observers = @observers.dup
  new_observers.delete(observer)
  @observers = new_observers
  observer
ensure
  @mutex.unlock
end

#delete_observersCopyOnWriteObserverSet

Deletes all observers



84
85
86
87
# File 'lib/garcon/task/copy_on_write_observer_set.rb', line 84

def delete_observers
  self.observers = {}
  self
end

#notify_and_delete_observers(*args, &block) ⇒ CopyOnWriteObserverSet

Notifies all registered observers with optional args and deletes them.



112
113
114
115
116
# File 'lib/garcon/task/copy_on_write_observer_set.rb', line 112

def notify_and_delete_observers(*args, &block)
  old = clear_observers_and_return_old
  notify_to(old, *args, &block)
  self
end

#notify_observers(*args, &block) ⇒ CopyOnWriteObserverSet

Notifies all registered observers with optional args



101
102
103
104
# File 'lib/garcon/task/copy_on_write_observer_set.rb', line 101

def notify_observers(*args, &block)
  notify_to(observers, *args, &block)
  self
end