Sha256: 84d2377c9f9a9be72c8e4fe5b63c86a729428866d8716528508e5bba83b93019

Contents?: true

Size: 1.24 KB

Versions: 8

Compression:

Stored size: 1.24 KB

Contents

module Denko
  module Behaviors
    module Threaded
      attr_reader :thread, :interrupts_enabled

      module ClassMethods
        def interrupt_with(*args)
          interrupts = self.class_eval('@@interrupts') rescue []
          interrupts = (interrupts + args).uniq
          self.class_variable_set(:@@interrupts, interrupts)
        end
      end

      def self.included(base)
        base.extend ClassMethods
      end

      def threaded(&block)
        stop_thread
        enable_interrupts unless interrupts_enabled
        @thread = Thread.new(&block)
      end

      def threaded_loop(&block)
        threaded do
          loop(&block)
        end
      end

      def stop_thread
        @thread.kill if @thread
      end

      def stop
        stop_thread
        super if defined?(super)
      end

      def enable_interrupts
        interrupts = self.class.class_eval('@@interrupts') rescue []
        interrupts.each do |method_name|
          standard_method = self.method(method_name)

          singleton_class.send(:define_method, method_name) do |*args|
            stop_thread unless (Thread.current == @thread)
            standard_method.call(*args)
          end
        end

        @interrupts_enabled = true
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
denko-0.14.0 lib/denko/behaviors/threaded.rb
denko-0.13.6 lib/denko/behaviors/threaded.rb
denko-0.13.5 lib/denko/behaviors/threaded.rb
denko-0.13.4 lib/denko/behaviors/threaded.rb
denko-0.13.3 lib/denko/behaviors/threaded.rb
denko-0.13.2 lib/denko/behaviors/threaded.rb
denko-0.13.1 lib/denko/behaviors/threaded.rb
denko-0.13.0 lib/denko/behaviors/threaded.rb