Sha256: 466a9ec45d5a76e30bee6806e5b7b4b8cc296af328a73e96e8c14b1050304e1f

Contents?: true

Size: 1.87 KB

Versions: 12

Compression:

Stored size: 1.87 KB

Contents

#--
#            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
#                    Version 2, December 2004
#
#            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
#   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
#
#  0. You just DO WHAT THE FUCK YOU WANT TO.
#++

require 'thread'

# A delay is an object that incapsulates a block which is called upon
# value retrieval, and its result cached.
class Thread::Delay
	# Create a delay with the passed block.
	def initialize (&block)
		raise ArgumentError, 'no block given' unless block

		@mutex = Mutex.new
		@block = block
	end

	# Check if an exception has been raised.
	def exception?
		@mutex.synchronize {
			instance_variable_defined? :@exception
		}
	end

	# Return the raised exception.
	def exception
		@mutex.synchronize {
			@exception
		}
	end

	# Check if the delay has been called.
	def delivered?
		@mutex.synchronize {
			instance_variable_defined? :@value
		}
	end

	alias realized? delivered?

	# Get the value of the delay, if it's already been executed, return the
	# cached result, otherwise execute the block and return the value.
	#
	# In case the block raises an exception, it will be raised, the exception is
	# cached and will be raised every time you access the value.
	def value
		@mutex.synchronize {
			raise @exception if instance_variable_defined? :@exception

			return @value if instance_variable_defined? :@value

			begin
				@value = @block.call
			rescue Exception => e
				@exception = e

				raise
			end
		}
	end

	alias ~ value

	# Do the same as {#value}, but return nil in case of exception.
	def value!
		begin
			value
		rescue Exception
			nil
		end
	end

	alias ! value!
end

class Thread
	# Helper to create Thread::Delay
	def self.delay (&block)
		Thread::Delay.new(&block)
	end
end

module Kernel
	# Helper to create a Thread::Delay
	def delay (&block)
		Thread::Delay.new(&block)
	end
end

Version data entries

12 entries across 12 versions & 3 rubygems

Version Path
thread-0.2.2 lib/thread/delay.rb
thread-0.2.1 lib/thread/delay.rb
seekingalpha_thread-1.0.1 lib/thread/delay.rb
thread-0.2.0 lib/thread/delay.rb
thread-0.1.7 lib/thread/delay.rb
thread-0.1.6 lib/thread/delay.rb
thread-0.1.5 lib/thread/delay.rb
thread-0.1.4 lib/thread/delay.rb
thread-0.1.3 lib/thread/delay.rb
thread-0.1.2 lib/thread/delay.rb
vinted-thread-0.1.1 lib/thread/delay.rb
thread-0.1.1 lib/thread/delay.rb