Today I Learned

A Hashrocket project

25 posts by dillonhafer @dillonhafer

Rails/PG Statement Timeout 🐘⏰

By default, Rails does not set a timeout on database statements. For example, this will run for a full day, even if your ruby process goes away.

  select pg_sleep(86400);

The good news is that Rails provides a way to prevent this from happening from the database.yml with the statement_timeout variable.

default: &default
  adapter: postgresql
    statement_timeout: 5000

I'm starting to think that this should always be set low. And then explicitly set higher on a per-query basis, when one is expecting something to take a long time.

Update a specific gem with bundler

bundle update <gemname> does not update the gem specified.


bundle update --source <gemname> will update only the gem specified.

group by 1, 2, 3 🔢

Postgres allow group by and order by to reference column order in a sql statement. This is particularly useful when an aggregate result needs to be referenced in the group by or order by statement.

-- group by aggregate
  (created_at at time zone 'UTC' at time zone 'America/Chicago')::date,
from posts
group by (created_at at time zone 'UTC' at time zone 'America/Chicago')::date
order by (created_at at time zone 'UTC' at time zone 'America/Chicago')::date


-- group by 1, 2, 3
  (created_at at time zone 'UTC' at time zone 'America/Chicago')::date,
from posts
group by 1
order by 1

Open images in vim with iTerm 🖼

iTerm 3 has a built in shell script called imgcat for displaying images in the terminal. With one simple autocmd in my vim configuration I can open images*:

:autocmd BufEnter *.png,*.jpg,*gif exec "! ~/.iterm2/imgcat ".expand("%") | :bw

In my command I wipe the image buffer(:bw) because I don't want large images sitting around in buffers, but this is easy to change.


*imgcat does not work with tmux

where am i @?

When using the pry gem, @ is an alias for whereami

🐚 Private Shell History

Sometimes you don't want to put a dangerous command into your shell history, for example:

git reset --hard HEAD~

In zsh you can prevent a command from being saved in you history by setting the zsh option: setopt HIST_IGNORE_SPACE

then just prefix your command with a space:

 git reset --hard HEAD~

You have new mail.

Sometimes you forget to give that cron task somewhere to output its results... so it dumps them in your mail box... 📬😣 all 30,000 times it failed to run.

You don't have to delete all those emails one by one 😉

echo 'd *' | mail -N

d * means delete all mail. The -N means:

-N      Inhibit the initial display of message headers
        when reading mail or editing a mail folder.

Use PostgreSQL socket in database.yml 🐘🔌

When using the host: configuration option in the database.yml set to localhost or, I would need to add an entry to PostgreSQL's pg_hba.conf file to allow my ip address access. But, if you give the host: option the directory of your PostgreSQL sockets, rails will be able to use the socket, without needing to add an entry to the PostgreSQL configuration file.

  database: fancy_things
  host: '/var/run/postgres'

Drop connections with Nginx

You can ignore requests sent to nginx by responding with the status 444

server {
  listen 80;
  listen [::]:80;
  listen 443;
  listen [::]:443 ssl http2;

  location /no-response {
    return 444;

The primary use for this is to prevent processing requests with undefined server names:

# block for requests with undefined server names
server {
  listen 80;
  listen [::]:80;

  return 444;

Swap tmux panes

To swap panes in tmux use

prefix {


prefix }

Respect Do Not Track 👁‍🗨

Before I put google analytics, adwords, or other third party scripts on my sites I can respect the DNT headers a user has set. Here's how I can do it with Google Analytics:

  if (window.navigator.doNotTrack !== '1') {
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

    ga('create', 'UA-xxxxxxx-5', 'auto');
    ga('send', 'pageview');

In the above snippet I check if the user has enabled DNT. If they haven't set the header or they have turned it off the script will run. Checking for window.navigator.doNotTrack !== '1' ensures that the user purposely set the header.

Remove a shell function

Say you wrote a function that you don't want anymore:

# ~/.bashrc
function rake() {
  echo 'rake is gone ;)'
$ rake db:migrate
rake is gone ;)

You can remove it with the unset command:

$ unset -f rake

The -f flag passed to unset ensures that we only remove a function.

Chaining TLS Certificates 🐱

Apache allows you to declare an intermediate TLS certificate along with your regular certificate in your configuration, but many web servers only allow you to provide one certificate option. Like Nginx, go, or heroku.

In those cases, you will need to concatenate the entire certificate chain into one certificate file. This may sound daunting, but the process is very simple. Let me introduce cat -- concatenate and print files.

cat is normally used for printing files, but in this case we actually want to concatenate files. Below is a simple example on how we can do this:

cp example_com.crt example_com.chained.crt
cat AddTrustExternalCARoot.crt >> example_com.chained.crt
cat COMODORSAAddTrustCA.crt >> example_com.chained.crt
cat COMODORSADomainValidationSecureServerCA.crt >> example_com.chained.crt

To shorten it, we only need to use cat once:

cp example_com{,.chained}.crt &&
cat AddTrustExternalCARoot.crt COMODORSAAddTrustCA.crt COMODORSADomainValidationSecureServerCA.crt >> example_com.chained.crt

Verify TLS cert with private key

Hopefully you're never in a situation where you don't know what private key you used to generate your TLS certificate, but if you do... here's how you can check.

Note: this is better than uploading the certs to production to check on them 😉

Assuming we have generated a private key named and a certificate named we can use openssl to check that the MD5 hashes are the same:

openssl x509 -noout -modulus -in | openssl md5
openssl rsa -noout -modulus -in | openssl md5

To make things better, you can write a script:

CERT_MD5=$(openssl x509 -noout -modulus -in | openssl md5)
 KEY_MD5=$(openssl rsa  -noout -modulus -in | openssl md5)

if [ "$CERT_MD5" == "$KEY_MD5" ]; then
  echo "Private key matches certificate"
  echo "Private key does not match certificate"

Trust Issues 🤔

Our computers trust a scary amount of Root Certificate Authorites, and sometimes I have trust issues with some of them. Most recently being the StartCom bug, which allowed anyone to get a certificate for any domain they wanted.

I can't trust them. Period. And I don't have to.

Here is how you can revoke trust for any Root CA in OSX:

  1. Open Keychain Access.
    open /Applications/Utilities/Keychain\
  2. Click on System Roots from the left Keychains sidebar.
  3. Typestartcom in the search bar.
  4. Select all the root certificates and press ⌘i.
  5. Expand the Trust section
    and change the option
    When using this certificate
    Never Trust.

Put -L in your ssh config

If you've used ssh you've probably had to use local port forwarding before. If you use complex flags often, you will find remembering what you need is tiresome. Stop. Write it down so you can forget all about it. Save your memory.

Instead of doing this:

ssh -L 3000:localhost:3002

Add those flags to the ~/.ssh/config file instead:

# /home/dillon/.ssh/config

Host example
  User         not_dillon
  LocalForward 3000 localhost:3002

From now on, all you need to type is:

ssh example

Enable ScreenSharing from a terminal

At some point you may need VNC access to your remote mac, but you never enabled it. This will let you enable VNC (screen sharing) from a local or SSH connection.

sudo defaults write /var/db/launchd.db/ -dict Disabled -bool false
sudo launchctl load /System/Library/LaunchDaemons/

The Case of the Default 🕵

In Apple's Swift language switch statements must be what apple calls exhaustive. I've felt the term to be very literal. Literally exhaustive?

Example that does not work:

let count = 42

switch count {
case 1:
case 7:

The above statement does not work because it's missing a default case. Why? What if I don't want to do anything else? Why do I need to write something that won't be used? Don't worry, there is an amazing and less exhaustive way to handle these situations; simply default: ()

Correct example:

let count = 42

switch count {
case 1:
case 7:
default: ()

-y apt-get?

When installing packages on Ubuntu, you may find it really tiring to constantly confirm 'yes' all the time. I know I did. And when it comes to scripting your installs... that really becomes a nuisance. Today I learned that apt-get has a -y flag:

Automatic yes to prompts;
assume "yes" as answer to all prompts and run non-interactively.

Rails Sandbox 🏖

When you are working with a complicated database structure, and find yourself needing to debug a complex or dangerous (delete) action, you might be hesitant to experiment. Keep experimenting! Don't want to setup all that data again? No worries. You can use a sandbox $ rails c -s

Usage: rails console [environment] [options]
  -s, --sandbox      Rollback database modifications on exit.

The sandbox flag will keep all database changes in a database transaction when you start the rails console and automatically issue a rollback when you quit the console.

Keep mina fast

One thing I've loved about mina is the speed of deployments. One way mina achieves fast deploys is by avoiding unnecessary tasks.

I recently started using webpack with rails and soon found I needed that same performance boost. Because I was using mina/rails I had a nice little macro already available for me 😁

Example of #check_for_changes_script

desc "Install npm dependencies"
task :install do
  queue check_for_changes_script \
    check: 'package.json',
    at: ['package.json'],
    skip: %[echo "-----> Skipping npm installation"],
    changed: %[
      echo "-----> #{message}"
      #{echo_cmd %[NODE_ENV=#{ENV['to']} npm install]}
    default: %[
      echo "-----> Installing npm modules"
      #{echo_cmd %[NODE_ENV=#{ENV['to']} npm install]}

Encrypt a zip archive

When you're using the zip CLI on your machine or a remote server and you need some extra security you can use the -e flag to encrypt a zip archive. Be sure to use a super long random password for this.

zip -e ~/Documents/*.pdf


  Encrypt the contents of the zip archive using a password which is entered on
  the  terminal  in response to a prompt (this will not be echoed; if standard
  error is not a tty, zip will exit with an error).  The  password  prompt  is
  repeated to save the user from typing errors.

Use rsync with a custom port

You can rsync over a custom port for cases when you have custom ssh tunnels setup using rsync's -e flag. The -e flag tells rsync to use a specific shell, in this case it's still ssh, but with the addition of the -p flag.

Setup a custom tunnel

ssh -N -L 2222: user@remote-machine

Use rsync over the custom tunnel

rsync -avz -e 'ssh -p 2222' localhost:/files /myfiles

Line Kill

Sometimes you completely mess up a command on your terminal and need to start over again. UNIX has a control key for killing a line: control+u

$ ddtae
control + u
$ date
Mon Sep 26 12:23:39 EDT 1983 

Limit SSH by IP address

SSH has some nice security features like password-less authentication. For the sysadmin who wants even more fine-grained control, the ssh configuration has a setting for what users are allowed to authenticate based on their IP address.

# /etc/ssh/sshd_config
AllowUsers admin@ deployer@ git@*

This configuration says that admin & deployer are only allowed to login from, but git can login from any IP address. You can also use wildcards the other way:

AllowUsers *@

The most useful thing here is the ability to use * to match users and hosts.

h/t Chris Erin