Skip to content
This repository has been archived by the owner on Feb 2, 2022. It is now read-only.

Commit

Permalink
add memory cache
Browse files Browse the repository at this point in the history
  • Loading branch information
phunold committed Jan 7, 2013
1 parent 347e194 commit 2c7c38d
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
22 changes: 22 additions & 0 deletions lib/mymemcache.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# simplistic in-memory cache
class MyMemCache

def initialize
@cache = {}
@cache_ttl = 60 # default expiration time(hardcoded I know!)
end

def get(key)
return nil unless @cache.has_key? key
# check if expired?
return nil if @cache[key][1] + @cache_ttl < Time.now
# else return cache content for this key
return @cache[key][0]
end

def set(key,val)
@cache[key] = [val,Time.now()]
return val
end

end
12 changes: 10 additions & 2 deletions pdns.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
# borrowing 'number_to_human' from ActionView
include ActionView::Helpers::NumberHelper

# load modules
require Pathname.new(__FILE__).dirname + 'lib/mymemcache.rb'


class App < Sinatra::Base
configure do
enable :protection
Expand All @@ -19,6 +23,8 @@ class App < Sinatra::Base
:database => settings.database,
:user => settings.username,
:password =>"#{settings.password}")
# init cache
@@cache = MyMemCache.new
end

before do
Expand All @@ -27,7 +33,8 @@ class App < Sinatra::Base
# otherwise just die ungracefully with HTTP 500
begin
# database counter for all pages
@counter ||= Pdns.count
@counter ||= @@cache.get('count')
@counter ||= @@cache.set('count',Pdns.count)
rescue Sequel::DatabaseError => e
halt 500, "Database error: #{e.message}"
rescue Sequel::DatabaseConnectionError => e
Expand All @@ -36,7 +43,8 @@ class App < Sinatra::Base

# get all MAPTYPEs aka DNS Query Types (CNAME,A,SOA,MX,etc) for navigation
# dropdown menu on all pages
@maptypes ||= Pdns.group(:MAPTYPE).map(:MAPTYPE)
@maptypes ||= @@cache.get('maptypes')
@maptypes ||= @@cache.set('maptypes',Pdns.group(:MAPTYPE).map(:MAPTYPE))
end

# routes
Expand Down

0 comments on commit 2c7c38d

Please sign in to comment.