Skip to content
Browse files

More doco.

  • Loading branch information...
1 parent 88260e0 commit 38955bc3f6e5ac6431bdaa853542b861e6ceba64 @mdub committed Apr 6, 2010
Showing with 65 additions and 4 deletions.
  1. +65 −4 README.rdoc
View
69 README.rdoc
@@ -3,10 +3,71 @@
Arboreal is yet another extension to ActiveRecord to support tree-shaped
data structures.
-Internally, Arboreal maintains a computed "ancestry_string" column, which
-caches the path from the root of a tree to each node, allowing efficient
-retrieval of both ancestors and descendants.
-
Arboreal surfaces relationships within the tree like +children+,
+ancestors+, +descendants+, and +siblings+ as scopes, so that additional
filtering/pagination can be performed.
+
+== Getting started
+
+First, install the "arboreal" gem, and add it to your Rails project's <tt>config/environment.rb</tt>.
+
+Next, you'll need a migration to add an +ancestry_string+ column, and index thereupon:
+
+ class MakeThingsArboreal < ActiveRecord::Migration
+
+ def self.up
+ add_column "things", "ancestry_string", :string
+ add_index "things", ["ancestry_string"]
+ Thing.rebuild_ancestry
+ end
+
+ def self.down
+ remove_index "things", ["ancestry_string"]
+ remove_column "things", "ancestry_string"
+ end
+
+ end
+
+This assumes that the table concerned already has a +parent_id+ column; if not, add that too (type +integer+, with a supporting index).
+
+Finally, you can declare you model arboreal:
+
+ class Thing < ActiveRecord::Base
+
+ acts_arboreal
+
+ # .. etc etc ...
+
+ end
+
+== Navigating the tree
+
+Arboreal adds the relationships you'd expect:
+
+* <tt>parent</tt>
+* <tt>children</tt>
+
+In addition, it provides the following handy methods on each tree-node:
+
+* <tt>ancestors</tt>
+* <tt>descendants</tt>
+* <tt>subtree</tt> (the node itself, plus descendants)
+* <tt>siblings</tt>
+* <tt>root</tt> (the topmost ancestor)
+
+The first four return scopes, to which additional filtering, ordering or limits may be applied.
+
+At the class-level:
+
+* <tt>roots</tt> is a named-scope returning all the nodes without parents
+* <tt>rebuild_ancestry</tt> rebuilds the ancestry cache, as described below
+
+== Rebuilding the ancestry cache
+
+Internally, Arboreal uses the +ancestry_string+ column to cache the path down the tree to each node (or more correctly, it's parent. This technique - a variant of "path enumeration" or "materialized paths" - allows efficient retrieval of both ancestors and descendants.
+
+It's conceivable that the computed ancestry-string values may get out of whack, particularly if changes are made directly to the database. If you suspect corruption, you can restore sanity using <tt>rebuild_ancestry</tt>, e.g
+
+ Thing.rebuild_ancestry
+
+The ancestry rebuild is implemented in SQL to leverage the underlying DBMS, and so is pretty efficient, even on large trees.

0 comments on commit 38955bc

Please sign in to comment.
Something went wrong with that request. Please try again.