Imagine I have an object model:
A Blog has many Articles, and an Article has many Comments
Imagine also that I have two blogs, Blog A and Blog B.
Blog A - Article id 1 - Comment id 1 "fun stuff"
- Article id 2 - Comment id 2 "cool"
and
Blog B - Article id 3 - Comment id 3 "no fun"
I need to compare the object graph for Blog A and Blog B, and update Blog B based on the value of objects in Blog A.
In this case, Blog B should change Comment 3 to be “fun stuff”, and instantiate new objects with values identical to Article 2 and Comment 2.
Recursively walking the graph is the obvious solution, but the logic gets convoluted. I’d rather not re-invent the wheel…is there a pattern or process to do this?
I’m using Ruby/Rails
After reading more about the visitor pattern, I decided a Rubyish variant of it was the most appropriate approach to solving this problem.
The visitor pattern allows you to separate the algorithm for walking the hierarchy, from the code to execute on each node in the hierarchy. A more functional approach to this using map or inject/fold is possible…but as I want to reuse the operators, it seemed easier to break them into separate classes.
The hierarchy is implemented in each model, which should define a “children” method that returns children.
Below is my implementation, based off of various references, I may wrap it up into a gem.