Skip to content

Instantly share code, notes, and snippets.

@mauricioszabo
Created November 6, 2014 20:48
Show Gist options
  • Save mauricioszabo/6a713fd416c512e49f70 to your computer and use it in GitHub Desktop.
Save mauricioszabo/6a713fd416c512e49f70 to your computer and use it in GitHub Desktop.
Akka 2.3.2 in JRuby
require 'config-1.2.0.jar'
require 'java'
require 'scala-library.jar'
require 'akka-actor_2.10-2.3.2.jar'
java_import 'akka.actor.UntypedActor'
java_import 'akka.actor.Actor'
java_import 'akka.actor.ActorRef'
java_import 'akka.actor.ActorSystem'
java_import 'akka.actor.UntypedActorFactory'
java_import 'akka.actor.ReceiveTimeout'
java_import 'akka.actor.SupervisorStrategy'
java_import 'akka.routing.RoundRobinRouter'
java_import 'akka.actor.Props'
java_import 'java.lang.System'
java_import 'scala.concurrent.duration.Duration'
java_import 'java.util.concurrent.TimeUnit'
java_import 'akka.japi.Creator'
java_import 'akka.japi.Procedure'
java_import 'akka.pattern.Patterns'
module Akka
class Creator
include Java::akka.japi.Creator
def initialize(klass, *params)
@klass = klass
@params = params
end
def create
@klass.new(*@params)
end
end
class Actor < UntypedActor
def self.props(*params)
Props.create(java_class, Akka::Creator.new(self, *params))
end
def actor
get_self
end
alias :myself :actor
def onReceive(msg)
receive(msg)
end
def tell(other_actor, msg, sender = actor)
other_actor.tell(msg, sender)
end
def ask(other_actor, msg, timeout = 10_000)
Patterns.ask(other_actor, msg, timeout)
end
def forward(other_actor, msg)
other_actor.forward(msg, context)
end
def self.receive(&block)
context(:receive, &block)
define_method :receive do |msg|
partial = ProcedureCreator.new(self)
partial.instance_exec &block
partial.apply(msg)
end
end
def self.context(method_name, &block)
define_method method_name do |*args|
partial = ProcedureCreator.new(self)
partial.instance_exec *args, &block
partial
end
end
end
class ProcedureCreator
include Procedure
def initialize(actor)
@actor = actor
@cases = {}
@unhandled = ->(msg) { unhandled(msg) }
end
def match(obj, &block)
@cases[obj] = block
end
def otherwise(&block)
@unhandled = block
end
def apply(msg)
_, block = @cases.find { |key, _| key === msg }
if(block)
@actor.instance_exec(msg, &block)
else
@actor.instance_exec(msg, &@unhandled)
end
end
end
end
require_relative 'actor'
Greeting = Struct.new(:who)
class GreetingActor < Akka::Actor
receive do
match(Greeting) { |message| puts "Hello, #{message.who}" }
end
end
system = ActorSystem.create("MySystem")
greeter = system.actor_of(GreetingActor.props, "greeter")
greeter.tell(Greeting.new("Charlie Parker"), ActorRef.no_sender)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment