2014-09-02 18:07:02 +05:30
|
|
|
class BroadcastMessage < ActiveRecord::Base
|
2016-11-03 12:29:30 +05:30
|
|
|
include CacheMarkdownField
|
2015-04-26 12:48:37 +05:30
|
|
|
include Sortable
|
|
|
|
|
2016-11-03 12:29:30 +05:30
|
|
|
cache_markdown_field :message, pipeline: :broadcast_message
|
|
|
|
|
2015-12-23 02:04:40 +05:30
|
|
|
validates :message, presence: true
|
2014-09-02 18:07:02 +05:30
|
|
|
validates :starts_at, presence: true
|
2015-12-23 02:04:40 +05:30
|
|
|
validates :ends_at, presence: true
|
2014-09-02 18:07:02 +05:30
|
|
|
|
2015-12-23 02:04:40 +05:30
|
|
|
validates :color, allow_blank: true, color: true
|
|
|
|
validates :font, allow_blank: true, color: true
|
2014-09-02 18:07:02 +05:30
|
|
|
|
2016-01-19 16:12:03 +05:30
|
|
|
default_value_for :color, '#E75E40'
|
|
|
|
default_value_for :font, '#FFFFFF'
|
|
|
|
|
2017-09-10 17:25:29 +05:30
|
|
|
CACHE_KEY = 'broadcast_message_current'.freeze
|
|
|
|
|
|
|
|
after_commit :flush_redis_cache
|
|
|
|
|
2014-09-02 18:07:02 +05:30
|
|
|
def self.current
|
2018-10-15 14:42:47 +05:30
|
|
|
messages = Rails.cache.fetch(CACHE_KEY, expires_in: cache_expires_in) { current_and_future_messages.to_a }
|
2017-09-10 17:25:29 +05:30
|
|
|
|
|
|
|
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
|
2018-03-17 18:26:18 +05:30
|
|
|
where('ends_at > :now', now: Time.zone.now).order_id_asc
|
2016-01-19 16:12:03 +05:30
|
|
|
end
|
|
|
|
|
2018-10-15 14:42:47 +05:30
|
|
|
def self.cache_expires_in
|
|
|
|
nil
|
|
|
|
end
|
|
|
|
|
2016-01-19 16:12:03 +05:30
|
|
|
def active?
|
|
|
|
started? && !ended?
|
|
|
|
end
|
|
|
|
|
|
|
|
def started?
|
|
|
|
Time.zone.now >= starts_at
|
|
|
|
end
|
|
|
|
|
|
|
|
def ended?
|
|
|
|
ends_at < Time.zone.now
|
2014-09-02 18:07:02 +05:30
|
|
|
end
|
2017-09-10 17:25:29 +05:30
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
def flush_redis_cache
|
|
|
|
Rails.cache.delete(CACHE_KEY)
|
|
|
|
end
|
2014-09-02 18:07:02 +05:30
|
|
|
end
|