diff --git a/README.md b/README.md index 65adf926..c5de4aac 100644 --- a/README.md +++ b/README.md @@ -226,27 +226,63 @@ Typhoeus includes built in support for caching. In the following example, if the ```ruby class Cache - attr_accessor :memory - def initialize @memory = {} end def get(request) - memory[request] + @memory[request] end def set(request, response) - memory[request] = response + @memory[request] = response end end Typhoeus::Config.cache = Cache.new -Typhoeus.get("www.example.com") == Typhoeus.get("www.example.com") +Typhoeus.get("www.example.com").cached? +#=> false +Typhoeus.get("www.example.com").cached? #=> true ``` +For use with [Dalli](https://github.com/mperham/dalli): + +```ruby +class Cache + def initialize + @client = Dalli::Client.new + end + + def get(request) + @client.get(request.cache_key) + end + + def set(request, response) + @client.set(request.cache_key, response) + end +end + +Typhoeus::Config.cache = Cache.new +``` + +For use with Rails: + +```ruby +class Cache + def get(request) + Rails.cache.read(request) + end + + def set(request, response) + Rails.cache.write(request, response) + end +end + +Typhoeus::Config.cache = Cache.new +``` + ### Direct Stubbing Hydra allows you to stub out specific urls and patterns to avoid hitting diff --git a/lib/typhoeus/request.rb b/lib/typhoeus/request.rb index 70d1c6ea..321974ff 100644 --- a/lib/typhoeus/request.rb +++ b/lib/typhoeus/request.rb @@ -154,7 +154,15 @@ def eql?(other) # # @api private def hash - Zlib.crc32 "#{self.class.name}#{base_url}#{hashable_string_for(options)}" + Zlib.crc32 cache_key + end + + # Returns a cache key for use with caching methods that required a string + # for a key. Will get used by ActiveSupport::Cache stores automatically. + # + # @return [ String ] The cache key. + def cache_key + "#{self.class.name}#{base_url}#{hashable_string_for(options)}" end # Mimics libcurls POST body generation. This is not accurate, but good