2010-01-14 10:30:53 +00:00
|
|
|
class Item
|
|
|
|
|
|
|
|
include MongoMapper::Document
|
|
|
|
|
|
|
|
key :_type, String
|
|
|
|
|
|
|
|
key :name, String, :required => true, :index => true
|
|
|
|
|
2010-01-18 07:52:52 +00:00
|
|
|
key :parent_name, String, :index => true
|
2010-01-18 08:23:33 +00:00
|
|
|
key :parent_id, String, :index => true
|
2010-01-18 07:52:52 +00:00
|
|
|
|
2010-01-14 10:30:53 +00:00
|
|
|
key_i18n :title, String, :required => true
|
|
|
|
|
|
|
|
key :position, Integer, :required => true
|
|
|
|
key :is_published, Boolean, :required => true, :default => true, :index => true
|
2010-01-18 07:52:52 +00:00
|
|
|
|
2010-01-28 09:30:35 +00:00
|
|
|
validates_format_of :name, :with => /^[a-zA-Z-_]+$/
|
2010-01-18 07:52:52 +00:00
|
|
|
belongs_to :parent, :class_name => "Item", :foreign_key => :parent_id
|
|
|
|
many :children, :class_name => "Item", :foreign_key => :parent_id
|
2010-01-14 10:30:53 +00:00
|
|
|
|
|
|
|
before_validation :setup_default_value
|
|
|
|
|
|
|
|
def self.find_by_name(item_name)
|
|
|
|
Item.find(:first, :conditions => { :name => item_name, :is_published => true })
|
|
|
|
end
|
2010-01-18 07:52:52 +00:00
|
|
|
|
|
|
|
def ancestors
|
|
|
|
node, nodes = self, []
|
|
|
|
nodes << node = node.parent while !node.parent.blank?
|
|
|
|
nodes.reverse
|
|
|
|
end
|
|
|
|
|
2010-01-14 10:30:53 +00:00
|
|
|
protected
|
|
|
|
|
|
|
|
def setup_default_value
|
|
|
|
if self.position.blank?
|
|
|
|
max_page = Page.find(:last, :order => 'position')
|
|
|
|
self.position = (max_page)? max_page.position.to_i + 1 : 1
|
|
|
|
end
|
|
|
|
|
2010-01-18 07:52:52 +00:00
|
|
|
if self.parent_name.blank?
|
|
|
|
self.parent_name = nil
|
|
|
|
self.parent_id = nil
|
|
|
|
else
|
|
|
|
self.parent_id = Item.find_by_name( self.parent_name ).id
|
2010-01-14 10:30:53 +00:00
|
|
|
end
|
2010-01-28 09:42:55 +00:00
|
|
|
|
|
|
|
if self.layout_name
|
|
|
|
self.layout_id = Layout.find_by_name( self.layout_name ).id
|
|
|
|
end
|
|
|
|
|
2010-01-14 10:30:53 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
end
|