Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Ruby%20On%20Rails%20Interview%20Questions%20and%20Answers

Question: How will you implement Observer Pattern in Ruby on Rails?
Answer:

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 
	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
Is it helpful? Yes No

Most helpful rated by users:

©2024 WithoutBook