Created
April 5, 2011 19:26
-
-
Save blowmage/904325 to your computer and use it in GitHub Desktop.
Quick example on using a local hash to hold event callbacks.
This file contains 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
class Foo | |
def start | |
# Do something important here | |
perform :start | |
end | |
def finish | |
perform :finish | |
# Clean up stuff here | |
end | |
# Add a new callback to the event queue | |
def on event | |
queue[event] << Proc.new | |
end | |
private | |
def queue | |
@queue ||= Hash.new { |h, k| h[k] = [] unless h.key? k } | |
end | |
def perform event, *args | |
queue[event].each do |p| | |
p.call args if p.respond_to? :call | |
end | |
end | |
end | |
# Create a new object | |
foo = Foo.new | |
# Register new callbacks on events | |
foo.on :start do | |
puts 'Starting!' | |
end | |
foo.on :finish do | |
puts 'So done!' | |
end | |
# Use the object as you normally would | |
foo.start | |
foo.finish | |
########################################## | |
# And we can have fun with state | |
class Bar | |
attr_accessor :name | |
def log | |
puts "Logging #{@name}" | |
end | |
end | |
bar = Bar.new | |
bar.name = 'FOO' | |
foo.on :finish do | |
bar.log | |
end | |
foo.finish | |
# Change the objects name and the callback uses it | |
bar.name = 'bar' | |
foo.finish |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment