Module: HTTParty::DryIce
- Defined in:
- lib/dry_ice.rb
Overview
Caching for HTTParty
See documentation in HTTParty::Icebox::ClassMethods.cache
Defined Under Namespace
Modules: ClassMethods Classes: CachedHTTPartyResponse, IceCache
Class Method Summary collapse
-
.included(receiver) ⇒ Object
When included, extend class with
cache
method and redefineget
method to use cache.
Class Method Details
.included(receiver) ⇒ Object
When included, extend class with cache
method and redefine get
method to use cache
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
# File 'lib/dry_ice.rb', line 52 def self.included(receiver) #:nodoc: receiver.extend ClassMethods receiver.class_eval do # Get reponse from network # # TODO: Why alias :new :old is not working here? Returns NoMethodError # def self.get_without_caching(path, ={}) perform_request Net::HTTP::Get, path, end # Get response from cache, if available # def self.get_with_caching(path, ={}) return get_without_caching(path, ) unless get_cache key = path.downcase # this makes a copy of path key << [:query].to_s if defined? [:query] if res = get_cache.read(key) return res else response = get_without_caching(path, ) if cache_for = self.cache_response?(response) get_cache.write(key,response, :expires_in => cache_for) return response else return response end end end #returns falsy if the response should not be cached - otherwise returns the timeout in seconds to cache for def self.cache_response?(response) return false if !response.body return false unless response.code.to_s == "200" timeout = response.headers['cache-control'] && response.headers['cache-control'][/max-age=(\d+)/, 1].to_i() return false unless timeout && timeout != 0 return timeout end # Redefine original HTTParty +get+ method to use cache # def self.get(path, ={}) self.get_with_caching(path, ) end end end |