Lover of all things beautiful

2015-12-22
Using Amazon Route53/S3 to redirect your root domain

The Backstory

You may find yourself needing to redirect all traffic from your root domain example.com, otherwise known as the apex, to your real hostname www.example.com. Maybe you didn’t know this, but you cannot use a CNAME on your apex domain. This will bite you in the butt when you try to use your root domain example.com with Heroku’s SSL (HTTPS) service. Heroku will give you a hostname and tell you to create a CNAME to that hostname. However, this is not strictly possible. Some registrars can get around this by essentially providing you an HTTP redirect, but his is hack. In short, don’t use your apex domain e.g. example.com, even though you see all the cool kids on the block doing it.

Just Do It!

Create an Amazon S3 Bucket

First you are going to create a bucket in Amazon S3. You can name it after your domain, but the name is immaterial. The important part is going to be select Static Website Hosting. In that section, you’re going to select Enable Website Hosting. The Index Document is also immaterial, you can name it foo.html.

The important part is the Redirection Rules. You’ll use this.

1
2
3
4
5
6
7
8
9
<RoutingRules>
<RoutingRule>
<Redirect>
<Protocol>REPLACEME with either HTTP or HTTPS</Protocol>
<HostName>REPLACEME with www.example.com</HostName>
<HttpRedirectCode>301</HttpRedirectCode>
</Redirect>
</RoutingRule>
</RoutingRules>

You wont forget to actually replace the protocol and hostname sections will you?

Create a Route53 Alias

Now, walk over to Amazon Route53. I’m totally assuming that you’re using Route53 for your DNS records, otherwise, this whole article is pretty much pointless. Click on your root (apex) record. Now we want to select Type: A IPv4 Address, then you’ll select Alias: Yes. For the Alias Target you will get a dropdown, you’ll see one of them listed as S3 Website Endpoints, that’s the S3 bucket you just set up. Select that.

Now Save Record Set and you’re done.

Recap

You created an S3 bucket that acts like a webserver, anything that hits this S3 bucket will be immediately redirected to your desired hostname. You configured your domain example.com to hit your S3 bucket.

Caveat

  • This will not work for HTTPS => HTTPS, only HTTP => HTTP(s). So https://example.com will not work, it just times out. This might be a deal killer for some in which case you might want to stick with using an A record for your apex domain by setting up a real server.
Read More

2015-10-14
Leveraging Reflux (flux) with React like a pro

#Leveraging Reflux (flux) with React like a pro

My latest project for a well known clothing retailer has involved writing a React based web app. It has a staggering amount of data that needs to update different parts of the app. To accomplish this, we are using React (of course) and Reflux.

So you’ve heard React is the new hotness that all the cool developers are adding to their resume. It’s supposed to cure all your front-end woes. But in fact, you’ll find yourself with some new hand wringing problems to get you down. Don’t Fret. There is a better way.

Flux is not so much a software, but a way to keep data synchronized in your front-end app. What am I talking about? Say a person enters some data into a form and presses Send, we need to keep that data in sync in other parts of the app. Reflux is just a re-invention of the flux concept with some powerful features and simplified tools.

A simplified diagram of data flow

1
╔═════════╗       ╔════════╗       ╔═════════════════╗
║ Actions ║──────>║ Stores ║──────>║ View Components ║
╚═════════╝       ╚════════╝       ╚═════════════════╝
     ^                                      │
     └──────────────────────────────────────┘

The major players

  • The React component (View Component)
  • The Reflux Actions file
  • The Reflux Store file

Think of this one way data flow like this. The component says “Hey, the person has updated their name in an input field”, so it calls the action that is defined in the Action file. The Action takes care of sending out a broadcast with the data the person entered. The Store is listening to the Actions file and gets called, it updates itself and then triggers an update. The component is listening to the Store and updates itself because it has new state values.

A simple web form

FirstNameHeader.js (For displaying the name entered into the input)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import React from 'react';
import Reflux from 'reflux';
// We import the PersonStore so we can get its value and updated when it's updated
import PersonStore from './PersonStore.js';

export default React.createClass({
mixins: [
/* The value of the PersonStore is set in the local state as 'person' */
Reflux.connect(PersonStore, 'person')
],
renderer() {
return (
<h1>{this.state.person.first_name}</h1>
);

}
});

FirstNameInput.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import React from 'react';
import Actions from './Actions.js';

export default React.createClass({
renderer() {
return (
<input type="text" name="first_name" defaultValue="" onChange={this._onUpdate} />
);

},
_onUpdate(event) {
let name = event.target.name;
let value = event.target.value;
// `updatedPerson` is defined in Actions.js, and PersonStore.js has a `onUpdatePerson` method that matches the following
Actions.updatePerson(name, value);
}
});

Actions.js

1
2
3
4
5
6
import Reflux from 'reflux';

// This file is small, but essential
export default Reflux.createActions([
'updatePerson'
]);

PersonStore.js The data store for person data

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import Reflux from 'reflux';
import Actions from './Actions.js';

let person = {
first_name: ''
};

export default Reflux.createStore({
// This is magic that matches up the Actions to the listening methods below
listeners: Actions,
init() {
// Need to provide the initial value to compenents
return person;
},

// A `magic` method that matches up to the `updatePerson` Action
// This is called in our `FirstNameInput.js` file
onUpdatePerson(name, value) {
person[name] = value;

// Needed for any component listening to these updates
this.trigger(person);

}
});

So what does this lame web app do? Why so complex?

Glad you asked. When a person enters their name in the input, the change is reflected in the header component. But wait, you could add another component that would also be able to get those updates too. Later we’ll see how you can combine multiple Actions and Stores to create powerful workflows for your data.

I admit, the documentation for Reflux is lacking and not very easy to follow, but it’s a very powerful and elegant framework for keeping state across components. We’ve found it essential to building a very complex React web app.

Disclaimers

  • I’m using ES6 in my examples
  • Reflux has several different ways to skin a cat, this is the one of the simple more magical ways
  • We’ll cover async actions in a different post
Read More

2015-06-10
The Life of a Vagabond Software Engineer

The Life of a Vagabond Software Engineer, Part 1.

Constant change requires reliable tools

Maybe you’re like me, you love to change things up, find new places, explore the horizons. This could be the far flung corners of the earth, or just a part of town you’ve never been. I’m a die hard explorer, but I’m also a software engineer. I need to be connected, I need power, and I need an environment that works. In this post, we’ll explore the tools. In subsequent posts, we will explore other factors, such as finding the right places to work, hints on helps.

Minimalism

I gravitate towards minimalism (although in practice it may not always appear that way). I take only what I need and usually items should have dual purposes. The items you choose should be of high quality, durable, and fixable if need be.

Go Light, Go Right.

Technical Accouterments

So let’s get right to it. I need reliable tools. My personal choice for computers is a MacBook Pro 13”. I’ve been using a Mac for almost 10 years now and have had little to no trouble. I usually buy a new one every two years (having a backup is also crucial in my line of work). I need to protect my Mac while it’s in my pack so I use an Aerostich Padded Laptop Computer Sleeve.

For the technical needs I have a small Granite Gear Ripstop Stuffsack. In this bag you’ll find.

Stuff Bag

  • Etymotic HF5 Earphones (great for noise free listening)
  • Simple lens cleaner (I wear glasses)
  • MacBook Power cord in a bag (having cords in their own containers/bags really helps reduce tangle)
  • MacBook Power Extension rolled up with velcro ties
  • iPhone wall charger
  • iPhone Earphones in an old makeup remover case
  • Granite Gear Stuff Sack
  • iPhone cord
  • Microfiber cloth
  • Moleskine Classic Notebook Squared 5x8.25 (not in stuff sack, but inner pocket of the Deuter Backpack)
  • Zebra Ball point pen

I can grab the bag in pack and easily have what I need to power up the Mac or iPhone, clean my glasses, take notes, jump on a conference call and more.

Ready, Set, Eat!

Cup and Spork

For the more culinary, eco friendly needs. I have a simple GSI Cup and a Snowpeak Titanium Spork. Notice the lanyard tied around the spork, this really helps to hang items, find it a lot easier if you happen to drop it (e.g. in the snow). Rant I hate styrofoam cups and plastic forks and spoons. Think of the overflowing landfills that have billions of plastic spoons that were merely used to stir coffee for a few seconds then thrown away forever. EndRant

The Girl Scout cup is sort of a running joke. My wife picked it up at a garage sale as part of a kit for our son. He didn’t want the branded cup, so I took it. Oh, and by the way I’m a Scoutmaster in the Boy Scouts, no scout ever wants to borrow my cup :D

Survival & Emergency

While out of doors in this wonderful world, you will run into situations. It may be as simple as a bandaid, or more life threatening involving emergency medical care and survial. In such cases there are a few items that can make all the difference.

Survival Items

  • Paracord rope
  • Batteries
  • Altoid Mini Container
    • Super glue
    • Cotton ball
    • Dental floss
    • Tweezers
    • Sewing needles
    • Mini compass (I was lost in the woods once, no fun)
    • Safety pin
  • Bandaids & Alligator clips
  • Petzl eLite headlamp
  • Real compass (yeah, being lost is no fun)
  • Lighters (forget the matches)
  • Ripstop bag to carry all these items
  • Leatherman Skeletool CX (not pictured, on my person)

The Rucksack

Lastly, you need a way to carry all those tools. I’ve used a Duluth Pack in that past and it works well, but doesn’t have the back support I’m looking for in a pack. My main stay is a Deuter Trans Alpine 30 AC (I have an older model than the one in the link). The Deuter backpack has a waist belt to take the weight off your shoulders. Plenty of pockets (but not too many). It has an integrated rain cover if I get caught out in the weather (can’t have that expensive Mac getting wet). It’s just the right size if I want to repurpose it for a long day hike with the scouts.

In Short

So that’s most of my kit. I didn’t mention the Kermit Kamping Chair that I use if I know I’m going to be sitting in the woods or park somewhere, or the smaller more personal items (such as flushable wet wipes for the those times, you know). Stay tuned for the next installment where we’ll discuss the ins and outs of finding good Wifi and other great things about working remote, working from anywhere.

Read More

2014-12-11
NG-Form To The Rescue

A project I’m currently work on (for a very popular apparel company) is employing AngularJS for their site. I’ve created some directives to handle collecting addresses for billing and shipping. Reusable directives with their own isolate scope. To add more awesome to the mix, I’m using ngMessage to show various error messages with the form.

This all works great, but the problem was showing the error messages correctly when there are two forms on the page.

For example, if I had a form that had two addresses in my form, it might look like this with my directives.

1
2
3
4
5
6
<form name="myForm">

<div my-address-form-directive="billing"></div>
<div my-address-form-directive="shipping"></div>

</form>

One of my directives might have template code that looks like this to show the error messages. This would show the errors when the input for city had errors.

1
2
3
4
5
<span class="text-danger" data-ng-messages="myForm.city.$error" data-ng-show="myForm.city.$dirty">
<span data-ng-message="required">: this field is required</span>
<span data-ng-message="maxlength">: Please enter only 200 characters</span>
</span>
<input name="city" ng-required="true" ng-maxlength="200" ng-model="city" />

But do you see how the myForm form name is sort of hard coded?

How to get the name of the form?

The individual directives do not know how to get the name of the form since it’s outside the code of the directive. Hard coding would be a bad idea. Even if you can get the name, then if you had two my-address-form-directive on the page, the errors would show on each of the forms (even though they only applied to one)

One way to get the form is to require it in the directive and then assign it to the scope of the directive like this

1
2
3
4
5
6
7
8
9
function myDirective() {
return {
restrict: 'AE',
require: '^form', // The ^ means look at the parent elements
link: function(scope, ele, attrs, form) {
scope.parentForm = form;
}
};
}

This would allow you to grab the parent form and then use that in your template like this (notice we changed myForm to parentForm to match what we’ve assigned to the scope).

1
<span class="text-danger" data-ng-messages="parentForm.city.$error" data-ng-show="parentForm.city.$dirty">

Double Trouble

Now you’ve solved the problem of knowing what name the form has, but what about having two directives under the same form like my top example? The error messages would show on both directives when one of them tripped the error. Not what we want.

Most problems you encounter in your everyday coding have already been solved. Find the solution and your job is that much easier

ngForm To The Rescue

The answer is depressingly simple. Just add a ng-form="formName" around your directive template. Like this.

1
2
3
4
5
6
7
<div ng-form="myForm">
<span class="text-danger" data-ng-messages="myForm.city.$error" data-ng-show="myForm.city.$dirty">
<span data-ng-message="required">: this field is required</span>
<span data-ng-message="maxlength">: Please enter only 200 characters</span>
</span>
<input name="city" ng-required="true" ng-maxlength="200" ng-model="city" />
</div>

You can actually get rid of the code that require: ^form from the directive and its matching scope.parentForm = form. No longer needed, ngForm kills two birds with one stone.

Happy Bird Hunting.

Read More

2014-11-12
Reformat with Tabs for Vim

While I’m not a big fan of TABS in my source code, a recent project I’m on has declared tabs are the way to go. So I needed to figure out two things.

  1. How do I tell Vim to use TABS on this project, but not on other project’s I’m on?
  2. How do I reformat some of my code to be tabs instead of spaces?

Using directory specific .vimrc file

This one was easy. Go into your global .vimrc file and enter this

1
set exrc " Per directory .vimrc file

Now in the root directory of your project, you will add a .vimrc file with these contents

1
2
3
4
5
6
set noexpandtab
set copyindent
set preserveindent
set softtabstop=0
set shiftwidth=4
set tabstop=4

NOTE: You may want to add .vimrc to your global .gitignore file so you don’t accidentally include it in your code :)

Reformatting code to use tabs instead of spaces

This one is already built right in. Just highlight a section of text in visual mode. Then type :retab! this should swap tabs for spaces. Try it out and tell me what you think.

Read More

2014-10-21
Divorce is a good thing, for Single Page Apps

Read More

2014-10-10
Why Vim

A coworker asked me the other day.

Why Vim, what do you like so much about it?

I would dare say everyone who encounters Vim has a similar story. Many years ago, while on a linux machine I first encounted Vim. It was a simple way to edit text on the server. It didn’t make sense, but it worked. That was the extent of engagement with Vim for about 10 years, just being able to do simple editing of text. More than a handleful of times I would get into some mode that I would not know how to get out of and have to force quit my session.

If you feel dumb, you’re in a good place, you’re learning.

Then a lot of developers that I admired would either show their screen during a presentation or screencast and they would be using Vim. Maybe it was Felix Geisendörfer, who said While vim may not help you to impress the ladies, it will please our BDFL and your grandpa will also approve. He’s not the only prolific developer that uses Vim, there are others and it made me think “Hey, maybe there is more to this Vim thing that first meets the eye”.

The article that by far helped me get starte with Vim was Learn Vim Progressively. The key is, get the basics down, then gradually learn more. Vim is not a, read the manual once and master it, but rather a 10 year plan. It’s old and odd at first, but the odd is there for good reasons.
G
Back to our question

Why Vim, what do yo like so much about it?

Here are a few of the features of Vim I use everyday, that make my life so much easier. Some of these you can find in other editors, but Vim really shines.

1. Replace inside quotes, parenthesis, brackets, you name it

