Skip to content
This repository has been archived by the owner on Feb 28, 2024. It is now read-only.
/ malachite Public archive

Call Go functions from Rails

Notifications You must be signed in to change notification settings

zhubert/malachite

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Malachite

Call Go functions directly from Rails.

Requirements

Requires Ruby >= 2.0.0, Go 1.5+.

Installation

Install Go. You must have a proper GOPATH.

Add this to your Gemfile:

gem 'malachite'

Write Some Go Functions

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

  • name the methods you want exported like: HandleFoo
  • the Handle methods can only take one JSON-serializable argument, works best with arrays or structs

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

package main

import (
	"strings"
)

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

Then use your function from Rails:

Malachite.upcase(["foo","bar"])
=> ["FOO", "BAR"]

More examples can be found in examples.

Note: This would actually be slower than doing it in Ruby, due to the JSON serialization.

Testing

Check out the wiki on Testing

How Does it Work?

Code generation.

  • On every load in development and one time on boot elsewhere, Malachite will build a shared library from all the Go code in your app/go folder
  • It then uses Ruby's Fiddle to call the shared library
  • Arguments are passed back and forth via JSON

Because of the JSON step, you'll only see real performance gains on computationally difficult tasks. Ruby's JSON conversion is a large tax.

Ruby 2.2.4+

It's strongly recommended to use the newest release of Ruby as there was a security issue with older versions of Fiddle.

About

Call Go functions from Rails

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published