Share This Article
Implementing the Interpreter pattern in Ruby is pretty straightforward. Let’s take a look at a simple example.
In this example, we have a simple DSL for creating a list of todos.
class Todo
def initialize(description)
@description = description
end
def to_s
"#{description}"
end
attr_reader :description
end
class TodoList
def initialize
@todos = []
end
def add_todo(todo)
@todos << todo
end
def to_s
@todos.join("\n")
end
end
class Parser
def initialize(todo_list, input)
@todo_list = todo_list
@input = input
end
def parse
@input.split("\n").each do |line|
todo = Todo.new(line)
@todo_list.add_todo(todo)
end
end
end
# usage
todo_list = TodoList.new
parser = Parser.new(todo_list, "buy milk\nclean house\npaint fence")
parser.parse
puts todo_list
You can see that the Parser
class is responsible for parsing the input string and creating the Todo
objects.
The TodoList
class is responsible for storing the Todo
objects.
And the Todo
class is a simple data object that represents a todo.
Implementing the Interpreter Pattern
The interpreter pattern is all about creating a language within your application.
In this example:
parser = Parser.new(todo_list, "buy milk\nclean house\npaint fence")
parser.parse
puts todo_list
The Parser
class is the interpreter.
The to-do list DSL is the language.
The buy milk\nclean house\npaint fence
string is the source code of our program.
The parser.parse
method is the interpreter that executed our program.
In this case, our program is pretty simple; it just creates a to-do list.
Another Example
Let’s say we want to create a simple calculator language.
# the source code of our program
input = "1 + 2 * 3"
# we need a class for our interpreter
class Calculator
# the interpreter method
def calculate(input)
# do the calculation here
end
end
# create an instance of the interpreter
calculator = Calculator.new
# execute the program
result = calculator.calculate(input)
puts result # => 7
If you have used a language like Ruby or JavaScript, you are already familiar with DSLs.
Most templating languages are, in fact, DSLs.
Summary
The interpreter pattern is a way to create your own language within your application.
You’ve learned how to implement the interpreter pattern in ruby in this article.
You’ve also seen a couple of examples of how this pattern can be used. ¡¡