Module: ActiveRecordTweaks::Integration::InstanceMethods

Defined in:
lib/active_record_tweaks/integration.rb

Instance Method Summary collapse

Instance Method Details

#cache_key_from_attributes(*attribute_names) ⇒ Object Also known as: cache_key_from_attribute

Works like #cache_key in rails 4.1, but does not check column Useful when you have some virtual timestamp attribute method (cached or not)

Parameters:

  • attribute_names (Array<Symbol,String>)

    Names of attributes method(s) It does not have to be column(s)

Raises:

  • (ArgumentError)

    when attribute_names is empty



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/active_record_tweaks/integration.rb', line 38

def cache_key_from_attributes(*attribute_names)
  attribute_names.any? || fail(ArgumentError)

  timestamp = max_updated_attribute_timestamp_for_cache_key(attribute_names)
  if timestamp
    timestamp_str = timestamp.utc.yield_self do |utc_time|
      if utc_time.respond_to?(:to_fs)
        utc_time.to_fs(cache_timestamp_format)
      else
        utc_time.to_s(cache_timestamp_format)
      end
    end
    "#{self.class.model_name.cache_key}/#{id}-#{timestamp_str}"
  else
    "#{self.class.model_name.cache_key}/#{id}"
  end
end

#cache_key_without_timestampObject

Returns a cache key that can be used to identify this record. Timestamp is not used to allow custom caching expiration (e.g. Cookie based caching with expiration )

Product.new.cache_key_without_timestamp     # => "products/new"
Product.find(5).cache_key_without_timestamp # => "products/5" (updated_at not available)
Person.find(5).cache_key_without_timestamp  # => "people/5" (updated_at available)


22
23
24
25
26
27
28
# File 'lib/active_record_tweaks/integration.rb', line 22

def cache_key_without_timestamp
  if new_record?
    "#{self.class.model_name.cache_key}/new"
  else
    "#{self.class.model_name.cache_key}/#{id}"
  end
end