Class: Thread::Delay

Inherits:
Object
  • Object
show all
Defined in:
lib/thread/delay.rb

Overview

A delay is an object that incapsulates a block which is called upon value retrieval, and its result cached.

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ Delay

Create a delay with the passed block.

Raises:

  • (ArgumentError)


17
18
19
20
21
22
# File 'lib/thread/delay.rb', line 17

def initialize (&block)
	raise ArgumentError, 'no block given' unless block

	@mutex = Mutex.new
	@block = block
end

Instance Method Details

#delivered?Boolean Also known as: realized?

Check if the delay has been called.

Returns:

  • (Boolean)


39
40
41
42
43
# File 'lib/thread/delay.rb', line 39

def delivered?
	@mutex.synchronize {
		instance_variable_defined? :@value
	}
end

#exceptionObject

Return the raised exception.



32
33
34
35
36
# File 'lib/thread/delay.rb', line 32

def exception
	@mutex.synchronize {
		@exception
	}
end

#exception?Boolean

Check if an exception has been raised.

Returns:

  • (Boolean)


25
26
27
28
29
# File 'lib/thread/delay.rb', line 25

def exception?
	@mutex.synchronize {
		instance_variable_defined? :@exception
	}
end

#valueObject Also known as: ~

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.



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/thread/delay.rb', line 52

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

#value!Object Also known as: !

Do the same as #value, but return nil in case of exception.



71
72
73
74
75
76
77
# File 'lib/thread/delay.rb', line 71

def value!
	begin
		value
	rescue Exception
		nil
	end
end