Sha256: 5144644747c9fda761c4eb56cfb4f283163eacf3a0ccf6c2759995f6b1502fa2

Contents?: true

Size: 1.35 KB

Versions: 6

Compression:

Stored size: 1.35 KB

Contents

# frozen_string_literal: true

module Spina
  module Admin::Conferences::Blog
    # Spina::Blog::Post
    class Post < ApplicationRecord
      extend FriendlyId

      friendly_id :title, use: :slugged

      belongs_to :image, optional: true, class_name: 'Spina::Image'

      belongs_to :user
      belongs_to :category, inverse_of: :posts

      validates :title, :content, presence: true

      before_save :set_published_at

      # Create a 301 redirect if the slug changed
      after_update :rewrite_rule, if: -> { saved_change_to_slug? }

      scope :available, -> { where('published_at <= ?', Time.zone.now) }
      scope :future, -> { where('published_at >= ?', Time.zone.now) }
      scope :draft, -> { where(draft: true) }
      scope :live, -> { where(draft: false) }
      scope :featured, -> { where(featured: true) }
      scope :unfeatured, -> { where(featured: false) }

      def self.table_name
        'spina_blog_posts'
      end

      private

      def set_published_at
        self.published_at = Time.now if !draft? && published_at.blank?
      end

      def should_generate_new_friendly_id?
        slug.blank? || draft_changed? || super
      end

      def rewrite_rule
        ::Spina::RewriteRule.create(
          old_path: "/blog/posts/#{slug_before_last_save}",
          new_path: "/blog/posts/#{slug}"
        )
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
spina-admin-conferences-blog-0.2.0 app/models/spina/admin/conferences/blog/post.rb
spina-admin-conferences-blog-0.1.4 app/models/spina/admin/conferences/blog/post.rb
spina-admin-conferences-blog-0.1.3 app/models/spina/admin/conferences/blog/post.rb
spina-admin-conferences-blog-0.1.2 app/models/spina/admin/conferences/blog/post.rb
spina-admin-conferences-blog-0.1.1 app/models/spina/admin/conferences/blog/post.rb
spina-admin-conferences-blog-0.1.0 app/models/spina/admin/conferences/blog/post.rb