Install CtrlP to save time hunting for files in Vim December 25, 2016

Vim is my favorite text editor. I've used it exclusively since 2004, having fallen in love with its near-infinite customizability and "one tool, one job" philosophy.

But if there's one feature that's always felt missing, it's a great fuzzy file search. Other text editors like Atom, TextMate, and Sublime offer the user a convenient way to search files by typing partial substrings of the full filename. So if you have a file in lib/foobar/baz.rb, typing foobaz into the fuzzy finder would find the file.

This becomes especially useful in the context of modern JavaScript, where you'll often have file trees that look like this:

reducers/todos.js
actions/todos.js
components/TodoList.js

Using tab completion to resolve these paths works, but it's a lot of keyboard crunching. Not the smoothest approach.

Luckily, CtrlP offers a turnkey solution.

Installation

To install CtrlP, clone it into your ~/.vim/bundle directory:

git clone https://github.com/ctrlpvim/ctrlp.vim.git ~/.vim/bundle/ctrlp.vim

Then, add it to your Vim's runtime path in your ~/.vimrc:

set runtimepath^=~/.vim/bundle/ctrlp.vim

You'll probably also want to tell CtrlP to ignore files matching some paths by setting the wildignore option in your ~/.vimrc:

set wildignore+=*/.git/*,*/.hg/*,*/.svn/*,*/build/*,*/node_modules/*

This tells CtrlP to ignore version control meta files (Git/Mercurial/SVN), files inside build directories (I use Middleman frequently and it dumps its output files here), and your NPM node_modules directory. If you have other project-specific paths you don't want to show up in your fuzzy search results, add them here.

Usage

To use CtrlP, open Vim in the root directory of the codebase of your choice and press, well, Ctrl+P. A buffer will appear at the bottom of your Vim. Type some characters that are a part of the file you want to find, and you'll see the list of files reduce to those matching your query. Press Return and the selected file will open!

Hopefully CtrlP will improve your workflow like it has improved mine. Reducing the friction between your brain and your fingers is paramount in creating a work environment that enables great work instead of getting the way. Cheers!

Beware of making database queries in Goroutines December 24, 2016

The past couple days I've been struggling to patch an issue in a client's codebase wherein PostgreSQL is reporting the following repeatedly in my error tracker:

pq: sorry, too many clients already
pq: remaining connection slots are reserved for non-replication superuser connections

In an earlier post, I hypothesized that perhaps I wasn't closing connections I'd opened using db.Query. While I did find some instances of this, I found that the actual culprit was opening database connections inside of Goroutines created and run in a for loop:


for _, user := range users {
  go doStuff(user)
}

func doStuff(user User) {
  rows, err := db.Query("SELECT * FROM cars where user_id=$1;", user.Id)
  defer rows.Close()
}

The above example would work just fine if not for running doStuff in concurrent Goroutines. PostgreSQL would execute the queries in series, closing the previous connection before opening a new one. But when we tell Go to execute them in parallel, open connections pile up and bad things happen.

So: If Postgres is complaining that you've got too many concurrent connections, think about the architecture of your application. Is there some place where you might be trying to execute queries in parallel? Is there any way you can execute the queries in series? Or perhaps complete your queries ahead of the concurrent processing?

If you've struggled with having too many concurrent open connections in your Go application, I'd love to hear how you overcame the problem.

Too many connections using PostgreSQL with Golang December 21, 2016

If you're building a database-backed Golang application using PostgreSQL, you might come across one or both of the following errors:

pq: sorry, too many clients already
pq: remaining connection slots are reserved for non-replication superuser connections

Both of these errors are signs that you've tried opening more database connections than your PostgreSQL server can handle.

It's tempting to go into your PostgreSQL server configuration and increase the number of connections your server will accept. But that will only lead to performance problems, especially if you're running your PostgreSQL server on a smaller instance with less memory and CPU.

More likely than the database not accepting connections being the culprit is the possibility of your Golang code leaking database connections.

Wherever you open a query connection, you're responsible for deferring a Close() call on the resulting row set:

rows, err := db.Query("SELECT * FROM cars;")
defer rows.Close()

It's a good bet that somewhere, you're not closing a connection you've opened. Over time, this could result in your database connection pool being consumed by idle connections. Auditing your code for queries where you're not closing the connection afterward will help ensure your application can still connect to its database.

Depending on the size of your application, this process could take awhile. But it's a surefire way to get things moving in the right direction.

Alias your common Ruby commands for a faster workflow December 21, 2016

If you're a Rubyist, you probably use the likes of rspec, cucumber, rake, and other commands frequently. And it's likely that you might be running them using bundle exec to execute them in the context of your project's bundle. After finding I was spending a lot of time typing each of these commands, I added a few aliases to my shell config to speed up my workflow:

alias rsp='bundle exec rspec'
alias cuc='bundle exec cucumber'
alias rak='bundle exec rake'
alias mm='bundle exec middleman'

Paste these into your ~/.bashrc or ~/.zshrc, restart your shell, and now running an rspec test in the context of your bundle is as simple as:

rsp spec/models/banana_spec.rb

Have other useful aliases? Post them in the comments below!

Using Gulp to generate image thumbnails in a Middleman app December 21, 2016

var gulp = require('gulp');
var imageResize = require('gulp-image-resize');

var paths = {
  images: "source/images/**/*"
}

