Module: ActiveRecordTweaks::Integration::ClassMethods

Defined in:
lib/active_record_tweaks/integration.rb

Instance Method Summary collapse

Instance Method Details

#cache_key(*args) ⇒ Object

Returns a cache key for the ActiveRecord class based based on count and maximum value of update timestamp columns (e.g. Cookie based caching with expiration)

Product.cache_key     # => "products/0" (empty, has updated timestamp columns or not)
Product.cache_key     # => "products/1" (not empty but has no updated timestamp columns)
Person.cache_key     # => "people/1-20071224150000" (not empty and has updated timestamp columns)

Parameters:

  • args (Array<String, Symbol>)

    The column name with timestamp to check



33
34
35
36
37
38
39
40
41
42
# File 'lib/active_record_tweaks/integration.rb', line 33

def cache_key(*args)
  timestamp_columns = args.empty? ? [:updated_at] : args

  if timestamp = max_updated_column_timestamp_for_cache_key(timestamp_columns)
    timestamp = timestamp.utc.to_s(cache_timestamp_format)
    "#{self.model_name.cache_key}/all/#{self.count}-#{timestamp}"
  else
    "#{self.model_name.cache_key}/all/#{self.count}"
  end
end

#max_updated_column_timestamp_for_cache_key(timestamp_columns) ⇒ Object



44
45
46
47
48
49
50
# File 'lib/active_record_tweaks/integration.rb', line 44

def max_updated_column_timestamp_for_cache_key(timestamp_columns)
  available_timestamp_columns = timestamp_columns.select { |c| self.column_names.include?(c.to_s) }

  if (timestamps = available_timestamp_columns.map { |column| self.maximum(column) }.compact).present?
    timestamps.map { |ts| ts.to_time }.max
  end
end