Let’s say you have some code like such: var song = "I'm a little tea pot";, and you want to replace it with var song = "We will, we will, rock you". In Vim you simply place your cursor inside the quotes and press ci". This means Change (c), In (i), Quotes ("). This will clear out everything inside the " and you can begin typing what you want.

This works for any enclosing characters, (), [], ''; would be ci(, ci[, ci' respectively.

2. Navigation

Getting around in Vim is very quick. Use w or W to jump words. Use e or E to jump to the end of words. Use ft to jump to the next occurrence of t in the current line. Use $ to just to the end of the line (yeah, just like in RegExp). Try G to go to the bottom of the file, or Ctrl + o to go back to where you were (even in other files).

This isn’t monumental, but you can type /hello and it will find Hello and heLLo and hELL0, but if you type /Hello, it only find Hello, not hello. That’s because as soon as you type of capital, it turns into case sensitive.

4. Plugins, endless configurations

There are way too many plugins to cover them, but suffice to say here are a few that I use and depend on.

The dot .

Let’s say you type something like I just did https://github.com/. One you do that you can use the . to do that over and over anywhere. Move to different location, then press ., it inserts https://github.com/.

Read More

2014-10-10
Why you should be using a README

You’re one of the elite and have long since kept your code in git. You know how to branch, commit, and merge like a boss. Yeah, yeah, you comment your code (we known, your code is so solid it doesn’t really need comments).

But What About Process?

This is not as easy to describe. I’ve seen Google Docs, Confluence, and everything under the sun to document the details about an app. For years Github has suggested to create a README.md file when you create a new repo, why not try it sometime.

Advantages of using a README.md for documentation

  1. Changes with the code. Docs will always be uptodate
  2. It resides with the code, no hunting around
  3. You can use Markdown and Github will render it nicely on the web

What should be in your README.md

First, your README should give a general rundown of the app. Do you have any workflows to deploy the app that need to be followed a certain way? Think about it, you don’t remember much, why not write down what you need to do as a reminder to your future self what in the world you were doing.

Another good thing to put in the README is links to other types of documentation. I like to make Google Drawings, then linik to the PNG file in my READMEs, they get updated as you update the Google Drawing (ooops, kind of broke my own advantage about being source controller, crap).

Bonus

You can have a README in every folder of your app. Maybe talk about what the files in this folder do, why are they grouped together? Are they all models, controllers, config files, or what.

Resources

Read More

2014-10-10
Using Environment Variables in Node.js with Amazon OpsWorks

I find it hard to believe that I could not find a good article online of how to get env vars working in OpsWorks. I think even more astounding is that it takes a custom recipe to accomplish this end. When you host your app on Heroku, you can easily just do an heroku config:set FOO=bar with the Heroku Toolbelt. In AWS OpsWorks, it’s a little more involved. Let’s see just how.

The Key Elements

Add a Custom Chef Cookbook to your Stack Settings

Here you are going to have to go to your Stack Settings and Edit them. You will see a section to Use custom Chef cookbooks. In this section you are going to choose git as the repository type and https://github.com/vlamic/OpsWorksEnvy.git as the repository URL. NOTE: You are more than welcome to fork this repo and use your fork.

Config Management

Add your JSON

Now while we are in the Stack Settings, we’ll add our Custom JSON that will specify our environment variables. Replace the information below with your own. NOTE: There are two sections below, one for the server instance, and one specifically for each App

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
"environment_variables": {
"NODE_ENV": "production"
}
,

"deploy": {
"THE_SHORT_NAME_OF_YOUR_APP": {
"environment_variables": {
"NODE_ENV": "production",
"PORT": 80,
"mongoUri": "mongodb://xxxx",
"adminUsername": "admin",
"adminPassword": "password",
"s3Key": "XXX",
"s3Secret": "XXX",
"s3Bucket": "BUCKET",
}
}

}

}

Integration Custom Recipe into your Layer.

I think this was the hard part for me since I’m not real familiar with Ruby or Chef. Go to Layers, then Recipes, then Edit. Now you want to add environment_variables::default to the Deploy section. Then press the + to add it. When you are done, it will look like this.

Custom Recipe

Deploy your App

Now when you deploy your app, those variables will be in process.env. Use these like a boss and have pity on those that include passwords and such in their app source code.

One More Thing.

This is a plug for the best friend of your Environment Variables, the Node.js module nconf. It makes using these variables in your app a snap. I usually have it set up like this in my apps. That way you can easily provide env vars in a gitignore’d file in your app directory.

1
2
3
4
5
// Load config vars from commandline, ENV, file, and defaults
nconf.argv()
.env()
.file(YOUR_APP_ROOT_DIR/.env.json)
.set('VERSION', pkg.version);

Just to be sure, I have this in my .gitignore file to ignore anything that starts with .env...

1
.env*

Happy Camping.

Read More

2014-10-10
Deploy Web App with Grunt Compiled Assets to Heroku

The conundrum is how do you deploy a web app to Heroku that needs to be compiled without including compiled files in your source?

Maybe you have some SASS that needs to be compiled into CSS. Maybe you want to minify your JavaScript, or cache bust with some appended hash tags. In any case you want to run some tasks on your code to produce your distribution or build.

Here are some options.

Just include them in your your source code

This is the least desirable, but you could just include your dist or build folder in your source code. This gets to be messy as you will have compiled assets in your source code and if you have multiple people deploying you will get merge conflicts and what not. Only use this if you’re nuts.

Have Heroku compile them for you

You can do this by including all your devDependencies in your dependencies in your package.json file. Then have a Grunt task for compiling that is hooked to npm prepublish. Here is an example that will run grunt --env production on Heroku when Heroku runs npm install.

1
2
3
"scripts": {
"prepublish": "grunt --env production"
},

This works, but the drawbacks are having to include all those devDependencies in your code and then having Heroku download them and run. My Grunt tasks are kind of elaborate, so this becomes a pain for me. This can blow up in your face in the rare instance that npm is having issues :D.

Use a local distribution Git branch

This is a strategy I’ve started to use and works pretty good. It uses a local branch to add commit your compiled assets to Heroku, but doesn’t pollute your main branches (master and develop). Here is how it goes.

Setup

  1. Your dist or build folder is listed in .gitignore so that the files there are generally ignored by git.
  2. You create a branch that is used just to compile and push to heroku.

    1
    git checkout -b dist
  3. Run your Grunt task to create your distribution files

    1
    grunt buildprod
  4. In that branch you force git to include all the dist or build files that your Grunt task just made

    1
    2
    git add -f ./dist
    git commit -m 'Adding dist files'
  5. Now you can deploy to Heroku using the dist branch to push like this. This command tells git to push the local dist branch to the remote heroku branch of master. We use force.

    1
    git push heroku dist:master --force
  6. Now your files are on Heroku and have the compiled version

Updating Heroku

  1. Back on your develop branch you do a bunch of work, commit, etc.
  2. When you get ready to deploy again you will checkout your dist branch, then rebase against your develop branch

    1
    2
    git checkout dist
    git rebase develop
  3. Run your Grunt task

    1
    grunt buildprod
  4. Add newly created dist files

    1
    2
    git add -f ./dist
    git commit -m 'Adding dist files'
  5. Now you can deploy to Heroku using the dist branch to push like this. This command tells git to push the local dist branch to the remote heroku branch of master. We use force.

    1
    git push heroku dist:master --force
  6. Now your files are on Heroku and have the compiled version

Somethings to keep in mind, you can change these values to match your environment.

  1. My remote is called heroku
  2. My local branch for deploying to heroku is called dist
  3. My local folder that holds compiled assets is in ./dist
  4. I originally created the branch dist from develop, use master if that’s your gig.
Read More