$: << File.dirname(__FILE__)
require "connect"
require "logger"
require "rubygems"
require_gem "activerecord"

require "./nested_set.rb"

#ActiveRecord::Base.logger = Logger.new(STDOUT)

#START:model
class Category < ActiveRecord::Base
  acts_as_nested_set  
end
#END:model

Category.delete_all

#START:setup

def add_child(parent, name)
  child = Category.create(:name => name)
  parent.add_child(child) || fail("Impossible d'ajouter #{name}")
  child
end

root        = Category.create(:name => "Livres")
fiction     = add_child(root, "Fiction")
non_fiction = add_child(root, "Non Fiction")

              add_child(non_fiction, "Science")
              add_child(non_fiction, "Histoire")
computers   = add_child(non_fiction, "Informatique")
              add_child(computers,   "Logiciel")
              add_child(computers,   "Matériel")

              add_child(fiction,     "Mystère")
              add_child(fiction,     "Roman")
              add_child(fiction,     "Science Fiction")
#END:setup

def display_children(list)
  puts list.map {|child| child.name + "[#{child.id}]" }.join(", ")
end

#START:demo
display_children(root.direct_children)         # Fiction, Non Fiction

display_children(non_fiction.direct_children)  #Science[129], Histoire[130], Informatique[131]
display_children(non_fiction.all_children)     #Roman[135], Science Fiction[136]
display_children(non_fiction.full_set)         #Roman[135], Science Fiction[136], Non Fiction[128], Science[129]
#END:demo
