Skip to content

Instantly share code, notes, and snippets.

@caryhaynie
Created March 31, 2011 03:16
Show Gist options
  • Select an option

  • Save caryhaynie/895761 to your computer and use it in GitHub Desktop.

Select an option

Save caryhaynie/895761 to your computer and use it in GitHub Desktop.
Simple Event Handling in Ruby
module Eventable
def def_event(evt_name)
#puts "creating a new event: #{evt_name}"
class_eval do
attr_reader "#{evt_name}_cb"
eval <<-END_EVAL
def on_#{evt_name}(&blk)
(@#{evt_name}_cb ||= []) << blk
nil
end
def emit_#{evt_name}(*args)
@#{evt_name}_cb.each do |cb|
# in ruby 1.8, there appears to be a bug re: arity retuning
# a correct value ( returns -1 when it should be 0 ).
# In ruby 1.9 this works correctly.
if cb.arity == args.length then
cb.call *args
end
end
nil
end
END_EVAL
end
nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment