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.

Fixing Postgres errors after an ungraceful shutdown on your Mac December 20, 2016

Every so often, I'm forced to shut down my Mac by holding down the power button. When this happens, PostgreSQL often doesn't shut down properly, and when my computer starts again it doesn't start automatically.

It turns out this is because there's a stale pid file kicking around inside your PostgreSQL var folder. To fix it, simply delete the postmaster.pid file. PostgreSQL will start automatically thereafter.

rm /usr/local/var/postgres/postmaster.pid

Things I wish I'd known at 20 November 2, 2016

I'm turning 31 in less than two weeks. In tech nerd terms, that means I'm basically an ancient relic. There are a few things I wish I'd been told, and other things I was told but wish I had listened to. If you're a young aspiring geek about to excitedly enter a career in technology, maybe I can save you some heartache in your twenties.

  1. Programming is hard, but (usually) it's not an emergency. Enjoy yourself and don't sweat the day-to-day.
  2. Ideas are worthless. Execution is everything.
  3. Learn how to solve problems, not how to use the latest tech. No one ever hired a builder because they were really good at hammers. They hired them to build a house.
  4. Avoid lifestyle inflation. Live like you're middle class, even if you make six figures. (American median income: $51,939)
  5. Save six months' worth of expenses in a savings account as fast as you can.
  6. Keep your recurring expenses as low as possible. This means things like rent, debt payments, utilities, and your gym membership.
  7. Stay out of debt. If you're in debt, eat dog food and work until you're out.
  8. Remember your colleague with the big house and nice car probably makes about the same you do. Also remember they're probably stuck in their job paying for them. Choose mobility.
  9. Don't buy a house unless it's a really, really good deal. Even then, probably don't.
  10. Commuting to an office eats more of your salary than you think.
  11. Fall in love. It keeps you out of bars, in bed early, and attentive to your work.
  12. Eat lots of vegetables. Allocate time to cook.
  13. Invest in ergonomics. Stand at work.
  14. Listen to others unconditionally.
  15. Learn basic yoga postures. Practice them daily.
  16. Take frequent breaks while working.
  17. Drink lots of water.
  18. Avoid alcohol. Especially chronic use, since it becomes difficult to notice its negative effects when you're always hungover.
  19. Track every penny you earn and every penny you spend.
  20. Buy a small, inexpensive, efficient car.
  21. Run your household like a business with shareholders.
  22. You're going to be old and sexually undesirable someday. You're likely more attractive now than you'll be at the end. Enjoy that.
  23. Give to others spontaneously.
  24. Don't let your salaried job get in the way of your own dreams.
  25. Don't let your dreams be diluted by the day-to-day challenges of your salaried job.
  26. Don't let Apple tell you the things you need to buy.
  27. Chat and email aren't actual work.
  28. Choose clients and employers based on how you get along, not on how much you get paid.
  29. Symbols of status matter, but the symbols aren't your car, house, or clothes.
  30. Enrich yourself with knowledge and art. They're inexpensive hobbies and you'll always be fulfilled.
  31. Your parents are wrong about a lot of things. But they're also right about some. Choose your own path, but respect their guidance.
  32. The world is in peril. But it's always been that way.
  33. Gratitude is effective therapy.
  34. The best time to start has already past. But the second best time is right now.

So you're really good at hammers November 2, 2016

If you're about to hire a contractor to remodel your kitchen, you won't ask them if they're really good at hammering nails.

And if you hire a personal trainer, you're not going to be too interested in if they use the latest and greatest weight machines.

So why then, do software consultants often value themselves based on the tools they use? What value is it to your clients to know you have a theoretical knowledge of framework X, when framework Y is threatening its demise?

As your customer, I already know you can hammer nails. I want to know what kind of house you can build me. I want to know that, in the event nails suddenly become passé, you can deliver me a functional house using screws or bolts or glue.

More often than not, your hard skills don't matter. It's your meta-skill— your ability to learn new skills rapidly and under pressure—that is truly valuable.

Just like hard skills, meta-skills can be learned. Through conditioning, you can train your body and mind to be really good at learning. Here are some things that have worked for me.

  1. Spend an hour per day reading about the latest technologies in your discipline. Apply one of them to a side project. Ask your clients or employer if you can give a talk on one. If you think there's a new technology that could add value to your client's project, say so, and lobby to use it.

  2. Adopt a product-oriented mentality. Don't get caught in the weeds of implementation. Be sure to poke your head out to make sure what you're doing matches your product's overarching vision. Talk more and code less.

  3. Start with the solution in mind. If you're going to build a new feature, sketch it out first and ask for feedback. It's likely you're wrong in at least one of your assumptions. Better to make it wrong on a napkin than in code.

  4. Learn to distill everything in lists. Developers are communicators above all. If you are a capable analyst, you will excel no matter the toolset. Lists convey to your team and stakeholders an itemized vision of the future. They're easy to clarify and easy to change. And, they ultimately produce more value than the code that spawns from them.

  5. Don't be afraid of not doing it best way the first time. On a recent project, I was tasked with building a new user interface feature. I decided that, since React is eating the world of web interfaces, it was time we caught up with the times. My first release of the feature worked great for the user, but under the hood I neglected some of the best practices I would later learn. While we're still in the process of adopting those practices, my code is currently chugging along in production, adding value to the product. If we're to brave new frontiers, it's likely we'll end up backtracking along the way.

Technologies change, but your own meta-skill will keep you valuable for your entire life. Even if you're really good at hammers, make sure you know how to build a house.