How to Find File Objects in JRuby?

I’d like to be able to introspect into the Ruby VM to find any open file
objects.

In MRI Ruby I can use ObjectSpace, e.g.:

files= ObjectSpace.each_object(File).to_a

…and could find a given filespec by:

ObjectSpace.each_object(File).select { |f| /input.txt/ === f.path }

Since ObjectSpace is disabled in JRuby, is there another way I could
accomplish this? The file may be opened by a gem over which I have no
control, so I can’t change the place where it’s open to hold on to the
handle.

Thanks,
Keith

Are you aware you can enable ObjectSpace? You use the -X+O flag. This
will
reduce performance as JRuby cannot currently ask the JVM to enumerate
live
objects, so we need to manually maintain a set of live objects.

Or are you aware of -X+O and asking for a workaround? Sorry, I’m not
aware
of one, beyond maybe you could monkey patch File#initialize to store a
list
of them yourself. You’d need a way to remove dead file objects.

Chris

Chris -

Thanks for responding. I’d like to find a solution that I could use in
a
gem that people could use without having a requirement to set a global
flag
like that. I guess though that I could document this issue, support the
file closing only if ObjectSpace is enabled, and let the users decide
for
themselves which way to go.

Is there some flag I can query at runtime to see if ObjectSpace is
enabled? I guess I could always look to see if the constant itself is
defined and points to a Module.

The File.open monkey patch idea is interesting.

Thanks again,
Keith

You can tell if it’s enabled via

require ‘java’
enabled = org.jruby.util.cli.Options::OBJECTSPACE_ENABLED.load

Monkey patching File.open is probably the best idea if this is really
what
you need to do.

Chris