Skip to content

Instantly share code, notes, and snippets.

@jreisstudio
Last active December 11, 2015 05:58
Show Gist options
  • Save jreisstudio/4555385 to your computer and use it in GitHub Desktop.
Save jreisstudio/4555385 to your computer and use it in GitHub Desktop.
A Ruby observer implementation...the idea is to use that in my Arduino Tank Monitor!
require "./Subscriber"
require "./InheritanceSub"
require "./InheritanceSubB"
require"./ObserverRuby"
observer = ObserverRuby.new
sub1 = Subscriber.new
sub2 = Subscriber.new
sub3 = InheritanceSub.new
sub4 = InheritanceSubB.new
observer.add_subscribers sub1,sub2,sub3,sub4
observer.publish "First publish....done!"
puts
puts
observer.remove_subscribers sub1
observer.publish " Second Publish....done!!"
class InheritanceSub < Subscriber
def some_method
#do some Thing....
end
end
class InheritanceSubB < Subscriber
def receive_notification notification
super "| SUbB | "+notification
end
end
class ObserverRuby
$subscriberList=[]
def subscriberList
$subscriberList
end
def add_subscribers *subscribers
subscribers.each{|subscriber|
if subscriber.respond_to?('receive_notification')
self.subscriberList<< subscriber
end
}
end
def remove_subscribers *subscribers
subscribers.each{|subscriber|
self.subscriberList.delete subscriber
}
end
def publish notification
self.subscriberList.each{|subscriber|
subscriber.receive_notification notification
}
end
end
class Subscriber
def receive_notification notification
puts notification
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment