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

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, options={})
      perform_request Net::HTTP::Get, path, options
    end

    # Get response from cache, if available
    #
    def self.get_with_caching(path, options={})
      return get_without_caching(path, options) unless get_cache
      key = path.downcase # this makes a copy of path
      key << options[:query].to_s if defined? options[:query]
      if res = get_cache.read(key) 
        return res
      else
        response =  get_without_caching(path, options)
        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, options={})
      self.get_with_caching(path, options)
    end

  end
end