Skip to content

Instantly share code, notes, and snippets.

@danbernier
Created September 16, 2016 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danbernier/9b8cf8f66834918b153814a4f963e576 to your computer and use it in GitHub Desktop.
Save danbernier/9b8cf8f66834918b153814a4f963e576 to your computer and use it in GitHub Desktop.
Detect cycles in a collection of `acts_as_tree` objects
def has_cycle?(items) # hash: { id => parent_id, id => nil }
return false if items.size < 2
items = items.dup
items.keys.each do |starting_point|
visited_items = []
item = starting_point
while item.present?
return true if visited_items.include?(item)
visited_items << item
item = items[item]
end
end
return false
end
# Usage:
graph = Category.where(...).pluck(:id, :parent_id).to_h
has_cycle?(graph)
# Note: this works in-memory, so it's not suitable for huge collections.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment