Sha256: 1338a1238489b3a6d6ec646b5dda8e52029ed06a4a29786e7804ce77d579b6b6

Contents?: true

Size: 1.33 KB

Versions: 1

Compression:

Stored size: 1.33 KB

Contents

require 'ara/exception'

# This class allow you to create simple actors. 
class SimpleActor
  def initialize #:nodoc:
    raise ActorInitializationError, "You can't initialize SimpleActor directly, use Actors.actor_of" if self.class == ::SimpleActor
    @actorQueue = Queue.new
  end

  # Start actor and return it
  #
  #   myActor = Actors.actor_of(MyActor)
  #   myActor.start
  def start
    self.send(:pre_start) if self.respond_to?(:pre_start, true)
    @thread = Thread.new do 
      loop do
        receive(@actorQueue.shift)
      end
    end

    return self
  end

  # Stop actor
  #
  #   myActor = Actors.actor_of(MyActor).start
  #   ...
  #   myActor.stop
  def stop
    @thread.kill
    self.send(:post_stop) if self.respond_to?(:post_stop, true)
  end

  # Send a simple message without expecting any response
  #
  #   myActor = Actors.actor_of(MyActor).start
  #   message = ...
  #   myActor | message
  def |(message)
    if @thread.alive?
      @actorQueue << message
    else 
      raise DeadActor, "Actor is dead!"
    end
  end
  alias :message :|

  private
  # Method receiver for the actor
  #
  # When you create an actor (simple or not) you *must* define a <tt>receive</tt> method.
  #
  #   class MyActor < Actor
  #     def receive(message)
  #       ...
  #     end
  #   end
  def receive(message)
    raise "Define me!"
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ara-0.0.3 lib/ara/simple_actor.rb