Skip to content

Commit

Permalink
Merge pull request #345 from mschulkind/cache_fix
Browse files Browse the repository at this point in the history
Make caching easier for non-memory caches.
  • Loading branch information
hanshasselberg committed Dec 27, 2013
2 parents 1eaedcc + bbd817c commit 72f3746
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 6 deletions.
46 changes: 41 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 9 additions & 1 deletion lib/typhoeus/request.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 72f3746

Please sign in to comment.