Sha256: dc8e1cf0f5270a338b6c3e2cc2dc74c0114ad39f9163d0610f90bdf0f129be75

Contents?: true

Size: 1.25 KB

Versions: 3

Compression:

Stored size: 1.25 KB

Contents

# frozen_string_literal: true
require 'redis'

module Pears
  module Provider
    # Config using redis subscription. This updates automatically upon Redis
    # channel updates.
    class Subscription < Base
      attr_reader :subscription

      def initialize(channel,
          redis_host: Pears.config.redis_host,
          &fetcher)
        @channel = channel
        @fetcher = fetcher

        establish_connection(redis_host)
        subscribe
        reload
      end

      def reload
        @data = @fetcher.call(Pears::Providers::Builder.new(self))
            .data
      end

      # This seems a bit "rough" of an approach. we should check if
      # unsubscribing can be done more gracefully.
      def unsubscribe
        @subscription.terminate
      end

      private

      def subscribe
        @subscription = Thread.new do
          connection.subscribe(@channel) do |on|
            on.message do |channel, message|
              reload
            end
          end
        end
      end

      def connection
        @connection ||= establish_connection
      end

      def establish_connection(host='redis')
        @connection = ::Redis.new(host: host,
            reconnect_attempts: 10,
            reconnect_delay: 5)
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
pears-0.0.3 lib/pears/provider/subscription.rb
pears-0.0.2 lib/pears/provider/subscription.rb
pears-0.0.1 lib/pears/provider/subscription.rb