Created
December 8, 2017 13:26
-
-
Save iliabylich/1dc265ae589749eb5e0f926d814e8b80 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
# Cache store that gets automatically expired after each request | |
# | |
# @example | |
# UsersCache = RequestStore::Cache.new(namespace: 'users') | |
# UsersCache.read(:user1) | |
# # => nil | |
# UsersCache.fetch(:user1) { User.find(1) } | |
# # => #<User id:1 ...> | |
# UsersCache.read(:user1) | |
# # => #<User id:1 ...> | |
# UsersCache.write(:user1, User.find(2)) | |
# # => true | |
# UsersCache.delete(:user1) | |
# # => true | |
# | |
class RequestStore::Cache | |
def initialize(namespace:) | |
@namespace = namespace | |
end | |
delegate :clear, to: :data | |
def read(key) | |
data[key] | |
end | |
def write(key, value) | |
data[key] = value | |
true | |
end | |
def fetch(key) | |
if data.key?(key) | |
data[key] | |
else | |
data[key] = yield | |
end | |
end | |
private | |
def data | |
RequestStore[@namespace] ||= {} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment