Skip to Content
Course content

95: The Observer Pattern with Ruby's Observable Module

Click on the "Edit" button in the top corner of the screen to edit your slide content.

You've probably encountered situations where one part of your app needs to react whenever something happens in another part. Your first instinct might be to just call a method on that second object directly. But as your app grows, that creates a "spiderweb" of dependencies where every class knows too much about every other class. That's where the Observer pattern comes in.

Why not just call the method directly on the other object?

Sure, you could. If you have a StockPrice class, you could just call @email_service.send_alert inside your price setter. But what happens when your boss tells you that you also need to update a live dashboard, log the change to a database, and send a Slack notification? Now your StockPrice class is bloated with references to five different services.

I prefer the Observer pattern because it decouples the "subject" (the thing being watched) from the "observers" (the things reacting). The subject doesn't need to know who is listening or what they do with the information; it just broadcasts that a change happened. This makes your code much easier to test and extend because you can add or remove listeners without ever touching the core business logic of the subject.

How do I actually set this up using the Observable module?

Ruby makes this pretty straightforward with the Observable module. You include it in your subject class, and then you can add any object as an observer as long as that object implements an update method. That's the "contract" the pattern relies on.

require 'observer'

class StockPrice
  include Observable

  attr_reader :symbol, :price

  def initialize(symbol, price)
    @symbol = symbol
    @price = price
  end

  def update_price(new_price)
    @price = new_price
    changed # This is crucial!
    notify_observers(@symbol, @price)
  end
end

class EmailAlert
  def update(symbol, price)
    puts "Email sent: #{symbol} is now $#{price}!"
  end
end

class DashboardUI
  def update(symbol, price)
    puts "Updating UI: #{symbol} display changed to $#{price}."
  end
end

# Wiring it up
apple_stock = StockPrice.new("AAPL", 150)
email_notifier = EmailAlert.new
dashboard = DashboardUI.new

apple_stock.add_observer(email_notifier)
apple_stock.add_observer(dashboard)

apple_stock.update_price(155)
# Output:
# Email sent: AAPL is now $155!
# Updating UI: AAPL display changed to $155.

Wait, why isn't my observer actually getting notified?

This is the most common "gotcha" I see with the Observable module. If you call notify_observers but forget to call changed first, nothing happens. No error, no warning—just silence.

I know it feels redundant, but there's a logical reason for it. In a real-world scenario, you might have a setter that is called frequently, but the value doesn't always actually change. For example, if you set the stock price to 150 and it was already 150, you probably don't want to trigger a dozen emails and UI refreshes. By requiring a manual call to changed, Ruby lets you decide exactly when the state has shifted enough to warrant a notification.

def update_price(new_price)
  return if @price == new_price # Don't do anything if the value is the same
  
  @price = new_price
  changed 
  notify_observers(@symbol, @price)
end

Can I pass specific data to the observers?

Absolutely. As you saw in the example above, any arguments you pass to notify_observers are forwarded directly to the update method of every registered observer. I usually recommend passing the most relevant data points or the subject object itself if the observer needs to query more complex state from the subject.

Just remember that since you're designing the update method signature in your observer classes, you need to make sure they match what the subject is sending, or you'll hit an ArgumentError.




📋 Practical Task

Exercise: Building a User Account Event Dispatcher

You are building a system that handles user account updates. You need to ensure that whenever a user's email address is changed, several independent systems are notified without the UserAccount class needing to know the details of those systems.

Requirements:

  • Create a UserAccount class that includes the Observable module. It should have username and email attributes.
  • Implement a method update_email(new_email) that updates the email and notifies observers only if the email is actually different from the current one.
  • Create a WelcomeEmailService class with an update method that prints: "Sending confirmation email to [new_email]..."
  • Create a AuditLogService class with an update method that prints: "Log: User [username] changed their email to [new_email]."
  • Instantiate the classes, register both services as observers to a user account, and trigger an email update to verify that both services respond.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.