Module: HTTParty::Icebox

Defined in:
lib/httparty-icebox.rb

Overview

Caching for HTTParty

See documentation in HTTParty::Icebox::ClassMethods.cache

Defined Under Namespace

Modules: ClassMethods, Store Classes: Cache

Class Method Summary collapse

Class Method Details

.included(receiver) ⇒ Object

When included, extend class with cache method and redefine get method to use cache



49
50
51
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
# File 'lib/httparty-icebox.rb', line 49

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={})
      key = path.downcase # this makes a copy of path
      key << options[:query].to_s if defined? options[:query]
      if cache.exists?(key) and not cache.stale?(key)
        Cache.logger.debug "CACHE -- GET #{path}#{options[:query]}"
        return cache.get(key)
      else
        Cache.logger.debug "/!\\ NETWORK -- GET #{path}#{options[:query]}"

        begin
          response = get_without_caching(path, options)
          cache.set(key, response) if response.code.to_s == "200" # this works for string and integer response codes
          return response
        rescue
          if cache.exists?(key)
            Cache.logger.debug "!!! NETWORK FAILED -- RETURNING STALE CACHE"
            return cache.get(key, true)
          else
            raise
          end
        end
      end
    end

    # Redefine original HTTParty +get+ method to use cache
    #
    def self.get(path, options={})
      self.get_with_caching(path, options)
    end

  end
end