Gem developers: Let the user choose the JavaScript enginePublished on Oct 10, 2012

As gem developers, we sometimes need to make a decision about what JavaScript engine to use together with our code or assets. This decision usually means adding a dependency on other gem that provides such an engine.

There are choices depending on your platform, such as therubyracer or therubyrhino to name a few. What gem and JS engine to use? Well, neither one of them. The reason behind this is fairly simple - you should stay as open as possible and try not to lock your users to a particular engine and the mostly native code behind it.

What’s the way out of this? There’s a great gem created by Sam Stephenson and other contributors called ExecJS. By depending on ExecJS you state that your gem needs a JS engine but you leave the rest onto the end users. ExecJS can automatically detect available JS engines and choose the most appropriate one. As of writing this text, there are 5 supported engines:

  • therubyracer - Google V8 embedded within Ruby
  • therubyrhino - Mozilla Rhino embedded within JRuby
  • Node.js
  • Apple JavaScriptCore - Included with Mac OS X
  • Microsoft Windows Script Host (JScript)

The end users decide what JS engine they want to or even can use on their target platforms. Often we have been burned by the therubyracer gem not being able to successfully compile on some BSD systems. By depending on ExecJS you allow users to easily solve this problem by for example installing a standalone Node.js.

Long story short, please think of your users and always use ExecJS instead of hard coded dependency.

Written by Jiri Pospisil of sensible.io.

Do you manage email campaigns for your business?

We're building a tool to help businesses reach out to their customers more easily. It's called SendingBee and it's going to be awesome.