Class: EventDelegate

Inherits:
Object
  • Object
show all
Defined in:
lib/events.rb

Overview

Stores observers for a single event. This is used for the observer (publish/subscribe) model.

Examples:

Adding an event to a class

class MyClass
  event :foo
  ...
end

Subscribing to an event

class MyClass
  event :foo
  ...
end

def Listener
  def call(sender, *args)
    puts "Foo occurred from #{sender} and sent #{args}"
  end
end

listener = Listener.new
subject  = MyClass.new
subject.event << listener

Shorthand listener

class MyClass
  event :foo
  ...
end

subject = MyClass.new
subject.foo do |sender, *args|
  puts 'Got notified!'
end

Triggering an event

class MyClass
  event :foo
  ...
  def do_something
    ...
    @foo.notify(args)
    ...
  end
end

Instance Method Summary collapse

Constructor Details

#initialize(owner, event_name) ⇒ EventDelegate

Creates the delegate.


50
51
52
53
54
55
# File 'lib/events.rb', line 50

def initialize(owner, event_name)
  @owner           = owner
  @event_name      = event_name
  @listeners       = []
  @listeners_mutex = Mutex.new
end

Instance Method Details

#<<(observer) ⇒ self

Note:

Make sure to unsubscribe from the event before the observer is destroyed.

Adds a new observer to the event.


61
62
63
64
65
66
67
68
69
70
# File 'lib/events.rb', line 61

def <<(observer)
  fail ArgumentError if observer.nil?
  fail ArgumentError unless observer.respond_to?(:call)

  @listeners_mutex.synchronize do
    @listeners << observer
  end

  self # Return self for chaining.
end

#notify(*args) ⇒ nil

Notifies all of the observers that the event has occurred. This method should only be called by the event owner.


86
87
88
89
90
91
92
# File 'lib/events.rb', line 86

def notify(*args)
  @listeners_mutex.synchronize do
    @listeners.each do |listener|
      listener.call(@owner, *args)
    end
  end
end

#remove(observer) ⇒ nil

Removes an existing observer from the event. The observer will no longer receive notifications about the event.


76
77
78
79
80
# File 'lib/events.rb', line 76

def remove(observer)
  @listeners_mutex.synchronize do
    @listeners.delete(observer)
  end
end

#to_sString

Gets the string representation of the event.


96
97
98
# File 'lib/events.rb', line 96

def to_s
  "<Event:#{@event_name} on #{@owner}>"
end