Skip to content

Instantly share code, notes, and snippets.

@philtr
Last active February 17, 2016 15:12
Show Gist options
  • Save philtr/6f98d6dae9fce189d70a to your computer and use it in GitHub Desktop.
Save philtr/6f98d6dae9fce189d70a to your computer and use it in GitHub Desktop.
class ApplicationPresenter
# Override this in your presenter
def to_hash
{}
end
def to_json
to_hash.to_json
end
class << self
def render
JSON.parse(retrieve, object_class: OpenStruct)
rescue TypeError => error
if saved?
raise error
else
save
render
end
end
def retrieve
if perform_caching?
redis.get(redis_key)
else
instance.to_json
end
end
def save
redis.set(redis_key, instance.to_json)
end
def saved?
redis.exists(redis_key)
end
private
def instance
@instance ||= new
end
def perform_caching?
ENV["CACHE_PRESENTERS"] || Rails.application.config.action_controller.perform_caching
end
def redis
REDIS
end
def redis_key
self.to_s.split("::").map(&:underscore).join(":")
end
end
end
class SamplePresenter < ApplicationPresenter
def to_hash
{
data: really_expensive_computation!
}
end
private
def really_expensive_computation!
sleep 10
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment