Skip to content

Instantly share code, notes, and snippets.

@JonKernPA
Created February 16, 2012 03:10
Show Gist options
  • Save JonKernPA/1841379 to your computer and use it in GitHub Desktop.
Save JonKernPA/1841379 to your computer and use it in GitHub Desktop.
Tree example in MongoMapper
class Node
include MongoMapper::Document
key :name
belongs_to :parent, :class_name => 'Node'
many :children, :class_name => 'Node'
def root?
parent.nil?
end
def branch?
children.each {|c| return true if c.leaf? }
false
end
def leaf?
self.children.empty?
end
def depth(d=1)
depth = d
depth += parent.depth(d) if parent
depth
end
def to_s(starting_here=true)
text = name
starting_depth = self.depth
starting_depth = 1 if starting_here
children.each do |c|
depth = c.depth(starting_depth)
spacer = " "*depth
text += "\n#{spacer}#{c.to_s(false)}"
end
text
end
def self.show_all
Node.where(:parent_id => nil).sort(:created_at).all.each do |n|
puts n
end
end
end
=begin
animals
fish
mammals
extinct
region
asia
japan
china
europe
france
=end
Node.destroy_all
root = Node.create(:name => "root")
animals = Node.create( :name => "animals", :parent => root )
fish = Node.create(:name => "fish", :parent => animals)
mammals = Node.create(:name => "mammals", :parent => animals)
horse = Node.create(:name => "horse", :parent => mammals)
dog = Node.create(:name => "dog", :parent => mammals)
human = Node.create(:name => "human", :parent => mammals)
mammals.children << [horse, dog, human]
mammals.save!
animals.children << [fish, mammals]
animals.save!
reptiles = Node.create(:name => "reptiles", :parent => root)
extinct = Node.create( :name => "extinct", :parent => root )
region = Node.create( :name => "region", :parent => root )
asia = Node.create( :name => "asia", :parent => region )
japan = Node.create(:name => "japan", :parent => asia)
china = Node.create(:name => "china", :parent => asia)
asia.children << [japan, china]
asia.save!
region.children << asia
region.save!
root.children << [animals, reptiles, extinct, region]
root.save!
Node.show_all
If you dump the above "code" into mmconsole, you should get something like this:
ruby-1.9.2-p180 :2651 > Node.show_all
root
extinct
animals
fish
mammals
human
horse
dog
reptiles
region
asia
japan
china
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment