Module: MiniTree::Utils::ClassMethods

Defined in:
lib/mini_tree/utils.rb

Instance Method Summary collapse

Instance Method Details

#ancestors(id) ⇒ Object



49
50
51
52
53
54
# File 'lib/mini_tree/utils.rb', line 49

def ancestors(id)
  parent_id = find(id).parent_id
  return [id] if parent_id == 0

  ancestors(parent_id) << id
end

#create_item(id, legend) ⇒ Object



37
38
39
# File 'lib/mini_tree/utils.rb', line 37

def create_item(id, legend)
  create! id:, legend:, parent_id: 0, position: id, kind: "leaf"
end

#destroy_item(id) ⇒ Object



41
42
43
# File 'lib/mini_tree/utils.rb', line 41

def destroy_item(id)
  where(id:).delete_all
end

#flatObject

used by tests



57
58
59
60
61
62
63
# File 'lib/mini_tree/utils.rb', line 57

def flat
  res = []
  sorted.each { |item|
    res << [item.id, item.parent_id]
  }
  res
end


65
66
67
68
69
70
# File 'lib/mini_tree/utils.rb', line 65

def print
  puts "*** #{name}.all ***"
  sorted.each_with_index { |item, index|
    puts "#{index}: #{item}"
  }
end

#refreshObject



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/mini_tree/utils.rb', line 15

def refresh
  missing_cnt = delete_cnt = refresh_cnt = 0
  owner_class = Kernel.const_get(name[0..-5])
  owner_ids = owner_class.all.pluck(:id)
  ids = all.pluck(:id)

  (owner_ids - ids).each { |id|
    legend = owner_class.find_by(id:).legend
    create_item(id, legend)
    missing_cnt += 1
  }
  (ids - owner_ids).each { |id|
    destroy_item(id)
    delete_cnt += 1
  }
  (owner_ids & ids).each { |id|
    update_item(id, owner_class.find_by(id:).legend)
    refresh_cnt += 1
  }
  [missing_cnt, delete_cnt, refresh_cnt]
end

#sortedObject



72
73
74
# File 'lib/mini_tree/utils.rb', line 72

def sorted
  all.order(:position)
end

#update_item(id, legend) ⇒ Object



45
46
47
# File 'lib/mini_tree/utils.rb', line 45

def update_item(id, legend)
  find_by(id:).update!(legend:)
end