pg gem with Postgres.app

There is no doubt Postgres.app is the easiest way to get started with the latest version of postgresql, however, using it with pg gem could result a bit frustrating at first so here I describe full steps to get it working in El Capital(OSX 10.11) and Postgres.app 9.4+.

Changes are you're looking at an output similar to this:

Building native extensions with: '--with-pg-config=...'
This could take a while...
ERROR:  Error installing pg:
    ERROR: Failed to build gem native extension.

This means that the gem was unable to locate a postgresql installation in your OSX system even when you have a functional Postgres.app working in your trail bar.

1. Xcode and the Compilation toolchain

If you're in a brand new OSX installation, you'd need to install Xcode first, you can download for free from the appstore.

With Xcode installed you'll now have a new command line program called xcode-select that you'd use to install the necessary compilation toolchain:

xcode-select --install

Let it run for a few minutes.

2. Locating pg_config

It's widely known that Postgresql keep changing the location of pg_config, so what we do is to make sure we know the path of this program by performing a search in your OSX system:

sudo find / -name "pg_config"

In my computer and for the current version of Postgresql shipped with Postgres.app that fetches:

/Applications/Postgres.app/Contents/Versions/9.4/bin/pg_config

We can finally use that path to compile our gem as follows:

sudo env ARCHFLAGS="-arch x86_64" gem install pg -- --with-pg-config=/Applications/Postgres.app/Contents/Versions/9.4/bin/pg_config

Once it installs, you can resume the usual setup of your app with bundle.