Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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)
Add Comment
Please, Sign In to add comment