lib/stepladder/worker.rb in stepladder-0.0.2 vs lib/stepladder/worker.rb in stepladder-0.2.0
- old
+ new
@@ -4,39 +4,50 @@
def initialize(p={}, &block)
@supplier = p[:supplier]
@filter = p[:filter] || default_filter
@task = block || p[:task]
+ # don't define default task here
+ # because we want to allow for
+ # an initialized worker to have
+ # a task injected, including
+ # method-based tasks.
end
def product
- if ready_to_work?
- work.resume
- end
+ ensure_ready_to_work!
+ workflow.resume
end
def ready_to_work?
- @task ||= default_task
- if (task_accepts_a_value? && supplier.nil?)
- raise "This worker's task expects to receive a value from a supplier, but has no supplier."
- end
- true
+ @task && (supplier || !task_accepts_a_value?)
end
def |(subscribing_worker)
subscribing_worker.supplier = self
subscribing_worker
end
private
- def work
+ def ensure_ready_to_work!
+ @task ||= default_task
+ # at this point we will ensure a task exists
+ # because we know that the worker is being
+ # asked for product
+
+ unless ready_to_work?
+ raise "This worker's task expects to receive a value from a supplier, but has no supplier."
+ end
+ end
+
+ def workflow
@my_little_machine ||= Fiber.new do
loop do
value = supplier && supplier.product
if value.nil? || passes_filter?(value)
- handoff @task.call(value)
+ Fiber.yield @task.call(value)
end
end
end
end
@@ -73,10 +84,6 @@
def passes_filter?(value)
@filter.call value
end
end
-end
-
-def handoff(product)
- Fiber.yield product
end