Format Your Elixir Code Now

Elixir 1.6 will be shipping with an important new feature: autoformatting. Let's explore it today.

Autoformatting is a common practice in languages communities like Go.
Now, this practice is coming to Elixir as part of the language. Borrowing the
arguments
in favor of autoformatting
from the Go community, autoformatted code ought to be:

  • Easier to write: never worry about minor formatting concerns while hacking away.
  • Easier to read: when all code looks the same you need not mentally convert others' formatting style into something you can understand.
  • Easier to maintain: mechanical changes to the source don't cause unrelated changes to the file's formatting; diffs show only the real changes.
  • Uncontroversial: never have a debate about spacing or brace position ever again!

Whether you agree with all these points or not, the Elixir language (which is
largely written in Elixir) just underwent a massive community-powered
refactor
to conform with its

Continue reading “Format Your Elixir Code Now”

Generate Dates in PostgreSQL

PostgreSQL has shipped with the generate_series() function for quite some
time. This function is often used to generate series of numeric data. For
instance, in my post, Understanding Common Table Expressions with
FizzBuzz
,
I used it to generate a series of integers from 1 to 100.

As of PostgreSQL 8.4, support for generating series of timestamp data was
added. I don't see this used often, so let's take a look at it.

We could take a peak at the online documentation to see the function
signature, or we could pull it up in psql using \df.

> \df generate_series()
                                                               List of functions
   Schema   |      Name       |         Result data type          |                        Argument data types                         |  Type
------------+-----------------+-----------------------------------+--------------------------------------------------------------------+--------
 pg_catalog | generate_series | SETOF bigint                      | bigint, bigint                                                     | normal
 pg_catalog | generate_series | SETOF bigint                      | bigint, bigint, bigint                                             | normal
 pg_catalog | generate_series | 
Continue reading "Generate Dates in PostgreSQL"

Why Vim?

Hashrocket is known as a Vim shop; what does that mean?

When visitors learn Hashrocket is a "100% Vim shop", questions follow:

  1. Does everyone use Vim?
  2. Is Vim mandatory at Hashrocket?
  3. Why Vim?

These are fair, and I admit that from the outside, our company's
preference for Vim might seem unusual.

When we evangelize Vim to the development
world, via the Vim Chicago Meetup and
others, the questions become more acute. In a recent
talk
I tried to sell Vim to
React.js developers. I feel obligated to have compelling, succinct
answers on hand.

I'll tackle this subject in three parts: why Hashrocket uses Vim, what
Vim is, and why we think every developer should try Vim. Few subjects
are as contentious in the development world as text editors. Whatever you use,
learn and make it your own. I hope to simply add Vim to the list of things
people

Continue reading “Why Vim?”

Swap Two Column Values in SQL: Part 2

In the first part of this post we looked at a technique for swapping two
column values for existing records in a single statement. It is a relatively
sound solution that takes advantage of subqueries and a case statement.
Unfortunately, it has a couple drawbacks which we will address in this post.

This post builds off of Part 1. If you haven't already, give it a
read.

The first drawback can be demonstrated by building on our existing example,
the pages table which has the following data.

select * from pages order by ordering;
 id |  name  | ordering
----+--------+----------
  3 | Green  |        1
  1 | Red    |        2
  4 | Yellow |        3
  2 | Blue   |        4

In the interest of maintaining data integrity, it is reasonable to expect
that a table like this would have a uniqueness constraint on ordering.
Let's add that to ensure

Continue reading “Swap Two Column Values in SQL: Part 2”

Hashrocket and Code Platoon

Hashrocket's collaboration with Code Platoon continues this October!

For the past three cohorts, Hashrocket has taught an intensive all-day workshop at the Code Platoon bootcamp. Here's a
description of this unique developer training program, from their website:

Code Platoon is a Chicago-based non-profit program exclusively for veterans.
We’ll teach you full-stack development over the course of 20-weeks (6 weeks
remotely, 14 weeks in our Chicago classroom), and train you to be eligible
for paid internships and full-time employment as a web developer. No previous
programming experience is necessary.

In this post, I'd like to talk about this important program, and what we offer to it.

About Code Platoon

The world needs more
programmers; there's a mountain of work to be done. Code bootcamps rise
to this challenge by recognizing that a college degree isn't enough, or perhaps
even required, to do what we do, and that the fundamentals can be

Continue reading “Hashrocket and Code Platoon”

Swap Two Column Values in SQL: Part 1

I recently needed to write a PostgreSQL snippet that would massage some
data. More specifically, I needed to swap the ordering of two different
records in the pages table. These records are made up of an id, a
name, and an ordering.

Here is a snapshot of the data in pages.

select * from pages order by ordering;
 id |  name  | ordering
----+--------+----------
  3 | Green  |        1
  1 | Red    |        2
  4 | Yellow |        3
  2 | Blue   |        4

We've been informed that we need to swap the ordering of Red and Blue.
We can see here in this snapshot of the data that Red has an ordering of
2 and Blue has an ordering of 4.

Doing a swap based on the data that we have locally would be most easily
accomplished with a couple update statements.

update pages set ordering 
Continue reading "Swap Two Column Values in SQL: Part 1"

Observing Change: A Gold Master Test in Practice

How do we test a system that seems untestable?

Untested legacy code is the bane of many a developer's existence. In a
permissive language like Ruby, continued development in an untested legacy
codebase requires adding tests. Users expect certain behavior to survive each release intact.

For some systems, the traditional pyramid of test types (unit, API, and
integration) is insufficient. Unit and API tests must presumably cover hundreds
or thousands of functions; which matter? Integration tests could cover a wide
range of user interactions; which are likely? Familiarity with the project is a luxury we don't all enjoy.

I recently worked on an application that took a complex input (a
production database), ran it through a large SQL function, outputting a
giant CSV file representing thousands of permutations of data. Each stage of
the transformation was complex enough that visual inspection would fail to
determine if something was amiss.

None

Continue reading “Observing Change: A Gold Master Test in Practice”

Advanced Queries with ActiveRecord’s From Method

For those of us that write database-backed Rails apps,
ActiveRecord is a
familiar beast. We know its various query building methods well: where,
order, limit, and even group. The most important SQL clause is
conspicuously missing from our repertoire: the from clause.

Chances are you can't think of many, if any, times that you've used
ActiveRecord's from method. This is to be expected. The from clause in
SQL specifies the target table of a query. In the context of ActiveRecord, the
target table is explicitly expressed by the model from which you query.

Consider the times you use one-liners such as Developer.first,
Developer.all, and Developer.count. With each of these, the developers
table as the target of the query is expressed by the use of the Developer
model.

So, where does the from method come into the picture?

The
docs
describe the

Continue reading "Advanced Queries with ActiveRecord’s From Method"

Today I Learned in Phoenix

The Phoenix port of Today I Learned, Tilex, is live.

Today I Learned began as a Ruby on Rails application.
We open-sourced the code after launch and have maintained it for over two
years. Our mission:

Today I Learned is an open-source project by Hashrocket that exists to
catalogue the sharing & accumulation of knowledge as it happens day-to-day.
Posts have a 200-word limit, and posting is open to any Rocketeer as well as
selected friends of Hashrocket. We hope you enjoy learning along with us.

Today, we are moving forward with an Elixir/Phoenix port of the project.
Here's a little more about the project, focusing on the work, technology, some
observations, the people behind it, and the future.

Work

This project began over two years ago as my
Hashrocket apprentice project. Here's the launch
announcement
from that time.

We open-sourced the Ruby on Rails
application in February 2016.

Continue reading “Today I Learned in Phoenix”

Go 0 to 60 with create-react-app

I remember the first time I tried out React.js. It was several years back. The promise of painlessly building interactive UIs was too enticing to ignore. As I worked through the first couple introductory tutorials, my computer screen began to shimmer in a way that it had never done before. The pure functions and composable components brought the browser to life.

Just as my excitement for React was mounting, I was stopped in my tracks. Before I could go much further I was faced with tons of tangential decisions about how the project would be configured.

Can't someone just make these decisions for me?

This is the impetus for create-react-app.

Create React apps with no build configuration.

This tagline is another way of saying, "Create React apps! We made all the build configuration decisions for you."

So, what kinds of things do we get for free with create-react-app?

Get Started with redux-form

The redux-form library bills itself as the best way to manage your form state in Redux. It provides a higher-order form component and a collection of container components for dealing with forms in a React and Redux powered application. Most importantly, it makes it easy to get a form up and running with state management and validations baked in.

redux-form sign in

To get a feel for what redux-form can do for us, let's build a simple Sign In form. You can follow along below or check out the resulting source code directly.

Start with React

We are going to start by getting the React portion of this application setup. The easiest way to spin up a React app is with create-react-app. Install it with npm or yarn if you don't already have it globally available.

$ yarn global add create-react-app

Let's generate our project.

$ create-react-app redux-form-sign-in

The create-react-app binary that is

Continue reading “Get Started with redux-form”

Writing Prettier JavaScript in Vim

JavaScript is an incredibly powerful and fickle language. In the face of
quickly evolving frameworks and tooling, it can be cognitively challenging
to grapple even with a familiar codebase. Even just having one less thing to
think about goes a long way in helping us deal with the rest. Figuring out
how to format each line of code is accidental complexity and one less thing
we ought to think about.

As Brian Dunn put it, "Once you stop formatting your code, life becomes
beautiful." And so does your code, but without any of the effort.

This is where Prettier comes in.

Using Prettier in Vim

At Hashrocket, Vim is an essential part of our development tooling.
neoformat makes it easy to
incorporate prettier into our existing workflow. As you can see in the
above gif, Prettier formats the file on save.

Here is how we set it up.

Step 1

Install prettier if

Continue reading “Writing Prettier JavaScript in Vim”

Do The Shuffle

How should we break up teams for this game? In what order should we do
presentations? Which lunch spot should we go to this week? The need for some
randomization arises often. With irb at our fingertips, we often reach for
Ruby's shuffle.

But have you ever wondered how shuffle works?

I can imagine writing a loop that randomly shuffles around the contents of
an array, but what would I need to do in order to sufficiently and
efficiently shuffle an array? What I need is an algorithm.

An Algorithm

When I do a google search for "algorithm to shuffle a
list"
, the first result
is a Wikipedia article on the Fisher-Yates shuffle.

The Fisher–Yates shuffle is an algorithm for generating a random
permutation of a finite sequence—in plain terms, the algorithm shuffles
the sequence. The algorithm effectively puts all the elements into a hat;
it continually determines the

Continue reading “Do The Shuffle”

A Typical Day at Hashrocket

What is a typical day like for you at Hashrocket?

This is a question people ask. If you've never worked with a
consultancy, what happens on the inside can be mysterious. We're
consultants… does that mean we write code? We're developers…
does that mean we only take projects in languages and frameworks we know very
well? And perhaps most importantly: do we have a ping-pong table?

Today I aim to answer some of these questions the best way I can, by describing my
typical day as a developer at Hashrocket in Chicago. I hope this gives insight into consulting,
and how one person can find their place in the industry.

My typical day flows through team standup, client standups, development,
lunch, development again, and individual contributions, not always in that
order.

Team & Client Standups

At Hashrocket, a vital part of our process is standing up together every day,
something

Continue reading “A Typical Day at Hashrocket”

The Hashrocket Apprenticeship

The Hashrocket apprenticeship is currently open. We hire one apprentice at a
time and typically only one per year. We receive many applications for this
position every week, but few are qualified, because few have the professional
experience in Ruby on Rails we require. You may read this and think "Yes this
is for me", if so, please apply.

Our Apprenticeship Program is not a First Job

It's not really an apprenticeship. "Apprentice" is the easiest term to
describe what we have, which is an opportunity to learn web development and
consulting in a great, supportive environment. What distinguishes this position
from other apprenticeships is that we are specifically looking for developers
who already have some professional development experience.

At Hashrocket we sell senior web development expertise to our clients. The
goal of our apprenticeship is to hire someone who already has some
experience with Ruby and Rails and in

Continue reading “The Hashrocket Apprenticeship”

The Hashrocket Chicago Apprenticeship

The Hashrocket apprenticeship is currently open in Chicago. We hire one apprentice at a
time and typically only one per year. We receive many applications for this
position every week, but few are qualified, because few have the professional
experience in Ruby on Rails we require. You may read this and think "Yes this
is for me", if so, please apply.

Our Apprenticeship Program is not a First Job

It's not really an apprenticeship. "Apprentice" is the easiest term to
describe what we have, which is an opportunity to learn web development and
consulting in a great, supportive environment. What distinguishes this position
from other apprenticeships is that we are specifically looking for developers
who already have some professional development experience.

At Hashrocket we sell senior web development expertise to our clients. The
goal of our apprenticeship is to hire someone who already has some
experience with Ruby and Rails

Continue reading “The Hashrocket Chicago Apprenticeship”

Exploring Hashrocket’s Vimbundle: Vim Hashrocket

Hashrocket committed to Vim early in our history, and it's been a crucial decision. When we set up a new development machine, we
install the Dotmatrix, a library of
configurations that includes our favorite, must-have Vim plugins. This blog
post is part of a series exploring some of those plugins, focusing on Vim Hashrocket.

Vim Hashrocket

Vim Hashrocket is a collection
of settings our team shares. Spend enough time
writing code with Vim on a shared machine, and you'll find that the Vim configuration
file in the root directory (.vimrc) swells to hundreds of lines,
as each developer adds their own favorite settings. Vim Hashrocket codifies that into a plugin. It's a neatly organized
junk drawer that reflects many of our evolving goals as a development team.

Here are a few noteworthy settings in the 227-LOC hashrocket.vim plugin.

NotRocket

:NotRocket (line 36) is one of those

Continue reading “Exploring Hashrocket’s Vimbundle: Vim Hashrocket”

A Module By Any Other Name: Aliases in Elixir

Modules provide a way for us to organize our code and compose complex
systems.

"A module is a collection of functions, something like a namespace. Every
Elixir function must be defined inside a module. To call a function of a
module, you use the syntax ModuleName.function_name(args)."

— Elixir in Action, pg. 22, Saša Jurić

Any module, whether part of the standard library or defined by us,
is available if it has been loaded into memory or is on the BEAM's code
path. It is easy to see this in practice within an IEx session. For
instance, the String and Enum modules are readily accessible.

> "1 2 3"
  |> String.split()
  |> Enum.map(fn(x) -> String.to_integer(x) * 10 end)
[10, 20, 30]

Enum and String are aliases. They are a convenient syntax

Continue reading “A Module By Any Other Name: Aliases in Elixir”

Embrace the Database with Ecto

The database is a hugely important, and often times underappreciated, part
of the development stack we use to build most web applications.

Web frameworks, such as Ruby on Rails, and their database adapter layers can
sometimes lull us into a false understanding of the world. They leave us so
far removed from the actual database that we sometimes forget it is even
there. It becomes a mysterious black box that we can shovel data into and
then ask very rigid standard questions to get that data back out. When we
treat the database in this way — as a dumb data store — we miss out on all
it has to offer. However, if we seek to understand the database and how to
fully utilize it, we can harness guarantees about the correctness of our
data, build a solid data model, and write expressive, powerful, and highly
performant queries.

The

Continue reading “Embrace the Database with Ecto”

Running Out Of IDs

People have fingerprints. Products have bar codes. Cars have vehicle
identification numbers (VINs). Internet connected devices have IP
addresses. Anything that needs to be uniquely identifiable tends to have a
mechanism for uniquely identifying it. It makes sense. This is particularly
important for the data that we store as part of the applications we build.
Every user, every product, every financial transaction should all have
some kind of identifier that we can use to uniquely identify it.

The limits of these identifiers is the subject of this post.

Though we can utilize fancier schemes like UUIDs and composite keys, the
most common approach to uniquely identifying records is an id — an
integer that we guarantee is unique. But where do these unique integer ids
come from?

A Sequence

In PostgreSQL, we generally create an id column as a primary key using
serial.

create table products (
  id serial 
Continue reading "Running Out Of IDs"