Class: Nursery

Inherits:
Object
  • Object
show all
Defined in:
lib/nursery/child.rb,
lib/nursery/nursery.rb,
lib/nursery/version.rb,
lib/nursery/annotations.rb

Defined Under Namespace

Modules: Annotations Classes: Child

Constant Summary collapse

CancelledJob =
Class.new(StandardError)
VERSION =
"0.1.0"

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(default_config = {}) ⇒ Nursery

Returns a new instance of Nursery.



7
8
9
10
11
12
# File 'lib/nursery/nursery.rb', line 7

def initialize(default_config = {})
	@children = []
	@cancelled = false
	@finished = false
	@default_config = default_config
end

Class Attribute Details

.child_classObject

Returns the value of attribute child_class.



27
28
29
# File 'lib/nursery/child.rb', line 27

def child_class
  @child_class
end

Instance Attribute Details

#cancelledObject (readonly)

Returns the value of attribute cancelled.



3
4
5
# File 'lib/nursery/nursery.rb', line 3

def cancelled
  @cancelled
end

#childrenObject (readonly)

Returns the value of attribute children.



3
4
5
# File 'lib/nursery/nursery.rb', line 3

def children
  @children
end

#default_configObject (readonly)

Returns the value of attribute default_config.



3
4
5
# File 'lib/nursery/nursery.rb', line 3

def default_config
  @default_config
end

#finishedObject (readonly)

Returns the value of attribute finished.



3
4
5
# File 'lib/nursery/nursery.rb', line 3

def finished
  @finished
end

Class Method Details

.checkpointObject



52
53
54
55
56
57
# File 'lib/nursery/nursery.rb', line 52

def self.checkpoint
	if Thread.current[:nursery] && Thread.current[:nursery].cancelled
		yield if block_given?
		raise CancelledJob
	end
end

.with_nursery(config = {}, &block) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/nursery/nursery.rb', line 40

def self.with_nursery(config = {}, &block)
	nursery = new(config)
	begin
		retval = block.call(nursery)
	rescue StandardError
		nursery.cancel
		raise
	end
	nursery.finish
	retval
end

Instance Method Details

#cancelObject



35
36
37
38
# File 'lib/nursery/nursery.rb', line 35

def cancel
	@cancelled = true
	finish		
end

#finishObject



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/nursery/nursery.rb', line 22

def finish
	exceptions = children.map do |child|
		begin
			child.finish
			nil
		rescue Exception => e
			e
		end
	end.compact
	exceptions.each { |e| raise(e) }
	@finished = true
end

#run(config = default_config, &job) ⇒ Object



14
15
16
17
18
19
20
# File 'lib/nursery/nursery.rb', line 14

def run(config = default_config, &job)
	Nursery.checkpoint
	raise("Nursery#run called outside of with_nursery block") if finished
	child = self.class.child_class.new(self, config, job)
	children << child
	child
end