Ruby On Rails Interview Questions and Answers

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

Ans.

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: