Module: SecondLevelCache::ActiveRecord::Associations::Preloader::BelongsTo

Extended by:
ActiveSupport::Concern
Defined in:
lib/second_level_cache/active_record/preloader.rb

Instance Method Summary collapse

Instance Method Details

#records_for_with_second_level_cache(ids) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/second_level_cache/active_record/preloader.rb', line 13

def records_for_with_second_level_cache(ids)
  return records_for_without_second_level_cache(ids) unless klass.second_level_cache_enabled?

  map_cache_keys = ids.map{|id| klass.second_level_cache_key(id)}
  records_from_cache = ::SecondLevelCache.cache_store.read_multi(*map_cache_keys)
  # NOTICE
  # Rails.cache.read_multi return hash that has keys only hitted.
  # eg. Rails.cache.read_multi(1,2,3) => {2 => hit_value, 3 => hit_value}
  hitted_ids = records_from_cache.map{|key, _| key.split("/")[2].to_i}
  missed_ids = ids.map{|x| x.to_i} - hitted_ids

  ::SecondLevelCache::Config.logger.info "missed ids -> #{missed_ids.inspect} | hitted ids -> #{hitted_ids.inspect}"

  if missed_ids.empty?
    RecordMarshal.load_multi(records_from_cache.values)
  else
    records_from_db = records_for_without_second_level_cache(missed_ids)
    records_from_db.map{|record| write_cache(record); record} + RecordMarshal.load_multi(records_from_cache.values)
  end
end