Skip to content

Instantly share code, notes, and snippets.

@darrencauthon
Last active August 29, 2015 14:24
Show Gist options
  • Save darrencauthon/54050a11404fbb0aba73 to your computer and use it in GitHub Desktop.
Save darrencauthon/54050a11404fbb0aba73 to your computer and use it in GitHub Desktop.
open-closed
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
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
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