Skip to content

Instantly share code, notes, and snippets.

@entombedvirus
Created November 26, 2008 20:40
Show Gist options
  • Select an option

  • Save entombedvirus/29560 to your computer and use it in GitHub Desktop.

Select an option

Save entombedvirus/29560 to your computer and use it in GitHub Desktop.
module CachedAttributes
def self.included(klass)
klass.extend ClassMethods
end
module ClassMethods
def has_cached_attribute(name, default_value)
# Only include the InstanceMethods module once
after_initialize do |instance|
store = instance.read_attribute(:cached_attrs) || {}
val = default_value.respond_to?(:call) ? default_value.call(instance) : default_value
store[name] = val
instance.write_attribute(:cached_attrs, store) unless instance.attributes.keys.include?(name)
end
end
end
module InstanceMethods
def cached_attr(name)
(read_attribute(:cached_attrs) || {})[name]
end
end
end
ActiveRecord::Base.send(:include, CachedAttributes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment