Sneaking Into the Everyday

Standing in cold, pre-dawn WWDC keynote line, I met a couple of the friendly Mac & iOS engineers from 6wunderkinder, makers of the beautiful Wunderlist apps. I'd tried Wunderlist in the past, but some weeks later, I thought I'd give it another go. Turns out, it's been great! Just the mix of power and simplicity that I need to stay focused on my tasks.

This change made me realise that quite a lot of my most-used tools are also things I'd picked up only in the last year or so. On the Mac, they are:

And on iOS:

All this has happened without any particular conscious effort. Apps come to my attention, and if I like them, there's a good chance they stick around. Granted, as a software developer I may be more curious than most, but I still take this as a heartening thing: no matter when you launch, if you offer something better or compellingly different, you stand a real chance of finding your way into people's everyday.

objc.io

objc.io is a "periodical about best practices and advanced techniques in Objective-C." Its first issue has a series of articles all about lighter view controllers. I subscribed right away; this looks like it has to potential to set alongside NSHipster and iOS Dev Weekly as valuable and regularly-updated resources for Cocoa developers.

Levelling Up With AngularJS: Building a Reusable Click to Edit Directive

In my last article about AngularJS, I shared how easy it was to build a simple "click to edit" field, and along the way introduced some of Angular's core concepts: controllers, expressions & two-way bindings between your markup and the controller's scope. This was a nice introduction, but the resulting code has a shortfall: it's not easily reusable. For something that behaves as a form field, you want the ability to sprinkle it across your pages wherever you like. This is where directives come in. Spurred on by Max's recent foray into data-backed directives, I'll now take the next steps and turn this click to edit example into a reusable Angular directive.

If you've sprinkled Angular into your apps at all, you've already worked with its built-in directives, things like ng-model, ng-repeat and even ng-controller and ng-app. With a directive you can add hooks into the HTML markup for injecting your own custom markup and logic. As the AngularJS documentation puts it, "directives are a way to teach HTML new tricks." They help you keep your markup declarative and intention-revealing, and your implementation packaged away in a self-contained, reusable components.

Here's how we'd want a click to edit directive to look in practice:

<div click-to-edit="someModelName"></div>

We want the click-to-edit attribute to bind to a model in the current scope (just like ng-model does) and have that entire <div> replaced with the markup needed to show the field. Here's the directive to do it:

app = angular.module("formDemo", []);

app.directive("clickToEdit", function() {
    var editorTemplate = '<div class="click-to-edit">' +
        '<div ng-hide="view.editorEnabled">' +
            '{{value}} ' +
            '<a ng-click="enableEditor()">Edit</a>' +
        '</div>' +
        '<div ng-show="view.editorEnabled">' +
            '<input ng-model="view.editableValue">' +
            '<a href="#" ng-click="save()">Save</a>' +
            ' or ' +
            '<a ng-click="disableEditor()">cancel</a>.' +
        '</div>' +
    '</div>';

    return {
        restrict: "A",
        replace: true,
        template: editorTemplate,
        scope: {
            value: "=clickToEdit",
        },
        controller: function($scope) {
            $scope.view = {
                editableValue: $scope.value,
                editorEnabled: false
            };

            $scope.enableEditor = function() {
                $scope.view.editorEnabled = true;
                $scope.view.editableValue = $scope.value;
            };

            $scope.disableEditor = function() {
                $scope.view.editorEnabled = false;
            };

            $scope.save = function() {
                $scope.value = $scope.view.editableValue;
                $scope.disableEditor();
            };
        }
    };
});

Let's break this down a little. Right at the top we have its name: "clickToEdit." Angular directives use camelCase names in the JavaScript, which are matched to their name-with-dashes equivalent in HTML. Next, you'll see we've provided an HTML template string for the editor. It can use all of the same Angular-provided facilities that you'd otherwise use in your own page templates.

The directive function must return an object that specifies its behaviour and configuration. In our case, we use restrict: "A" to specify that the directive will only match HTML attributes, and replace: true to have the directive's template entirely replacing any elements that it matches.

We also specify a custom scope for the directive. You'll want to at least provide an empty object here if you want your directives to have their own independent scope, but you can also use this scope object to create a mapping from the HTML element's attributes to varaibles in the directive's scope. In our case, value: =clickToEdit sets up a bi-directional binding between the value in the directive's scope and the value of the click-to-edit attribute in the parent scope.

The last thing we provide in the directive configuration is a controller that provides logic to back the directive's template. This packaging of a template and its behaviour is what can turn a directive into a truly reusable component. The controller here is just a direct copy of all the code from my earlier post, but because it's packaged along with the directive, we've now made it reusable.

How would it look in practice? We might have something like a LocationFormCtrl controller that manages the editable form for a "location" record:

app.controller("LocationFormCtrl", function($scope) {
    $scope.location = {
        state: "California",
        city: "San Francisco",
        neighbourhood: "Alamo Square"
    };
});

And if we wanted to make each of these attributes have a "click to edit" field, it's now as simple as this:

<div ng-controller="LocationFormCtrl">
    <h2>Editors</h2>
    <div class="field">
        <strong>State:</strong>
        <div click-to-edit="location.state"></div>
    </div>
    <div class="field">
        <strong>City:</strong>
        <div click-to-edit="location.city"></div>
    </div>
    <div class="field">
        <strong>Neighbourhood:</strong>
        <div click-to-edit="location.neighbourhood"></div>
    </div>
</div>

Straightforward, declarative, no-cruft. This is how Angular can transform your apps, and directives play a big part in that.

To give you something to play with, here's a working demo. Below the editable fields, we also directly print the LocationFormCtrl scope's location attributes, so you can see how changes of the attributes in the fields propogate back up to the parent controller's scope.

Of course, there's even more we could do. Right now, this directive only deals with straightforward <input type="text"> fields. What about if you wanted <input type="date"> or even a <select>? This is where you could add some extra attribute names to the directive's scope, like fieldType, and then change some elements in the template based on that value. Or for full customisation, you could even turn off replace: true and add a compile function that wraps the necessary click to edit markup around any existing content in the page. I'll leave both of these as exercises to the reader, for when it's time to level up yet again!

Two i's

I think it’s always good to be working on two things: The next most important thing, and the next most interesting thing.

Jason Fried

Things Get Fuzzy Fast: Examine Your Day So You Can Learn From It

Many of you will have seen Benjamin Franklin's daily schedule.

Benjamin Franklin's daily schedule

I love it, especially how it brackets the day with moments for reflection. He lives the examined life. He uses his morning to "contrive [the] day's business and take the resolution of the day." If Franklin were at a present-day web or design business, he'd be right in there at the daily stand-up, with all his plans lined up nicely.

But the most interesting part of Franklin's schedule is in the evening, in his "examination of the day." This is the moment that allows for learning and growth, for a conscious inspection of matters that gives you true agency over your work. Just in the way the web business runs a retrospective at the end of a project, you can achieve a much tighter cycle of personal evaluation, allowing your experience from one day to inform and improve the next. Without this, you can resign yourself to be little more than a sheet of paper – perhaps the one outlining your morning's good intentions – cast out to flutter in the wind, hostage to the whims of myriad external forces.

Taking back control takes a mere few minutes a day, and the results are worth it. In doing it myself, last week I learnt that I would start most days with a big goal in mind and a bunch of small chores alongside, but the chores would always end up taking longer than my drinking-my-first-coffee self predicts. I'd get to the end of each day with too little time for my most important work. Without any kind of examination, it's too easy to let a situation like this leave you feeling vaguely embattled and just press on without any change. This is not a recipe for improvement.

You might ask why a mornings-only cycle of evaluation wouldn't also work. At the end of the work day you just want to shut the computer and move onto something else, right? The trouble there is that you'd lose information. You best know how your day went when you've just finished living it. If you want to be active in adjusting your days so you can end them feeling accomplished, that's when you need to be recording things.

These daily reflections become even more powerful once you're part of a team. Write at the end of each day and this small investment in time can bring about a huge boost to everyone's general awareness of each other's work. If you're struggling with something, your teammates don't need to wait and see if you deem it important enough to bring up again the next morning. Instead, they can jump in and offer a hand as soon as they can see you could do with one. Then when things go well, there's no better motivation than seeing the continuing great work of your teammates, and you can boost the positive mood even further by joining in and celebrating their wins.

The way I see it is that, if I haven't shared it in writing with my teammates, then the work never happened. Prose is just as important as code.

Have you ever reached the end of a long stretch of work and thought, "Wow, didn't that time fly?" If you then thought more deeply, would you even be able to recall the particular ups and downs that defined the course of that work? What if you waited a couple of weeks and tried again? Things get fuzzy fast, and since the most instructive aspects of the work may not always be the most memorable, there's only a small window where you can learn from it. Become a diarist of your work, and you can keep this window open.

Being ignorant is not so much a shame, as being unwilling to learn.

