Sha256: cc54e0e8b3f511412a9f5ae5fa9ec9a8e2b42c46601577e18d666ba73bafa75d

Contents?: true

Size: 890 Bytes

Versions: 3

Compression:

Stored size: 890 Bytes

Contents

# -*- encoding : utf-8 -*-
module SecondLevelCache
  module ActiveRecord
    module FetchByUniqKey
      def fetch_by_uniq_key(value, uniq_key_name)
        return self.where(uniq_key_name => value).first unless self.second_level_cache_enabled?
        if _id = SecondLevelCache.cache_store.read(cache_uniq_key(value, uniq_key_name))
          self.find(_id) rescue nil
        else
          record = self.where(uniq_key_name => value).first
          record.tap{|record| SecondLevelCache.cache_store.write(cache_uniq_key(value, uniq_key_name), record.id)} if record
        end
      end

      def fetch_by_uniq_key!(value, uniq_key_name)
        fetch_by_uniq_key(value, uniq_key_name) || raise(::ActiveRecord::RecordNotFound)
      end

      private

      def cache_uniq_key(value, uniq_key_name)
        "uniq_key_#{self.name}_#{uniq_key_name}_#{value}"
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
second_level_cache-2.1.0.rc1 lib/second_level_cache/active_record/fetch_by_uniq_key.rb
second_level_cache-2.0.0 lib/second_level_cache/active_record/fetch_by_uniq_key.rb
second_level_cache-2.0.0.rc1 lib/second_level_cache/active_record/fetch_by_uniq_key.rb