marcuswestin/store.js — pull request #54 by whitehat101 (2012-09-17 02:47:34+00:00)
Title: Automatic String Fallback

When I first decided to use store.js I had already been using localStorage directly. I wanted to add support for Microsoft products. I used the following CoffeeScript to patch in a fallback feature. It allowed a painless transition from the direct API to the store.js API.

```coffeescript
# Patch backwards compatability with plain localStorage
# this basically promotes strings to JSON strings, as most primitives toString()s return JSON strings anyways
@store._get = @store.get
@store.get = (key)->
# console.log 'store#GET', key, @_get key
try
@_get key
catch e
val = window.localStorage[key]
@set key, val
val
```

I wrote some tests, and added this feature at the core by catching the parse error in deserialize 07a2fd2 (instead of get, like my patch above). I tested on Mac browsers, and I'm sure it will work just as well on windows due to the elegance of the fix.

```javascript
store.deserialize = function(value) {
if (typeof value != 'string') { return undefined }
try { return JSON.parse(value) }
catch(e) { return value }
}
```