Benjamin Franklin

Live an examined life, and you give yourself the best chance to improve it.

A Manageable Multi-Database Redis Development Setup

Redis has quickly become the companion to Postgres in most of our Rails apps. This creates a problem for development, since a Redis server only uses numbered databases. That's 1-16 by default. Hardly memorable, unless your app is called "5", in which case you're golden. On a single machine alone, it's easy enough to lose track of them once you have a few apps connecting to redis for both development and testing databases. Once you have multiple developers and designers working on an app, it's even worse. The solution I've found is to run a separate Redis server for each app, listening via a named socket.

This is easy to set up. First, take your standard Redis config file (mine is /usr/local/etc/redis.conf, thanks to Homebrew) and copy it to redis-common.conf. Edit this new file and change its port to port 0, ensuring it doesn't listen over TCP.

Then, create a separate config file for each app you want to use Redis. I call them /usr/local/etc/redis-server-<app_name>.conf. These files are nice and short:

include /usr/local/etc/redis-common.conf
pidfile /usr/local/var/run/redis-app_name.pid
unixsocket /tmp/redis-app_name.sock
dbfilename dump-app_name.rdb
vm-swap-file /tmp/redis-app_name.swap

These per-app config files are enough to run an entire Redis instance: they load the common config, followed by the app-specific paths that allow the server to run in isolation from other apps.

You can then start the Redis server like this:

redis-server /usr/local/etc/redis-server-app_name.conf

Currently, I have 5 different app-specific configs like this. This makes bringing Redis up and down a bit of a chore. I simplified the process with a couple of shell functions:

function redstart {
  redstop
  for file in `ls /usr/local/etc/redis-server-*.conf`; do
    redis-server $file
  done
}

function redstop {
  for file in `ls /usr/local/etc/redis-server-*.conf`; do
    pidfile=`grep pidfile $file | awk '{print $2}'`
    if [ -f $pidfile ]; then
      kill `cat $pidfile`
    fi
  done
}

Easy. Redis up and Redis down in one hit.

There's another benefit to running Redis like this: loading production data onto your development machine. Most cloud-hosted Redis providers give you backups in Redis' .rdb format, which is the data file for the whole server. You can't load this for a single numbered database. Splitting your local Redis servers by app means you can just replace the file specified in dbfilename with this backup file and now your app has the latest production data without interfering with any other app's Redis data.

Bonus: Redis config management functions

Want an easier way to build and manage those per-app config files? Here you go:

function redls {
  ls /usr/local/etc/redis-server-*.conf
}

function redgen {
  if [ -z "$1" ]; then
    echo "You need to specify an app name, eg. redgen decafsucks"
    return 1
  fi

  app=$1
  config="/usr/local/etc/redis-server-${app}.conf"

  redstop

  echo "include /usr/local/etc/redis-common.conf"     > $config
  echo "pidfile /usr/local/var/run/redis-${app}.pid"  >> $config
  echo "unixsocket /tmp/redis-${app}.sock"            >> $config
  echo "dbfilename dump-${app}.rdb"                   >> $config
  echo "vm-swap-file /tmp/redis-${app}.swap"          >> $config

  redstart
}

function redrm {
  if [ -z "$1" ]; then
    echo "You need to specify an app name, eg. redrm decafsucks"
    return 1
  fi

  redstop
  rm -f "/usr/local/etc/redis-server-${app}.conf"
  redstart
}

Bonus: Rails redis initializer

Here is the do-it-all Redis initializer I use in my Rails apps:

require "redis"

if (redis_url = ENV["REDIS_URL"] || ENV["REDISTOGO_URL"]).present?
  uri = URI.parse(redis_url)
  REDIS = Redis.new(
    host: uri.host,
    port: uri.port,
    password: uri.password)
else
  redis_socket = "/tmp/redis-myappname.sock"
  if File.exist?(redis_socket)
    REDIS = Redis.new(
      path: redis_socket,
      db: !Rails.env.test? ? 0 : 1)
  else
    REDIS = Redis.new(
      host: "localhost",
      port: 6379,
      db: !Rails.env.test? ? 0 : 1)
  end
end

This looks for Redis URL ENV vars first, which are used on Heroku to specify the Redis location. If they're not found, we must be in development, so it looks for the named Redis socket for the app (change redis_socket to make it your own). If that's there, it uses database 0 for Rails development and production modes, and database 1 for test. Finally, we don't want to fail completely if someone hasn't yet starting using the named redis sockets, so we fall back to the standard Redis TCP port.