My first novel is available!

Read Singular

Malachite: Go inside Rails

A couple weeks ago I was fiddling around with using FFI to call code written in Go from a Ruby program.

Well, since I work for a fantastic company that provides a week every two months to work on whatever we want, I decided to create a Ruby Gem for Rails which makes it easy to use Go functions inside Rails.

Mainly because it’s tedious to keep spinning up microservices for every super fast Go thing we’d like to do.

Enter Malachite.


Install Go 1.5 or later on relevant machines. They added the really cool -buildmode=c-shared in that version, so it’s essential.

Add Malachite to your Gemfile:

gem 'malachite'

In your Rails app, make a subdirectory in “app” called “go”.

Write Some Go Functions

For instance, if you wanted to upcase strings, you’d put the following in app/go/upcase.go:

package main

import (

func HandleUpcase(things []string) (upperCased []string) {
	for _, thing := range things {
		upperCased = append(upperCased, strings.ToUpper(thing))

Then use your function from Rails:

=> ["FOO", "BAR"]

Everything in app/go will get compiled into one library, so to get it to work with Malachite, you need to follow some conventions:

  • name the methods you want exported like: HandleFoo
  • the Handle methods can only take one JSON-serializable argument, works best with arrays or structs
  • Go routines seem to leak memory in cgo, avoid for now while I figure it out

It’s certainly not production-ready or anything like that, but I thought you might enjoy fiddling around with it too.

Published under programming