Class: Awssh::Cache
- Inherits:
-
Object
- Object
- Awssh::Cache
- Defined in:
- lib/awssh/cache.rb
Instance Attribute Summary collapse
-
#data ⇒ Object
readonly
Returns the value of attribute data.
Class Method Summary collapse
Instance Method Summary collapse
- #fetch(key, force) ⇒ Object
-
#initialize(file, expires) ⇒ Cache
constructor
A new instance of Cache.
- #read(key) ⇒ Object
- #write(key, value) ⇒ Object
Constructor Details
#initialize(file, expires) ⇒ Cache
Returns a new instance of Cache.
18 19 20 21 22 23 24 25 26 27 |
# File 'lib/awssh/cache.rb', line 18 def initialize(file, expires) if file @file = File.(file) else @disabled = true @file = nil end @expires = expires @data = load end |
Instance Attribute Details
#data ⇒ Object (readonly)
Returns the value of attribute data.
16 17 18 |
# File 'lib/awssh/cache.rb', line 16 def data @data end |
Class Method Details
.instance ⇒ Object
10 11 12 13 |
# File 'lib/awssh/cache.rb', line 10 def instance raise 'cache not loaded?' unless @instance.data @instance end |
.load(file) ⇒ Object
6 7 8 |
# File 'lib/awssh/cache.rb', line 6 def load(file) @instance = new(file) end |
Instance Method Details
#fetch(key, force) ⇒ Object
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/awssh/cache.rb', line 40 def fetch(key, force) if force || @disabled diff = Time.now.to_i else time = @data[key] ? @data[key][:time] : 0 diff = Time.now.to_i - time end if diff > @expires value = yield write(key, value) return value else read(key) end end |
#read(key) ⇒ Object
36 37 38 |
# File 'lib/awssh/cache.rb', line 36 def read(key) @data[key][:value] end |
#write(key, value) ⇒ Object
29 30 31 32 33 34 |
# File 'lib/awssh/cache.rb', line 29 def write(key, value) time = Time.now.to_i data = {time: time, value: value} @data[key] = data save end |