Class: Threaded::Promise

Inherits:
Object
  • Object
show all
Defined in:
lib/threaded/promise.rb

Defined Under Namespace

Classes: NoJobError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&job) ⇒ Promise

Returns a new instance of Promise.



13
14
15
16
17
18
19
20
21
# File 'lib/threaded/promise.rb', line 13

def initialize(&job)
  raise "Must supply a job" unless job
  @mutex   = Mutex.new
  @has_run = false
  @running = false
  @result  = nil
  @error   = nil
  @job     = job
end

Instance Attribute Details

#errorObject (readonly)

Returns the value of attribute error.



11
12
13
# File 'lib/threaded/promise.rb', line 11

def error
  @error
end

#has_runObject (readonly) Also known as: has_run?

Returns the value of attribute has_run.



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

def has_run
  @has_run
end

#runningObject (readonly) Also known as: running?

Returns the value of attribute running.



10
11
12
# File 'lib/threaded/promise.rb', line 10

def running
  @running
end

Instance Method Details

#callObject



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/threaded/promise.rb', line 28

def call
  @mutex.synchronize do
    return true if running? || has_run?
    begin
      raise NoJobError unless @job
      @running = true
      @result  = @job.call
    rescue Exception => error
      @error   = error
    ensure
      @stdout = Thread.current[:stdout].dup if Thread.current[:stdout]
      Thread.current[:stdout] = nil
      @has_run = true
    end
  end
end

#laterObject



23
24
25
26
# File 'lib/threaded/promise.rb', line 23

def later
  Threaded.enqueue(self)
  self
end

#nowObject Also known as: join, value

Raises:



45
46
47
48
49
50
# File 'lib/threaded/promise.rb', line 45

def now
  wait_for_it!
  raise error, error.message, error.backtrace if error
  puts @stdout.string if @stdout
  @result
end