class Salus::ObserversSet
Loosely based on code from github.com/ruby-concurrency/concurrent-ruby/
Public Class Methods
new()
click to toggle source
# File lib/salus/thread/observable.rb, line 6 def initialize synchronize { @observers = {} } end
Public Instance Methods
add(observer=nil, func=:update, &block)
click to toggle source
# File lib/salus/thread/observable.rb, line 10 def add(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, 'cannot provide both an observer and a block' end if block observer = block func = :call end synchronize do new_observers = @observers.dup new_observers[observer] = func @observers = new_observers observer end end
count()
click to toggle source
# File lib/salus/thread/observable.rb, line 60 def count synchronize { @observers.count } end
delete(observer)
click to toggle source
# File lib/salus/thread/observable.rb, line 30 def delete(observer) synchronize do new_observers = @observers.dup new_observers.delete(observer) @observers = new_observers observer end end
delete_all()
click to toggle source
# File lib/salus/thread/observable.rb, line 39 def delete_all synchronize { @observers = {} } self end
notify(*args, &block)
click to toggle source
# File lib/salus/thread/observable.rb, line 44 def notify(*args, &block) obs = synchronize { @observers } notify_to(obs, *args, &block) self end
notify_and_delete(*args, &block)
click to toggle source
# File lib/salus/thread/observable.rb, line 50 def notify_and_delete(*args, &block) old = synchronize do old = @observers @observers = {} old end notify_to(old, *args, &block) self end
Private Instance Methods
notify_to(obs, *args) { || ... }
click to toggle source
# File lib/salus/thread/observable.rb, line 65 def notify_to(obs, *args, &block) raise ArgumentError.new('cannot give arguments and a block') if block_given? && !args.empty? obs.each do |observer, function| args = yield if block_given? observer.send(function, *args) end end