Skip to content

Instantly share code, notes, and snippets.

@brianstorti
Created March 4, 2012 20:48
Show Gist options
  • Save brianstorti/1974728 to your computer and use it in GitHub Desktop.
Save brianstorti/1974728 to your computer and use it in GitHub Desktop.
Observer in ruby
module Subject
attr_reader :observers
def subscribe_observer(observer)
@observers ||= []
@observers << observer
end
def unsubscribe_observer(observer)
@observers.delete(observer)
end
def notify_observers(*args)
@observers.each do |observer|
observer.update(*args)
end
end
end
class WeatherData
include Subject
def some_action
puts "some action take place here"
notify_observers "some useful information "
end
end
module Observer
def initialize(subject)
@subject = subject
@subject.subscribe_observer(self)
end
def unsubscribe
@subject.unsubscribe_observer(self)
end
end
class FirstDisplay
include Observer
def update(info)
puts info + "from first display"
end
end
class SecondDisplay
include Observer
def update(info)
puts info + "from second display"
end
end
weather = WeatherData.new
first_display = FirstDisplay.new(weather)
second_display = SecondDisplay.new(weather)
weather.some_action
first_display.unsubscribe
weather.some_action
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment