Created
May 14, 2016 04:33
-
-
Save fadhlirahim/951780ecf2f344ef0b7fd3e399e2487b to your computer and use it in GitHub Desktop.
An elegant base presenter to help build json and caching solution using redis and marshalling & parsing json using Oj gem
This file contains hidden or 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 BasePresenter | |
CACHE_TTL = 600 | |
def initialize(resource, includes, flag) | |
@resource = resource | |
@includes = includes | |
@flag = flag | |
end | |
private | |
def pr_cache_key | |
"pr:#{resource.id}:#{flag}:#{resource.class.name}:#{includes.join(":")}" | |
end | |
def cached_hash | |
hash = $redis_reader.get(pr_cache_key) | |
return unless hash.present? | |
Oj.load(hash) | |
end | |
def set_cache(hash, ttl = CACHE_TTL) | |
return unless hash.present? | |
$redis_writer.setex(pr_cache_key, ttl, Oj.dump(hash, mode: :compat)) | |
end | |
def del_cache | |
$redis_writer.del(pr_cache_key) | |
end | |
end |
This file contains hidden or 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 UserPresenter < BasePresenter | |
def initialize(user, includes: [], flag: nil) | |
super(user, includes, flag) | |
end | |
def as_json | |
return cached_hash if cached_hash.present? | |
hash = { id: @resource.id, | |
username: @resource.username, | |
email: @resource.email, | |
first_name: @resource.first_name, | |
last_name: @resource.last_name } | |
set_cache(hash) | |
hash | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment