Created
November 26, 2008 20:40
-
-
Save entombedvirus/29560 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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