Skip to content

Instantly share code, notes, and snippets.

@ponkotuy
Created February 28, 2019 10:01
Show Gist options
  • Save ponkotuy/70a5505a2fa723ec602cfeb810ef0352 to your computer and use it in GitHub Desktop.
Save ponkotuy/70a5505a2fa723ec602cfeb810ef0352 to your computer and use it in GitHub Desktop.
CacheAPIWrapper
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
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