orbit-basic/app/models/item.rb

66 lines
1.7 KiB
Ruby
Raw Normal View History

class Item
include MongoMapper::Document
key :_type, String
key :name, String, :required => true, :index => true
2010-02-05 09:18:57 +00:00
key :full_name, String, :required => true, :index => true
2010-02-22 07:27:11 +00:00
2010-02-05 08:53:52 +00:00
key :parent_id, ObjectId, :index => true
2010-01-18 07:52:52 +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-02-22 07:27:11 +00:00
validates_format_of :name, :with => /^[0-9a-zA-Z\-_]+$/
2010-02-05 09:18:57 +00:00
validates_uniqueness_of :name, :scope => :parent_id
2010-01-18 07:52:52 +00:00
belongs_to :parent, :class_name => "Item", :foreign_key => :parent_id
2010-02-05 08:53:52 +00:00
many :children, :class_name => "Item", :foreign_key => :parent_id, :dependent => :destroy
before_validation :setup_default_value
2010-02-22 07:27:11 +00:00
2010-02-22 09:09:39 +00:00
attr_accessor :parent_name
2010-02-22 07:27:11 +00:00
def parent_name
2010-02-22 09:09:39 +00:00
@parent_name || self.parent.name
2010-02-22 07:27:11 +00:00
end
def self.find_by_name(item_name)
2010-03-01 08:18:28 +00:00
Item.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-02-05 09:18:57 +00:00
def url
urls = ancestors.map{ |a| a.name } << self.name
urls.delete("root")
"/#{urls.join("/")}"
end
protected
2010-02-05 08:53:52 +00:00
def setup_default_value
if self.position.blank?
max_page = Page.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-02-11 08:46:20 +00:00
end
full_node = self.ancestors.map{ |a| a.name }.push( self.name )
full_node.shift if full_node.size >= 2
self.full_name = full_node.join("/")
end
end