Skip to content

Instantly share code, notes, and snippets.

@fadhlirahim
Created May 14, 2016 04:33
Show Gist options
  • Save fadhlirahim/951780ecf2f344ef0b7fd3e399e2487b to your computer and use it in GitHub Desktop.
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
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
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