Sha256: d0e5189c43f218bd3a4101807fdb4d78e3119d928257fa508829552e641f83ed

Contents?: true

Size: 1.95 KB

Versions: 6

Compression:

Stored size: 1.95 KB

Contents

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 maxAge then
    local fileAge = os.time() - wax.filesystem.attributes(path).modifiedAt
    if fileAge > maxAge then
      return nil
    end
  end

  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)
    return nil
  else
    return result
  end
end

-- Creates a cache for the key with contents
--    key: string # value for the cache
--    contents: object # whatever is NSKeyedArchive compatible
function wax.cache.set(key, contents)
  local path = wax.cache.pathFor(key)

  if not contents then -- delete the value from the cache
    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
  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
    local path = wax.cache.pathFor(key)
    wax.filesystem.delete(path)
  end
end

-- Removes entire cache dir
function wax.cache.clearAll()
  wax.filesystem.delete(NSCacheDirectory)
  wax.filesystem.createDir(NSCacheDirectory)
end

function wax.cache.pathFor(key)
  return NSCacheDirectory .. "/" .. wax.base64.encode(key)
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
candle-0.0.7 lib/candle/generators/lua/wax/lib/stdlib/helpers/cache.lua
candle-0.0.6 lib/candle/generators/lua/wax/lib/stdlib/helpers/cache.lua
candle-0.0.4 lib/candle/generators/lua/wax/lib/stdlib/helpers/cache.lua
candle-0.0.3 lib/candle/generators/lua/wax/lib/stdlib/helpers/cache.lua
candle-0.0.2 lib/candle/generators/lua/wax/lib/stdlib/helpers/cache.lua
candle-0.0.1 lib/candle/generators/lua/wax/lib/stdlib/helpers/cache.lua