gulp.task('images', function() {

    gulp.src(['source/images/**/*.png', 'source/images/**/*.jpg'])
        .pipe(imageResize({
            width: 538,
            height: 538
        }))
        .pipe(gulp.dest('tmp/dist/assets/images/538x538'));

    gulp.src(['source/images/**/*.png', 'source/images/**/*.jpg'])
        .pipe(imageResize({
            width: 1076,
            height: 1076
        }))
        .pipe(gulp.dest('tmp/dist/assets/images/1076x1076'));

});

gulp.task('watch', function() {
  gulp.watch(paths.images, ['images']);
});

gulp.task('default', ['watch', 'images']);
gulp.task('build', ['images']);

Remap ESC key in Vim for better ergonomics December 21, 2016

A couple months ago, I had a sharp, shooting pain in my left hand. It was right after I switched from an Apple keyboard to using a WASD mechanical keyboard.

After a couple weeks of pain, I realized I'd been reaching my left hand to the Escape key in Vim, probably hundreds of times per day! No wonder my hand was hurting.

I finally resolved to remapping Vim not to use the Esc key, in favor of using the consecutive letters jk in its place. Lo and behold, my pain went away. Hopefully it resolves yours, too!

To remap your Esc key like I have, add the following line to your ~/.vimrc:

inoremap jk <esc>

Naming conventions for modern JavaScript December 20, 2016

If you're like me, you've struggled to come up with a reasonable scheme for naming things in JavaScript. I'd like to share the conventions I use, with the hope that you can put them to use in your project and never think about it again.

In my mind, there are three main types of JavaScript files:

  • Collections of functions
  • Single functions
  • Classes

Collections of functions

Let's say you have a couple utility functions called add and subtract, each exported from a single file:

export function add(a, b) {
  return a + b;
}

export function subtract(a, b) {
  return a - b;
}

When I have a group of functions like this, I name the file using drunkenCamelCase, (lowercase first letter) with a name that suggests the library's contents. This module I'd probably call math.js.

When I go to use one of the functions from another file, now I can refer to it like so:

import { subtract } from 'math';

console.log(subtract(5, 1));

Single functions

What if you have a single helper function you want to use from a few places in your codebase that you'd like to give its own file?

For instance, let's say you have a function that generates a fully-qualified URL from a URL path:

export default function(path) {
  return "http://www.guilded.co" + path;
}

In this case, I'd name the file using drunken camel case, but would name the file explicitly after the exported function. That way, when I go to import it from another file, I can refer to it thusly:

import urlFor from 'urlFor';

console.log(urlFor('/about.html'));

Classes

Now that ES6 has support for classes built into the language, there's a good chance you'll use them to represent the stateful objects in your codebase.

I like to make it clear that classes are distinct from functions, so I name them using CamelCase (capital first letter) notation:

class MyClass {
  // ...
}

When producing a new file for a class, export the class directly, omitting its name:

export default class {
  // ...
}

File names for classes should be CamelCased as well. So our MyClass class would be in MyClass.js.

If you use React, you probably know you're required to name React components in the same CamelCased format. If you use ES6 classes to construct your React components, this convention will come in handy.

Fixing a Ruby crash using Middleman 4.1x with Ruby 2.3.0 December 20, 2016

I went to update a Middleman project's gems today. After I did, I noticed middleman server exited with the following error:

Assertion failed: (!STR_EMBED_P(shared)), function str_new_frozen, file string.c, line 1075.

This is an internal Ruby error generated from within its C source. I found a discussion about the topic in the Ruby bug tracker, but that wasn't much help.

Once I modified my Gemfile to use Ruby 2.3.1 and re-bundled my gems, middleman server worked just fine.

If you're running into this problem, try upgrading to a more recent Ruby and running Middleman on it. There's a chance this bug has nothing to do with Middleman and could be due to another gem, but I figured I'd mention it here in case someone else is having the same problem.

Why doesn't React immediately mutate state when calling setState? December 20, 2016

When setting the state on a React component within an event handler, you'll find that the state isn't updated if you dump the state to the console immediately after:

The React documentation warns:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

I learned today that setState accepts a callback in this scenario. So modifying handleChange to the following will result in the console receiving the updated state:

How to bind React component event handlers in ES6 December 20, 2016

When creating React components using ES6 class notation, you'll need to bind event handlers passed as props to this, or you'll find that the handlers will be bound instead to the DOM element.

There are a few ways to do this. You can reassign the bound handler in the constructor:

class MyComponent extends React.Component {
  render() {
    return (
      <div>
        <button onClick={this.onClick.bind(this)}>Click Me</button>
      </div>
    );
  }

  onClick(event) {
    alert("You clicked me!");
  }
}

This works fine, but now you have .bind(this) littering your otherwise elegant JSX.

To remedy that, you can use the fat arrow prototype method syntax:

class MyComponent extends React.Component {
  render() {
    return (
      <div>
        <button onClick={this.onClick.bind(this)}>Click Me</button>
      </div>
    );
  }

  onClick = (event) => {
    alert("You clicked me!");
  }
}

Except... now you have two separate syntaxes for declaring methods, which could make your code less readable and more confusing.

I think the most elegant way is to use the new double-colon (::) notation, which is a shortcut for calling .bind(this) on a given handler:

class MyComponent extends React.Component {
  render() {
    return (
      <div>
        <button onClick={::this.onClick}>Click Me</button>
      </div>
    );
  }

  onClick(event) {
    alert("You clicked me!");
  }
}

Now your caller is binding the method to this without an ugly .bind(this) call, and the method body isn't unnecessarily decorated with fat arrow notation.