Class: Para::Cloneable::IncludeTreeBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/para/cloneable/include_tree_builder.rb

Overview

This object acts as a service to compile a nested cloneable options hash to be provided to the ‘deep_clone` method from the `deep_cloneable` gem. It iterates over every reflections that must be included for a given model when it’s cloned, and creates a nested hash of :include and :except directives based on the tree that is created by nested ‘acts_as_cloneable` calls on the different models of the application

Example :

Given the following model structure :

  class Article < ApplicationRecord
    acts_as_cloneable :category, :comments, except: [:publication_date]

    belongs_to :category
    has_many :comments
  end

  class Category < ApplicationRecord
    acts_as_cloneable :category, except: [:articles_count]

    has_many :articles
  end

  class Comment < ApplicationRecord
    acts_as_cloneable :author

    belongs_to :article
    belongs_to :author
  end

  class Author < ApplicationRecord
    acts_as_cloneable except: [:email]

    has_many :articles
  end

The behavior would be :

  Para::Cloneable::IncludeTreeBuilder.new(article).build
  # => {
         include: [:category, { comments: :author }],
         except: [:publication_date, {
           category: [:articles_count],
           comments: { author: [:email] }
         }]
       }

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(resource) ⇒ IncludeTreeBuilder

Returns a new instance of IncludeTreeBuilder.



56
57
58
59
# File 'lib/para/cloneable/include_tree_builder.rb', line 56

def initialize(resource)
  @resource = resource
  @cloneable_options = resource.cloneable_options.deep_dup
end

Instance Attribute Details

#cloneable_optionsObject (readonly)

Returns the value of attribute cloneable_options.



54
55
56
# File 'lib/para/cloneable/include_tree_builder.rb', line 54

def cloneable_options
  @cloneable_options
end

#resourceObject (readonly)

Returns the value of attribute resource.



54
55
56
# File 'lib/para/cloneable/include_tree_builder.rb', line 54

def resource
  @resource
end

Instance Method Details

#buildObject



61
62
63
64
65
66
# File 'lib/para/cloneable/include_tree_builder.rb', line 61

def build
  options_tree = build_cloneable_options_tree(resource)
  exceptions = extract_exceptions_from(options_tree)
  inclusions = clean_options_tree(options_tree)
  cloneable_options.merge(include: inclusions, except: exceptions)
end