Skip to content

Instantly share code, notes, and snippets.

@cheerfulstoic
Created February 20, 2015 13:02
Show Gist options
  • Save cheerfulstoic/117ad8770aa5e5f165e2 to your computer and use it in GitHub Desktop.
Save cheerfulstoic/117ad8770aa5e5f165e2 to your computer and use it in GitHub Desktop.
GithubClientCache - First, not ideal attempt, at caching `github_api` responses
class GithubClientCache
CACHE = ActiveSupport::Cache::FileStore.new('cache')
CACHE_EXPIRY_PERIOD = (60 * 60 * 24 * 365) # 1 year
def initialize(current_object, arg_stack = [])
@current_object = current_object
@arg_stack = arg_stack
end
def method_missing(method, *args, &block)
new_arg_stack = @arg_stack + [[method, *args]]
if args.size > 0
CACHE.fetch(new_arg_stack.inspect, expires_in: cache_expiry_time) do
@current_object.send(method, *args, &block)
end.tap do |result|
# Ensure the result's body is a Hashie::Mash
# This doesn't happen on deserialization
result.body = if result.body.is_a?(Array)
result.body.map { |i| Hashie::Mash.new(i) }
else
Hashie::Mash.new(result.body)
end
end
else
self.class.new(@current_object.send(method, *args, &block), new_arg_stack)
end
end
private
def cache_expiry_time
Time.now + CACHE_EXPIRY_PERIOD
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment