Module: SupportTableCache::Associations::ClassMethods
- Defined in:
- lib/support_table_cache/associations.rb
Instance Method Summary collapse
-
#cache_belongs_to(association_name) ⇒ void
Specify that a belongs_to association should use the cache.
Instance Method Details
#cache_belongs_to(association_name) ⇒ void
This method returns an undefined value.
Specify that a belongs_to association should use the cache. This will override the reader method for the association so that it queries from the cache. The association must already be defined.
If you need cached associations to be cleared when data changes, then the associated class will need to include SupportTableCache and cache by the primary key for the association.
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/support_table_cache/associations.rb', line 18 def cache_belongs_to(association_name) reflection = reflections[association_name.to_s] unless reflection&.belongs_to? raise ArgumentError.new("The belongs_to #{association_name} association is not defined") end if reflection.scopes.present? raise ArgumentError.new("Cannot cache belongs_to #{association_name} association because it has a scope") end class_eval <<~RUBY, __FILE__, __LINE__ + 1 def #{association_name}_with_cache foreign_key = self.send(#{reflection.foreign_key.inspect}) return nil if foreign_key.nil? key = [#{reflection.class_name.inspect}, {#{reflection.association_primary_key.inspect} => foreign_key}] cache = #{reflection.class_name}.send(:current_support_table_cache) ttl = #{reflection.class_name}.send(:support_table_cache_ttl) if cache cache.fetch(key, expires_in: ttl) do #{association_name}_without_cache end else #{association_name}_without_cache end end alias_method :#{association_name}_without_cache, :#{association_name} alias_method :#{association_name}, :#{association_name}_with_cache RUBY end |