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
# File 'lib/moxml/xpath/cache.rb', line 12

def initialize(max_size = DEFAULT_SIZE)
  @max_size = max_size
  @cache = {}
  @access_order = []
end

Instance Method Details

#clearvoid

This method returns an undefined value.

Clears the cache.



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

def clear
  @cache.clear
  @access_order.clear
end

#get(key) ⇒ Object?

Gets a value from the cache.

Parameters:

  • key (Object)

Returns:

  • (Object, nil)


59
60
61
62
63
64
65
# File 'lib/moxml/xpath/cache.rb', line 59

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

  @access_order.delete(key)
  @access_order.push(key)
  @cache[key]
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



23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/moxml/xpath/cache.rb', line 23

def get_or_set(key)
  if @cache.key?(key)
    # Move to end (most recently used)
    @access_order.delete(key)
    @access_order.push(key)
    @cache[key]
  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)


86
87
88
# File 'lib/moxml/xpath/cache.rb', line 86

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

#set(key, value) ⇒ Object

Sets a value in the cache.

Parameters:

  • key (Object)
  • value (Object)

Returns:

  • (Object)

    The value



41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/moxml/xpath/cache.rb', line 41

def set(key, value)
  if @cache.key?(key)
    @access_order.delete(key)
  elsif @cache.size >= @max_size
    # Remove least recently used
    lru_key = @access_order.shift
    @cache.delete(lru_key)
  end

  @cache[key] = value
  @access_order.push(key)
  value
end

#sizeInteger

Returns the current size of the cache.

Returns:

  • (Integer)


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

def size
  @cache.size
end