Sha256: 304efe305bc2a708059b7f82299a31420562eef7e12b410dc4000100e0a8560c

Contents?: true

Size: 1.53 KB

Versions: 13

Compression:

Stored size: 1.53 KB

Contents

# -*- encoding : utf-8 -*-
module SecondLevelCache
  module ActiveRecord
    module Associations
      class Preloader
        module BelongsTo
          extend ActiveSupport::Concern

          included do
            alias_method_chain :records_for, :second_level_cache
          end

          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

          private

          def write_cache(record)
            record.write_second_level_cache
          end
        end
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
second_level_cache-2.1.16 lib/second_level_cache/active_record/preloader.rb
second_level_cache-2.1.15 lib/second_level_cache/active_record/preloader.rb
second_level_cache-2.1.14 lib/second_level_cache/active_record/preloader.rb
second_level_cache-2.1.13 lib/second_level_cache/active_record/preloader.rb
second_level_cache-2.1.10 lib/second_level_cache/active_record/preloader.rb
second_level_cache-2.1.9 lib/second_level_cache/active_record/preloader.rb
second_level_cache-2.1.8 lib/second_level_cache/active_record/preloader.rb
second_level_cache-2.1.7 lib/second_level_cache/active_record/preloader.rb
second_level_cache-2.1.6 lib/second_level_cache/active_record/preloader.rb
second_level_cache-2.1.5 lib/second_level_cache/active_record/preloader.rb
second_level_cache-2.1.2 lib/second_level_cache/active_record/preloader.rb
second_level_cache-2.1.1 lib/second_level_cache/active_record/preloader.rb
second_level_cache-2.1.0 lib/second_level_cache/active_record/preloader.rb