Install Nokogiri on macOS Sierra

Today, I made the mistake of running gem pristine while helping someone debug an issue. Not only did this not resolve their issue, but now my ruby projects were now also unusable. By re-installing all of my gems it re-compiled Nokogiri which was now, for some reason, not compiling against the system libraries.

I'd used Nokogiri for weeks on macOS Sierra without an issue. In fact I'd even created new projects with fresh bundles just hours prior to this issue. It appears that Nokogiri (and all other native gems) has actually compiled against the previous version of OS X system libraries and that's what had been in use up until now.

By default, Nokogiri comes with it's own packaged version of libxml2 which appears incompatible with macOS. After googling I was able to figure out the two following commands to get everything back to normal. Change the version of Nokogiri to match the version you want. This docs recommend against this, which is ironic because their recommended version is broken and this one works. Hopefully this will be fixed in the future and this workaround will no longer be needed.

brew install libxml2 libxslt
gem install nokogiri -v '' -- --use-system-libraries --with-xml2-include=/usr/local/opt/libxml2/include/libxml2

It's also possible to do this at the Bundler level; Helpful if you have multiple different versions of Nokogiri across your projects.

bundle config build.nokogiri --use-system-libraries --with-xml2-include=/usr/local/opt/libxml2/include/libxml2
bundle install

I hope this saves someone some time. I know I'll almost certainly need to refer back to this if I do a fresh system install or run pristine again.