Module: SteamCondenser::Community::Cacheable::ClassMethods

Defined in:
lib/steam-condenser/community/cacheable.rb

Overview

This module implements functionality to access the cache of a class that includes the SteamCondenser::Community::Cacheable module as class methods

Author:

  • Sebastian Staudt

Instance Method Summary collapse

Instance Method Details

#cacheHash<Object, Cacheable> (private)

Returns the current cache for the cacheable class


117
118
119
# File 'lib/steam-condenser/community/cacheable.rb', line 117

def cache
  class_variable_get :@@cache
end

#cache_idsArray<Symbol, Array<Symbol>> (private)

Returns the list of IDs used for caching objects


124
125
126
# File 'lib/steam-condenser/community/cacheable.rb', line 124

def cache_ids
  class_variable_get :@@cache_ids
end

#cacheable_with_ids(*ids) ⇒ Object

Note:

A call to this method is needed if you want a class including this module to really use the cache.

Defines wich instance variables which should be used to index the cached objects


66
67
68
# File 'lib/steam-condenser/community/cacheable.rb', line 66

def cacheable_with_ids(*ids)
  class_variable_set :@@cache_ids, ids
end

#cached?(id) ⇒ Boolean

Returns whether an object with the given ID is already cached


75
76
77
78
# File 'lib/steam-condenser/community/cacheable.rb', line 75

def cached?(id)
  id.downcase! if id.is_a? String
  cache.key?(id)
end

#clear_cacheObject

Clears the object cache for the class this method is called on


81
82
83
# File 'lib/steam-condenser/community/cacheable.rb', line 81

def clear_cache
  class_variable_set :@@cache, {}
end

#new(*args) ⇒ Object

This checks the cache for an existing object. If it exists it is returned, otherwise a new object is created. Overrides the default new method of the cacheable object class.


93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/steam-condenser/community/cacheable.rb', line 93

def new(*args)
  arity = self.instance_method(:initialize).arity.abs
  args += [nil] * (arity - args.size) if args.size < arity
  bypass_cache = args.size > arity + 1 ? !!args.pop : false
  fetch = args.size > arity ? !!args.pop : true

  object = self.allocate
  object.send :initialize, *args
  cached_object = object.send :cached_instance
  object = cached_object unless cached_object.nil? || bypass_cache

  if fetch && (bypass_cache || !object.fetched?)
    object.fetch
    object.cache
  end

  object
end