Sha256: 5fd62a2fe2108f5c327f209a5fd308e360a5c3ebca215bf46bda8b737caeee8e

Contents?: true

Size: 1.49 KB

Versions: 3

Compression:

Stored size: 1.49 KB

Contents

module ZK
  # Basic pattern for objects that have the concept of a parent (the thing that 
  # granted this subscription), a callback, and that can unregister (so the
  # callback no longer receives events). 
  #
  # expects the 'parent' to respond_to? the 'unregister' method, and will
  # be passed the subscription instance 
  module Subscription
    class Base
      include ZK::Logging

      # the object from which we will attempt to #unregister on
      # XXX: need a better name for this
      attr_reader :parent
      
      # the user-supplied callback block, used to create a ThreadedCallback
      attr_reader :callable

      def initialize(parent, block)
        raise ArgumentError, "block must repsond_to?(:call)" unless block.respond_to?(:call)
        @parent   = parent
        @callable = block
        @mutex    = Monitor.new
      end

      def unregistered?
        @parent.nil?
      end

      # calls unregister on parent, then sets parent to nil
      def unregister
        obj = nil

        synchronize do
          return false unless @parent
          obj, @parent = @parent, nil
        end

        obj.unregister(self)
      end

      # an alias for unregister
      def unsubscribe
        unregister
      end

      # @private
      def call(*args)
        callable.call(*args)
      end

      # @private
      def reopen_after_fork!
        @mutex = Monitor.new
      end

      protected
        def synchronize
          @mutex.synchronize { yield }
        end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
zk-1.5.2 lib/zk/subscription.rb
zk-1.5.1 lib/zk/subscription.rb
zk-1.5.0 lib/zk/subscription.rb