Class: MeterCat::Cache
- Inherits:
-
Hash
- Object
- Hash
- MeterCat::Cache
- Includes:
- Singleton
- Defined in:
- app/models/meter_cat/cache.rb
Instance Method Summary collapse
-
#add(name, value, created_on) ⇒ Object
Adds the given value to the hash Flushes expired data to DB.
-
#cache(name, value, created_on) ⇒ Object
Creates a new Meter and stores is in the hash.
-
#flush(name) ⇒ Object
Flushes data to the DB and removes it from the hash.
-
#flush_all ⇒ Object
Flushes all keys.
-
#initialize ⇒ Cache
constructor
A new instance of Cache.
Constructor Details
Instance Method Details
#add(name, value, created_on) ⇒ Object
Adds the given value to the hash Flushes expired data to DB
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'app/models/meter_cat/cache.rb', line 15 def add(name, value, created_on) meter = fetch(name, nil) # If the name isn't cached, cache it and return return cache(name, value, created_on) unless meter # If the cached value is for a different day, flush it, cache the new value and return if meter.created_on != created_on flush(name) cache(name, value, created_on) return end # Add the new value to the cached value and flush if expired meter.value += value flush(name) if meter.expired? end |
#cache(name, value, created_on) ⇒ Object
Creates a new Meter and stores is in the hash
35 36 37 38 |
# File 'app/models/meter_cat/cache.rb', line 35 def cache(name, value, created_on) meter = Meter.new(name: name, value: value, created_on: created_on, created_at: Time.now) store(name, meter) end |
#flush(name) ⇒ Object
Flushes data to the DB and removes it from the hash
42 43 44 45 46 |
# File 'app/models/meter_cat/cache.rb', line 42 def flush(name) meter = delete(name) return unless meter meter.add_with_retry end |
#flush_all ⇒ Object
Flushes all keys
50 51 52 |
# File 'app/models/meter_cat/cache.rb', line 50 def flush_all keys.each { |key| flush(key) } end |