Skip to content

Instantly share code, notes, and snippets.

@frsyuki
Created July 28, 2010 21:18
Show Gist options
  • Save frsyuki/496335 to your computer and use it in GitHub Desktop.
Save frsyuki/496335 to your computer and use it in GitHub Desktop.
class EventBus
def initialize
@map = {} # kind => [block]
end
def signal(kind, *args)
if blocks = @map[kind]
blocks.each {|block|
block.call(*args) rescue nil
}
end
end
def call(kind, *args)
if blocks = @map[kind]
blocks.first.call(*args)
else
raise "slot not connected"
end
end
def connect(kind, &block)
if blocks = @map[kind]
blocks << block
else
@map[kind] = [block]
end
end
end
if $0 == __FILE__
$ebus = EventBus.new
class StorageService
def initialize
@db = {}
$ebus.connect(:set, &method(:set))
$ebus.connect(:get, &method(:get))
end
def set(key, value)
@db[key] = value
end
def get(key)
@db[key]
end
end
storage = StorageService.new
$ebus.signal(:set, "key", "value")
p $ebus.call(:get, "key") #=> value
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment