-
-
Save practicingruby/4565954 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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