Class: Moxml::XPath::Cache

Inherits:
Object
  • Object
show all
Defined in:
lib/moxml/xpath/cache.rb

Overview

Simple LRU (Least Recently Used) cache for compiled XPath expressions.

Constant Summary collapse

DEFAULT_SIZE =
1000

Instance Method Summary collapse

Constructor Details

#initialize(max_size = DEFAULT_SIZE) ⇒ Cache

Returns a new instance of Cache.

Parameters:

  • max_size (Integer) (defaults to: DEFAULT_SIZE)

    Maximum number of entries to cache



12
13
14
15
16
17
18
19
20
# File 'lib/moxml/xpath/cache.rb', line 12

def initialize(max_size = DEFAULT_SIZE)
  @max_size = max_size
  # One insertion-ordered hash: re-inserting a key on access
  # makes the first entry the least-recently-used. An
  # Array-backed order list cost ~600ns per hit in O(n)
  # deletes — the adapter's xpath path hits three caches per
  # call.
  @entries = {}
end

Instance Method Details

#clearvoid

This method returns an undefined value.

Clears the cache.



64
65
66
# File 'lib/moxml/xpath/cache.rb', line 64

def clear
  @entries.clear
end

#get(key) ⇒ Object?

Gets a value from the cache.

Parameters:

  • key (Object)

Returns:

  • (Object, nil)


54
55
56
57
58
59
# File 'lib/moxml/xpath/cache.rb', line 54

def get(key)
  return unless @entries.key?(key)

  value = @entries.delete(key)
  @entries[key] = value
end

#get_or_set(key) { ... } ⇒ Object

Gets a value from the cache or sets it using the provided block.

Parameters:

  • key (Object)

    Cache key

Yields:

  • Block to execute if key is not in cache

Returns:

  • (Object)

    Cached or newly computed value



27
28
29
30
31
32
33
34
35
36
# File 'lib/moxml/xpath/cache.rb', line 27

def get_or_set(key)
  if @entries.key?(key)
    value = @entries.delete(key)
    @entries[key] = value
  else
    value = yield
    set(key, value)
    value
  end
end

#key?(key) ⇒ Boolean

Checks if a key exists in the cache.

Parameters:

  • key (Object)

Returns:

  • (Boolean)


79
80
81
# File 'lib/moxml/xpath/cache.rb', line 79

def key?(key)
  @entries.key?(key)
end

#set(key, value) ⇒ Object

Sets a value in the cache.

Parameters:

  • key (Object)
  • value (Object)

Returns:

  • (Object)

    The value



43
44
45
46
47
48
# File 'lib/moxml/xpath/cache.rb', line 43

def set(key, value)
  @entries.delete(key)
  @entries[key] = value
  @entries.shift if @entries.size > @max_size
  value
end

#sizeInteger

Returns the current size of the cache.

Returns:

  • (Integer)


71
72
73
# File 'lib/moxml/xpath/cache.rb', line 71

def size
  @entries.size
end