Class: LruQache
- Inherits:
-
Object
- Object
- LruQache
- Defined in:
- lib/lru_qache.rb
Overview
require “lru_qache/lru_queue”
Constant Summary collapse
- MAX_CAPACITY =
LRU cache is caching technique based on recently used data.
5- DEFAULT_VAL =
-1
- InvalidCapacityError =
Class.new RuntimeError
- INVALID_CAPACITY =
'Capacity must be valid number'.freeze
Instance Attribute Summary collapse
-
#cache ⇒ Object
readonly
Returns the value of attribute cache.
-
#capacity ⇒ Object
readonly
Returns the value of attribute capacity.
-
#options ⇒ Object
readonly
Returns the value of attribute options.
Instance Method Summary collapse
-
#get(key) ⇒ Object
(also: #[])
This gets the value based on the key is provided, updates the key usage.
-
#initialize(capacity = MAX_CAPACITY, options = { default_val: DEFAULT_VAL }) ⇒ LruQache
constructor
key is not present.
-
#set(key, val) ⇒ Object
(also: #[]=)
Sets the value of cache’s key.
Constructor Details
#initialize(capacity = MAX_CAPACITY, options = { default_val: DEFAULT_VAL }) ⇒ LruQache
key is not present
15 16 17 18 19 20 |
# File 'lib/lru_qache.rb', line 15 def initialize(capacity = MAX_CAPACITY, = { default_val: DEFAULT_VAL }) raise InvalidLimitError, INVALID_CAPACITY unless capacity.is_a?(Integer) @cache = {} @options = @capacity = capacity end |
Instance Attribute Details
#cache ⇒ Object (readonly)
Returns the value of attribute cache.
9 10 11 |
# File 'lib/lru_qache.rb', line 9 def cache @cache end |
#capacity ⇒ Object (readonly)
Returns the value of attribute capacity.
9 10 11 |
# File 'lib/lru_qache.rb', line 9 def capacity @capacity end |
#options ⇒ Object (readonly)
Returns the value of attribute options.
9 10 11 |
# File 'lib/lru_qache.rb', line 9 def @options end |
Instance Method Details
#get(key) ⇒ Object Also known as: []
This gets the value based on the key is provided, updates the key usage
27 28 29 30 31 |
# File 'lib/lru_qache.rb', line 27 def get(key) value = retrieve(key) update_lru(key) unless value == [:default_val] value end |
#set(key, val) ⇒ Object Also known as: []=
TODO:
Add validation to the key e.g. only Symbol, String or Integer etc.
Sets the value of cache’s key
39 40 41 42 43 44 |
# File 'lib/lru_qache.rb', line 39 def set(key, val) @cache.delete(key) if cache.has_key?(key) @cache[key] = val remove_lru_if_needed val end |