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



144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/elasticsearch/model/extensions/outer_document_updating.rb', line 144

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