Sha256: dc5093f674edf525e82a62e748997d84ec36219124b275b0ec9914cb3b963144

Contents?: true

Size: 1.07 KB

Versions: 6

Compression:

Stored size: 1.07 KB

Contents

module Parentry
  module ClassMethods
    def parentry(options = {})
      self.parentry_strategy = options.fetch(:strategy, 'ltree').to_s
      self.parentry_column = options.fetch(:parentry_column, 'parentry')
      self.depth_offset = options.fetch(:depth_offset, 0)
      self.cache_depth = options.fetch(:cache_depth, false)
      self.touch_ancestors = options.fetch(:touch, false)

      include Strategy::Ltree if parentry_strategy == 'ltree'
      include Strategy::Array if parentry_strategy == 'array'
    end

    def arrange(options = {})
      scope =
        if (order = options.delete(:order))
          self.base_class.order_by_parentry.order(order)
        else
          self.base_class.order_by_parentry
        end

      scope.where(options).each_with_object(Hash.new { |h, k| h[k] = {} }) do |node, memo|
        insert_node = node.ancestor_ids.reduce(memo) do |subtree, ancestor_id|
          match = subtree.find { |parent, _children| parent.id == ancestor_id }
          match ? match[1] : subtree
        end
        insert_node[node] = {}
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
parentry-1.3.0 lib/parentry/class_methods.rb
parentry-1.2.0 lib/parentry/class_methods.rb
parentry-1.1.0 lib/parentry/class_methods.rb
parentry-0.5.0 lib/parentry/class_methods.rb
parentry-1.0.1 lib/parentry/class_methods.rb
parentry-1.0.0 lib/parentry/class_methods.rb