module Elabs module Concerns module ContentEntity extend ActiveSupport::Concern included do before_save :set_publication_date scope :by_member, ->(user_id) { where(user_id: user_id) } scope :published, -> { where(published: true) } scope :unlocked, -> { where(locked: false) } scope :publicly_visible, -> { published.unlocked } scope :for_relation, -> { published.order(published_at: 'desc').limit(Elabs.max_related_items) } end def locked? locked end def unlocked? !locked end def draft? !published end def published? published end def publicly_visible? published? && !locked? end def not_publicly_visible? draft? || locked? end private def made_publicly_visible? (changes_include?(:published) || changes_include?(:locked)) && published? && unlocked? end def made_publicly_invisible? (changes_include?(:published) && draft?) || (changes_include?(:locked) && locked? && published?) end def was_published_before? (changes_include?(:published) && draft?) end def set_publication_date self.published_at = Time.new if changed.include?('published') && published? self.published_at = nil if changed.include?('published') && !published? end # method used by ActableEntity/NotifiableEntity to determine the events. def current_publish_action return :nothing unless unlocked? published? ? :publish : :unpublish end # method used by ActableEntity/NotifiableEntity to determine the events. def current_lock_action return :nothing unless published? locked? ? :lock : :unlock end # method used by ActableEntity/NotifiableEntity to determine the events. def current_update_action published? && unlocked? ? :update : :nothing end def changed_by_someone_else changed_by.present? && changed_by.id != user.id end class_methods do def find_publicly_visible(slug) entity = where(slug: slug).published.first raise ActiveRecord::RecordNotFound if entity.nil? entity end end end end end