Class: RDF::Util::Cache::WeakRefCache

Inherits:
RDF::Util::Cache show all
Defined in:
vendor/bundler/ruby/2.4.0/bundler/gems/rdf-da525ad24ff7/lib/rdf/util/cache.rb

Overview

This implementation uses the WeakRef class from Ruby's standard library, and provides adequate performance on JRuby and on Ruby 2.x.

Instance Method Summary collapse

Methods inherited from RDF::Util::Cache

#has_capacity?, #size

Constructor Details

#initialize(capacity = -1)) ⇒ WeakRefCache

Returns a new instance of WeakRefCache

Parameters:

  • capacity (Integer) (defaults to: -1))

Since:

  • 0.2.0



109
110
111
112
# File 'vendor/bundler/ruby/2.4.0/bundler/gems/rdf-da525ad24ff7/lib/rdf/util/cache.rb', line 109

def initialize(capacity = -1)
  require 'weakref' unless defined?(::WeakRef)
  super
end

Instance Method Details

#[](key) ⇒ Object

Parameters:

Returns:

Since:

  • 0.2.0



117
118
119
120
121
122
123
124
125
126
# File 'vendor/bundler/ruby/2.4.0/bundler/gems/rdf-da525ad24ff7/lib/rdf/util/cache.rb', line 117

def [](key)
  if (ref = @cache[key])
    if ref.weakref_alive?
      value = ref.__getobj__ rescue nil
    else
      @cache.delete(key)
      nil
    end
  end
end

#[]=(key, value) ⇒ Object

Parameters:

Returns:

Since:

  • 0.2.0



132
133
134
135
136
137
# File 'vendor/bundler/ruby/2.4.0/bundler/gems/rdf-da525ad24ff7/lib/rdf/util/cache.rb', line 132

def []=(key, value)
  if has_capacity?
    @cache[key] = WeakRef.new(value)
  end
  value
end

#delete(key) ⇒ Object

Remove cache entry for key

Parameters:

Returns:

  • (Object)

    the previously referenced object

Since:

  • 0.2.0



144
145
146
147
# File 'vendor/bundler/ruby/2.4.0/bundler/gems/rdf-da525ad24ff7/lib/rdf/util/cache.rb', line 144

def delete(key)
  ref = @cache.delete(key)
  ref.__getobj__ rescue nil
end