Class: Visionary::Future

Inherits:
Object
  • Object
show all
Defined in:
lib/visionary/future.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&blk) ⇒ Future

Returns a new instance of Future.



21
22
23
24
# File 'lib/visionary/future.rb', line 21

def initialize(&blk)
  @block = blk
  self.state = :pending
end

Instance Attribute Details

#errorObject (readonly)

Returns the value of attribute error.



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

def error
  @error
end

#stateObject

Returns the value of attribute state.



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

def state
  @state
end

#valueObject (readonly)

Returns the value of attribute value.



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

def value
  @value
end

Class Method Details

.setup!Object



5
6
7
8
9
10
11
12
# File 'lib/visionary/future.rb', line 5

def setup!
  unless setted_up
    Kernel.send :define_method, :future do |&blk|
      Future.new(&blk).run
    end
    self.setted_up = true
  end
end

Instance Method Details

#awaitObject



48
49
50
51
52
53
54
55
56
# File 'lib/visionary/future.rb', line 48

def await
  waiting_for && waiting_for.await

  unless thread
    run
  end

  thread.join
end

#runObject

Raises:

  • (RuntimeError)


26
27
28
29
30
# File 'lib/visionary/future.rb', line 26

def run
  raise RuntimeError, "This future have been already started" if thread
  @thread = Thread.new { run! }
  self
end

#then(&blk) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/visionary/future.rb', line 32

def then(&blk)
  fut = Future.new { blk.call(value) }
  fut.waiting_for = self

  case state
  when :pending
    callbacks << fut
  when :completed
    fut.run
  when :failed
    fut.fail_with(error)
  end

  fut
end