This repository has been archived on 2024-03-16. You can view files and clone it, but cannot push or open issues or pull requests.
orbit-4-1/app/models/item.rb

92 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
2012-05-11 08:16:09 +00:00
include Mongoid::Tree
include Mongoid::Tree::Ordering
LIST = YAML.load(File.read('config/list.yml'))
2012-05-11 08:16:09 +00:00
field :name
field :path
field :is_published, :type => Boolean, :default => false
field :enabled_for, :type => Array, :default => nil
field :menu_enabled_for, :type => Array, :default => nil
field :title, localize: true
field :sitemap_enabled, :type => Hash
2012-05-22 09:55:45 +00:00
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-05-11 08:16:09 +00:00
validates_presence_of :name
validates_associated :parent, :children
2012-05-22 09:55:45 +00:00
before_destroy :destroy_children
after_rearrange :rebuild_path, :if => "parent_id_changed? || name_changed?"
def enabled_for_lang(lang)
enabled_for.include?(lang)
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
2012-05-11 08:16:09 +00:00
def visible_children
objects = self.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
def shift_to(new_parent, position)
unless self.parent_id.to_s.eql?(new_parent) && self.position.eql?(position.to_i)
new_parent = Item.find(new_parent)
current_position_sibling = find_by_parent_and_position(new_parent, position.to_i)
if current_position_sibling
2013-01-03 11:12:52 +00:00
move_above(current_position_sibling)
elsif self.parent != new_parent
self.parent = new_parent
2013-01-03 11:12:52 +00:00
save
end
end
end
def show_in_sitemap_for(locale)
2012-12-28 03:37:37 +00:00
if sitemap_enabled && !sitemap_enabled[locale].blank?
sitemap_enabled[locale].eql?('true') ? true : false
else
true
end
end
2010-02-05 09:18:57 +00:00
protected
2010-02-05 08:53:52 +00:00
2012-05-11 08:16:09 +00:00
def rebuild_path
self.path = (self.ancestors_and_self - [Item.root]).collect{|x| x.name unless x.root?}.join('/')
self.rebuild_children_path
end
def rebuild_children_path
self.children.each do |child|
child.path = (child.ancestors_and_self - [Item.root]).collect{|x| x.name}.join('/')
child.save
child.rebuild_children_path
end
end
2012-05-11 08:16:09 +00:00
def find_by_parent_and_position(parent, position)
parent.children.detect{|child| child.position == position}
end
# Enable the validation for parent_id
def validates_presence_of_parent_id?
true
end
end