Orbit/app/models/item.rb

89 lines
2.4 KiB
Ruby
Raw Normal View History

class Item
include Mongoid::Document
2011-03-08 09:25:46 +00:00
include Mongoid::Timestamps
field :name, :index => true
field :full_name, :index => true
field :position, :type => Integer
2012-02-17 06:54:11 +00:00
field :is_published, :type => Boolean, :default => false, :index => true
field :enabled_for, :type => Array, :default => nil
field :menu_enabled_for, :type => Array, :default => nil
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\-_]+$/
validates :name, :exclusion => { :in => LIST[:forbidden_item_names] }
2010-02-05 09:18:57 +00:00
validates_uniqueness_of :name, :scope => :parent_id
2012-02-17 06:54:11 +00:00
validates_presence_of :name, :full_name, :position
belongs_to :parent, :class_name => "Item"
has_one :i18n_variable, :as => :language_value, :autosave => true, :dependent => :destroy
has_many :children, :class_name => "Item", :as => 'parent'
before_validation :setup_default_value
2010-02-22 07:27:11 +00:00
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
# Get an array of ancestors
2010-01-18 07:52:52 +00:00
def ancestors
node, nodes = self, []
nodes << node = node.parent while !node.parent.blank? rescue nil
2010-01-18 07:52:52 +00:00
nodes.reverse
end
2012-05-08 20:15:02 +00:00
# Get an array of ancestor's id
def ancestor_ids
node, nodes = self, []
while !node.parent.blank? do
node = node.parent rescue nil
nodes << node.id if node
end
# nodes << node = node.parent while !node.parent.blank? rescue nil
nodes.reverse
end
# Build the url from the array of ancestors
2010-02-05 09:18:57 +00:00
def url
urls = ancestors.map{ |a| a.name } << self.name
urls.join("/")
2010-02-05 09:18:57 +00:00
end
def ordered_children
self.children.asc(:position)
end
def ordered_and_visible_children
objects = ordered_children
a = []
if objects
objects.each do |object|
a << object if object.menu_enabled_for.nil? ? true : object.menu_enabled_for.include?(I18n.locale.to_s)
end
end
a
end
2010-02-05 09:18:57 +00:00
protected
2010-02-05 08:53:52 +00:00
def setup_default_value
# Set the position value within the parent scope
if self.position.blank?
max_page = Item.where(:parent_id => self.parent_id).count
self.position = (max_page)? max_page + 1 : 1
end
# Build the full_name from the ancestors array
2010-02-11 08:46:20 +00:00
full_node = self.ancestors.map{ |a| a.name }.push( self.name )
# Remove root node if not root
2010-02-11 08:46:20 +00:00
full_node.shift if full_node.size >= 2
self.full_name = full_node.join("/")
end
# Enable the validation for parent_id
def validates_presence_of_parent_id?
true
end
end