Design Patterns in Ruby | OBSERVER

rubyhub.io
2 min readSep 23, 2023

A behavioral design pattern that aims to create a subscription method to notify multiple objects of events in an observed object.

Problem

Our app has several different subscription plans. Every time a User changes their subscription plan, we want to notify some company teams about that change.

Photo by freestocks on Unsplash

Solution

Let’s create our user who will have a name and the type of subscription plan.

class User
attr_reader :name, :plan

def initialize(name:, plan:)
@name = name
@plan = plan
end
end

john_doe = User.new(name: 'John Doe', plan: 'Standard')

And also create a Team class.

class Team
attr_reader :name

def initialize(name)
@name = name
end
end

finance = Team.new('Finance')
support = Team.new('Support')

To create an Observer pattern, we need to add several methods to the observed class to be able to manage it from the outside,

class User
attr_reader :name, :plan, :observers

def initialize(name:, plan:)
@name = name
@plan = plan
@observers = [] # Store all observers in array
end

# After plan is changed we want to notify all observers
def plan=(plan)
@plan = plan

notify_observers
end

# Adding observers
def…

--

--

rubyhub.io

[🔴 100% Follow-Back 🔴] I'm Full Stack Developer with 5-years of experience working with Ruby on Rails, trying to share my knowledge with others.