about summary refs log tree commit diff stats
path: root/app/models/blog.rb
blob: db05432f8651c4c7a86c3a2c4bb3d97c212157d1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
class Blog < ApplicationRecord
  include Recordable
  include Votable

  acts_as_taggable

  has_many :comments
  belongs_to :user

  has_many_attached :images do |attachable|
    attachable.variant :thumb, resize_to_limit: [300, 300]
  end

  validates :title, presence: true
  validates :body, presence: true, if: :published
  validates :slug, presence: true, format: /\A[-a-z0-9]+\z/, if: :published
  validates :user, presence: true
  validates :images, content_type: ['image/png', 'image/jpeg']

  before_validation :set_draft_title
  before_save :set_published_at
  after_save :send_webmentions

  def path
    "/says/#{slug}"
  end

  def taggable
    self
  end

  def has_read_more
    body.include?("<!--MORE-->")
  end

  def short_body
    body[0..(body.index("<!--MORE-->")-1)]
  end

  def to_param
    slug
  end

  def visible_date
    if published
      published_at
    else
      updated_at
    end
  end

  def prev
    Blog.where(published: true).where("published_at < ?", published_at).order(published_at: :desc).first
  end

  def next
    Blog.where(published: true).where("published_at > ?", published_at).order(published_at: :asc).first
  end

  private
    def set_draft_title
      if self.title.blank? and not self.published
        self.title = "Untitled draft"
      end
    end

    def set_published_at
      if self.published
        if self.published_at.blank?
          self.published_at = DateTime.now
        end
      else
        self.published_at = nil
      end
    end

    def send_webmentions
      return unless self.published

      SendWebmentionsJob.perform_later self
    end
end