Ruby
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Methods and Blocks
-
Section 4: Object-Oriented Ruby
-
Section 5: Metaprogramming
-
Section 6: Working with Data and Files
-
Section 7: Ruby Frameworks Overview
-
Section 8: Ecosystem and Testing
-
Section 9: Practical Projects
-
Section 10: Interview Practice
-
Section 11: Data Structures and Algorithms in Ruby
-
Section 12: More Practice Exercises
-
Section 13: Enumerable and Functional Style
-
Section 14: More OOP Practice
-
Section 15: More Testing
-
Section 16: Enumerable and Comparable Modules In Depth
-
Section 17: Ruby Standard Library: Core Utilities
-
Section 18: Ruby Standard Library: Data and Security
-
Section 19: Ruby Standard Library: CLI and Text
-
Section 20: Ruby Networking
-
Section 21: Ruby on Rails Deep Dive
-
Section 22: Ruby Metaprogramming Deep Dive
-
Section 23: Ruby Design Patterns
-
Section 24: Ruby Concurrency
-
Section 25: Ruby Testing Deep Dive
-
Section 26: Ruby Gems and Packaging
-
Section 27: Ruby Performance
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Rails API Development
-
Section 31: Rails Authentication and Authorization
-
Section 32: Rails Testing Deep Dive
-
Section 33: Rails Performance
-
Section 34: Rails Deployment
-
Section 35: Sinatra and Lightweight Ruby Web Apps
-
Section 36: More Ruby Language Deep Dive
-
Section 37: Ruby 3.x Modern Features
-
Section 38: More Data Structures in Ruby
-
Section 39: More Practical Projects
-
Section 40: Ruby Ecosystem Tools
-
Section 41: More Practice and Review
-
Section 42: Final Practice and Mastery
-
Section 43: Ruby Interview Deep Dive
-
Section 44: Ruby Background Processing Deep Dive
-
Section 45: Ruby GraphQL
-
Section 46: Ruby Object Model Deep Dive
-
Section 47: Ruby Hanami Framework Overview
-
Section 48: Ruby gRPC and Protocol Buffers
-
Section 49: Ruby Data Processing
-
Section 50: Ruby Search Integration
-
Section 51: Ruby File Upload and Media
-
Section 52: Ruby Email and Notifications
-
Section 53: Ruby Admin Panels
-
Section 54: Ruby Feature Flags and Experimentation
-
Section 55: Ruby Monitoring and Observability
-
Section 56: Ruby Docker and Deployment Deep Dive
-
Section 57: Ruby Security Deep Dive
-
Section 58: More Advanced Metaprogramming
-
Section 59: More Final Projects
95: The Observer Pattern with Ruby's Observable Module
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
UserAccountclass that includes theObservablemodule. It should haveusernameandemailattributes. - 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
WelcomeEmailServiceclass with anupdatemethod that prints:"Sending confirmation email to [new_email]..." - Create a
AuditLogServiceclass with anupdatemethod 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.
There are no comments for now.