Sha256: c0320ac328d71b11d37edceebe695a7a051dc70513f9dac989a5f4bb9cd59820

Contents?: true

Size: 1.05 KB

Versions: 8

Compression:

Stored size: 1.05 KB

Contents

# frozen_string_literal: true

require "weakref"

module Roo
  module Helpers
    module WeakInstanceCache
      private

      def instance_cache(key)
        object = nil

        if instance_variable_defined?(key) && (ref = instance_variable_get(key)) && ref.weakref_alive?
          begin
            object = ref.__getobj__
          rescue => e
            unless (defined?(::WeakRef::RefError) && e.is_a?(::WeakRef::RefError)) || (defined?(RefError) && e.is_a?(RefError))
              raise e
            end
          end
        end

        unless object
          object = yield
          ObjectSpace.define_finalizer(object, instance_cache_finalizer(key))
          instance_variable_set(key, WeakRef.new(object))
        end

        object
      end

      def instance_cache_finalizer(key)
        proc do |object_id|
          if instance_variable_defined?(key) && (ref = instance_variable_get(key)) && (!ref.weakref_alive? || ref.__getobj__.object_id == object_id)
            remove_instance_variable(key)
          end
        end
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 2 rubygems

Version Path
roo-2.10.1 lib/roo/helpers/weak_instance_cache.rb
roo-2.10.0 lib/roo/helpers/weak_instance_cache.rb
roo-2.9.0 lib/roo/helpers/weak_instance_cache.rb
ruh-roo-3.0.1 lib/roo/helpers/weak_instance_cache.rb
roo-2.8.3 lib/roo/helpers/weak_instance_cache.rb
roo-2.8.2 lib/roo/helpers/weak_instance_cache.rb
roo-2.8.1 lib/roo/helpers/weak_instance_cache.rb
roo-2.8.0 lib/roo/helpers/weak_instance_cache.rb