Hacking together a VCR for JavaScript

At SimpleReach we have a very large number of internal API endpoints and each one can bring back dozens of fields of data into our Ember.js application. In order to make integration tests we started with static fixtures, but very soon the sheer number of fields and endpoints become overwhelming.

I really wanted something like VCR for Rails, but alas, there is nothing in the front-end world that does that yet.

Chrome provided a great hack to use though. In the network developer tools you can right click and select “save as HAR with content”. This will save a recording of all network requests that have happened since you opened the tool. Voila, instant tape of all the network requests that have happened on a site.

Once you have the HAR saved, you need a way to serve the information up programatically. Sinon.js has a mock server that will respond with saved JS based on incoming requests. Setting it up looks something like this:

Now, as long as an object has been passed to “server.respondWith” the server will respond to that.

In order to make the HAR file play nice with Sinon, I forked an application called “Mockbuilder“. Mockbuilder allows you to add a HAR file to a folder and it will automatically convert it into something that plays nicely with Sinon. The fork allows you to specify a url for internal request overwrites and a location where the new mock file should go. That way you can have it send them immediately to the mock folder in your application.

Not only does this make writing JavaScript integration tests much easier, it is also a great way to make completely offline demos of your application. Simple click around, save the HAR file, and then with the new mocks in place, you can click around the same way and it will use the recordings instead of the actual requests. Perfect for sales teams who want to have a gurantee that things will work the way they expected.

Presentation below.

EmberConf Presentation: Using Ember to Make the Seemingly Impossible Easy

At this year’s EmberConf on the 25th of March I gave a presentation with Heyjin highlighting some examples of times where using Ember has made our jobs seem infinitely easier.

EmberConf was an amazing experience, the Ember community is full of genuine and welcoming people and I am so excited to see the great things that this community will build together.

Slides and video below.

Ember.js NYC presentation: Your front end is not your back end

Last month I gave a lightning talk at the Ember.js NYC meetup. The talk was about designing your API based on what it was going to be used for by the users instead of designing it based on what is in the database.  I think that this tactic can be really effective as it reduces the complexity of the front end code, which is where your users are and where you really want everything to revolve around their experience, not the intricacies of your data layer. With more and more complexity living in the front end through frameworks like Ember.js our design decisions need to be giving more weight to the front end than they used to.

Video and slides below:






Summary of “the Willpower Instinct”

A very well laid out book by Kelly McGonigal.

This is a quick summary of the principles that each chapter addresses as well as some of the tactics that she lays out for when tempted and the strategies that can be used to reduce your risk of failure.


Slow Habits: How to burst through the “one habit at a time” barrier.

Most of the habit gurus agree, when it comes to habits, the only way to succeed is to do one at a time. We have limited willpower and need all of it to invoke a habit change. I think they all got it wrong.

Ever since I started reflecting daily I’ve been experimenting with the idea of “slow habits” and I think it’s a far more natural way to form habits than the current paradigm. I’ve been an order of magnitude more successful with it that I have been with the normal methods.


So what’s the different?

Current wisdom:

Pick a habit then invest between 28-60 days concentrating on making sure you apply that habit.

Apply a variety of different techniques (triggers, rewards, starting small etc) to make sure it sticks.

After a certain amount of time (1-2 months) and willpower application,  your habit is effortlessly set for life (yeah right).

Slow habits:

Pick as many habits as you want.

Track how often you perform each one.

Watch as you slowly start to do them more and more often naturally.


The reason I think that the slow (not relying on every day) technique is a more natural way of doing things is that it’s the way most of our current habits have formed. Hit the snooze button 3 times EVERY morning? Regularly eating food that is killing you even though you know you should not? Procrastinating work by checking Facebook, Twitter etc daily? None of these habits are things that you spent 30 days developing triggers and rewards for, or applying all your willpower to. They just happen to you.

The idea with a slow habit is to have that same natural process happen to you, but for good habits.


How to form slow habits:Lift Checked habits

Step 1: Get Lift (or a spreadsheet).

You can do it without Lift, but this is what the Lift app seems to be designed for. It lets you track your habits, keeps track of streaks and provides your with frequency graphs for the habits. If you don’t have an iPhone you can do this with a spreadsheet (I did before I switched to iPhone) or an Android clone (Lift will be on Android and the web some day soon as well), but it’s much less fun.

