Skip to content
Tutorials Center
My learning

Topics

Lesson 89 of 134 ยท Standard Library

Observable, Singleton and Standard Patterns

Learn the Singleton module, the Observable pattern and Comparable in Ruby with runnable examples, test-friendly alternatives and the pitfalls of global state.

Some designs come up so often that Ruby's standard library ships a small module for them. Singleton guarantees that a class has exactly one instance. Observable lets an object announce "something changed" to anyone who is listening. Comparable turns one method, <=>, into a full set of comparison operators. Together they cover three classic patterns: one shared object, one-to-many notification and ordering.

These modules are tiny, and it is just as important to know when not to use them. A singleton is global state in a nicer coat, and an observer you forget to remove keeps objects alive. In this lesson you use each module, break it on purpose to see the real error messages, and learn the plainer alternatives that most experienced Rubyists prefer.

The Singleton module

Sometimes there should be only one of something: the application configuration, a connection registry, a clock. With include Singleton Ruby makes new private and adds a class method instance that creates the object the first time you ask and returns the same object afterwards.

Ruby One instance, many callers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The initialize message prints only once, even though instance ran three times. Creation is lazy: nothing exists until the first call. Both variables name the same object, so a change made through one is visible through the other.

require "singleton" is needed because the module lives in the standard library, not in the core. It is a default library, so it works in any Ruby installation without extra setup.

What the module forbids

Because the whole point is "exactly one", Ruby blocks every other way to get a second object: new, allocate, dup and clone.

Ruby Trying to make a second one (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

dup and clone raise TypeError with the message can't dup instance of singleton Registry (and can't clone instance of singleton Registry). The last line ends the program with private method 'new' called for class Registry (NoMethodError). Anybody who reads that message learns immediately that they should call Registry.instance.

What is really stored

You can look under the hood. The class keeps its instance in a class-level instance variable, and a mutex protects the lazy creation, so two threads that call instance at the same moment still get the same object.

Ruby Peeking inside, and thread safety

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The two variables are @singleton__instance__ and @singleton__mutex__. Eight threads asked for the instance and all saw one object (1 distinct id). Singleton sits in the ancestors of the class, together with an internal module of instance methods that disables copying. For more on threads, see Threads.

Inheritance and testing

Each subclass of a singleton class gets its own instance, and the parent's instance is separate. That surprises people who expect one object for the whole family.

The bigger practical problem is testing. A singleton keeps its state between tests, so test A can leave data behind that breaks test B. The usual cure is to reset the stored instance in a setup or teardown hook. That uses an implementation detail, so do it only in tests:

Ruby Subclasses and resetting for tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The subclass starts with an empty store and is a different object. After the reset the cache is empty again.

A singleton is global state. Every part of the program can reach it, so a bug in one place shows up far away, tests depend on each other, and you cannot easily run two configurations side by side. Treat Singleton as a last resort for things that are truly unique and cheap to reason about.

Plainer alternatives

Ruby offers simpler ways to get "one of something" without the module:

  • A module with module-level state. A module cannot be instantiated, so there is nothing to forbid. This is often the lightest solution.
  • A constant holding an object. SETTINGS = Settings.new.freeze makes the one instance explicit, and you can still pass it as an argument.
  • Dependency injection. Create the object once at startup and hand it to the code that needs it. Tests then pass a different object. This is the most flexible and the easiest to test.
Ruby A module as a singleton, and passing the object in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The second half shows why injection helps: the Greeter does not care where the "clock" comes from, so a test can supply any lambda it likes. Compare this with the singleton-class mechanics in Singleton Methods and the Singleton Class, which is a different idea despite the similar name: that lesson is about methods attached to one object, while this module is about one instance of a class.

The observer pattern with Observable

In the observer pattern an object (the subject) keeps a list of other objects (the observers) and tells them when something happens. A stock ticker publishes prices; a chart, an alert and a logger all want to know. The ticker does not need to know what they do with the information.

Observable lives in the observer library, which became a bundled gem in Ruby 3.4. On the runner here require "observer" works. In a real project that uses Bundler, add gem "observer" to your Gemfile, otherwise newer Ruby versions may refuse to load it.

Include Observable in the subject. An observer is any object that responds to update. The subject must call changed before notify_observers, because notifications are sent only when the "changed" flag is set.

Ruby A stock ticker with two observers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Each publish call passes the symbol and the price to every observer's update method, in the order they were added. After delete_observer only the alert bell is left.

The changed flag

changed is not decoration. notify_observers does nothing unless the subject is marked as changed, and it clears the flag after it has notified everyone. That lets a subject decide whether something is worth announcing.

