Skip to content

Instantly share code, notes, and snippets.

@timnew
Created August 28, 2012 15:27
Show Gist options
  • Save timnew/3499098 to your computer and use it in GitHub Desktop.
Save timnew/3499098 to your computer and use it in GitHub Desktop.
Cached Attributes
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