Module: DataMapper::Is::Tree::ClassMethods
Included Modules
An extension to DataMapper to easily allow the creation of tree structures from your DataMapper models. This requires a foreign key property for your model, which by default would be called :parent_id.
Example:
class Category
include DataMapper::Resource
include DataMapper::Is::Tree
property :id, Integer
property :parent_id, Integer
property :name, String
is_a_tree :order => "name"
end
root
+- child
+- grandchild1
+- grandchild2
root = Category.create("name" => "root")
child = root.children.create("name" => "child")
grandchild1 = child1.children.create("name" => "grandchild1")
grandchild2 = child2.children.create("name" => "grandchild2")
root.parent # => nil
child.parent # => root
root.children # => [child]
root.children.first.children.first # => grandchild1
Category.first_root # => root
Category.roots # => [root]
The following instance methods are added:
- children - Returns all nodes with the current node as their parent, in the order specified by :order ([grandchild1, grandchild2] when called on child)
- parent - Returns the node referenced by the foreign key (:parent_id by default) (root when called on child)
- siblings - Returns all the children of the parent, excluding the current node ([grandchild2] when called on grandchild1)
- generation - Returns all the children of the parent, including the current node ( [grandchild1, grandchild2] when called on grandchild1)
- ancestors - Returns all the ancestors of the current node ([root, child1] when called on grandchild2)
- root - Returns the root of the current node (root when called on grandchild2)
| Author: | Timothy Bennett (http://lanaer.com) |
Public Visibility
Public Instance Method Summary
| #is_a_tree(options = {}) #can_has_tree |
Configuration options are:. |
|---|
Public Instance Methods Included from DataMapper::Is::Tree::InstanceMethods
Public Instance Method Details
is_a_tree
public
is_a_tree(options = {})
Also known as: can_has_tree
Configuration options are:
- child_key - specifies the column name to use for tracking of the tree (default: parent_id)
[View source]
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
# File 'dm-more/dm-is-tree/lib/dm-is-tree/is/tree.rb', line 61 def is_a_tree(options = {}) configuration = { :child_key => :parent_id } configuration.update(options) if Hash === options many_to_one :parent, :class_name => name, :child_key => [ configuration[:child_key] ] has n, :children, :class_name => name, :child_key => [ configuration[:child_key] ] include DataMapper::Is::Tree::InstanceMethods class_eval "def self.roots\nall :\#{configuration[:child_key]} => nil, :order => \#{configuration[:order].inspect}\nend\n\ndef self.first_root\nfirst :\#{configuration[:child_key]} => nil, :order => \#{configuration[:order].inspect}\nend\n", __FILE__, __LINE__ class << self alias_method :root, :first_root # for people used to the ActiveRecord acts_as_tree end end