2010-04-25 00:33:38 +00:00
|
|
|
class Page
|
|
|
|
include Mongoid::Document
|
|
|
|
include Mongoid::Timestamps
|
2010-04-30 14:05:53 +00:00
|
|
|
include Mongoid::Acts::Tree
|
2010-04-25 00:33:38 +00:00
|
|
|
|
|
|
|
## fields ##
|
|
|
|
field :title
|
2010-04-30 14:05:53 +00:00
|
|
|
field :slug
|
2010-04-25 00:33:38 +00:00
|
|
|
field :published, :type => Boolean, :default => false
|
|
|
|
field :keywords
|
|
|
|
field :description
|
2010-04-30 14:05:53 +00:00
|
|
|
field :position, :type => Integer
|
2010-04-25 00:33:38 +00:00
|
|
|
|
|
|
|
## associations ##
|
|
|
|
belongs_to_related :site
|
|
|
|
embeds_many :parts, :class_name => 'PagePart'
|
|
|
|
|
|
|
|
## validations ##
|
2010-04-30 14:05:53 +00:00
|
|
|
validates_presence_of :site, :title, :slug
|
|
|
|
validates_uniqueness_of :slug, :scope => :site_id
|
|
|
|
validates_exclusion_of :slug, :in => Locomotive.config.reserved_slugs, :if => Proc.new { |p| p.depth == 0 }
|
2010-04-25 00:33:38 +00:00
|
|
|
|
|
|
|
## callbacks ##
|
2010-04-30 14:05:53 +00:00
|
|
|
before_create :add_to_list_bottom
|
2010-04-25 00:33:38 +00:00
|
|
|
before_create :add_body_part
|
2010-04-30 14:05:53 +00:00
|
|
|
before_destroy :remove_from_list
|
|
|
|
before_validate :normalize_slug
|
2010-04-25 00:33:38 +00:00
|
|
|
|
|
|
|
## named scopes ##
|
|
|
|
|
2010-04-30 14:05:53 +00:00
|
|
|
## behaviours ##
|
|
|
|
acts_as_tree
|
|
|
|
|
2010-04-25 00:33:38 +00:00
|
|
|
## methods ##
|
|
|
|
|
|
|
|
def add_body_part
|
|
|
|
self.parts.build :name => 'body', :value => '---body here---'
|
|
|
|
end
|
2010-04-30 14:05:53 +00:00
|
|
|
|
|
|
|
def parent=(owner) # missing in acts_as_tree
|
|
|
|
self[self.parent_id_field] = owner._id
|
|
|
|
self[self.path_field] = owner[owner.path_field] + [owner._id]
|
|
|
|
self[self.depth_field] = owner[owner.depth_field] + 1
|
|
|
|
self.instance_variable_set :@_will_move, true
|
|
|
|
end
|
|
|
|
|
|
|
|
def route
|
|
|
|
File.join self.self_and_ancestors.map(&:slug)
|
|
|
|
end
|
|
|
|
|
|
|
|
protected
|
2010-04-25 00:33:38 +00:00
|
|
|
|
2010-04-30 14:05:53 +00:00
|
|
|
def add_to_list_bottom
|
|
|
|
self.position = (Page.where(:_id.ne => self._id).and(:parent_id => self.parent_id).max(:position) || 0) + 1
|
|
|
|
end
|
|
|
|
|
|
|
|
def remove_from_list
|
|
|
|
Page.where(:parent_id => self.parent_id).and(:position.gt => self.position).each do |p|
|
|
|
|
p.position -= 1
|
|
|
|
p.save
|
2010-04-25 00:33:38 +00:00
|
|
|
end
|
|
|
|
end
|
2010-04-30 14:05:53 +00:00
|
|
|
|
|
|
|
def normalize_slug
|
|
|
|
self.slug.slugify!(:without_extension => true) if self.slug.present?
|
|
|
|
end
|
2010-04-25 00:33:38 +00:00
|
|
|
end
|