Sha256: 976f7cd15a1ac21d76689914dfd5ee1ea6aca31bee3d7a961e3deafa316dea10

Contents?: true

Size: 945 Bytes

Versions: 2

Compression:

Stored size: 945 Bytes

Contents

module DeviseOnlineable
  extend ActiveSupport::Concern

  def appear
    redis_client.multi do |multi|
      multi.set(online_status_key, 1)
      multi.expire(online_status_key, 3_600)
      multi.set("#{online_status_key}:last_seen", Time.zone.now.to_i)
      multi.expire("#{online_status_key}:last_seen", 3_600)
    end
  end

  def disappear
    redis_client.multi do |multi|
      multi.del(online_status_key)
      multi.del("#{online_status_key}:last_seen")
    end
  end

  def online_status
    return :offline unless redis_client.exists?(online_status_key)

    last_seen = redis_client.get("#{online_status_key}:last_seen").to_i

    Time.zone.at(last_seen) > 5.minutes.ago ? :online : :away
  end

  private

  def online_status_key
    "#{self.class.to_s.underscore}_online_presence:#{id}"
  end

  def redis_client
    @redis_client ||= Redis.new(
      url: ENV.fetch('REDIS_URL') { 'redis://localhost:6379/1' }
    )
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
webamm_to_rails-7.0.1 lib/webamm_to_rails/features/devise_onlineable/templates/app/models/concerns/devise_onlineable.rb.erb
webamm_to_rails-7.0.0 lib/webamm_to_rails/features/devise_onlineable/templates/app/models/concerns/devise_onlineable.rb.erb