-
-
Save TorD/fce766313e3261275212 to your computer and use it in GitHub Desktop.
TDD::StateCache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#============================================================================== | |
# ** 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
When you want to clear all cached objects, you can of course do:
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.