Today I Learned

hashrocket A Hashrocket project

57 posts by andrewvogel twitter @calllmehvogel

Remove Padding from Postgres Formatting Functions

Earlier today, I was trying to join a table on a formatted string row, but wasn’t getting the results I expected. Turns out that my formatting string had blank padding and I discovered “fill mode".

When using postgres formatting functions, like to_char, some of the formatting options include padding in the result. For example, the day format string will be blank padded to 9 chars.

select to_char(current_date, 'day');


You can use the “fill mode" (FM) option to remove any leading zeros or blank padding characters by prepending it to your format option:

select to_char(current_date, 'FMday')


Find Unused Cucumber Step Definitions

One of the challenges of using cucumber is properly managing your step definitions. Left unchecked, you will eventually have many unused steps. It’s extremely cumbersome to prune these manually. Luckily, you can use cucumber’s -f / --format flag to get feedback on unused step_definitions and their locations:

bundle exec cucumber --dry-run --format=stepdefs

If your step definition is unused, it will be annotated with a line under that says NOT MATCHED BY ANY STEPS. See the example -

/^I submit the proposal request form$/     # features/step_definitions/contact_steps.rb:39

Pattern Match Keyword List in Function Def

TIL that you can pattern match a keyword list in a function definition.

Sometimes you’ll receive the last argument as an empty keyword list; in this case, we’re calling it opts. You can pattern match key-values by defining the shape in a function.

  defmodule Example do
    def hello(opts \\ [])
   # will match when message is the only keyword included in opts
    def hello([message: message]) do
      IO.puts("Hello #{message}")

    # will match when there are multiple keywords but message is the first
    def hello([{:message, message} | _rest] = opts) do
      IO.puts("Hello #{message}")

> Example.hello(message: "World")
Hello World

# could also call in the more verbose way
> Example.hello([message: "World"])
Hello World

# :message but with other args after
> Example.hello(message: "World", something_else: "hi")
Hello World

Note: As a TIL reader pointed out, pattern matching Keywords will make your function args order dependent. The following would not work:

> Example.hello(foo: "bar", message: "World")
** (FunctionClauseError) no function clause matching in Example.hello/1 

If you need them to be order independent, use a map or just match on single argument, then check for each option appropriately with the Keyword module.

How to Change Password of SSH key

It’s possible to change the password of your current ssh key if you have the current password or it is not currently password protected. You can use the command:

ssh-keygen -p

From the man pages -

Requests changing the passphrase of a private key file instead of
creating a new private key.  The program will prompt for the file
containing the private key, for the old passphrase, and twice for
the new passphrase.

Lock Device Screen Orientation with JavaScript

The window object has a great API for working with screens(mobile devices, etc) and their related metadata - window.screen and window.screen.orientation.

For Mobile Devices and Full Screen browsers, you can use the following methods to toggle orientation locks:



Note that when you call the lock API on a web browser that is not full screen, it will raise a DOMException similar to following:

DOMException: screen.orientation.lock() is not available on this device.

Acceptable orientation values can be found in the docs linked below

Batch Active Record Operations with `find_each`

Iterating over a collection of ActiveRecord models can incur a performance hit to your application, especially when the result set is large.

A basic query like all or where could return tens of thousand of records. When that query returns, it will instantiate your records all at once, loading them into memory, and potentially leading to instability. Luckily if we need to operate on a large result set, we can use the find_each method to work in batches on our query.

find_each works by using the find_in_batches method under the hood, with a default batch size of 1000.

# This is bad ❌
Customer.where(active: true).each do |customer|
  # ....

# This is good ☑️
Customer.where(active: true).find_each do |customer|
  # ....

If you need to, you can also adjust the batch size by passing the batch_size kwarg to find_each

Customer.where(active: true).find_each(batch_size: 2000) do |customer|
  # ...


Override a form's action url with `formaction`

Recently, I found myself with a form that needed to be able to submit to multiple urls. You can definitely use some javascript to get around this but that seemed like overkill for my situation. That’s when I learned about the HTML formaction attribute.

You can use this attribute on a submit tag and it will override the action specified by the form. Here’s an example with a Ruby on Rails form, but you just as easily do something similar with plain HTML -

<% form_with url: false do |f| %>
  <% users.each do |user| %>
    <%= check_box_tag "user_ids[]",, false %>
  <% end %>

  <%= f.submit "Assign to Users", formaction: "/users/assign" %>
  <%= f.submit "Print for Users", formaction: "/users/print" %>
<% end %>

Understanding Query I/O in Postgres with BUFFERS

The EXPLAIN command in Postgres can help you understand the query plan for a given query. Furthermore, you can use EXPLAIN ANALYZE to see the estimated query plan and cost vs the actual time and rows.

To take it a step further, you can use EXPLAIN (ANALYZE, BUFFERS) to include a number that represents the I/O disk usage of certain parts of your query.

explain (analyze, buffers)
  from floor_plans
  order by created_at desc

                                                  QUERY PLAN
 Sort  (cost=2.56..2.60 rows=18 width=159) (actual time=0.062..0.065 rows=16 loops=1)
   Sort Key: created_at DESC
   Sort Method: quicksort  Memory: 28kB
   Buffers: shared hit=2
   ->  Seq Scan on floor_plans  (cost=0.00..2.18 rows=18 width=159) (actual time=0.018..0.032 rows=16 loops=1)
         Buffers: shared hit=2
 Planning Time: 0.111 ms
 Execution Time: 0.106 ms
(8 rows)

Make sure that if you run this with a query that writes, that you wrap it in a BEGIN...ROLLBACK statement.

Proxy Development Requests with Create-React-App

Create-React-App supports an optional proxy option in development, which can be added to your package.json. In my case, I was dealing with CORS issues locally because our frontend and backend run on the same server in production, but our development setup is different.

My backend was running on http://localhost:4000, and frontend on http://localhost:3000.

In my package.json, I specified that I wanted to proxy my requests to backend development server:

  "proxy": "http:localhost:4000"

Then I changed my fetch call to be a relative URL:

// Was fetch("http://localhost:4000/api/graph", ...params)

Create-react-app will recognize that this path is not a static asset and “will proxy the request (http://localhost:4000/api/graphql) as a fallback".

Create-React-App Docs - Proxying API Requests in Development

Resize Window Keyboard Shortcuts in Windows 10

After using Magnet, a window manager in OSX, I remembered hearing that there was a similar facility built into Windows. Turns out, they are very easy-to-remember shortcuts for resizing windows.

  • Win + Right Arrow - Snap to right half of screen**
  • Win + Left Arrow - Snap to left half of screen**
  • Win + Up Arrow - Maximize current window
  • Win + Down Arrow - Minimize window if not currently maximized

**(will maximize the window if it is currently split on the opposite side of the screen)

There’s a few others too, but these 4 I’m finding super useful. If you’re interested in other Windows shortcuts, I found some other cool ones in this Lifewire article

Be Careful with JavaScript Numbers

Today I Learned that you need to be careful when working with numbers in JavaScript. This is because of the way that JavaScript implements the Number type.

> The JavaScript Number type is a double-precision 64-bit binary format IEEE 754 value, like double in Java or C#. This means it can represent fractional values …

Take for example the following Ruby snippet:

> 2 / 5
=> 0

Our division here returns 0, which is what I expected. And if you want the remainder, you can get it with the modulus operator %

Now here’s the same snippet in JavaScript, which returns a double-precision number that is not zero

> 2 / 5

If you’re looking to do integer-like division in JavaScript, here’s a few ways you can accomplish that:

> Math.floor(2 / 5)

> Math.trunc(2 / 5)

> (2 / 5) >> 0



Here’s a callback to another JavaScript number TIL 😅

Get the Values for a Ecto Schema Enum Column

I recently started learning Elixir and had a model with an enum column with the following attributes:

 schema "keyboards" do
   field :nickname, :string
   field :form_factor, Ecto.Enum, values: [:macro, :num, :custom, :split, :forty, :sixty, :sixty_five, :seventy_five, :tkl, :full]


In my view, I had a form object where I wanted to have a select input with the values from my enum column, form_factor. Luckily, the Ecto.Enum module has a few functions that can help with this - mappings/2, values/2, and dump_values/2.

I ended up using the following in my form:

  <%= label f, :form_factor %>
  <%= select f, :form_factor, Ecto.Enum.mappings(Keyboard, :form_factor)  %>
  <%= error_tag f, :form_factor %>

Dynamically Render Client Side with Next.js

Next.js has a handy feature for rendering a child component client side, instead of on the server.

Consider the following example, where you have a component in src/components/Analytics.js with a default export.

import dynamic from "next/dynamic";

const DynamicAnalytics = dynamic(() => import("../components/Analytics"));

function Header(props) {
  return (
     import("../components/Analytics").then(mod => mod.Analytics)

function Header(props) {
  return (

Parse a Query String in Ruby

If you ever need to parse a query string in Ruby - or Rails, Rack has a convenient utility to do just that. parse_nested_query will parse from a string to a hash:


=>  {"sort_dir"=>"asc", "sort_by"=>"date_created", "filter_by"=>"lead"}

You can also go the opposite way with build_nested_query and generate a query string:

Rack::Utils.build_nested_query({"sort_dir"=>"asc", "sort_by"=>"date_created", "filter_by"=>"lead"})

=>  "sort_dir=asc&sort_by=date_created&filter_by=lead"

Conditionally Render Rails Links with `link_to_if`

ActionView::Helpers contains some really handy helpers for conditionally rendering links. For example, the link_to_if method will render the link if the given condition is met; otherwise it renders just the text.

<%= link_to_if(current_user.present?, "Admin Panel Tools", admin_tools_path) %>

When current_user.present? is true, yields the following HTML:

Admin Panel Tools

But when current_user.present? is false, yields the following:

Admin Panel Tools

Note, there are also methods for link_to_unless and link_to_unless_current

Easily Format Phone Numbers in Rails

Included as part of ActiveSupport, Rails has a handy helper for formatting phone numbers. Passing a number/string to the helper and some optional args and it will take care of the rest.

Here’s a few examples of how it works:

number_to_phone(8858846) # 885-8846
number_to_phone(8778858846) # 877-885-8846
number_to_phone(8778858846, area_code: true) # (877) 885-8846

To see all the options for the method, check out the Rails docs

What Is the Rails Notes Command?

While reading through the Rails 6 changelog, I noticed an entry for a rails command called notes. Having never seen this before, I took a quick look at the Rails Guides.

The command rails notes will return a list of all instances of the following annotations in your codebase - FIXME, OPTIMIZE, and TODO.

You can optionally search for your own custom annotations with the --annotations (-a) flag:

rails notes -a NOTE
  * [10] [NOTE] Only return the last 10 blog posts
  * [ 1] [NOTE] Set the following env variables

There’s also a way to register your own custom annotations for use with the default runner

config.annotations.register_tags("DEPRECATEME", "TESTME")

Rails Guides - Rails Notes

Disallow Large Jest Snapshots Using ESLint

eslint-plugin-jest has a handy rule to limit the size of snapshots - no-large-snapshots. This is especially useful for maintainability of snapshot tests. Snapshots of a large component are cumbersome to maintain as it requires the dev to have a deep knowledge of this components DOM and contained logic.

Github - eslint-plugin-jest/no-large-snapshots

Bonus Round: React Native has updated their documentation and added some great testing guidelines for mobile apps.

Show All Docker Containers (Running & Stopped)

docker ps was a confusing command for me, because I thought that it would show all containers by default. But trying to run a container that has been stopped will give you a an error that there is a container in use with that name. Running docker ps will be fruitless because that container will not be listed by default. You can easily view all your containers, running & stopped, with:

docker ps -a

H/T to the docs lol -

Import GraphQL Queries Where You Need Them (CRA)

If you want to export/import your GraphQL queries in your Create-React-App, you’ll need to add a library to make it work. You can use a library called grapql.macro to use .gql or .graphql files in your app.

If you’re also using jest, you’ll need to add jest-transform-graphql and update your jest configuration to pick up these file types.


Use `reset_column_information` to Migrate Data

If you’re generating a Rails migration, chances are you might need to facilitate migrating data to a new column. You can use reset_column_information in a migration file to pick up your changes and immediately do something with those new columns.

Assuming we have 2 models, DraftPost and Post -

  class AddColumnDraftToPosts < ActiveRecord::Migration[5.2]
    def change
      add_column :posts, :draft, :boolean, default: true
      DraftPost.all.each do |draft_post|
        Post.create(content: draftPost.content)

Define Your Refs with React ElementRef Flow Type

If you’re using flow in your React Native project, chances are that you are probably using refs. In this case, you’ll need to define your ref types.

Let’s say we have ref on a FlatList component from React Native:

import React from 'react'
import { FlatList } from 'react-native'
import data from './data.json'

class MyList extends React.Component {
  renderItem = () => {
    // rendering stuff
  render() {
       (this.l = l)}

Instead of being lazy and just using any, we’ll use the React.ElementRef flow type. It takes an additional typeof argument, which is the component type of your ref.

// @flow
import * as React from 'react'
import { FlatList } from 'react-native'
import data from './data.json'

class MyList extends React.Component<{}, {}> {
  l: ?React.ElementRef
  renderItem = () => {
    // rendering stuff
  render() {
       (this.l = l)}

Node Version - 10.14.1 Flow-Bin Version - 0.107.0

Flow docs - ref functions

Edited: 9/11/2019 - Fix fat arrow, Add typing to MyList, Update description to React Native, Resolve syntax error for ref typing

Fix Timeouts and Speed Up Jest on CI

If you have a large or complex test suite, running Jest on CI can make your build especially slow or cause timeouts. Luckily, Jest has an option cut out for this.

jest --runInBand

runInBand runs all tests serially inside the current process instead of creating a bunch workers. Using this option, we were able to trim suite time above 20mins down to less than 4 mins. 🏎️😎

Change Name of :id Param in Rails Resource Routing

You can change the name of the parameter used by rails resource routing by specifying the param option to the resource route.

For example, if we have a show endpoint:

resources :pages, only: :show

Running rake routes will return the pages#show url as:


We can change the id param to slug by doing:

resources :pages, only: :show, param: :slug

Then running rake routes will yield our new pages#show route as:


Generate Absolute File Path In Ruby

Pass a string to File.expand_path to generate the path to that file or directory. Relative paths will reference your current working directory, and paths prepended with ~ will use the owner’s home directory.

=> "/Users/avogel/My/Working/Directory/example.rb"

=> "/Users/avogel/example.rb"