Module: HTTParty::Icebox

Included in:
TMDBParty::Base
Defined in:
lib/tmdb_party/extras/httparty_icebox.rb

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



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
100
101
102
103
104
105
# File 'lib/tmdb_party/extras/httparty_icebox.rb', line 70

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.clone
      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 == 200
        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