Sha256: 874807ccc8ae2233c4f16577351b16443d6b868a0995c8de3e999ecafb75c50f
Contents?: true
Size: 1.95 KB
Versions: 1
Compression:
Stored size: 1.95 KB
Contents
module MptTree class Node < ActiveRecord::Base belongs_to :tree, :polymorphic=>true before_create :create_root_node before_destroy :delete_node def insert(node) Node.transaction do Node.where(:tree_type=>tree_type).where("rgt >= :rgt", :rgt=>self.rgt).update_all("rgt=rgt+2") Node.where(:tree_type=>tree_type).where("lft > :rgt", :rgt=>self.rgt).update_all("lft=lft+2") node.create_mpt_tree_node(:lft => self.rgt, :rgt=>self.rgt+1) end end def tree Node.where(:tree_type=>tree_type).where("lft > ? AND rgt < ?", self.lft, self.rgt ).order('lft').map(&:tree_id) end def ancestors Node.where(:tree_type=>tree_type).where("lft < ? AND rgt > ?", self.lft, self.rgt).order('lft').map(&:tree_id) end def leaf? self.rgt == self.lft+1 end def level(parent=nil) sql = "lft < :self_lft AND rgt > :self_rgt " arguments = {:self_lft=>self.lft, :self_rgt=>self.rgt} if parent sql+= "AND lft >= :parent_lft AND rgt <= :parent_rgt" arguments[:parent_lft]=parent.mpt_tree_node.lft; arguments[:parent_rgt]=parent.mpt_tree_node.rgt; end Node.where(:tree_type=>tree_type).where(sql, arguments).count(:id) end def self.root_created?(tree_type) !Node.where(:tree_type=>tree_type).empty? end private def delete_node allow_delete = false raise "the node you are trying to delete is not a leaf node!" unless(self.leaf?) Node.where(:tree_type=>tree_type).where("lft > ?", self.rgt).update_all("lft = lft-2") Node.where(:tree_type=>tree_type).where("rgt > ?", self.rgt).update_all("rgt = rgt-2") allow_delete = true allow_delete end def create_root_node unless Node.root_created?(tree_type) self.lft, self.rgt = 1, 2 else raise "root node is already created" if self.lft == nil || self.rgt == nil end end end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
mpt_tree-0.0.7 | app/models/mpt_tree/node.rb |