class ViewDelegates::Cache

View cache class

Constants

CacheEntry

Internal struct to save all the values

Attributes

entries[RW]

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

Public Class Methods

new(max_size: 10) click to toggle source

Initializer @param [Integer] max_size

# File lib/view_delegates/poros/cache.rb, line 11
def initialize(max_size: 10)
  @entries = []
  @max_size = max_size
end

Public Instance Methods

add(key:, value:) click to toggle source

Add a new entry @param [Symbol] key @param [String] value

# 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) click to toggle source

Get an entry @param [Symbol] key

# 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

Private Instance Methods

update_element(index) click to toggle source

Put the element at index one step to the right @param [Integer] index

# File lib/view_delegates/poros/cache.rb, line 38
def update_element(index)
  before = index - 1
  start = []
  start = @entries[0..before] unless before.negative?
  @entries = start, @entries[index..(index + 1)].reverse,
             @entries[(index + 2)..-1]
  @entries = @entries.flatten.uniq.reject &:nil?
end