|
The Visitor Pattern
Creating an AST containing Ruby objects is one thing, but generating an actual SQL statement is another. How does Arel do this? Why is building up an AST useful in any way?
Using a very elegant algorithm, Arel iterates over the nodes in the AST and concatenates different SQL fragments to form a complete SQL statement. This algorithm is an example of the “visitor pattern.” The term visitor pattern simply means that some object, function or other piece of code is executed once for each node in some data structure, such as an array, linked list or tree.
To understand this a bit better, let’s take our example AST and follow Arel’s visitor as it traverses the tree, starting at the SelectStatement root node:
|
|