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.
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:
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
Then use your function from Rails:
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:
- 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.