Module | Sequel::Plugins::Tree |
In: |
lib/sequel/plugins/tree.rb
|
The Tree plugin adds additional associations and methods that allow you to treat a Model as a tree.
A column for holding the parent key is required and is :parent_id by default. This may be overridden by passing column name via :key.
Optionally, a column to control order of nodes returned can be specified by passing column name via :order.
If you pass true for the :single_root option, the class will ensure there is only ever one root in the tree.
Examples:
class Node < Sequel::Model plugin :tree end class Node < Sequel::Model plugin :tree, :key=>:parentid, :order=>:position end
Create parent and children associations. Any options specified are passed to both associations. You can also specify options to use for just the parent association using a :parent option, and options to use for just the children association using a :children option.
# File lib/sequel/plugins/tree.rb, line 30 30: def self.apply(model, opts=OPTS) 31: opts = opts.dup 32: opts[:class] = model 33: 34: model.instance_eval do 35: @parent_column = (opts[:key] ||= :parent_id) 36: @tree_order = opts[:order] 37: end 38: 39: par = opts.merge(opts.fetch(:parent, {})) 40: parent = par.fetch(:name, :parent) 41: 42: chi = opts.merge(opts.fetch(:children, {})) 43: children = chi.fetch(:name, :children) 44: 45: par[:reciprocal] = children 46: chi[:recripocal] = parent 47: 48: model.many_to_one parent, par 49: model.one_to_many children, chi 50: 51: model.plugin SingleRoot if opts[:single_root] 52: end