Skip to content

Instantly share code, notes, and snippets.

@mvastola
Created May 3, 2012 06:10
Show Gist options
  • Save mvastola/2583659 to your computer and use it in GitHub Desktop.
Save mvastola/2583659 to your computer and use it in GitHub Desktop.
require 'dalli'
module App
class Settings
class << self
attr_accessor :cache_ttl, :fetch_timeout, :fetch_attempt_interval
end
end
class Cache
class << self
def fetch(name, &block)
start = Time.now
while Time.now - start < Settings.fetch_timeout do
value = get(name) || lock_and_block(name, &block)
return value if value
Kernel.sleep Settings.fetch_attempt_interval
end
nil
end
def reset!
!@dalli || @dalli.reset
true
end
private
def dalli
return @dalli if @dalli
@dalli = Dalli::Client.new('localhost:11211', {
:namespace => "blah",
:failover => false,
:compress => true,
:value_max_bytes => 1024 * 1024 * 10 # 10MB
})
end
def get(*args)
dalli.get(*args)
end
def add(*args)
dalli.add(*args)
end
def delete(*args)
dalli.delete(*args)
end
def lock_and_block(name, &block)
return unless add("#{name.to_s}-lock", true, Settings.fetch_timeout)
value = yield
add(name, value, Settings.cache_ttl)
delete("#{name.to_s}-lock")
value
end
end
end
end
if defined?(PhusionPassenger)
PhusionPassenger.on_event(:starting_worker_process) do |forked|
App::Cache.reset! if forked
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment