Created
July 28, 2010 21:18
-
-
Save frsyuki/496335 to your computer and use it in GitHub Desktop.
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 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