Class: FrugalTimeout::Storage
- Inherits:
-
Object
- Object
- FrugalTimeout::Storage
- Defined in:
- lib/frugal_timeout/support.rb
Overview
{{{1 Storage Stores values for keys, such as:
-
‘set key, val’ will store val.
-
‘set key, val2’ will store [val, val2].
-
‘delete key, val2’ will lead to storing just val again.
I.e. array is used only when it’s absolutely necessary.
While it’s harder to write code because of this, we do save memory by not instantiating all those arrays.
Instance Method Summary collapse
- #delete(key, val = nil) ⇒ Object
- #get(key) ⇒ Object (also: #[])
-
#initialize ⇒ Storage
constructor
A new instance of Storage.
- #set(key, val) ⇒ Object
Constructor Details
#initialize ⇒ Storage
Returns a new instance of Storage.
116 117 118 |
# File 'lib/frugal_timeout/support.rb', line 116 def initialize @storage = {} end |
Instance Method Details
#delete(key, val = nil) ⇒ Object
120 121 122 123 124 125 126 127 128 129 130 |
# File 'lib/frugal_timeout/support.rb', line 120 def delete key, val=nil return unless stored = @storage[key] if val.nil? || stored == val @storage.delete key return end stored.delete val @storage[key] = stored.first if stored.size == 1 end |
#get(key) ⇒ Object Also known as: []
132 133 134 |
# File 'lib/frugal_timeout/support.rb', line 132 def get key @storage[key] end |
#set(key, val) ⇒ Object
137 138 139 140 141 142 143 144 145 146 147 148 |
# File 'lib/frugal_timeout/support.rb', line 137 def set key, val unless stored = @storage[key] @storage[key] = val return end if stored.is_a? Array stored << val else @storage[key] = [stored, val] end end |