Skip to content

Instantly share code, notes, and snippets.

@ahawkins
Created March 5, 2015 14:18
Show Gist options
  • Save ahawkins/0183b879ebf7d1757c13 to your computer and use it in GitHub Desktop.
Save ahawkins/0183b879ebf7d1757c13 to your computer and use it in GitHub Desktop.
# Failsafe operation mode
#
# Instantiate the cache with a block. Conditionally store the correct value
# only if the operation succeeds. Future calls to get must provided a fallback
# block, or they will recieve an error
cache = SimpleCache.new expires: 4.hours do |store, from, to|
begin
# Don't referesh cache if my_thing fails. An existing previous value
# will not be overwritten. Future calls must provide a fallback.
store.save exchange_rate.calculate(from, to)
rescue => ex
# Log error somewhere to help in debugging
logger.error('counter-cache') { "Location refresh failed: #{ex}"}
logger.error('counter-cache') { ex }
end
end
cache.get :usd, :eur do
# fallback value. Used of original block could not load correct value
0.8
end
cache.get :get, :bar # => SimpleCache::FallbackError when noting stored
# Explode Operation Mode
#
# Populating the cache may be a process ending condition if it fails.
# Simply execute code as normal. Uncaught errors will propagate to the
# top of the stack.
cache = SimpleCache.new expires: 4.hours do |store, foo, bar|
# Don't referesh cache if my_thing fails. An existing previous value
# will not be overwritten. Future calls must provide a fallback.
store.save my_thing.get(foo, bar)
end
cache.get :foo, :bar # => returns cached value is stored & not expires
cache.get :foo, :bar # => returns value of my thing_get.get(foo, bar) when value not store or expired
cache.get :foo, :bar # => raises an error if my_thing.get raises one
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment