Event handling

Hi,

Does ruby has some standard event handling functionality? I’ve searched
google and the “Programming Ruby book” but it appears there isn’t much
info on event handling, so maybe it is named differently in ruby?

Oke, I’ve implemented the following observer/listener program:

class Cow
def initialize
@listeners = Array.new
end

def add_listener(listener)
raise ArgumentError if !listener.respond_to?(:sound_event) &&
!listeners.include?(listener)
@listeners << listener
end

def remove_listener(listener)
@listeners.delete(listener)
end

def notify_listeners
for i in [email protected]
@listeners[i].sound_event(‘MHOEEEE’)
end
end

def be_happy
notify_listeners
end
end

class Program
def sound_event(value)
puts value
end

def start
cow = Cow.new
cow.add_listener(self)
cow.be_happy
end
end

Program.new.start

Is this an appropriate way of doing event handling in ruby?

This seems like a decent approach; maintaining a list of listeners and
notifying them. A few notes:
for i in [email protected]
@listeners[i].sound_event(‘MHOEEEE’)
end

Closures or blocks in ruby are perfect for this:
@listeners.each do |listener|
listener.sound_event ‘MHOEEEE’
end

to get cool eventing like:

@car.when :crashing do
jump_out
end
I recommend looking at Publisher:
http://rubyforge.org/projects/atomicobjectrb/

Hello,

You can also have listeners register blocks to certain events instead
of implementing a specific method like “sound_event”. That way you
publisher can be more decoupled from the listeners’ implementation.
Have a look at http://nutrun.com/weblog/event-registry/

Thanks,
George

Thanks, I’ll check both of the suggested techniques.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs