Class: Ultracache::HasCachedAttribute
- Inherits:
-
Relationship
- Object
- Relationship
- Ultracache::HasCachedAttribute
- Defined in:
- lib/ultracache/relationship/has_cached_attribute.rb
Instance Attribute Summary
Attributes inherited from Relationship
Instance Method Summary collapse
-
#destroy_cache(obj) ⇒ Object
Destroys cache from storage.
-
#initialize(name, block, options = {}) ⇒ HasCachedAttribute
constructor
A new instance of HasCachedAttribute.
- #key(obj) ⇒ Object
-
#read_cache(obj, options = {}) ⇒ Object
Read stored cache from storage.
-
#save_cache(obj) ⇒ Object
Save serialized attribute to cache.
-
#update_cache(obj) ⇒ Object
Updates value of existing cache.
Methods inherited from Relationship
#associated_class, #self_class
Constructor Details
#initialize(name, block, options = {}) ⇒ HasCachedAttribute
Returns a new instance of HasCachedAttribute.
3 4 5 6 7 |
# File 'lib/ultracache/relationship/has_cached_attribute.rb', line 3 def initialize(name, block, ={}) super(name, ) @serializer_method = [:serializer] @serializing_block = block if block_given? end |
Instance Method Details
#destroy_cache(obj) ⇒ Object
Destroys cache from storage
38 39 40 |
# File 'lib/ultracache/relationship/has_cached_attribute.rb', line 38 def destroy_cache(obj) storage.del(key(obj)) end |
#key(obj) ⇒ Object
9 10 11 |
# File 'lib/ultracache/relationship/has_cached_attribute.rb', line 9 def key(obj) "#{@self_class.to_s.underscore}:#{obj.id}:#{@name}" end |
#read_cache(obj, options = {}) ⇒ Object
Read stored cache from storage. If the cache is not found, it tries to save corresponding cache to storage and return its value
31 32 33 34 35 |
# File 'lib/ultracache/relationship/has_cached_attribute.rb', line 31 def read_cache(obj, = {}) k = key(obj) storage.get(k) || save_cache(obj) end |
#save_cache(obj) ⇒ Object
Save serialized attribute to cache. If serializer method or serialization block is not given, Ultracache tries to serialize the object by serializeing hash returned by its ‘as_json` method.
16 17 18 19 20 21 22 23 24 25 26 27 |
# File 'lib/ultracache/relationship/has_cached_attribute.rb', line 16 def save_cache(obj) value = if @serializer_method serializer.serialize(obj.send(@serializer_method)) elsif @serializing_block serializer.serialize(@serializing_block.call(obj)) else serializer.serialize(obj.as_json) end storage.set(key(obj), value) value end |
#update_cache(obj) ⇒ Object
Updates value of existing cache. Its behavior is same with that of ‘save_cache`.
44 45 46 |
# File 'lib/ultracache/relationship/has_cached_attribute.rb', line 44 def update_cache(obj) save_cache(obj) end |