Guest User

Untitled

a guest
Feb 21st, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.77 KB | None | 0 0
  1. module CachedAttributes
  2. def self.included(klass)
  3. klass.extend ClassMethods
  4. end
  5.  
  6. module ClassMethods
  7. def has_cached_attribute(name, default_value)
  8. # Only include the InstanceMethods module once
  9.  
  10. after_initialize do |instance|
  11. store = instance.read_attribute(:cached_attrs) || {}
  12.  
  13. val = default_value.respond_to?(:call) ? default_value.call(instance) : default_value
  14. store[name] = val
  15.  
  16. instance.write_attribute(:cached_attrs, store) unless instance.attributes.keys.include?(name)
  17. end
  18. end
  19. end
  20.  
  21. module InstanceMethods
  22. def cached_attr(name)
  23. (read_attribute(:cached_attrs) || {})[name]
  24. end
  25. end
  26. end
  27.  
  28. ActiveRecord::Base.send(:include, CachedAttributes)
Add Comment
Please, Sign In to add comment