Sha256: 95b9959fce0917865e703a6b00594fa968fa074b52ed36f21897b3749bdf7625

Contents?: true

Size: 1.56 KB

Versions: 2

Compression:

Stored size: 1.56 KB

Contents

class SlightcmsPage < ActiveRecord::Base

  #has_many :elements, :class_name => "SlightcmsPageElement", :foreign_key => "page_id"
  
  #cts_as_tree :order => "position, title"
  #acts_as_list :scope => :parent_id
  
  validates_presence_of :title
  validates_uniqueness_of :slug, :scope => :parent_id
  
  before_validation do |record|
    if record.slug.blank? && !record.title.blank?
      generate_slug(record)
    end
  end
  
  before_create :generate_full_path
  
  # Render page's content to valid html
  def to_html
    elements = children.map {|child| child.to_html}
    elements.join('\n')
  end
  
  protected
  
  # Find a page by full path
  def find_by_path(path)
    find :first, :conditions => {:path => path, :published => true}
  end
  
  # Generate a unique slug for seo purposes
  def generate_slug(record)
    proposed_slug = record.title.downcase.gsub!(/[^a-z1-9]+/, '-')
    
    existing = true
    suffix = ""
    i = 1
    
    # Check if slug already exists
    while existing != nil
      existing = self.class.find :first, :conditions => {:slug => proposed_slug + suffix}
      if existing
        suffix = "-#{i}"
        i += 1
      else
        self.slug = proposed_slug + suffix     
      end
    end
  end
  
  # Generate the page's full path
  def generate_path
    self.path = parent_node.path + "/#{self.slug}"
  end
  
  # Generate the page's full path and save the object
  def generate_path!
    generate_path
    save
  end
  
  # Update the children's path
  def update_children_path
    children.each do |child|
      generate_path!
    end
  end
  
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
slightcms-0.0.2 lib/slightcms/slightcms_page.rb
slightcms-0.0.1 lib/slightcms/slightcms_page.rb