Module: Cacheable::ClassMethods

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

Overview

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

Author:

  • Sebastian Staudt

Instance Method Summary collapse

Instance Method Details

#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

Parameters:

  • ids (Array<Symbol>)

    The symbolic names of the instance variables representing a unique identifier for this object class



46
47
48
# File 'lib/steam/community/cacheable.rb', line 46

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

Parameters:

  • id (Object)

    The ID of the desired object

Returns:

  • (Boolean)

    ‘true` if the object with the given ID is already cached



55
56
57
58
# File 'lib/steam/community/cacheable.rb', line 55

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

#clear_cacheObject

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



61
62
63
# File 'lib/steam/community/cacheable.rb', line 61

def clear_cache
  class_variable_set :@@cache, {}
end

#new(id, fetch = true, bypass_cache = false) ⇒ 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.

Parameters:

  • id (Object)

    The ID of the object that should be loaded

  • fetch (Boolean) (defaults to: true)

    whether the object’s data should be retrieved

  • bypass_cache (Boolean) (defaults to: false)

    whether the object should be loaded again even if it is already cached

See Also:



75
76
77
78
79
80
81
82
83
# File 'lib/steam/community/cacheable.rb', line 75

def new(id, fetch = true, bypass_cache = false)
  if cached?(id) && !bypass_cache
    object = class_variable_get(:@@cache)[id]
    object.fetch if fetch && !object.fetched?
    object
  else
    super(id, fetch)
  end
end