EDIT/UPDATE: I created 2 scripts for it now: http://napprod.wordpress.com/2013/07/24/event/ & http://napprod.wordpress.com/2013/07/24/event-hook/
I tried to implement events in Ruby.
My event base class
Testing it:
Replacing the = to a += in a.on_foo + b.foo crashes.
Also "a.on_foo + b.method🙂foo)" is not really 'friendly' to code. I just want:
a.on_foo += b.fooa.on_foo -= b.foo"a.on_foo + b.method🙂foo), c.method🙂foo)" also crashes. But the + is implemented so it accepts multiple parameters.
I tried to implement events in Ruby.
My event base class
class Event def initialize @listeners = [] end def +(*methods) methods.each { |method| @listeners << method if [email protected]?(method) } end def -(*methods) methods.each { |method| @listeners.reject!{|m| m == method} } end def clear @listeners = [] end def start(*params) @listeners.each{|m| m.call(*params)} end def to_s return "obj id: '#{self.object_id}' methods: #{@listeners}" endend
module Debug class Foo1 attr_accessor 😮n_foo def initialize @on_foo = Event.new() end def foo p 'foo1' @on_foo.start end end class Foo2 def initialize # do nothing end def foo p 'foo2' end end class Foo3 def initialize # do nothing end def foo p 'foo3' end end def self.test1 a = Foo1.new() b = Foo2.new() c = Foo3.new() a.on_foo + b.method🙂foo) a.on_foo + b.method🙂foo) a.on_foo + c.method🙂foo)#~ a.on_foo + b.method🙂foo), c.method🙂foo) a.foo #if you see printed: #"foo1" #"foo2" #"foo3" # then it works. p '-----' a.on_foo - b.method🙂foo) a.foo #if you see printed: #"foo1" #"foo3" # then it works. end self.test1end
Also "a.on_foo + b.method🙂foo)" is not really 'friendly' to code. I just want:
a.on_foo += b.fooa.on_foo -= b.foo"a.on_foo + b.method🙂foo), c.method🙂foo)" also crashes. But the + is implemented so it accepts multiple parameters.