mirror of
https://github.com/rubyjs/therubyracer
synced 2023-03-27 23:21:42 -04:00
32 lines
No EOL
670 B
Ruby
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 |