Step 2: Form the tracking habit – Learn to use Lift every day.

This is the one and only time we need traditional habit theory to form a habit. It is the step that so many of my friends who have tried to use Lift have missed. People use it for a few weeks then forget about it. This tracking habit step is critical for success.

All the traditional habit theory applies here, so it’s up to you how you want to form this habit. The way I did it was to pick an easy habit that I was committed to doing every day. I used meditation, but flossing, “drink water” (don’t even worry about 8 glasses part) and “use Lift” are all viable candidates. Then pick a time (I use my reflection time before bed) and log that habit. Do this EVERY day for 30 days (if you break the streak, start over).

Step 3: Line up your slow habits.

Now that you’re using Lift daily start to add other habits to it. You should be doing this during the first 30 days. Add anything that you would possibly like to have as a habit. As you go through your day notice anything you would like to( or not) do and add it (I’ve added three while writing this post). Don’t stress about ticking them off, just have them there in case you accidentally happen to do them. Have a good mix of easy and hard habits. If you do perform one of these habits, be sure to tick them off at the same time as your first habit.

Step 4: Keep going, enjoy your streaks.

After the 30 days just keep your habit of using Lift (it’s a habit, you can’t stop). By now  you should have enough little habits that there will be something to log every day. There is no work left to do. You will naturally start to do your habits more as you anticipate the reward of ticking them off in Lift. If you start to develop big streaks you will perform the habit in order to stop losing the streak.


How well does this work?

Since January 15th when I started seriously applying step 1 in lift (less than 3 months ago) here are my stats:

I have 16 real habits in lift (not including the 3 I just added).

Over the last 8 days I’ve ticked off an average of 12 things a day.

I have 7 habits with streaks of over 2 weeks (not all of my habits are ones that I want to do every day anyway).


As you can see, this is way better than the theoretical maximum of 3 habits that I should have been able to form. And I am someone who has often struggled with and failed at the traditional methods of habit development despite working really hard at it. I’ve also used the traditional method to form many habits that I lost later on. This way you never lose your habits as breaking the streak after a large number of days would be heartbreaking!


Bonus, because the lovely Paulina asked, here are my “slow habits” in Lift and why I do them:

  • Mediate: My only new year’s resolution was to meditate every day. Willpower, happiness, presence, energy, health, emotional intelligence… I have a list of about 20 things that I think mediation could possibly help with. Worth it if it helps with even a fraction of them.Lift Frequencies
  • Inbox 0: Using my inbox as a to do list sucks and stresses me out.
  • Set priorities for the day: Take time to decide what the most important  things to spend time on the next day is.
  • Daily reflection: Okay, I’ve had this one for months, but there were periods where it would stutter and fizzle and I would prioritize going to bed or forget. This is a habit that would have died like others. The Lift streak feature makes sure that doesn’t happen.
  • Taekwondo training: It’s too easy to get busy and only go twice a week. Having it in Lift lets me pull my average up from around 3 to 4 times a week (any more and I would be overtraining my joints).
  • Don’t oversleep: Being polyphasic I have to really protect myself from falling back into my 26 year old monophasic sleep habit.
  • Dream Journal: I spend 1.5-2 hours a day dreaming. These are real experiences (you experience strong emotions) and a 10 minute dream can feel like it’s lasted hours. Journaling helps you form the habit of remembering your dreams and reclaiming those lost bits of your life. Remembering dreams can also help you make future dreams lucid… which is just awesome.
  • Eat mindfully: I used to eat every meal that I didn’t spend with someone else (and many that I did) in front of a screen. Now I try and just eat while doing nothing else. This habit helps you actually appreciate and enjoy your food. It also helps you notice and react to when you’ve put something poisonous into your body (a McDonalds burger for instance).
  • Wash your bowl: Instead of leaving dishes in the sink to stress me out from afar, I now try and wash my bowl as soon as I finish eating.
  • Floss: The easiest habit that so few of us do. Should save me lots in dentist bills in the future.
  • Stop biting fingernails: I’ve noticed a lot of programers have this habit. I still haven’t come up with a really good strategy for stopping, but it’s in the list so I know I will kick it one day!
  • Study Korean: I’m going to be competing at the World Taekwondo festival in Korea at the beginning of July and would like to have a decent grasp of the language before I go.
  • Stretch in the mornings: This habit will help me to kick people in the head at the aforementioned tournament.
  • 10 minutes of mobility work: Modern life breaks your body and leads to pain (for instance I couldn’t run more than a mile a couple of months ago because of  knee pain). Using Mobility WOD exercises helps fix this.
  • Cold showers: Willpower training (the best way to increase willpower is to train it like a muscle… and jumping into a cold shower is like lifting iron for willpower) along with numerous other health benefits.
  • Use standing desk: Kevin and I built a standing desk at work, but both of us started to slowly drift back toward our normal desks. Sitting kills so I want to use the desk much more.


Hopefully that provides a good start. At the moment, this works in a lab of one, so I can say that I’ve disproved the “one habit theory” by way of counter-example, but there is obviously a long way to go before knowing if this will work for the majority of people. I have a strong hunch that it does though and I’m sure the great team at Lift will back me up with numbers soon enough.




Being Polyphasic, Month 1: Adaptation

One of the reasons that polyphasic sleep is less well know is that many of the people who try it fail to adapt. It’s supposed to take around a month to fully adapt (get to the point where you have consistent energy and alertness levels) and can have 1-2 weeks of zombie-like hell where you need ridiculous amounts of willpower to keep going.

Because that sounds like it sucks a lot, I decided to try a hack called a “naptation”, or “exaptation“.

The basic idea:

  • Don’t sleep the night before the adaptation
  • When you need to go to bed (after the not sleeping the day before thing) only sleep for 20 minutes ever 2 hours for the next 48 hours.
  • After 48 hours start sleeping your planned schedule

The theory is that after missing one night of sleep, your brain goes into massive sleep deprivation mode. This forces it to  reset quickly and it learns to use the 2o minute naps as a reasonable source for REM sleep. After 48 hours of sleeping every 2 hours, you actually have more than enough sleep, so will not have any sleep debt left.

Here’s what my adaptation looked like:

8AM Wednesday: Wake up.

Thursday: Don’t sleep.

Friday: Felt great. “All nighters” are pretty easy if you are excited about what you are doing. I was able to work just fine all of Friday.

Saturday: Sleep at 1AM for 2o min and then again every 2 hours for 2o minutes.

Sunday: Sleep at 1AM for 3.5 hours and then again 20 min at 6, 8, 12 and 6.

Monday: My planned polyphasic schedule:         12:30AM – 4:00AM, 8-8:20AM      12-12:20PM,        6:00-6:20PM

Tuesday: One extra sleep to counteract any residual sleep deprivation (idea is to put in sleep to get rid of the deprivation, while still keeping the brain on a tight leash).

 What happened:

The Saturday was tough, between 3am and 11am was hell. I was cold all the time and had to fight to find things interesting enough to keep awake. Video games worked for a bit, so did some shows and movies, but I would get bored of each one relatively quickly. I was just counting down the minutes to my next nap.

Then when I woke up at 11:20 I felt better. I made myself a half a cup of coffee and the rest of the day went quite well. I was even awake enough to code a bit. I was feeling so awake at 11pm that I skipped that nap entirely.

Sunday morning I was super tired when I got up at 4AM and after the 6AM nap. By 8 I was feeling more myself and the rest of the day was fine (about the same as a normal day where I’ve slept 6 hours.

Morning coffee setup From then things have been working well. Most days, getting out of bed at 4 is really hard (I feel like i will never wake up) but after making my cup of coffee I feel good and ready to work. The fact that my coffee ritual involves manual labor and math (I use a manual grinder, Chemex and scale to make sure I pour the right amount of water) helps a bit with the waking up I think. It’s amazing how hard the problem of  (13g of coffee / 2 ) * 30ml of water can get at 4AM!


Most days since then I’ve felt perfectly functional with only minor bouts of tiredness. Meditation became very hard to do without drifting to sleep, so I use it as a measure to see how well I am adapting. There have been 2 days where throughout the morning I felt almost as sleepy as that very first day. I just resorted to napping every 2 hours on those days and was fixed by 10AM. I think that probably slows down the adaptation, but it means that I can be fully functional for at least 16 hours of that day.

Tips and things I’ve learnt by going through it myself:

Keep a list:

As per PureDoxyk’s suggestion, have a list of things that you can do when tired. There were times when I thought that nothing could keep me awake on the first adaptation day and only rapidly cycling TV shows, Movies and video games allowed me to pull through. As soon as I felt bored with one (which happened really quickly) I would switch to another.

Get two sleep masks:

One for home, one for the office if you are going to be napping there. It really helps with getting to sleep and being able to leave the lights on is a big bonus for waking up. I love this one. It even fits nicely with my Zeo headband and makes me feel like I am wrapping my world in a cozy cocoon of sleep.

Don’t feel guilty if other things slip:

This is a one month test of willpower. Willpower is a finite resource, don’t waste it on keeping other good habits that you could start again after adapting. If ever contemplating “to snack or not to snack…” go make some food. Write a blog post or play video games? Just play the games. After you have adapted, you will have time to put your house back in order!

Don’t let your guard down:

The biggest mistake that I made was thinking that he adaptation would be a linear process. After I got over the first few days I had a couple of days where I felt great and woke up from all my sleeps easily. So I stopped setting extra alarms. The next day I turned off my alarm with a lame excuse of having left my glasses at work (and not wanting to put contact lenses into sleep-deprived eyes) and slept 6 hours. A few days later I overslept a nap by an hour because again I had been so good at getting up straight away from naps. There are going to be good and bad days, and you will not be able to predict them. No matter what, stay hyper vigilant for the first month.

No less than three alarm clocks:

Alarm clockEvery time you oversleep, you set yourself back. Your subsequent naps will probably be bad and you will end up feeling like crap the next day. I’ve never chosen to oversleep, have have a few times due to alarm malfunctions. Get three! I have one next to my bed (which at this point is useless after my core, I turn it off without waking up almost every morning) my iPhone alarm and (after the last oversleep) an extra loud one from RadioShack which I keep in the living room, so I have to run to turn it off before it wakes up all my neighbors at 4AM (I think the guy upstairs is a 240 pound boxer, not pissing him off is great motivation).

Schedule design:

Spend a lot of time thinking about it. Your schedule is your new brand new polyphasic life, so come up with something that really works for you. You should not change it in the first month, as part of the adaptation is creating a new circadian rhythm for yourself.For me I love having 4AM-8AM. Ideally you want to go to bed as early as possible as that maximizes deep sleep. My 1AM bed time was way too late, so I’ve changed it now, but I still had to wait a month to make the change.


I’ve been waking up with a cup of coffee ever since I was 6 years old (the idea that coffee is bad for children didn’t really exist in South Africa). Not just from a chemical, but from an emotional level (I love the ritual) I could not give it up.

I did cut down how much I drink, so now I’m doing 1 cup when I wake up from my core (the process of simply making the coffee, is the thing in the morning that brings me out of my 4AM haze). I also will often have a cup of caffeinated tea after I wake up from my naps. Because of my history with caffeine, it really doesn’t affect my sleep much at all though, so your milage may vary.  Cutting down the amount you drink is always a good idea, because that leaves you the option of using larger doses to boost mental performance when absolutely critical.


One does not get to sleep in on the weekends anymore. This is actually a great thing. Normally I have things to do on the weekend that I don’t want to do, and those can all be shoved into the graveyard hours before anyone else has started their day. Then you get to have the whole weekend to yourself to do whatever you want to do.


I haven’t noticed any particular extra hunger. I generally eat a very Paleo diet, so my body is less susceptible to blood sugar swings. That being said, I made the conscious decision to put away my scale and to not worry about how much I eat (as long as it is still healthy) during this adaptation. Again, the less other drains you have on your willpower while doing it, the better.


My Zeo has been invaluable. I have the bedside and the mobile pro. The bedside was great when monophasic, but for polyphasic sleep I like the mobile one as I can track all my naps and core sleep. Knowing what’s going on while you sleep is key to making the small adjustments necessary to good sleep (even if you’re sleeping normally). 18, 20 or 30 minute nap… which is better? It depends on your body and then only way you know what to do is to test it with the Zeo and see how your body reacts.

Where do I go from here?

Well, I’m actually well into month 2 already. While everything has gone well, the one degradation in performance that I saw in the first month was that my flexibility needed longer recovery periods after Taekwondo. I think this is because I wasn’t getting enough deep sleep during my core sleep (thanks Zeo). I’m playing with shifting my schedule earlier and taking some supplements (valerian root, magnesium and melatonin) to see if that fixes it. The other goal of the second month is just to guard against laziness, making sure I set all my alarms and that I don’t let my guard down and snooze longer just because I think I’m adapted.

I’ve got some cool statistics on the effect of all of this on my live, which I will publish as soon as I’ve made some pretty graphs and charts. Spoiler: life got way more awesome.

Polyphasic Sleep

This week I started sleeping polyphasically.

Seeing as I’ve had explained this to a few people lately, here’s a quick FAQ to explain my craziness.

What is polyphasic sleep?

A polyphasic sleep pattern is one where your regular sleep pattern is broken into three or more sessions per day. This is opposed to monophasic (normal, 8 hours straight through the night) sleep.

Why would you do such a thing?

One reason to have a polyphasic sleep pattern is that it can radically reduce the amount of sleep that you need. Another reason is that it means that your energy can be more consistent throughout the day.

How does it work?

The two most popular patterns are:

Uberman: 6 naps of 20 minutes (one every 4 hours exactly) for a total of 2 hours of sleep per day.

On Uberman your brain becomes very sensitive to sleep. If you miss a nap by half an hour, it is supposed to feel like you haven’t slept a night. It also requires you to have a very specific lifestyle, most people can’t find a way to get out of whatever they are doing every 4 hours to nap.

Everyman 3:  3 hours “core” sleep and 3 naps of 20 minutes, for a total of 4 hours of sleep per day. (This is the schedule that I am trying).

The Everyman schedule is much more reasonable than Uberman. You sleep for 3 hours (meaning that you can actually go to bed like normal people) and then just wake up much earlier than most. After the 3 hour sleep, you just need to make sure that you get three 20 minute naps in throughout the day. My schedule is: Sleep from 1AM-4AM,  and then 20 min naps at 8AM, 12PM and 6PM.

How is this possible?

The theory on why it works, is that as we sleep we go through 3 basic stages, light, REM, and deep sleep. There are lots of theories on what each one does, but the prevailing (simplified) version is:

REM: Restores cognitive function.

Deep sleep: Restores physical function

Light sleep: (nobody knows for sure)?? safety ?? energy conservation?? ??

Polyphasic sleepers believe that the light sleep is actually just filler sleep, or if it did serve functions (like saving energy so that we don’t have to hunt so much or by making it easier to wake up to danger) it is a function that we don’t need anymore.

My theory is that the brain finds it difficult to sustain REM (maybe we would go insane if our dreams were 4 times longer) or deep sleep, so it needs something to do while it rests.

By getting your REM and deep sleep in different chunks throughout the day, polyphasic sleepers can reduce the amount of light sleep they get, while not being deprived of the very important REM and deep sleep.

Don’t you NEED 8 hours of sleep to be healthy?

My take on this is that if you are not feeling tired, then you are getting enough sleep. If you’re sleeping only 4 hours a day and you have lots of energy and don’t feel tired, then clearly your body is getting enough sleep. Lots of people sleep less than 8 hours naturally, there seems to be a large genetic variation already on how much people sleep, so the 8 hours is really one of those made up numbers (kind of like the 8 glasses of water a day one).

What do the SCIENTISTS have to say?

There was one study, like 25 years ago and although deeply flawed (only one participant, non-optimal polyphasic schedule) had promising results. Then… nothing.

Many sleep scientists think it’s an internet hoax and not worth looking into. I think the problem is that it is just too hard to study.



How am I doing?

I feel fantastic. According to all my reading, I’m supposed to feel a lot more tired at this stage than I do now. Waking up from my naps is super easy. I still have stages where I feel like when I normally had around 6 hours and getting up at 4 AM still feels like getting up at 4 AM but hopefully that goes away when I’m fully adapted.


That’s a start. The two sites that have the most information are puredoxyk’s site (she led the modern revival of polyphasic sleep) and the Polyphasic Society site.


Daily reflection – The best keystone habit.

I’ve always really thought that habits were important and have spent much of the past few years reading about and working on changing habits.

I’ve even given a few presentations where the central theme was that if you create good learning habits, then you will learn well. The only issue is that despite all of this, I’ve been terrible at actually following through and creating good habits.

Sure, I’ve had some success. For instance, one of the key learning habits that I’ve used over the past 6 months has been reading technical books on the subway to and from work. No fiction, or fun books, just books that help me be a better programmer. The habit is deeply ingrained, as soon as I get on the subway, I reach for my Kindle and start reading a technical book.

Everything changed though, when I committed to making daily reflection a habit. Not only have I been able to make reflection an incredibly strong habit (I instinctually do it before bed each night), but it’s proved to be a keystone habit.

The Power of HabitA keystone habit according to Charles Duhigg in “the Power of Habit” (a great book) is the following:

Some habits, say researchers, are more important than others because they have the power to start a chain reaction, shifting other patterns as they move through our lives. Keystone habits influence how we work, eat, play, live, spend, and communicate. Keystone habits start a process that, over time, transforms everything.

In the book, he talks about how this habit is different for everyone, but I think that the act of daily reflection is a keystone habit that by its very nature makes it a good keystone habit for many people. This is because what it does is it carves out a part of your day where you can reflect on what is most important. Once the reflection habit is in place, it will bring your goals to your attention at least once a day, thereby slowly making you more and more aware of your daily actions. This means that when you decide to change other habits, the daily reflection becomes a space in your day where you can contemplate your progress on the habit that you are changing and make adjustments in order to ensure that it works.

But how to go about starting the reflection habit? You can certainly do it wrong, as I have in the past. However, I think applying the “Seinfeld” method was the big breakthrough for me.

Simply create a table somewhere (I use Evernote) with one line for every day. I then make columns for the things that I want to note about my day. I started with just “Learning” and “Shortcuts” (as detailed here), but very soon added other stuff that I wanted to know (inspired by Andrei’s post ). I have quite a few boolean (yes/no) columns for things like “went to Taekwondo”, or “completed day’s most important task”.

With that table, the habit is “complete” if you have filled in at least something for at least 30 days in a row. You don’t have to do every column, but choose at least one column that is required (I did learning). From there it should be effortless and you can start concentrating your efforts in improving any of the columns in your table.


Coding Reflection – Reading and Testing


Technology booksReading books about the technologies that you are using is really important. It gives you something that just looking at existing code doesn’t. Over time a code base tends to train developers into doing things “it’s way” and it takes an external influence to help pull the team into better ways of doing things. My Kindle has been an amazing resource, as I can have all of my technical books with me whenever I am on the train or find myself waiting in line. Then, when I’m working at my computer, I can use the Kindle app to pull up relevant sections that I remember. Searching for something that you know exists in a good technical book can be 50 times faster than looking for it on Google.

One important optimization to this is to spend time reading books about the things that you are doing. And not just “oh, I’m writing rails code, so I should read a Ruby on Rails book”. That’s a great place to start, but if you have a specific thing you will be  working on the next day, read that book. So if I was going to spend my next day writing and fixing tests, I read an RSpec book. If the stuff that I’m working on is mainly plain Ruby code, I read a Ruby book. Playing with Routes tomorrow? read the Routes section of a Rails book.


Unit testing is unit testing, not integration testing. Don’t confuse them. Tightly coupled unit tests where you create factories for 6 objects and rely on pulling in RSS or JSON from an external service make life hell for everyone. Yes, it’s more work and it seems silly to mock everything out when you’re doing it, but being militant is the only way to keep things clean. It also makes the specs a lot faster, something that makes up for the extra time you spend building a mock object instead of just using FactoryGirl.

The other benefit is that if your proper unit tests are hard to write then that’s a pretty clear code smell. Rewriting the code to make the testing easier can lead to much cleaner, less coupled code. When you have to pay attention to everything that your code interacts with (by mocking out each interaction), you become a lot more sensitive to how much it relies on that other stuff that it really shouldn’t be relying on.