BigW Consortium Gitlab

broadcast_message.rb 1.42 KB
Newer Older
1
class BroadcastMessage < ActiveRecord::Base
2
  include CacheMarkdownField
3 4
  include Sortable

5 6
  cache_markdown_field :message, pipeline: :broadcast_message

7
  validates :message,   presence: true
8
  validates :starts_at, presence: true
9
  validates :ends_at,   presence: true
10

11 12
  validates :color, allow_blank: true, color: true
  validates :font,  allow_blank: true, color: true
13

14 15 16
  default_value_for :color, '#E75E40'
  default_value_for :font,  '#FFFFFF'

17 18 19 20
  CACHE_KEY = 'broadcast_message_current'.freeze

  after_commit :flush_redis_cache

21
  def self.current
22 23 24 25 26 27 28 29 30 31 32 33 34 35
    messages = Rails.cache.fetch(CACHE_KEY) { current_and_future_messages.to_a }

    return messages if messages.empty?

    now_or_future = messages.select(&:now_or_future?)

    # If there are cached entries but none are to be displayed we'll purge the
    # cache so we don't keep running this code all the time.
    Rails.cache.delete(CACHE_KEY) if now_or_future.empty?

    now_or_future.select(&:now?)
  end

  def self.current_and_future_messages
36
    where('ends_at > :now', now: Time.zone.now).order_id_asc
37 38 39 40 41 42 43 44 45 46 47 48 49
  end

  def active?
    started? && !ended?
  end

  def started?
    Time.zone.now >= starts_at
  end

  def ended?
    ends_at < Time.zone.now
  end
50

51 52 53 54 55 56 57 58 59 60 61 62
  def now?
    (starts_at..ends_at).cover?(Time.zone.now)
  end

  def future?
    starts_at > Time.zone.now
  end

  def now_or_future?
    now? || future?
  end

63 64 65
  def flush_redis_cache
    Rails.cache.delete(CACHE_KEY)
  end
66
end