diff --git a/app/models/group.rb b/app/models/group.rb index 4e12aed..316295e 100644 --- a/app/models/group.rb +++ b/app/models/group.rb @@ -7,5 +7,7 @@ class Group < ApplicationRecord has_many :children, class_name: 'Group', foreign_key: 'parent_id' belongs_to :parent, class_name: 'Group', optional: true + scope :roots, -> { where(parent_id: nil) } + has_many :guests end diff --git a/app/services/affinity_groups_hierarchy.rb b/app/services/affinity_groups_hierarchy.rb index 7c87ed9..48db7fc 100644 --- a/app/services/affinity_groups_hierarchy.rb +++ b/app/services/affinity_groups_hierarchy.rb @@ -6,6 +6,12 @@ class AffinityGroupsHierarchy < Array def initialize super @references = {} + + Group.roots.each do |group| + self << group.id + + hydrate(group) + end end def find(name) @@ -26,4 +32,14 @@ class AffinityGroupsHierarchy < Array @references[name_a].distance_to_common_ancestor(@references[name_b]) end + + private + + def hydrate(group) + group.children.each do |child| + register_child(group.id, child.id) + + hydrate(child) + end + end end diff --git a/config/initializers/affinity_groups.rb b/config/initializers/affinity_groups.rb deleted file mode 100644 index 1415e8d..0000000 --- a/config/initializers/affinity_groups.rb +++ /dev/null @@ -1,41 +0,0 @@ -# Copyright (C) 2024 Manuel Bustillo - -require_relative '../../app/services/affinity_groups_hierarchy' - -hierarchy = AffinityGroupsHierarchy.instance - -hierarchy << 'guests_a' -hierarchy << 'guests_b' -hierarchy << 'common_guests' - -hierarchy.register_child('guests_a', 'family_a') -hierarchy.register_child('family_a', 'close_family_a') -hierarchy.register_child('family_a', 'cousins_a') -hierarchy.register_child('family_a', 'relatives_a') - -hierarchy.register_child('guests_a', 'work_a') -hierarchy.register_child('work_a', 'besties_work_a') - -hierarchy.register_child('guests_a', 'friends_a') -hierarchy.register_child('friends_a', 'college_friends_a') -hierarchy.register_child('friends_a', 'high_school_friends_a') -hierarchy.register_child('friends_a', 'childhood_friends_a') - -hierarchy.register_child('guests_a', 'sports_a') -hierarchy.register_child('sports_a', 'basket_team_a') -hierarchy.register_child('sports_a', 'football_team_a') - -hierarchy.register_child('guests_b', 'family_b') -hierarchy.register_child('family_b', 'close_family_b') -hierarchy.register_child('family_b', 'cousins_b') -hierarchy.register_child('family_b', 'relatives_b') - -hierarchy.register_child('guests_b', 'work_b') -hierarchy.register_child('work_b', 'besties_work_b') - -hierarchy.register_child('guests_b', 'friends_b') -hierarchy.register_child('friends_b', 'college_friends_b') -hierarchy.register_child('friends_b', 'high_school_friends_b') -hierarchy.register_child('friends_b', 'childhood_friends_b') - -hierarchy.register_child('common_guests', 'dance_club') \ No newline at end of file