1
0
Fork 0
mirror of https://github.com/rubyjs/therubyracer synced 2023-03-27 23:21:42 -04:00
therubyracer/lib/v8/util/weakcell.rb
2012-06-12 03:44:50 -05:00

32 lines
No EOL
670 B
Ruby

require 'weakref'
module V8
module Util
module Weakcell
def weakcell(name, &block)
unless storage = instance_variable_get("@#{name}")
storage = instance_variable_set("@#{name}", Storage.new)
end
storage.access(&block)
end
class Storage
def access(&block)
if @ref
@ref.__getobj__
else
populate(block)
end
rescue RefError
populate(block)
end
private
def populate(block)
occupant = block.call()
@ref = WeakRef.new(occupant)
return occupant
end
end
end
end
end