Created
March 30, 2011 09:05
-
-
Save kusakari/894098 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
require 'memcache_client' | |
require 'singleton' | |
class DBCache | |
include Singleton | |
attr_accessor :connection | |
def load_config | |
self.connection = MemcacheClient.new("YOUR_HOST_WITH_PORT", { | |
:timeout => 5.0, | |
:check_size => false, | |
:prefix_key => "", | |
:prefix_delimiter => ":", | |
}) | |
end | |
def self.platform_prefix_key | |
pkey = Rails.env | |
return AppResources.mixi? ? pkey : "#{AppResources[:application_platform]}_#{pkey}" | |
end | |
module DummyClassMethods | |
def set(k, v, ttl=0, marshal=true) | |
end | |
def get(k, marshal=true) | |
end | |
def delete(k) | |
end | |
def server_by_key(key) | |
end | |
def reconnect! | |
# no implementation | |
end | |
end | |
module ClassMethods | |
def set(k, v, ttl=0, marshal=true) | |
# key, value, ttl=604800, marshal=true | |
return self.connection.set(k, v, ttl, marshal) | |
end | |
def get(k, marshal=true) | |
# keys, marshal=true | |
return autoload_missing_constants { self.connection.get(k, marshal) } | |
end | |
def delete(k) | |
return self.connection.delete(k) | |
end | |
def reconnect! | |
# no implementation | |
end | |
def autoload_missing_constants | |
begin | |
yield | |
rescue ArgumentError => error | |
lazy_load ||= Hash.new { |hash, hash_key| hash[hash_key] = true; false } | |
if error.to_s[/undefined class|referred/] && !lazy_load[error.to_s.split.last.sub(/::$/, '').constantize] | |
retry | |
else | |
raise error | |
end | |
end | |
end | |
end | |
def self.connection | |
self.instance.load_config if self.instance.connection.nil? | |
return self.instance.connection | |
end | |
def self.enabled | |
return AppResources['db_cache_enabled'] | |
end | |
if DBCache.enabled | |
extend ClassMethods | |
else | |
extend DummyClassMethods | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment