Created
August 28, 2012 15:27
-
-
Save timnew/3499098 to your computer and use it in GitHub Desktop.
Cached Attributes
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 CachedAttrs | |
def self.build_cache_variable_name(attr_name) | |
"@_cached_#{attr_name}".to_sym | |
end | |
def self.extended(mod) | |
mod.send(:include, CachedAttrs::InstanceMethods) | |
end | |
def cached_attr(attr_name, &block) | |
cache_variable_name = CachedAttrs.build_cache_variable_name(attr_name) | |
define_method attr_name do | |
return instance_variable_get cache_variable_name if instance_variable_defined? cache_variable_name | |
cached_value = instance_eval &block | |
instance_variable_set cache_variable_name, cached_value | |
cached_value | |
end | |
end | |
module InstanceMethods | |
def clear_cached_attr(attr_name) | |
remove_instance_variable CachedAttrs.build_cache_variable_name(attr_name) | |
end | |
def set_cached_attr(attr_name, value) | |
instance_variable_set CachedAttrs.build_cache_variable_name(attr_name), value | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment