Last active
December 18, 2015 01:19
-
-
Save mikesea/5702672 to your computer and use it in GitHub Desktop.
caching client-side responses
This file contains 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
require 'rest_client' | |
require 'active_support/cache' | |
class MyService | |
def self.find(id) | |
return unless id.present? | |
cache("my-service:#{id}", :ttl => 1.day) do | |
RestClient.get("http://myservice.com/foo/#{id}") | |
end | |
end | |
private | |
def self.cache(key, opts={}, &block) | |
@cache ||= ActiveSupport::Cache.lookup_store(:memory_store) | |
value = @cache.read(key) | |
if value.nil? && block_given? | |
value = block.call | |
opts[:expires_in] = 1.day unless opts[:expires_in] | |
@cache.write(key, value, opts) | |
end | |
value | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment