Module: AdvancedRelationshipManagement::PathToRoot

Extended by:
ActiveSupport::Concern
Defined in:
lib/advanced_relationship_management/path_to_root.rb

Instance Method Summary collapse

Instance Method Details

#path_to_root(format: :array, attribute: :id) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/advanced_relationship_management/path_to_root.rb', line 5

def path_to_root(format: :array, attribute: :id)
  path = []
  current_node = self
  while current_node
    path << current_node
    current_node = current_node.parent
  end
  path.reverse!
  
  case format
  when :array
    path
  when :symbolic
    path.map { |node| node.public_send(attribute) }.join(' -> ')
  when :json
    path.map { |node| { id: node.id, attribute => node.public_send(attribute) } }.to_json
  when :html
    path.map { |node| "<a href='/users/#{node.id}'>#{node.public_send(attribute)}</a>" }.join(' > ')
  when :reverse_symbolic
    path.map { |node| node.public_send(attribute) }.reverse.join(' -> ')
  when :nested_hash
    path.inject(nil) { |acc, node| { id: node.id, attribute => node.public_send(attribute), parent: acc } }
  else
    raise ArgumentError, "Unsupported format: #{format}"
  end
end