Navigation Menu

Skip to content

Commit

Permalink
Added wax.cache.age
Browse files Browse the repository at this point in the history
  • Loading branch information
Corey Johnson committed Jun 16, 2011
1 parent 2ab8e6a commit da95174
Showing 1 changed file with 15 additions and 5 deletions.
20 changes: 15 additions & 5 deletions lib/stdlib/helpers/cache.lua
@@ -1,14 +1,13 @@
wax.cache = {}
setmetatable(wax.cache, wax.cache)


-- Returns contents of cache keys
-- key: string # value for cache
-- maxAge: number (optional) # max age of file in seconds
function wax.cache.get(key, maxAge)
local path = wax.cache.pathFor(key)
if not wax.filesystem.isFile(path) then return nil end

if not wax.filesystem.isFile(path) then return nil end

local fileAge = os.time() - wax.filesystem.attributes(path).modifiedAt
if maxAge and fileAge > maxAge then
Expand All @@ -18,7 +17,7 @@ function wax.cache.get(key, maxAge)
local success, result = pcall(function()
return NSKeyedUnarchiver:unarchiveObjectWithFile(path)
end)

if not success then -- Bad cache
puts("Error: Couldn't read cache with key %s", key)
wax.cache.clear(key)
Expand All @@ -38,10 +37,21 @@ function wax.cache.set(key, contents)
wax.cache.clear(key)
else
local success = NSKeyedArchiver:archiveRootObject_toFile(contents, path)
if not success then puts("Couldn't archive cache '%s' to '%s'", key, path) end
if not success then puts("Couldn't archive cache '%s' to '%s'", key, path) end
end
end

function wax.cache.age(key)
local path = wax.cache.pathFor(key)

-- If there is no file, just send them back a really big age. Cleaner than
-- dealing with nils
if not wax.filesystem.isFile(path) then return wax.time.days(1000) end

local fileAge = os.time() - wax.filesystem.attributes(path).modifiedAt
return fileAge
end

-- Removes specific keys from cache
function wax.cache.clear(...)
for i, key in ipairs({...}) do
Expand Down

0 comments on commit da95174

Please sign in to comment.