Created
March 31, 2011 03:16
-
-
Save caryhaynie/895761 to your computer and use it in GitHub Desktop.
Simple Event Handling in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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