Sha256: fc5fdd30f13b43a7e3b1f5b0dbd3f06614440958289f8083aafb21883b7d3f52

Contents?: true

Size: 1.63 KB

Versions: 20

Compression:

Stored size: 1.63 KB

Contents

module Loco
  class WsConnectionManager
    def initialize resource
      @resource = resource
    end

    def identifier
      return @resource if @resource.is_a?(String)
      "#{@resource.class.name.downcase}:#{@resource.id}"
    end

    def connected? uuid
      connected_uuids.include? uuid
    end

    def connected_uuids
      data.find_all{ |k,v| v.is_a? String }.to_h.keys
    end

    def add uuid
      update uuid
      check_connections
    end

    def del uuid
      save data.tap{ |h| h.delete uuid }
      check_connections
    end

    def update uuid
      save data.tap{ |h| h[uuid] = current_time }
    end

    def destroy
      WsConnectionStorage.current.del identifier
    end

    protected

      def data
        serialized_uuids = WsConnectionStorage.current.get identifier
        return {} if serialized_uuids.blank?
        JSON.parse serialized_uuids
      end

      def uuids
        data.keys
      end

      def save hash
        WsConnectionStorage.current.set identifier, hash.to_json
      end

      def check_connections
        hash = data.to_a.map do |arr|
          uuid, val = arr.first, arr.last
          case val
          when String
            if Time.zone.parse(val) < 3.minutes.ago
              SenderJob.perform_later uuid, loco: {connection_check: true}
              val = {"check" => current_time}
            end
          when Hash
            if Time.zone.parse(val["check"]) < 5.seconds.ago
              uuid, val = nil, nil
            end
          end
          [uuid, val]
        end.to_h.compact
        save hash
      end

      def current_time
        Time.current.iso8601(6)
      end
  end
end

Version data entries

20 entries across 20 versions & 1 rubygems

Version Path
loco-rails-2.5.3 lib/loco/ws_connection_manager.rb
loco-rails-2.5.2 lib/loco/ws_connection_manager.rb
loco-rails-2.5.1 lib/loco/ws_connection_manager.rb
loco-rails-2.5.0 lib/loco/ws_connection_manager.rb
loco-rails-2.4.0 lib/loco/ws_connection_manager.rb
loco-rails-2.3.0 lib/loco/ws_connection_manager.rb
loco-rails-3.0.0 lib/loco/ws_connection_manager.rb
loco-rails-2.2.2 lib/loco/ws_connection_manager.rb
loco-rails-2.2.1 lib/loco/ws_connection_manager.rb
loco-rails-2.2.0 lib/loco/ws_connection_manager.rb
loco-rails-2.1.0 lib/loco/ws_connection_manager.rb
loco-rails-2.0.0 lib/loco/ws_connection_manager.rb
loco-rails-1.5.2 lib/loco/ws_connection_manager.rb
loco-rails-1.5.1 lib/loco/ws_connection_manager.rb
loco-rails-1.5.0 lib/loco/ws_connection_manager.rb
loco-rails-1.4.0 lib/loco/ws_connection_manager.rb
loco-rails-1.3.3 lib/loco/ws_connection_manager.rb
loco-rails-1.3.2 lib/loco/ws_connection_manager.rb
loco-rails-1.3.1 lib/loco/ws_connection_manager.rb
loco-rails-1.3.0 lib/loco/ws_connection_manager.rb