DEV Community

Cover image for How I got Ruby snippets to run browser side in less than a day
Ben Taylor
Ben Taylor

Posted on

How I got Ruby snippets to run browser side in less than a day

Over the last year I've been working on Runno, an open source library and tool for embedding code snippets that run client side in the browser.

Screenshot of the Runno website with Ruby support

I had some time yesterday to work on Runno and decided to see if I could add another language. I'd heard on twitter that Ruby was looking into adding official WASM support, so I had a look into what that was. Turns out the proposal to merge WASI based WebAssembly support was perfect for me!

WASI stands for WebAssembly System Interface and it's a standard way for WebAssembly (wasm) binaries to talk to a system. This allows developers to use a single binding interface to interact with multiple different binaries. It's been primarily adopted for server-side execution, but for my use case of runnable code snippets it also works well.

I went and had a look at the PR for WASI support, assuming this would be a many month long process. When I looked it had already been merged! To get Ruby running on Runno I'd need to figure out how to compile it to WASM. I went to look at the building instructions, then I thought - I wonder if someone has already put it up on WAPM (the WebAssembly Package Manager)?

And it turns out that kateinoigakukun who wrote that PR had also packaged Ruby for WAPM. Super handy!

With all of that sorted I could try out the package to see if it worked. Because there's a standard interface I don't need to put it into Runno to try it out, I can just use it in my terminal. I wrote an example ruby file:

puts "G'day legend, how are ya?"
Enter fullscreen mode Exit fullscreen mode

Then I tried running it with the Ruby package on WAPM:

$ wapm install katei/ruby
$ wapm run --dir=. ruby example.rb 
G'day legend, how are ya?
Enter fullscreen mode Exit fullscreen mode

That looks like it works! Heck yeah!

Runno installs its packages using WAPM, it's based off a fork of WebAssembly.sh and so adding support for a new language already on WAPM is quite simple. If you're interested here's the PR. The important change is:

if (name === "ruby") {
    return { run: `cat ${entryPath} | ruby --disable=gems` };
}
Enter fullscreen mode Exit fullscreen mode

I'm using cat to pipe the code over STDIN due to a bug I was seeing when the file path was passed as args to Ruby. I've also disabled gems because of another error I was seeing. I'll look into these in the future, but for now it works.

The result is that you can now make quick embeddable Ruby snippets for your website! Try clicking the run button below.

Top comments (1)

Collapse
 
starswan profile image
Stephen Dicks

Wow wow wow! Well done! Amazing. Next stop, full-stack apps running ruby....