develop with

Custom Ruby buildpack

Adding compilation steps to ruby build pack for heroku

Setup Heroku tools on your computer

Install the Heroku toolbelt: https://toolbelt.heroku.com/. Set up a Heroku account. Run heroku login to authenticate your computer.

Setup buildpack repo

Start by cloning the official Ruby buildpack. The reasons for making your own build pack is to add additional libraries and binaries over the default dyno environment.

For this example, we’ll add building native rake extensions during the compilation process, ie. rake extensions:build. Your ruby app may have non-gem C dependencies that must be compiled before boot by running rake extensions:build. So we will add that convention to Heroku deploys via the updates on the official Ruby buildpack.

We will update lib/language_pack/ruby.rb to adding a method call to the compile method:

def compile
    Dir.chdir(build_path)
    remove_vendor_bundle
    install_ruby
    install_jvm
    setup_language_pack_environment
    setup_profiled
    install_libgd
    allow_git do
      install_language_pack_gems
      build_bundler
      create_database_yml
      install_binaries
      build_native_extensions
      run_assets_precompile_rake_task
    end
    super
  end

Now time to define the method.

 def build_native_extensions
    topic "Running: rake extensions:build"
    time = Benchmark.realtime { pipe("env PATH=$PATH:bin bundle exec rake extensions:build 2>&1") }
    if $?.success?
      log 'extensions_build', :status => 'success'
      puts "Extensions built (#{"%.2f" % time}s)"
     else
      log 'extensions_build', :status => 'failure'
      error 'Error compiling native extensions'
    end
  end

Create a new Heroku app using your buildpack

For the rest of these instructions, we’ll assume your application name is my-app and your github username is johnny5. Adjust the commands for your particular app.

From the root of the your project:

heroku apps:create my-app \
  --remote my-app \
  --buildpack https://github.com/johnny5/heroku-buildpack-ruby.git

Now, everytime your application is deployed using heroku it will run your custom buildpack based on your git repo.

Making changes to the buildpack

Follow these steps when making any changes to your custom buildpack.

  1. Always rebase off official’s HEAD so our changes hang at the end of git history.
  2. When building libraries or binaries, use vulcan. Ryan Daigle has a great tutorial.
comments powered by Disqus

Want to see a topic covered? create a suggestion

Get more developer references and books in the developwith store.