|
class Cookie |
|
constructor: (opts) -> |
|
c = @ |
|
def = |
|
path: '/' |
|
domain: '' |
|
expires: do -> |
|
d = new Date().setFullYear(2020) |
|
d = new Date(d).toGMTString() |
|
d |
|
secure: '' |
|
|
|
c.opts = $.extend def, opts |
|
c.getCache() |
|
return |
|
|
|
getCache: -> |
|
c = @ |
|
c.cache = {} |
|
c.cacheStr = document.cookie |
|
cookiesArr = c.cacheStr.split('; ') |
|
dec = decodeURIComponent |
|
|
|
for cookie in cookiesArr |
|
separatorIdx = cookie.indexOf('=') |
|
key = dec(cookie.substr(0, separatorIdx)) |
|
val = dec(cookie.substr(separatorIdx + 1)) |
|
|
|
c.cache[key] = val if c.cache[key] is `undefined` |
|
|
|
return |
|
|
|
get: (key) -> |
|
c = @ |
|
c.getCache() if document.cookie isnt c.cacheStr |
|
c.cache[key] |
|
|
|
set: (key, val, opts) -> |
|
c = @ |
|
enc = encodeURIComponent |
|
opts = |
|
path: opts and opts.path or c.opts.path |
|
domain: opts and opts.domain or c.opts.domain |
|
expires: opts and opts.expires or c.opts.expires |
|
secure: if opts and opts.secure isnt `undefined` then opts.secure else c.opts.secure |
|
|
|
opts.expires = -1 if val is `undefined` |
|
|
|
switch typeof opts.expires |
|
|
|
# If a number is passed in, make it work like 'max-age' |
|
when "number" |
|
opts.expires = new Date(new Date().getTime() + opts.expires * 1000) |
|
|
|
# Allow multiple string formats for dates |
|
when "string" |
|
opts.expires = new Date(opts.expires) |
|
|
|
# Escape only the characters that should be escaped as defined by RFC6265 |
|
cookieStr = enc(key) + "=" + (val + "").replace(/[^!#-+\--:<-\[\]-~]/g, enc) |
|
cookieStr += if opts.path then ";path=" + opts.path else "" |
|
cookieStr += if opts.domain then ";domain=" + opts.domain else "" |
|
cookieStr += if opts.expires then ";expires=" + opts.expires.toGMTString() else "" |
|
cookieStr += if opts.secure then ";secure" else "" |
|
document.cookie = cookieStr |
|
return |
|
|
|
remove: (key) -> |
|
@set key, `undefined` |
|
|
|
window.Cookie = Cookie |