Skip to content

Instantly share code, notes, and snippets.

@TorD
Last active August 29, 2015 14:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TorD/a3b7a88e2f2803a2bfa7 to your computer and use it in GitHub Desktop.
Save TorD/a3b7a88e2f2803a2bfa7 to your computer and use it in GitHub Desktop.
StateCache Meta'd up
#==============================================================================
# ** 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