Class: Caddy::Cache
- Inherits:
-
Object
- Object
- Caddy::Cache
- Defined in:
- lib/caddy/cache.rb
Constant Summary collapse
- DEFAULT_REFRESH_INTERVAL =
60- REFRESH_INTERVAL_JITTER_PCT =
0.15
Instance Attribute Summary collapse
-
#error_handler ⇒ Object
Returns the value of attribute error_handler.
-
#refresh_interval ⇒ Object
Returns the value of attribute refresh_interval.
-
#refresher ⇒ Object
Returns the value of attribute refresher.
Instance Method Summary collapse
- #[](k) ⇒ Object
- #cache ⇒ Object
-
#initialize(key) ⇒ Cache
constructor
A new instance of Cache.
- #start ⇒ Object
- #stop ⇒ Object
Constructor Details
#initialize(key) ⇒ Cache
Returns a new instance of Cache.
9 10 11 12 13 14 |
# File 'lib/caddy/cache.rb', line 9 def initialize(key) @task = nil @refresh_interval = DEFAULT_REFRESH_INTERVAL @cache = nil @key = key end |
Instance Attribute Details
#error_handler ⇒ Object
Returns the value of attribute error_handler.
7 8 9 |
# File 'lib/caddy/cache.rb', line 7 def error_handler @error_handler end |
#refresh_interval ⇒ Object
Returns the value of attribute refresh_interval.
7 8 9 |
# File 'lib/caddy/cache.rb', line 7 def refresh_interval @refresh_interval end |
#refresher ⇒ Object
Returns the value of attribute refresher.
7 8 9 |
# File 'lib/caddy/cache.rb', line 7 def refresher @refresher end |
Instance Method Details
#[](k) ⇒ Object
16 17 18 |
# File 'lib/caddy/cache.rb', line 16 def [](k) cache[k] end |
#cache ⇒ Object
20 21 22 23 24 25 |
# File 'lib/caddy/cache.rb', line 20 def cache raise "Please run `Caddy.start` before attempting to access the cache" unless @task && @task.running? raise "Caddy cache access of :#{@key} before initial load; allow some more time for your app to start up" unless @cache @cache end |
#start ⇒ Object
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/caddy/cache.rb', line 27 def start unless refresher && refresher.respond_to?(:call) raise "Please set your cache refresher via `Caddy[:#{@key}].refresher = -> { <code that returns a value> }`" end raise "`Caddy[:#{@key}].refresh_interval` must be > 0" unless refresh_interval > 0 jitter_amount = [0.1, refresh_interval * REFRESH_INTERVAL_JITTER_PCT].max interval = refresh_interval + rand(-jitter_amount...jitter_amount) timeout_interval = [interval - 1, 0.1].max stop # stop any existing task from running @task = Concurrent::TimerTask.new( run_now: true, execution_interval: interval, timeout_interval: timeout_interval ) do @cache = refresher.call.freeze nil # no need to save the value internally to TimerTask end @task.add_observer(Caddy::TaskObserver.new(error_handler, @key)) @task.execute @task.running? end |
#stop ⇒ Object
55 56 57 |
# File 'lib/caddy/cache.rb', line 55 def stop @task.shutdown if @task && @task.running? end |