-
-
Save TorD/fce766313e3261275212 to your computer and use it in GitHub Desktop.
#============================================================================== | |
# ** Module TDD::StateCache | |
#------------------------------------------------------------------------------ | |
# This module provides methods that allow a class to easily cache its method | |
# calls for more dynamic state handling without using instance variables | |
#============================================================================== | |
module TDD | |
module StateCache | |
#-------------------------------------------------------------------------- | |
# * State Cache Store | |
#-------------------------------------------------------------------------- | |
def state_cache | |
@state_cache ||= {} | |
end | |
#-------------------------------------------------------------------------- | |
# * Set Cache for Calling Method | |
#-------------------------------------------------------------------------- | |
def set_cache(object) | |
state_cache[key] = object | |
return state_cache[key] | |
end | |
#-------------------------------------------------------------------------- | |
# * Check Cache for Calling Method | |
#-------------------------------------------------------------------------- | |
def cache | |
return state_cache[key] | |
end | |
#-------------------------------------------------------------------------- | |
# * Get Calling Method as Key String | |
#-------------------------------------------------------------------------- | |
def key | |
caller[1][/`.*'/][1..-2] | |
end | |
end | |
end |
Whenever you want to access the background_sprite, whether that be for moving it or what have you, you call the background_sprite method. Whenever you need to clear the background sprite, you can do:
state_cache.delete("background_sprite")
When you want to clear all cached objects, you can of course do:
state_cache.clear
If you want to, like me, redraw all these cached objects when a data model update has happened, just do state_cache.clear and make sure that you call the relevant objects in the next frame. Easy; no need to recall a setup method. You don't even need a setup method.
And when the class itself is disposed and set to nil, of course all its objects will to. The benefit of this is that you can call background_sprite anywhere; order doesn't matter. You don't have to set up @background_sprite somewhere first, then call it when you need to access, say, its width. No, you just call background_sprite when you need it; if it doesn't exist, it gets made. This takes a page from the book of Functional Programming by being stateless.
Example of use: