-
-
Save TorD/a3b7a88e2f2803a2bfa7 to your computer and use it in GitHub Desktop.
StateCache Meta'd up
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 | |
#-------------------------------------------------------------------------- | |
# * Extend Included Call with Class Methods | |
#-------------------------------------------------------------------------- | |
def self.included base | |
base.extend ClassMethods | |
end | |
module ClassMethods | |
#-------------------------------------------------------------------------- | |
# * Define Method as Cached | |
#-------------------------------------------------------------------------- | |
def cached_method(original_method) | |
# Setup alias | |
aliased_method = "cached_#{original_method}".to_sym | |
alias_method aliased_method, original_method | |
# Define cached method | |
define_method(original_method) do | |
return state_cache[original_method] if state_cache[original_method] | |
state_cache[original_method] = send(aliased_method) | |
end | |
end | |
end | |
#-------------------------------------------------------------------------- | |
# * State Cache Store | |
#-------------------------------------------------------------------------- | |
def state_cache | |
@state_cache ||= {} | |
end | |
end | |
end | |
# Testing it | |
class A | |
include TDD::StateCache | |
def test | |
return Random.rand(999) | |
end; cached_method(:test) | |
end | |
instance = A.new | |
puts instance.test | |
puts instance.test | |
instance.state_cache.clear | |
puts instance.test | |
instance_2 = A.new | |
puts instance_2.test | |
instance_2.state_cache.clear | |
puts instance_2.test |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment