Created
May 31, 2018 08:05
-
-
Save tagomoris/89f159c10ba39fbb53e97a46c5a43058 to your computer and use it in GitHub Desktop.
fiber hack
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
class Foo | |
def initialize | |
@closed = false | |
end | |
def close | |
@closed = true | |
end | |
def closed? | |
@closed | |
end | |
end | |
module Defender | |
def close(*args, **kwargs) | |
Fiber.yield | |
super(*args, **kwargs) | |
end | |
end | |
def defer(obj) | |
obj.extend Defender | |
f = Fiber.new do | |
yield | |
end | |
f.resume | |
f | |
end | |
f = Foo.new | |
pp(closed: f.closed?) # false | |
d = defer(f){ p("block called"); f.close } # => "block called" | |
pp(closed: f.closed?) # false | |
d.resume | |
pp(closed: f.closed?) # true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment