Last active
December 11, 2015 05:58
-
-
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!
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
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!!" |
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 InheritanceSub < Subscriber | |
def some_method | |
#do some Thing.... | |
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 InheritanceSubB < Subscriber | |
def receive_notification notification | |
super "| SUbB | "+notification | |
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 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 |
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 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