|
| 1 | +module Blog |
| 2 | + class Post < ActiveRecord::Base |
| 3 | + self.table_name = 'blog_posts' |
| 4 | + |
| 5 | + belongs_to :category, class_name: "Blog::Category", inverse_of: :posts |
| 6 | + belongs_to :author, class_name: "Blog::Author", inverse_of: :posts |
| 7 | + |
| 8 | + has_many :taggings, class_name: "Blog::Tagging", inverse_of: :post |
| 9 | + has_many :tags, through: :taggings |
| 10 | + has_many :post_relations, class_name: "Blog::PostRelation", inverse_of: :post |
| 11 | + has_many :related_posts, through: :post_relations, source: :related |
| 12 | + |
| 13 | + validates :title, :body, :category, :author, :published_at, presence: true |
| 14 | + validate :check_presence_of_featured_image_if_sticky |
| 15 | + |
| 16 | + extend FriendlyId |
| 17 | + friendly_id :seo_slug_or_title, use: :slugged |
| 18 | + |
| 19 | + scope :sorted_by_date, -> { order('published_at DESC') } |
| 20 | + scope :sticky, -> { where(sticky: true) } |
| 21 | + scope :matching_query, ->(query) { where("title LIKE :query OR body LIKE :query", query: "%#{query}%") } |
| 22 | + scope :visible, -> { where(visible: true) } |
| 23 | + scope :published, -> { visible.where('published_at < ?', Time.now) } |
| 24 | + |
| 25 | + has_image :featured_image |
| 26 | + |
| 27 | + attr_accessible :category_id, :author_id, :title, :abstract, :body, :sticky, |
| 28 | + :visible, :published_at, :seo_slug, :seo_title, :seo_description, |
| 29 | + :comma_separated_tags |
| 30 | + |
| 31 | + def seo_slug |
| 32 | + slug |
| 33 | + end |
| 34 | + |
| 35 | + def seo_slug=(slug) |
| 36 | + @seo_slug = slug |
| 37 | + end |
| 38 | + |
| 39 | + def seo_slug_or_title |
| 40 | + @seo_slug.presence || title |
| 41 | + end |
| 42 | + |
| 43 | + def comma_separated_tags |
| 44 | + tags.map(&:name).join(',') |
| 45 | + end |
| 46 | + |
| 47 | + def comma_separated_tags=(data) |
| 48 | + self.tags = [] |
| 49 | + data.split(/\s*,\s*/).each do |tag_name| |
| 50 | + self.tags << Tag.find_or_create!(tag_name) |
| 51 | + end |
| 52 | + end |
| 53 | + |
| 54 | + def author_name |
| 55 | + author.full_name |
| 56 | + end |
| 57 | + |
| 58 | + private |
| 59 | + |
| 60 | + def check_presence_of_featured_image_if_sticky |
| 61 | + if self.sticky && self.featured_image.nil? |
| 62 | + errors.add(:sticky, "richiede la presenza di una featured image") |
| 63 | + end |
| 64 | + end |
| 65 | + end |
| 66 | +end |
| 67 | + |
0 commit comments