Module: Elasticsearch::Model::Extensions::OuterDocumentUpdating::ClassMethods::AssociationTraversal

Defined in:
lib/elasticsearch/model/extensions/outer_document_updating.rb

Class Method Summary collapse

Class Method Details

.shortest_path(from:, to:, visited_classes: nil) ⇒ Object



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# 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