Exploring the Default Postgres Template Databases

I was recently poking around the psql terminal, and noticed something that I had never had to deal with before: the Postgres template databases. I decided to seize the moment and launched myself into an exploration of what the template databases are meant to do, and why the heck there are two of them.

My first plan of attack was to just list them and see if I could find a difference right away, but everything looked exactly the same.

postgres=# \l
                                   List of databases
   Name   |   Owner  | Encoding |   Collate   |    Ctype    |   Access privileges
postgres  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
template0 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres + postgres=CTc/postgres
template1 | postgres | UTF8     | en_US.UTF
Continue reading "Exploring the Default Postgres Template Databases"

Where Am I: URL Assertions with Cypress

The URL that appears in the browser's URL bar is one of the first and
primary ways that users interact with our web apps. The URL tells the app
and the user of their location within the route hierarchy of the app. It
sometimes even contains state. The URL consequently serves as an excellent
first assertion when writing integration tests.

When writing Cypress integration tests, there are
several ways for us to assert about the current URL.

The cy.url() and
functions are the primary ways for us to gain access to information about
the current state of the URL. From there, we can perform a variety of

We can assert about the entire URL:

// URL: http://localhost:8000/pokemon
cy.url().should('eq', 'http://localhost:8000/pokemon');
// ✅ passes

This is certain the most precise assertion. The tradeoff is that it requires
us to know something

Continue reading “Where Am I: URL Assertions with Cypress”

Wrap Parameters Without Changing Markup

While updating logic that caused a POST with a JSON body to change into a POST as multipart/form-data, I ran into an issue where the Rails controller was expected params in a nested way. Sure, I could change my inputs to have a different name that would cause the nested structure, but that was changing logic down the line.

Rails was wrapping the incoming parameters automatically since the prior request was of 'Content-Type': 'application/json'. Well, I'd really like this same behavior on my new request as it would solve my current conundrum.

Turns out ActionController has a method that can help out with that… the aptly named wrap_parameters method.

In my case, the name I needed was the same as the controller so I could use this:

class FooController < ApplicationController
  wrap_parameters format: %i[mutlipart_form json]

This produces a params payload like so:

ActionController::Parameters {
Continue reading "Wrap Parameters Without Changing Markup"

Query for NULL ‘or’ empty string in ActiveRecord

Sometimes you come across a query that looks for an attribute that is NULL 'OR' an empty string. Sure there are options we could employ that may remove the necessity of checking for both but let's see how we can improve our code a bit first!

The majority of the time I see this as a SQL fragment in ActiveRecord:

Foo.where("name is null or name = ''")

Which produces the following SQL:

SELECT * FROM "foos" WHERE (name is null or name = '')

Sure you can say now that ActiveRecord has or it could be done like so:

Foo.where(name: nil).or(name: '')

However, I'm currently in a project that doesn't support or yet so I went playing to see what I could come up with that wouldn't be a SQL fragment. My first thought was to

Continue reading “Query for NULL ‘or’ empty string in ActiveRecord”

Journey to ElixirDaze 2018

Last October I discovered an interesting Github issue, Elixir-Lang #6643. It was opened José Valim, the creator of Elixir.

Here's part of the introduction to this issue:

Elixir master now includes a code formatter that automatically formats your code according to a consistent style.

We want to convert Elixir's codebase to use the formatter on all files. We understand this means a lot of code churn now but, on the positive side, it means we can automatically enforce and/or format future contributions, making it easier for everyone to contribute to Elixir.1

This issue set off a massive refactoring project to get Elixir conforming with its new formatter. Today, new pull requests to Elixir must pass through the formatter without requiring changes. I think this will have a ripple effect on every Elixir project in production.

While closing this issue, José provided the following statistics on the refactor:

When To Use Redux

Have you had a conversation about Redux recently that has left you wondering — despite all of its praise and the assured recommendations — if you made a big mistake when you typed the words, yarn add redux?

Jani is being a bit facetious here. But if you’ve been following along on twitter, there has been a lot of discussion about redux. The crux of the conversation is aimed at whether most apps even call for the use of redux and consequently if we, as developers, are using it when we don’t need it.

Creating A Paper Wallet for Your CryptoCurrency with MyEtherWallet

When investing in cryptocurrency, security is a huge concern. In 2014, a famous online bitcoin exchange, Mt.Gox, was the target of a hack that saw 850,000 bitcoins stolen. For many investors, this was a wake-up call. Keeping your money in an online exchange is not a smart move. The best way to protect your investment is to be proactive. There are already many strategies for storing cryptocurrency, and one of the most secure ways is cold storage. Cold storage involves generating and storing your coins private keys offline. While it might not be ideal for you to keep all of your cryptocurrency stored offline, this option ultimately provides the best security.

Like many others, I too had kept my investments on online exchanges (mainly for convenience). After a few months of investing and seeing some positive gains, I decided it was finally time to move my assets off of

MEW - Create Wallet Password
MEW - Save KeyStore File
MEW - Print Paper Wallet
MEW - Wallet Log In

Continue reading “Creating A Paper Wallet for Your CryptoCurrency with MyEtherWallet”

Fun with Views and CTEs

A view is a stored query the results of which can be treated like a table. Note that it is the query that is saved and not the results of the query. Each time you use a view, its associated query is executed.

A related concept is that of the common table expression or CTE. A CTE can be thought of as a short-lived view; you can only use it within the query in which it appears (you can refer to it multiple times, however).

Let's say that you're the SQL-savvy owner of a store that sells kits for building robots. On your site, customers are guided through the process of selecting all of the components needed to build a quadrupedal robot, i.e. getting the right motors, microcontrollers, sensors, batteries, grippers, etc.

Robots have lots of component parts and you have to make sure that the correct components for

alt text
alt text
alt text
tree graph

Continue reading “Fun with Views and CTEs”

Binary Searching and Ruby’s bsearch Method

Binary search might be the most well-known search algorithm out there. If you went to school for computer science, you've probably heard the fundamentals of binary search hundreds of times. Chances are, you've been asked about binary search while interviewing for a development job – and for good reason. Binary search is a powerful algorithm. Compared to a linear search it performs very well, and the performance benefit is especially noticeable as the data set grows. A few weeks ago, I got the chance to use it in a live application, but it's been a while since I've worked with this algorithm, so I had to brush up on the implementation.

The Problem

My pair and I were working on a class in one of our client's applications. This class used a lot of finds and other linear search-esque code to check for items in sorted collections. Being the

Continue reading “Binary Searching and Ruby’s bsearch Method”

Document Your Confusion

Like a diary, but for code

On a few occasions, I've started work on a brownfield project and found that, either due to poor programming practices or because there was no elegant way to implement a feature, it's been necessary to create documentation beyond what is normally included in a README. This documentation often took the form of glossaries, diagrams, or additional exposition on the codebase.

Your typical README contains all or some of the following: a short introductory paragraph, a list of dependencies, instructions on how to install the app, configuration, how to run the test suite, database creation and migration, services, and how to deploy the app. If it's an open source project, there will likely be sections devoted to listing authors, rules around contributing, the license under which it can be used, as well as additional documentation around how to use the package.

There are contexts in

Continue reading “Document Your Confusion”

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
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
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
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
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

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

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.


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

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

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.


This project began over two years ago as my
Hashrocket apprentice project. Here's the launch
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?