Ruby Notify only when it matters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The reading of 20 is silent because changed was never called. The reading of 35 is announced, and afterwards changed? is false again. You can also call changed(false) to withdraw a pending change, and changed? to check the flag.

Observers are checked when you add them

add_observer verifies right away that the object responds to the method it will be called with. A mistake shows up at registration time and not in the middle of a notification.

Ruby An observer without update (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The program ends with observer does not respond to `update' (NoMethodError), reported from inside the gem's own add_observer method, with your line (from main.rb:8:in '<main>') in the trace. Notice the old-style backtick in that message; it is the library's own text and is not related to the quote style Ruby uses for its own messages.

Using a different method, or a lambda

add_observer takes an optional second argument naming the method to call. That means an observer can be a plain lambda, a method object or any object with a convenient method name:

Ruby Observers that are lambdas

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Procs and lambdas respond to call, so naming :call works without writing a class. This is already very close to the callback style shown below.

Pitfalls of Observable

  • A failing observer stops the others. notify_observers calls them in a plain loop. If the second of three raises an error, the third is never told, and the error reaches the caller of notify_observers. Rescue inside your update methods when observers should be independent.
  • Observers keep observers alive. The subject holds strong references. An observer you never remove cannot be garbage collected as long as the subject lives. Always delete_observer when an observer's job is done.
  • Order is registration order, but you should not rely on it for correctness.
  • No thread safety guarantee. Adding and removing observers while another thread notifies is not protected. Use a mutex (Mutex, Queue and ConditionVariable) if you share a subject across threads.
  • Everything is synchronous. A slow observer slows down whoever called notify_observers.

A callback-based alternative

Many Ruby programs skip the library and keep a list of blocks. The code is shorter, the "observer" can be any block, and there is no update convention to remember.

Ruby A tiny event emitter with blocks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Several events share one emitter, each with its own list of handlers, and emitting an event nobody listens to is simply a no-op. This is the design behind most GUI toolkits and the Node.js EventEmitter. See Blocks and Procs and Lambdas for the building blocks.

Comparable: ordering from one method

You met Comparable in Comparable; here is the idea as a pattern. A class defines <=> (the spaceship operator), includes Comparable, and gets <, <=, >, >=, ==, between? and clamp for free. Because Enumerable collections call <=> for sorting, sort, min and max then work as well.

Ruby Money that knows its order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The important detail is the return nil unless other.is_a?(Money) line. Returning nil from <=> means "these cannot be compared". The operators then behave sensibly: == answers false, while < raises ArgumentError with the message comparison of Money with 5 failed. If you skipped the check, comparing with an integer would crash inside your own method with a confusing NoMethodError.

Which one should you use?

Need Reach for Think twice because
Exactly one shared object A module with state, a frozen constant, or an injected object; Singleton if you want Ruby to enforce it Global state makes tests depend on each other
One-to-many notification Observable for a quick job, a block-based emitter for most others Unremoved observers leak, errors stop the loop
Ordering and ranges Comparable with a careful <=> <=> must return nil for foreign objects

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does include Singleton do to a class?

    Singleton makes new private (and blocks dup and clone), then provides Class.instance, which creates the object lazily and returns the same object on every call.
  2. 2. A subscriber is registered with add_observer, but its notify_observers call prints nothing. What is the most likely cause?

    notify_observers does nothing unless the subject has been marked changed. It also resets the flag after notifying.
  3. 3. What happens to the remaining observers when one observer raises an error inside update?

    notify_observers is a simple loop. An exception stops it, so later observers are never told. Rescue inside update if observers must be independent.
  4. 4. Why should a <=> method in a Comparable class return nil for objects of another class?

    A nil result means 'not comparable'. Comparable then answers false for == and raises ArgumentError (comparison of X with Y failed) for the ordering operators.
  5. 5. Which is usually the most test-friendly way to share one object across a program?

    Passing the object in (dependency injection) lets tests supply a different one and avoids hidden global state.

Summary

  • include Singleton makes new private, blocks dup and clone, and gives you Class.instance, created lazily and thread-safely.
  • A singleton is global state: tests share it, subclasses get their own instance, and a module, a frozen constant or an injected object is often simpler.
  • Observable (a bundled gem; add gem "observer" in a real project) needs changed before notify_observers, checks the observer at add_observer time, and calls observers in registration order.
  • A raising observer stops the notification loop, and observers you never remove are never garbage collected.
  • A hash of event names to blocks is a small, popular alternative to Observable.
  • Comparable needs a careful <=> that returns nil for foreign objects.

Next: Threads