Skip to content

Instantly share code, notes, and snippets.

@mikesea
Last active December 18, 2015 01:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikesea/5702672 to your computer and use it in GitHub Desktop.
Save mikesea/5702672 to your computer and use it in GitHub Desktop.
caching client-side responses
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