module Elasticsearch::Model::Extensions::OuterDocumentUpdating::ClassMethods::AssociationTraversal

Public Class Methods

shortest_path(from:, to:, visited_classes: nil) click to toggle source
# File lib/elasticsearch/model/extensions/outer_document_updating.rb, line 123
def shortest_path(from:, to:, visited_classes: nil)
  visited_classes ||= []
  current_class = from
  destination_class = to

  paths = []

  current_class.reflect_on_all_associations.each do |association_found|

    next if association_found.options[:polymorphic]

    key = association_found.name

    begin
      klass = association_found.class_name.constantize
    rescue => e
      warn "#{e.message} while reflecting #{current_class.name}\##{key}\n#{e.backtrace[0...1].join("\n")}"
      next
    end

    next if visited_classes.include? association_found.class_name

    if klass == destination_class
      return [key]
    else
      suffix_found = shortest_path(
        from: klass,
        to: destination_class,
        visited_classes: visited_classes.append(association_found.class_name)
      )

      if suffix_found
        paths << [key] + suffix_found
      end
    end
  end

  if paths.empty?
    nil
  else
    paths.min_by { |path| path.size }
  end
end