2013-11-12 06:47:28 -05:00
|
|
|
class BroadcastMessage < ActiveRecord::Base
|
2016-10-06 17:17:11 -04:00
|
|
|
include CacheMarkdownField
|
2015-02-05 17:20:55 -05:00
|
|
|
include Sortable
|
|
|
|
|
2016-10-06 17:17:11 -04:00
|
|
|
cache_markdown_field :message, pipeline: :broadcast_message
|
|
|
|
|
2015-12-01 18:53:44 -05:00
|
|
|
validates :message, presence: true
|
2013-11-12 07:28:12 -05:00
|
|
|
validates :starts_at, presence: true
|
2015-12-01 18:53:44 -05:00
|
|
|
validates :ends_at, presence: true
|
2013-11-12 08:08:20 -05:00
|
|
|
|
2015-12-01 18:53:44 -05:00
|
|
|
validates :color, allow_blank: true, color: true
|
|
|
|
validates :font, allow_blank: true, color: true
|
2013-12-19 13:11:01 -05:00
|
|
|
|
2015-12-31 17:07:11 -05:00
|
|
|
default_value_for :color, '#E75E40'
|
|
|
|
default_value_for :font, '#FFFFFF'
|
|
|
|
|
2017-08-09 09:49:30 -04:00
|
|
|
CACHE_KEY = 'broadcast_message_current'.freeze
|
|
|
|
|
|
|
|
after_commit :flush_redis_cache
|
|
|
|
|
2013-11-12 08:08:20 -05:00
|
|
|
def self.current
|
2017-08-18 08:52:11 -04:00
|
|
|
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
|
2017-08-15 06:27:37 -04:00
|
|
|
where('ends_at > :now', now: Time.zone.now).order_id_asc
|
2015-12-31 17:07:11 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def active?
|
|
|
|
started? && !ended?
|
|
|
|
end
|
|
|
|
|
|
|
|
def started?
|
|
|
|
Time.zone.now >= starts_at
|
|
|
|
end
|
|
|
|
|
|
|
|
def ended?
|
|
|
|
ends_at < Time.zone.now
|
|
|
|
end
|
2017-08-09 09:49:30 -04:00
|
|
|
|
2017-08-18 08:52:11 -04:00
|
|
|
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
|
|
|
|
|
2017-08-09 09:49:30 -04:00
|
|
|
def flush_redis_cache
|
|
|
|
Rails.cache.delete(CACHE_KEY)
|
|
|
|
end
|
2013-11-12 06:47:28 -05:00
|
|
|
end
|