class Shifty::Worker

Attributes

supply[R]

Public Class Methods

new(p={}, &block) click to toggle source
# File lib/shifty/worker.rb, line 7
def initialize(p={}, &block)
  @supply   = p[:supply]
  @task     = block || p[:task]
  @context  = p[:context] || OpenStruct.new
  # 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

Public Instance Methods

"|"(subscribing_party)
Alias for: supplies
ready_to_work?() click to toggle source
# File lib/shifty/worker.rb, line 23
def ready_to_work?
  @task && (supply || !task_accepts_a_value?)
end
shift() click to toggle source
# File lib/shifty/worker.rb, line 18
def shift
  ensure_ready_to_work!
  workflow.resume
end
suppliable?() click to toggle source
# File lib/shifty/worker.rb, line 38
def suppliable?
  @task && @task.arity > 0
end
supplies(subscribing_party) click to toggle source
# File lib/shifty/worker.rb, line 27
def supplies(subscribing_party)
  subscribing_party.supply = self
  subscribing_party
end
Also aliased as: "|"
supply=(supplier) click to toggle source
# File lib/shifty/worker.rb, line 33
def supply=(supplier)
  raise WorkerError.new("Worker is a source, and cannot accept a supply") unless suppliable?
  @supply = supplier
end

Private Instance Methods

default_task() click to toggle source
# File lib/shifty/worker.rb, line 61
def default_task
  Proc.new { |value| value }
end
ensure_ready_to_work!() click to toggle source
# File lib/shifty/worker.rb, line 44
def ensure_ready_to_work!
  @task ||= default_task

  unless ready_to_work?
    raise "This worker's task expects to receive a value from a supplier, but has no supply."
  end
end
task_accepts_a_value?() click to toggle source
# File lib/shifty/worker.rb, line 65
def task_accepts_a_value?
  @task.arity > 0
end
task_method_accepts_a_value?() click to toggle source
# File lib/shifty/worker.rb, line 73
def task_method_accepts_a_value?
  self.method(:task).arity > 0
end
task_method_exists?() click to toggle source
# File lib/shifty/worker.rb, line 69
def task_method_exists?
  self.methods.include? :task
end
workflow() click to toggle source
# File lib/shifty/worker.rb, line 52
def workflow
  @my_little_machine ||= Fiber.new do
    loop do
      value = supply && supply.shift
      Fiber.yield @task.call(value, supply, @context)
    end
  end
end