Design Patterns in Ruby | STATE

rubyhub.io
2 min readNov 10, 2022

--

“State is a behavioral design pattern that allows an object to change its behavior when its internal state changes.”

As the name suggests, this pattern helps us work with the states of a given object. For today’s example, let’s take the states that orders in a restaurant go through. Our order will go through 4 states:

  • New
  • In Progress
  • Ready
  • Received
Photo by Daniel Bradley on Unsplash

New

The first state appears when we create a new order. At this point, we will be able to perform two actions:

  • pay for the order
  • check order status

In Progress

This condition appears just after paying. In this state, we can only:

  • check order status

Ready

A state that says our order is ready for pickup. At this point, we can take two actions:

  • check order status
  • take the order

Received

The last state appears after receiving the order. At this point, we can:

  • check order status
  • rate the order

Code Example

We’ll first create a State class that implements all the methods we want to use on the Order class. Each of these methods will raise an error.

Having the main State class, we are able to create subclasses that will represent a particular State and implement only those methods that we want to use in a given state.

We have already created specific State classes, so now we can create our Order class. This class will contain all the methods we need, but in fact, they will be executed according to a specific state.

The order created in this way allows the Order to use only those methods that are allowed in a given State.

More reading

--

--

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.