Last active
August 29, 2015 14:24
-
-
Save darrencauthon/54050a11404fbb0aba73 to your computer and use it in GitHub Desktop.
open-closed
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 EventSubscriber | |
def self.inherited subscriber | |
@subscribers ||= [] | |
@subscribers << subscriber | |
end | |
def self.all | |
@subscribers ||= [] | |
end | |
def self.subscribers_for event | |
all.select { |s| s.subscribe? event } | |
.map { |s| s.new } | |
end | |
def self.publish event | |
subscribers_for(event).each { |s| s.execute event } | |
end | |
def execute event | |
# do something, or initiate a new job | |
end | |
end |
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 SendAnEmailForNewAccounts < EventSubscriber | |
def self.subscribe? event | |
event.type == 'new account' | |
end | |
def execute event | |
account = Account.find event.account_id | |
EmailSender.send_email_for account | |
end | |
end |
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 DestroyRobots | |
def self.subscribe? event | |
event.type == 'robot appeared' | |
end | |
def execute event | |
robot = Robot.find event.robot_id | |
RobotSmasher.smash robot | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment