Created
July 2, 2011 14:25
-
-
Save jemminger/1060484 to your computer and use it in GitHub Desktop.
Make any Ruby method asynchronous
This file contains 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 http://stackoverflow.com/questions/6499654/is-there-an-asynchronous-logging-library-for-ruby/6527134#6527134 | |
require 'thread' | |
require 'singleton' | |
require 'delegate' | |
require 'monitor' | |
class Async | |
include Singleton | |
def initialize | |
@queue = Queue.new | |
Thread.new { loop { @queue.pop.call } } | |
end | |
def run(&blk) | |
@queue.push blk | |
end | |
end | |
class Work < Delegator | |
include MonitorMixin | |
def initialize(&work) | |
super work; @work, @done, @lock = work, false, new_cond | |
end | |
def calc | |
synchronize { | |
@result, @done = @work.call, true; | |
@lock.signal | |
} | |
end | |
def __getobj__ | |
synchronize { @lock.wait_while { !@done } } | |
@result | |
end | |
end | |
Module.class.class_exec { | |
def async(*method_names) | |
method_names.each do |method_name| | |
original_method = instance_method(method_name) | |
define_method(method_name) do |*args,&blk| | |
work = Work.new { original_method.bind(self).call(*args,&blk) } | |
Async.instance.run { work.calc } | |
return work | |
end | |
end | |
end | |
} |
This file contains 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
require 'Logger' | |
class Logger | |
async :debug | |
end | |
log = Logger.new STDOUT | |
log.debug "heloo" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment