class SpudPage < ActiveRecord::Base include CmsDeprecatedMultisite include TbRedirects::HasRedirects belongs_to :spud_page, required: false has_many :spud_page_partial_revisions has_many :spud_pages, dependent: :nullify has_many :spud_page_partials, dependent: :destroy belongs_to :created_by_user, class_name: 'SpudUser', foreign_key: :created_by, required: false belongs_to :updated_by_user, class_name: 'SpudUser', foreign_key: :updated_by, required: false before_validation :generate_url_name validates :name, presence: true, uniqueness: { scope: :spud_page_id } validates :url_name, presence: true, uniqueness: true after_update :create_redirect_if_necessary accepts_nested_attributes_for :spud_page_partials, allow_destroy: true scope :parent_pages, -> { where(spud_page_id: nil) } scope :published_pages, -> { where(published: true) } scope :viewable, -> { where(visibility: 0) } scope :ordered, -> { order(page_order: :asc, name: :asc) } def full_content_processed ActiveSupport::Deprecation.warn('#full_content_processed is deprecated; use #full_content instead.') spud_page_partials.collect(&:content_processed).join(' ') end def full_content spud_page_partials.collect(&:content).join(' ') end # Returns an array of pages in order of heirarchy # :fitler Filters out a page by ID, and all of its children # :value Pick an attribute to be used in the value field, defaults to ID def self.options_tree_for_page(config = {}) collection = config[:collection] || all.group_by(&:spud_page_id) level = config[:level] || 0 parent_id = config[:parent_id] || nil filter = config[:filter] || nil value = config[:value] || :id list = [] collection[parent_id]&.each do |c| if filter.blank? || c.id != filter.id list << [Array.new(level) { '- ' }.join('') + c.name, c[value]] list += options_tree_for_page(collection: collection, parent_id: c.id, level: level + 1, filter: filter) end end return list end def is_private? return visibility == 1 end def self.find_ignoring_case(url_name) find_by(arel_table[:url_name].matches(url_name)) end private def generate_url_name if url_name.blank? parts = [] parts << spud_page.url_name if spud_page.present? parts << name.try(:parameterize) self.url_name = parts.join('/') end return true end def create_redirect_if_necessary if saved_change_to_attribute?(:url_name) TbRedirect.create_smart(source: "/#{attribute_before_last_save(:url_name)}", destination: "/#{url_name}", created_by: 'cms', owner: self) end true end end