Skip to content

Instantly share code, notes, and snippets.

@practicingruby
Created January 18, 2013 16:44
Show Gist options
  • Select an option

  • Save practicingruby/4565954 to your computer and use it in GitHub Desktop.

Select an option

Save practicingruby/4565954 to your computer and use it in GitHub Desktop.
# from Alberto Fernandez-Capel(afcapel) for a practicing ruby article
require 'thread'
module Actor
module ClassMethods
def new(*args, &block)
Thread.current[:actor] = Proxy.new(super)
end
end
class << self
def included(klass)
klass.extend(ClassMethods)
end
def current
Thread.current[:actor]
end
end
end
class Proxy
def initialize(target)
@target = target
@mailbox = Queue.new
@running = true
run
end
def run
Thread.new do
Thread.current[:actor] = self
begin
while @running
method, args = @mailbox.pop
@target.send(method, *args)
end
rescue Exception => ex
puts "Error while running actor: #{ex}"
puts ex.backtrace.join("\n")
end
end
end
def terminate
@running = false
end
def method_missing(method, *args)
if match = method.to_s.match(/(.*)!$/)
unbanged_method = match[1]
@mailbox << [unbanged_method, args]
else
@target.send(method, *args)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment