Module: TypedViewModel::WithCacheKey

Extended by:
ActiveSupport::Concern
Defined in:
lib/typed_view_model/with_cache_key.rb

Instance Method Summary collapse

Instance Method Details

#cache_key_modifierObject

Override in your view-model subclass to scope cache keys (e.g. by app-level cache version, deploy ID, locale). Returning nil/empty means no modifier.



62
63
64
# File 'lib/typed_view_model/with_cache_key.rb', line 62

def cache_key_modifier
  nil
end

#cache_keys_for_sources(key_attributes) ⇒ Object



66
67
68
69
70
71
72
# File 'lib/typed_view_model/with_cache_key.rb', line 66

def cache_keys_for_sources(key_attributes)
  sources = key_attributes.flat_map { |n| n.is_a?(Proc) ? instance_eval(&n) : send(n) }
  sources.compact.map do |item|
    next if item == self
    ::TypedViewModel::HashedKey.call(item)
  end
end

#cacheable?Boolean

instance methods

Returns:

  • (Boolean)


56
57
58
# File 'lib/typed_view_model/with_cache_key.rb', line 56

def cacheable?
  respond_to? :cache_key
end

#generate_cache_key(index) ⇒ Object



74
75
76
77
78
79
80
81
82
83
# File 'lib/typed_view_model/with_cache_key.rb', line 74

def generate_cache_key(index)
  key_attributes = self.class.named_cache_key_attributes[index]
  return nil unless key_attributes
  key = "#{self.class.name}/#{cache_keys_for_sources(key_attributes).join("/")}"
  if key.blank? || key == "#{self.class.name}/"
    raise ::TypedViewModel::CacheKeyError,
      "Cache key for `#{self.class.name}` (slot `#{index.inspect}`) is blank — source list resolved to no values"
  end
  @cache_key[index] = cache_key_modifier.present? ? "#{key}/#{cache_key_modifier}" : key
end