One more Sunday post and another attempt to hide weird looking, overcomplicated code under the “hacking” label. That’s what we use it for right? Maybe not but here it goes!
Intro - Metaprogramming
I got my initial feel on what all these people going on about through ruby with help from these two excellent resources:
Dave Thomas’ Screencast: The Ruby Object Model and Metaprogramming
Metaprogramming Ruby 2
In fact these operation can be taken to such an unimaginable level of control that could completely destroy any kind of semantics and standard behavior(check this!). I really dig that, a lot of discipline is needed of course but i believe understanding these kind of things and more importantly when or not to use them really improves our out of the box thinking and creativity.
So, what’s wrong then?
Using these techniques without bringing total calamity for your program with eval() ( or eval()-like ) operations, dirty checking loops(as you will see below) and more.
ES6 brings new features that improve the situation a lot!
Proxies are on of them and i will some time soon write a part 2 of this post using them.
Recently, there was a need for our internal testing tool to provide a kind of “session-like” behavior on localStorage values(but keeping them on localStorage, not on session) and without modifications on the
So, i thought i could auto-append a specific identifier(session id, timestamp, whatever) in front of the localStorage keys and auto-remove it for retrieval, here is how i did it.
First step: Overwriting
Nothing weird here.
So you usually have to clone them(for functions
function and the original remains intact(read more here), cool stuff!
So now we end up with something like this:
What about the alternative forms:
This is where it gets a little messy. There might be better ways but this is what i came up with:
In an interval of 100ms check for new keys, re-save them with a modified key, keep track of the modification, remove the original and create a getter for retrieval.
Here is what it looks like:
And here is one more detail, on page reload we need to re-track them and re-define the getters:
Here is a complete gist
Side Note/Update: As people pointed on reddit you can use the storageEvent
to respond to changes instead of the
setInterval(). What i forgot to mention is that this was made for a testing tool that needed to target IE 9 and up and unfortunately these events are completely broken on IE 10/11.
So if you don’t care about IE please use the events.
It works fine for my usecase, not the most elegant piece of code but it fits its purpose(looking forward to rewrite it with proxies!).
Give it a try, mess with localStorage or anything else you thought was impossible!