Created
September 16, 2016 18:48
-
-
Save danbernier/9b8cf8f66834918b153814a4f963e576 to your computer and use it in GitHub Desktop.
Detect cycles in a collection of `acts_as_tree` objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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