Sha256: 96e881692e8c01c812f7a60a7136cdc7a313a5957a29bd3942034ce9b8856bcb

Contents?: true

Size: 1.73 KB

Versions: 10

Compression:

Stored size: 1.73 KB

Contents

# frozen_string_literal: true
require 'redis'


module Pears
  module Provider
    # Config using redis subscription. This updates automatically upon Redis
    # channel updates.
    # This class would register as "alternative classes with different interfaces".
    # I ought to clean this up and maybe make "triggers" a different entity
    # from a provider available in the builder.

    class Subscription < Base
      attr_reader :subscription
      def initialize(channel=nil,
          redis_host: Pears.config.redis_host,
          **opts,
          &fetcher)
        @builder = opts[:builder] || Builder.new(nil)
        @channel = channel

        # Fetcher is a "Provider" of some sort.
        @fetcher = fetcher

        # Setup redis subscription
        establish_connection(redis_host)
        load_config
        subscribe
      end

      def channel
        @channel ||= @builder.subject_name
      end

      def load_config
        @builder.freeze_layers do
          @data = @fetcher.call.data
        end
      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|
              load_config
            end
          end
          puts "Redis connection died!"
        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

10 entries across 10 versions & 1 rubygems

Version Path
pears-0.2.0 lib/pears/provider/subscription.rb
pears-0.1.4 lib/pears/provider/subscription.rb
pears-0.1.3 lib/pears/provider/subscription.rb
pears-0.1.2 lib/pears/provider/subscription.rb
pears-0.1.1 lib/pears/provider/subscription.rb
pears-0.1.0 lib/pears/provider/subscription.rb
pears-0.0.11 lib/pears/provider/subscription.rb
pears-0.0.10 lib/pears/provider/subscription.rb
pears-0.0.9 lib/pears/provider/subscription.rb
pears-0.0.8 lib/pears/provider/subscription.rb