Exams Attended

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Ruby On Rails Interview Questions and Answers

Ques. How will you implement Observer Pattern in Ruby on Rails?

Letís 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.

Hereís 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 
	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) 
  class Warner
     def initialize ticker  
     ticker.add_observer(self)   # all warners are observers     
class SMSAlert < Warner     
   def update time, price       # callback for observer         
      print "--- #{time.to_s}: SMS Alert for price: #{price}n"     

class EmailAlert < Warner     
   def update time, price       # callback for observer         
      print "+++ #{time.to_s}: Email Alert Price changed to #{price}n"    
Is it helpful? Yes No

Most helpful rated by users:

©2022 WithoutBook