Share This Article
The State Pattern in Ruby is a widely used design pattern that allows an object to change its behavior based on its internal state.
An everyday use case for the state pattern is a simple state machine.
For example, you could use the state pattern to implement a simple text editor with different modes (e.g., insert, delete, etc.).
A separate state object would represent each mode, and the text editor object would delegate the actual editing operations to the active state object.
The State Pattern in action
Let’s see how we could implement a simple text editor using the state pattern in ruby.
First, let’s define the base State
class.
class State
def insert_character(character)
raise NotImplementedError
end
end
Next, let’s define the InsertState
class, which represents the insert mode.
class InsertState < State
def insert_character(character)
puts "Inserting character #{character}"
end
end
Finally, let’s define the TextEditor
class, which delegates the editing operations to the active state object.
class TextEditor
def initialize
@state = InsertState.new
end
def insert_character(character)
@state.insert_character(character)
end
def set_state(state)
@state = state
end
end
Now we can create a new TextEditor
object and insert some characters.
editor = TextEditor.new
editor.insert_character("h")
editor.insert_character("e")
editor.insert_character("l")
editor.insert_character("l")
editor.insert_character("o")
# => Inserting character h
# => Inserting character e
# => Inserting character l
# => Inserting character l
# => Inserting character o
We can also change the state of the text editor, for example, to delete mode.
class DeleteState < State
def insert_character(character)
puts "Deleting character #{character}"
end
end
editor = TextEditor.new
editor.set_state(DeleteState.new)
editor.insert_character("h")
editor.insert_character("e")
# => Deleting character h
# => Deleting character e
A state pattern is a powerful tool that can make your code more flexible and easier to maintain.
It’s also one of the most commonly used patterns in the Ruby on Rails framework.
If you want to learn more about the state pattern, I recommend reading the following resources:
- Design Patterns in Ruby
- Design Patterns: Elements of Reusable Object-Oriented Software
- Ruby State Machine