Class: Dunder::Future

Inherits:
SimpleDelegator
  • Object
show all
Defined in:
lib/dunder.rb

Constant Summary collapse

FORBIDDEN =
[Symbol]
@@threads =
{}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(group = nil, &block) ⇒ Future

Returns a new instance of Future.

Raises:

  • (ArgumentError)


21
22
23
24
25
# File 'lib/dunder.rb', line 21

def initialize(group = nil,&block)
  raise ArgumentError,"No block was passed for execution" unless block
  @_thread = group ? group.start_thread(&block) : Thread.start(&block)
  @@threads[@_thread.object_id] = @_thread
end

Instance Attribute Details

#_threadObject (readonly)

Returns the value of attribute _thread.



19
20
21
# File 'lib/dunder.rb', line 19

def _thread
  @_thread
end

Class Method Details

.ensure_threads_finished(timeout = nil) ⇒ Object



13
14
15
16
17
# File 'lib/dunder.rb', line 13

def self.ensure_threads_finished(timeout = nil)
  @@threads.values.each do |t|
    raise 'Thread did not timeout in time' unless t.join(timeout)
  end
end

.threadsObject



9
10
11
# File 'lib/dunder.rb', line 9

def self.threads
  @@threads
end

Instance Method Details

#__getobj__Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/dunder.rb', line 27

def __getobj__
  # Optimizing a bit
  return super if @delegate_sd_obj
  __setobj__(@_thread.value)
  #@delegate_sd_obj = @_thread.value
  if FORBIDDEN.include?(super.class)
    error = "Your block returned a #{super.class} and because of how ruby handles #{FORBIDDEN.join(", ")}"
    error << " the #{super.class} won't behave correctly. There are two known workarounds:"
    error << " add the suffix ._thread.value or construct the block to return a array of length 1 and say lazy_array.first."
    error << "Ex: puts lazy_object becomes lazy_object._thread.value"
    raise ArgumentError,error
  end
  @@threads.delete @_thread.object_id
  super
end

#classObject



43
44
45
# File 'lib/dunder.rb', line 43

def class
  __getobj__.class
end