Sha256: 454934df47241647973eab05a9c997c3723caa1a15c7e540f65eb8c07ced9b62

Contents?: true

Size: 1.23 KB

Versions: 7

Compression:

Stored size: 1.23 KB

Contents

# frozen_string_literal: true

class PagePath < ApplicationRecord
  class PageNotSavedError < StandardError; end

  class NoPathError < StandardError; end

  class NoLocaleError < StandardError; end

  belongs_to :page
  validates :locale, presence: true
  validates :path, presence: true, uniqueness: { scope: :locale }

  class << self
    def build(page)
      page.locales.each do |locale|
        localized = page.localize(locale)
        localized.ensure_path_segment
        associate(localized) if !localized.deleted? && localized.full_path?
      end
      page.children.each { |p| build(p) }
    end

    def build_all
      Page.roots.each do |p|
        build(p)
      end
    end

    def get(locale, path)
      find_by(locale:, path:)
    end

    def associate(page, locale: nil, path: nil)
      locale ||= page.locale
      path ||= page.full_path
      raise PageNotSavedError unless page.id?
      raise NoLocaleError unless locale
      raise NoPathError unless path

      page_path = get_or_create(locale, path, page)
      page_path.update(page:) unless page_path.page_id == page.id
      page_path
    end

    private

    def get_or_create(locale, path, page)
      get(locale, path) || create(locale:, path:, page:)
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
pages_core-3.15.5 app/models/page_path.rb
pages_core-3.15.4 app/models/page_path.rb
pages_core-3.15.3 app/models/page_path.rb
pages_core-3.15.2 app/models/page_path.rb
pages_core-3.15.1 app/models/page_path.rb
pages_core-3.14.0 app/models/page_path.rb
pages_core-3.13.0 app/models/page_path.rb