Project

General

Profile

Actions

Feature #19561

closed

ObjectSpace::WeakMap#delete and ObjectSpace::WeakKeyMap#delete

Added by byroot (Jean Boussier) over 1 year ago. Updated over 1 year ago.

Status:
Closed
Assignee:
-
Target version:
-
[ruby-core:113051]

Description

I just realized in https://bugs.ruby-lang.org/issues/19560#Ruby-shim that there's no way to remove elements from either WeakMaps.

I think they could both benefit from a delete method.

Use case

For example, to keep track of a subset of instances of a class, you may need to remove some from the list when a condition changes:

class Connection
  CLOSE_ON_FORK = ObjectSpace::WeakMap.new

  class << self
    def after_fork
      CLOSE_ON_FORK.each_key do |connection|
        connection.close if connection.close_on_fork?
      end
    end
  end

  def close_on_fork=(enabled)
    if enabled
      CLOSE_ON_FORK[self] = true
    else
      CLOSE_ON_FORK.delete(self)
    end
    @close_on_fork = enabled
  end

  def close_on_fork?
    @close_on_fork
  end
end

module CloseOnFork
  IOS = ObjectSpace::WeakMap.new

  def _fork
    pid = super
    if pid == 0 # child
      ::Connection.after_fork
    end
    pid
  end
end
Process.singleton_class.prepend(CloseIOOnFork)
Actions

Also available in: Atom PDF

Like1
Like0Like0