Class: Astronoby::Cache
- Inherits:
-
Object
- Object
- Astronoby::Cache
- Includes:
- Singleton
- Defined in:
- lib/astronoby/cache.rb
Defined Under Namespace
Classes: Entry
Constant Summary collapse
- DEFAULT_MAX_SIZE =
10_000
Instance Attribute Summary collapse
-
#max_size ⇒ Object
Returns the value of attribute max_size.
Instance Method Summary collapse
-
#[](key) ⇒ Object?
The value, or nil if not found.
-
#[]=(key, value) ⇒ Object
The value set.
- #clear ⇒ void
-
#fetch(key) ⇒ Object
Cached or computed value.
- #initialize(max_size = DEFAULT_MAX_SIZE) ⇒ void constructor
- #size ⇒ Integer
Constructor Details
#initialize(max_size = DEFAULT_MAX_SIZE) ⇒ void
18 19 20 21 22 23 24 |
# File 'lib/astronoby/cache.rb', line 18 def initialize(max_size = DEFAULT_MAX_SIZE) @max_size = max_size @hash = {} @head = nil @tail = nil @mutex = Monitor.new end |
Instance Attribute Details
#max_size ⇒ Object
Returns the value of attribute max_size.
14 15 16 |
# File 'lib/astronoby/cache.rb', line 14 def max_size @max_size end |
Instance Method Details
#[](key) ⇒ Object?
Returns the value, or nil if not found.
28 29 30 31 32 33 34 35 36 |
# File 'lib/astronoby/cache.rb', line 28 def [](key) @mutex.synchronize do entry = @hash[key] if entry move_to_head(entry) entry.value end end end |
#[]=(key, value) ⇒ Object
Returns the value set.
41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/astronoby/cache.rb', line 41 def []=(key, value) @mutex.synchronize do entry = @hash[key] if entry entry.value = value move_to_head(entry) else entry = Entry.new(key, value) add_to_head(entry) @hash[key] = entry evict_last_recently_used if @hash.size > @max_size end end end |
#clear ⇒ void
This method returns an undefined value.
72 73 74 75 76 77 |
# File 'lib/astronoby/cache.rb', line 72 def clear @mutex.synchronize do @hash.clear @head = @tail = nil end end |
#fetch(key) ⇒ Object
Returns Cached or computed value.
59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/astronoby/cache.rb', line 59 def fetch(key) return self[key] if @mutex.synchronize { @hash.key?(key) } value = yield @mutex.synchronize do self[key] = value unless @hash.key?(key) end value end |
#size ⇒ Integer
80 81 82 |
# File 'lib/astronoby/cache.rb', line 80 def size @mutex.synchronize { @hash.size } end |