Class: MeterCat::Cache

Inherits:
Hash
  • Object
show all
Includes:
Singleton
Defined in:
app/models/meter_cat/cache.rb

Instance Method Summary collapse

Constructor Details

#initializeCache

Returns a new instance of Cache.


7
8
9
# File 'app/models/meter_cat/cache.rb', line 7

def initialize
  at_exit { MeterCat::Cache.instance.flush_all }
end

Instance Method Details

#add(name, value, created_on) ⇒ Object

Adds the given value to the hash Flushes expired data to DB


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'app/models/meter_cat/cache.rb', line 14

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


34
35
36
37
# File 'app/models/meter_cat/cache.rb', line 34

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


41
42
43
44
# File 'app/models/meter_cat/cache.rb', line 41

def flush( name )
  return unless meter = delete( name )
  meter.add_with_retry
end

#flush_allObject

Flushes all keys


48
49
50
# File 'app/models/meter_cat/cache.rb', line 48

def flush_all
  keys.each { |key| flush( key ) }
end