Module: HTTParty::Icebox

Included in:
PostcodeAnywhere::BankAccountValidation
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



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
100
101
102
103
104
105
106
107
108
# File 'lib/httparty_icebox.rb', line 73

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]}"
        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
      end
    end

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

  end
end