foodsoft/plugins/wiki/app/models/page.rb

87 lines
2.1 KiB
Ruby
Raw Permalink Normal View History

class Page < ApplicationRecord
2012-11-24 16:41:34 +01:00
include ActsAsTree
2012-11-24 16:49:19 +01:00
belongs_to :user, foreign_key: 'updated_by'
2009-05-15 17:32:45 +02:00
acts_as_versioned version_column: :lock_version
self.non_versioned_columns += %w[permalink created_at title]
2012-11-24 16:41:34 +01:00
acts_as_tree order: 'title'
attr_accessor :old_title # Save title to create redirect page when editing title
2009-05-15 17:32:45 +02:00
validates_presence_of :title, :body
validates_uniqueness_of :permalink, :title
before_validation :set_permalink, on: :create
before_validation :update_permalink, on: :update
after_update :create_redirect
scope :non_redirected, -> { where(redirect: nil) }
scope :no_parent, -> { where(parent_id: nil) }
def self.permalink(title)
title.gsub(%r{[/.,;@\s]}, '_').gsub(/["']/, '')
end
def homepage?
permalink == 'Home'
end
2017-10-20 12:10:54 +02:00
def self.dashboard
where(permalink: 'Dashboard').first
2017-10-20 12:10:54 +02:00
end
def self.public_front_page
where(permalink: 'Public_frontpage').first
end
2020-03-06 11:46:39 +01:00
def self.welcome_mail
where(permalink: 'Welcome_mail').first
2020-03-06 11:46:39 +01:00
end
def set_permalink
return if title.blank?
self.permalink = Page.count == 0 ? 'Home' : Page.permalink(title)
end
2017-10-20 12:08:52 +02:00
2014-01-04 20:12:01 +01:00
def diff
current = versions.latest
old = versions.where(['page_id = ? and lock_version < ?', current.page_id,
current.lock_version]).order('lock_version DESC').first
2017-10-20 12:08:52 +02:00
2014-01-04 20:12:01 +01:00
if old
o = ''
Diffy::Diff.new(old.body, current.body).each do |line|
case line
when /^\+/ then o += "#{line.chomp}<br />" unless line.chomp == '+'
when /^-/ then o += "#{line.chomp}<br />" unless line.chomp == '-'
2014-01-04 20:12:01 +01:00
end
end
o
else
current.body
end
end
protected
def update_permalink
return unless changed.include?('title')
set_permalink
self.old_title = changes['title'].first # Save title for creating redirect
end
def create_redirect
return if old_title.blank?
Page.create redirect: id,
title: old_title,
body: I18n.t('model.page.redirect', title: title),
permalink: Page.permalink(old_title),
updated_by: updated_by
end
end