Class: ViewDelegates::Cache

Inherits:
Object
  • Object
show all
Defined in:
lib/view_delegates/poros/cache.rb

Overview

View cache class

Defined Under Namespace

Classes: CacheEntry

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(max_size: 10) ⇒ Cache

Initializer

Parameters:

  • max_size (Integer) (defaults to: 10)


11
12
13
14
# File 'lib/view_delegates/poros/cache.rb', line 11

def initialize(max_size: 10)
  @entries = []
  @max_size = max_size
end

Instance Attribute Details

#entriesObject

Accessor for the current entries Entries is an array, the most recent elements are at the end of the array



8
9
10
# File 'lib/view_delegates/poros/cache.rb', line 8

def entries
  @entries
end

Instance Method Details

#add(key:, value:) ⇒ Object

Add a new entry

Parameters:

  • key (Symbol)
  • value (String)


18
19
20
21
22
# File 'lib/view_delegates/poros/cache.rb', line 18

def add(key:, value:)
  @entries << CacheEntry.new(key, value)
  # If the array is full, remove the first element, since its the oldest
  @entries.delete_at 0 if @entries.length > @max_size
end

#get(key) ⇒ Object

Get an entry

Parameters:

  • key (Symbol)


25
26
27
28
29
30
31
32
33
# File 'lib/view_delegates/poros/cache.rb', line 25

def get(key)
  result = nil
  index = @entries.index { |e| e.key == key } rescue byebug
  if index
    result = @entries[index].value
    update_element index
  end
  result
end