Created
February 28, 2019 10:01
-
-
Save ponkotuy/70a5505a2fa723ec602cfeb810ef0352 to your computer and use it in GitHub Desktop.
CacheAPIWrapper
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
class CommonCache | |
def initialize(prefix, expire) | |
@prefix = prefix | |
@expire = expire | |
end | |
def key(id) | |
"#{@prefix}_#{id}" | |
end | |
def read(id) | |
Rails.cache.read(key(id)) | |
end | |
def write(id, value) | |
Rails.cache.write(key(id), value, expires_in: @expire) | |
end | |
def fetch(id, &block) | |
Rails.cache.fetch(key(id), expires_in: @expire, &block) | |
end | |
end |
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
class JsonCache < CommonCache | |
def read(id) | |
res = super(id) | |
res && JSON.load(res, symbolize_names: true) | |
end | |
def write(id, value) | |
super(id, JSON.dump(value)) | |
end | |
def fetch(id, &block) | |
res = super(id) do | |
JSON.dump(block.call) | |
end | |
JSON.load(res) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment