Ruby On Rails Interview Questions and Answers
Question: How will you implement Observer Pattern in Ruby on Rails?Answer:Lets review first what an observer pattern is all about. The observer pattern (sometimes known as publish/subscribe) is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems. You might have used them in other programming languages as listener objects. You use them whenever a button is clicked on the screen and a method gets called automatically. As in the case of the singleton pattern, the observer pattern is also implemented by mixing in a module. In the Ruby implementation, the notifying class mixes in the Observable module, which provides the methods for managing the associated observer objects. And, the observers must implement the update method to receive notifications. Heres an example. Say you want to send an SMS alert to users if a company stock drops then you can do something like this: require "observer"
require "observer"
class Ticker # Periodically fetch a stock price
include Observable
attr_accessor :price
def initialize symbol, price
@symbol = symbol
@price = price
end
def run
lastPrice = nil
loop do
@price = @price+Random.rand(11)
print "Current price: #{price}n"
if @price != lastPrice
changed # notify observers
lastPrice = @price
notify_observers(Time.now, @price)
end
end
end
end
class Warner
def initialize ticker
ticker.add_observer(self) # all warners are observers
end
end
class SMSAlert < Warner
def update time, price # callback for observer
print "--- #{time.to_s}: SMS Alert for price: #{price}n"
end
end
class EmailAlert < Warner
def update time, price # callback for observer
print "+++ #{time.to_s}: Email Alert Price changed to #{price}n"
end
end |
Save For Revision
Bookmark this item, mark it difficult, or place it in a revision set.
Log in to save bookmarks, difficult questions, and revision sets.
Most helpful rated by users:
- What is Ruby On Rails?
- Why Ruby on Rails?
- Explain how (almost) everything is an object in Ruby.
- What are Gems and which are some of your favorites?
- How would you declare and use a constructor in Ruby?