Sha256: b5cbe8408c1d7b9d2cdb5f964ce75366017cc05e0345a8bed858bf546c4b57c4

Contents?: true

Size: 1.33 KB

Versions: 10

Compression:

Stored size: 1.33 KB

Contents

# -*- encoding : utf-8 -*-
module SecondLevelCache
  module ActiveRecord
    module FetchByUniqKey
      def fetch_by_uniq_keys(where_values)
        cache_key = cache_uniq_key(where_values)
        if _id = SecondLevelCache.cache_store.read(cache_key)
          self.find(_id) rescue nil
        else
          record = self.where(where_values).first
          record.tap{|record| SecondLevelCache.cache_store.write(cache_key, record.id)} if record
        end
      end
      
      def fetch_by_uniq_keys!(where_values)
        fetch_by_uniq_keys(where_values) || raise(::ActiveRecord::RecordNotFound)
      end
      
      def fetch_by_uniq_key(value, uniq_key_name)
        # puts "[Deprecated] will remove in the future, use fetch_by_uniq_keys method instead."
        fetch_by_uniq_keys(uniq_key_name => value)
      end

      def fetch_by_uniq_key!(value, uniq_key_name)
        # puts "[Deprecated] will remove in the future, use fetch_by_uniq_keys! method instead."
        fetch_by_uniq_key(value, uniq_key_name) || raise(::ActiveRecord::RecordNotFound)
      end

      private
      
      def cache_uniq_key(where_values)
        ext_key = where_values.collect { |k,v|
          v = Digest::MD5.hexdigest(v) if v && v.size >= 32
          [k,v].join("_")
        }.join(",")
        "uniq_key_#{self.name}_#{ext_key}"
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
second_level_cache-2.1.16 lib/second_level_cache/active_record/fetch_by_uniq_key.rb
second_level_cache-2.1.15 lib/second_level_cache/active_record/fetch_by_uniq_key.rb
second_level_cache-2.1.14 lib/second_level_cache/active_record/fetch_by_uniq_key.rb
second_level_cache-2.1.13 lib/second_level_cache/active_record/fetch_by_uniq_key.rb
second_level_cache-2.1.10 lib/second_level_cache/active_record/fetch_by_uniq_key.rb
second_level_cache-2.1.9 lib/second_level_cache/active_record/fetch_by_uniq_key.rb
second_level_cache-2.1.8 lib/second_level_cache/active_record/fetch_by_uniq_key.rb
second_level_cache-2.1.7 lib/second_level_cache/active_record/fetch_by_uniq_key.rb
second_level_cache-2.1.6 lib/second_level_cache/active_record/fetch_by_uniq_key.rb
second_level_cache-2.1.5 lib/second_level_cache/active_record/fetch_by_uniq_key.rb