akicho8/tree_support

TreeSupport.records_to_tree(records).to_s_tree is not working.

storm9acl opened this issue · 2 comments

This is the error I'm having.

test.rb:31:in "<main>": undefined method "to_s_tree" for #<Array:0x00000000036eee40> (NoMethodError)

This is my code:

require "tree_support"

class Node
  attr_accessor :name, :parent, :children

  def initialize(name = nil, &block)
    @name = name
    @children = []
    if block_given?
      instance_eval(&block)
    end
  end

  def add(*args, &block)
    tap do
      children << self.class.new(*args, &block).tap { |v| v.parent = self }
    end
  end
end

Node.include(TreeSupport::Stringify)

records = [
  {key: :a, parent: nil},
  {key: :b, parent: :a},
  {key: :c, parent: :a},
  {key: :d, parent: :a}
]

puts TreeSupport.records_to_tree(records).to_s_tree

Thank you for using.
The above problem was partly document wrong.
If you add the root_key option as follows, to_s_tree moves since the top element can be specified.
Since the Node class has it inside, you do not have to define it yourself.

require "tree_support"

records = [
  {key: :a, parent: nil},
  {key: :b, parent: :a},
  {key: :c, parent: :a},
]

# Add root_key option
puts TreeSupport.records_to_tree(records, root_key: :root).to_s_tree
# >> root
# >> └─a
# >>     ├─b
# >>     ├─c
# >>     └─d

# If you do not specify root_key, you must know yourself that the first record is a parent
puts TreeSupport.records_to_tree(records).first.to_s_tree
# >> a
# >> ├─b
# >> ├─c
# >> └─d

Oh, I see, thank you very much for the explanation!