List of open files in your Rails Environment

Rohit Sharma 2013-07-13
List of open files in your Rails Environment

Sometimes when you are processing a huge number of files, you might need end up having the error “Too many open files”. I recently bumped into a similar issue, and the following code helped me solve the issue

ObjectSpace.each_object(File) do |f|
    if f.path.include?("rails_app_directory/tmp/uploads") && !f.closed?
        f.close
    end
end

The above code looks for open file descriptors from the desired directory and closes them. You can definitely change the file path according to your needs. This basically helps you keep the number of open files in your application in control, and in turn also improves the performance of your servers.