How do you precompile the native extensions for a ruby gem for linux?

Jacob picture Jacob · Sep 8, 2010 · Viewed 7.2k times · Source

We have a ruby application that depends on a gem with native extensions (in this specific case Nokogiri). However, for various reasons we cannot install the build prerequisites (such as build-essential, libxslt-dev, ruby-dev, etc) for that gem onto our production host.

Is there a (standard?) way to repackage the gem with the native extensions pre-built?

It should be possible (it seems to be fairly standard to do this for Windows), but I can't find any documentation on the subject.

Note that we only need to support a single platform, with known versions of all system libraries (Ubuntu 9.04 Server 64 bit, Ruby 1.8.7).

UPDATE: We're using Bundler, so we want to still have a gem to install at the end of the day, not a debian package.

Answer

Jacob picture Jacob · Oct 10, 2010

Finally found a way to do this for gems that use rake-compiler for building their C extensions (which is most of them).

You need to do the following on a machine that is identical to the one you want to deploy to, or it simply won't work:

Install the build prerequisites for building C extensions:

# apt-get install build-essentials ruby-dev # ... etc
# gem install rake-compiler

Unpack the gem you want to rebuild:

$ gem unpack nokogiri

Build your shiny new precompiled gem:

$ rake native gem

You can now install the native gem on a machine without any build tools installed:

$ gem install pkg/nokogiri-1.4.3.1-x86-linux.gem 
Successfully installed nokogiri-1.4.3.1-x86-linux
1 gem installed