module PagesCms class Article < ActiveRecord::Base includes MarkdownRenderer def to_param "#{id}-#{title.parameterize}" end belongs_to :account belongs_to :image validates :title, presence: true validates :tags, presence: true validate :xor_article validate :has_account def content? content.present? end def content_md? content_md.present? end def content_either if content_md? self.content_md_rendered elsif content? self.content else 'Article not saved properly.' end end def content_md=(value) old = value if value.nil? new = value else new = markdown(value) end self[:content_md_rendered] = new self[:content_md] = old end def tags=(val) write_attribute(:tags, val.strip.gsub(/\s+/, '_').split(',') ) end def self.published self.where('archived != true AND draft != true') end def article_status if self.draft && !self.archived 'Draft' elsif self.archived && !self.draft 'Archived' elsif !self.draft && !self.archived 'Published' elsif self.draft && self.archived 'Archived' end end scope :search, -> (search) { where('content ILIKE ? OR tags @> ? OR title ILIKE ? ',"#{search}",'{' + search + '}',"#{search}") } scope :status, -> (status) do case status when 'Archived' where(archived: true) when 'Drafts' where(draft: true) when 'Published' where('archived != true AND draft != true') else all end end def xor(a,b) (a || b) && !(a && b) end private def xor_article unless xor(content_md?, content?) errors.add(:base, "Content can't be blank") end end def has_account if self.account.nil? errors.add(:base, 'Must be associated with an account') end end end end