Skip to content

WeakRef doesn't work #855

mperham opened this Issue May 3, 2011 · 3 comments

4 participants

mperham commented May 3, 2011

WeakRefs should pass through method invocations to the underlying objects. This seems to work on 1.9.2 but blows up on rbx.

require 'weakref'

x = "mike"
f =
puts f.size
Rubinius member
jc00ke commented Aug 20, 2011
@jfirebaugh jfirebaugh added a commit that closed this issue Apr 16, 2012
@jfirebaugh jfirebaugh Fix WeakRef delegation
On 1.8, implement #method_missing and #respond_to?. On 1.9,
#method_missing and #respond_to_missing?.

Also, in order to delegate the maximal set of methods to the
weakly-referenced object, remove #object, :object=, and
#inspect and inherit from BasicObject on 1.9.

Fixes #855.
headius commented Apr 17, 2012

I will point out that this behavior of WeakRef is a terrible feature. Having methods transparently pass through to the underlying impl means that at any time any method you're calling against it could fail. That could happen in the middle of your using that object if there are no strong references to it. Do not perpetuate this terrible abstraction if you can at all avoid it.

The pattern you want, in all cases without exception is:

obj = weakref.__getobj__
raise AppropriateError if obj.nil?

You should always be grabbing a reference to the object for any non-trivial use, and never allowing methods to transparently delegate to the referenced object.

headius commented Apr 17, 2012

FWIW, in an effort to eliminate this pattern I've filed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.