Skip to content

Instantly share code, notes, and snippets.

@onyxraven
Last active December 15, 2015 05:09
Show Gist options
  • Save onyxraven/5206981 to your computer and use it in GitHub Desktop.
Save onyxraven/5206981 to your computer and use it in GitHub Desktop.
A stab at using RequestStore (https://github.com/steveklabnik/request_store) as a rails Cache::Store
class RequestCacheStore < ActiveSupport::Cache::Store
# Delete all entries with keys matching the pattern.
#
# Options are passed to the underlying cache implementation.
#
# All implementations may not support this method.
def delete_matched(matcher, options = nil)
options = merged_options(options)
instrument(:delete_matched, matcher.inspect) do
matcher = key_matcher(matcher, options)
RequestStore.keys.each do |key|
delete_entry(key, options) if key.match(matcher)
end
end
end
# Increment an integer value in the cache.
#
# Options are passed to the underlying cache implementation.
#
# All implementations may not support this method.
def increment(name, amount = 1, options = nil)
options = merged_options(options)
if num = read(name, options)
num = num.to_i + amount
write(name, num, options)
num
else
nil
end
end
# Decrement an integer value in the cache.
#
# Options are passed to the underlying cache implementation.
#
# All implementations may not support this method.
def decrement(name, amount = 1, options = nil)
options = merged_options(options)
if num = read(name, options)
num = num.to_i - amount
write(name, num, options)
num
else
nil
end
end
# Cleanup the cache by removing expired entries.
#
# Options are passed to the underlying cache implementation.
#
# All implementations may not support this method.
def cleanup(options = nil)
options = merged_options(options)
RequestStore.store.keys.each do |key|
entry = RequestStore.store[key]
delete_entry(key, options) if entry && entry.expired?
end
end
# Clear the entire cache. Be careful with this method since it could
# affect other processes if shared cache is being used.
#
# Options are passed to the underlying cache implementation.
#
# All implementations may not support this method.
def clear(options = nil)
RequestStore.clear!
end
protected
# Read an entry from the cache implementation. Subclasses must implement
# this method.
def read_entry(key, options) # :nodoc:
RequestStore.store[key]
end
# Write an entry to the cache implementation. Subclasses must implement
# this method.
def write_entry(key, entry, options) # :nodoc:
RequestStore.store[key] = entry
end
# Delete an entry from the cache implementation. Subclasses must
# implement this method.
def delete_entry(key, options) # :nodoc:
RequestStore.store.delete(key)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment