Sha256: 7953f21c10bcd277eb1b3318ae694160a0721beaf17441f6e1b76c0bddfd43f4

Contents?: true

Size: 1.77 KB

Versions: 12

Compression:

Stored size: 1.77 KB

Contents

module PandaCms
  # Represents a template in the Panda CMS application.
  class Template < ApplicationRecord
    self.table_name = "panda_cms_templates"

    # Enables versioning for the Template model using the `has_paper_trail` gem.
    has_paper_trail versions: {
      class_name: "PandaCms::TemplateVersion"
    }

    # Associations
    has_many :pages, class_name: "PandaCms::Page", dependent: :restrict_with_error, inverse_of: :template, foreign_key: :panda_cms_template_id
    has_many :blocks, class_name: "PandaCms::Block", dependent: :restrict_with_error, inverse_of: :template, foreign_key: :panda_cms_template_id
    has_many :block_contents, through: :blocks

    # Validations
    validates :name, presence: true, uniqueness: true

    validates :file_path,
      presence: true,
      uniqueness: true,
      format: {with: /\Alayouts\/.*\z/, message: "must be a valid layout file path"}

    validate :validate_template_file_exists

    # Scopes
    scope :ordered, -> { order(:sort_order) }
    scope :available, -> { where("max_uses IS NULL OR (pages_count < max_uses)") }

    private

    # Custom validation method to check if the file_path is a valid layout file path
    # NB: Currently only supports .html.erb templates, may want to expand in future?
    # @return [void]
    def validate_template_file_exists
      # Remove any directory traversal attempts from the file_path
      safe_file_path = file_path.to_s.gsub("../", "")
      # Check if the file_path is an ERB template that exists in app/views
      template_path = Rails.root.join("app", "views", "#{safe_file_path}.html.erb")
      # NB: file? checks for files and excludes directories (unlike exist?)
      errors.add(:file_path, "must be an existing layout file path") unless File.file?(template_path)
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
panda_cms-0.3.3 app/models/panda_cms/template.rb
panda_cms-0.3.2 app/models/panda_cms/template.rb
panda_cms-0.3.1 app/models/panda_cms/template.rb
panda_cms-0.3.0 app/models/panda_cms/template.rb
panda_cms-0.2.7 app/models/panda_cms/template.rb
panda_cms-0.2.6 app/models/panda_cms/template.rb
panda_cms-0.2.5 app/models/panda_cms/template.rb
panda_cms-0.2.4 app/models/panda_cms/template.rb
panda_cms-0.2.3 app/models/panda_cms/template.rb
panda_cms-0.2.2 app/models/panda_cms/template.rb
panda_cms-0.2.1 app/models/panda_cms/template.rb
panda_cms-0.2.0 app/models/panda_cms/template.rb