2010-01-04 07:52:30 +00:00
|
|
|
class Snippet
|
2009-05-07 18:13:27 +00:00
|
|
|
|
2011-04-13 10:19:51 +00:00
|
|
|
include Mongoid::Document
|
|
|
|
|
|
|
|
field :name, :index => true
|
|
|
|
field :full_name, :index => true
|
|
|
|
|
|
|
|
field :parent_id, :index => true
|
|
|
|
field :parent_name
|
|
|
|
|
|
|
|
field :content
|
|
|
|
|
|
|
|
before_validation :setup_default_value
|
|
|
|
validates_presence_of :name, :full_name, :parent_id
|
|
|
|
validates_uniqueness_of :name, :scope => :parent_id
|
|
|
|
|
|
|
|
referenced_in :parent, :class_name => "Item", :foreign_key => :parent_id
|
2010-01-18 08:23:33 +00:00
|
|
|
|
2011-04-13 10:19:51 +00:00
|
|
|
# Get an array of ancestors
|
|
|
|
def ancestors
|
|
|
|
node, nodes = self, []
|
|
|
|
nodes << node = node.parent while !node.parent.blank? rescue nil
|
|
|
|
nodes.reverse
|
|
|
|
end
|
|
|
|
|
|
|
|
def setup_default_value
|
|
|
|
# Set the parent value
|
|
|
|
self.parent_name = Item.find( self.parent_id ).name rescue nil
|
|
|
|
|
|
|
|
# Build the full_name from the ancestors array
|
|
|
|
full_node = self.ancestors.map{ |a| a.name }.push( self.name )
|
|
|
|
# Remove root node if not root
|
|
|
|
full_node.shift if full_node.size >= 2
|
|
|
|
self.full_name = full_node.join("/")
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|