To increase approachability for the Riak database, Basho wanted to provide a means to build various bits of client functionality in javascript. To enable this, they built a library called erlang_js that makes interacting with a SpiderMonkey interpreter pretty trivial. Let's look at how you could use it.

Project

Setup (not on the video)

mix new js_playground
cd js_playground
vim mix.exs
  defp deps do
    [
      {:erlang_js, github: "basho/erlang_js"}
    ]
  end
mix deps.get

Playing

Now we're just going to open up the tests and play around with this library. Open up test/js_playground_test.exs:

  test "getting data out of the JavaScript interpreter" do
    # First, we start this app and its dependencies
    :application.ensure_all_started(:erlang_js)
    # Next, we make a new instance of SpiderMonkey
    {:ok, js} = :js_driver.new
    # Next, we define a variable in it that is wrapping a function
    :ok = :js.define(js, "var addOne = function(n) { return n+1; };")
    # Finally, we call the function with an erlang data type, and we get back an
    # erlang data type out of it
    assert {:ok, 3} == :js.call(js, "addOne", [2])
  end

This is the core of the library - you really can just do anything javascripty that you want from here. A good follow-up is reading through HashNuke's coffeescript rotor. Let's have a look:

((( open up https://github.com/HashNuke/coffee_rotor/blob/master/lib/coffee_rotor.ex )))

Here we can see that he just loads in coffeescript, then maps a list of files through the javascript coffeescript compiler. I love the simplicity of this, and the fact that it really does feel like using complicated javascript libraries just isn't a hassle.

Summary

I just wanted to show this off. It's been on my list for at least 6 months but it never bubbled to the top. There's been a lot of talk about Elixir and JavaScript interoperability on the Mailing List in the past few weeks, so I figured it was time. See you soon!

Resources

Josh Adams

I've been building web-based software for businesses for over 18 years. In the last four years I realized that functional programming was in fact amazing, and have been pretty eager since then to help people build software better.

  1. Comments for erlang_js

You must login to comment

You May Also Like