Search code examples
ruby-on-railsrubydesign-patternsobject-graph

Pattern for recursively updating two related object graphs


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


Solution

  • 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.

    module Visitable
      def accept visitor
        child_vals = []
        if respond_to?(:children)
          children.each do |child|
            child_vals << child.accept(visitor)
          end
        end
        val = visitor.visit(self)
        child_vals.any? ? val + child_vals : val
      end
    end
    
    class Survey
      attr_accessor :name, :children
    
      include Visitable
    
    end
    
    class Category
      attr_accessor :name, :children
    
      include Visitable
    
    end
    
    class Question
      attr_accessor :name
      include Visitable
    end
    
    s = Survey.new
    s.name = 's1'
    c = Category.new
    c.name = 'c1'
    c2 = Category.new
    c2.name = 'c2'
    q = Question.new
    q.name = 'q1'
    q2 = Question.new
    q2.name = 'q2'
    
    c.children = [q]
    c2.children = [q2]
    s.children = [c,c2]
    
    class ReturnVisitor
      def visit obj
        obj.name
      end
    end
    
    s.accept(ReturnVistor.new)
    -> ['s1', ['c1', ['q1'], ['c2', ['q2']]]]
    
    # "poorly implemented lisp"?