macOS で pg gem を利用する

April 18, 2019

macOS で pg gem を bundle すると、「pg_config がない」と失敗します。 この解決策について記述します。

環境

  • macOS 10.14.3
  • Ruby 2.6.2
  • Bundler version 2.0.1
  • PostgreSQL.app 11

エラーメッセージ

Fetching pg 1.1.4
Installing pg 1.1.4 with native extensions
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    current directory: /Users/chick-p/.rbenv/versions/2.6.2/lib/ruby/gems/2.6.0/gems/pg-1.1.4/ext
/Users/chick-p/.rbenv/versions/2.6.2/bin/ruby -I /Users/chick-p/.rbenv/versions/2.6.2/lib/ruby/2.6.0 -r
./siteconf20190418-22299-193ha91.rb extconf.rb
checking for pg_config... no
No pg_config... trying anyway. If building fails, please try again with
 --with-pg-config=/path/to/pg_config
checking for libpq-fe.h... no
Can't find the 'libpq-fe.h header
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:

...()...

An error occurred while installing pg (1.1.4), and Bundler cannot continue.
Make sure that `gem install pg -v '1.1.4' --source 'https://rubygems.org/'` succeeds before bundling.

In Gemfile:
  pg

解決策

bundle のビルドオプションを指定します。 なお、PosgreSQL は、Postgresql.appを Application ディレクトリに入れて利用しています。

bundle config build.pg --with-pg-config=/Applications/Postgres.app/Contents/Versions/latest/bin/pg_config
bundle

参考 URL