WebAssembly (WASM): Opportunities for Ruby Developers
Tags: ruby, webassembly, programming, learning
Published: 2023-09-29 14:38:58

Most websites are built with high-level languages like Ruby. Developers can always optimize their code for improved performance. Yet, even with top-notch optimization practices, what if your website still lags? How could WASM help improve the performance (time and speed) of your Ruby apps?

Web Assembly is a technology that allows developers to compile code written in languages other than Javascript and run it on the web browser. This essay will delve deeply into the world of WASM and examine how it can be a game changer for Ruby developers.

By the end of this article, you’ll have learned about: 
* What is WASM and what are its goals?
* Benefits of integrating WASM into your Ruby applications.
* How to compile a Ruby application to WASM.


## Introduction to WebAssembly

Web Assembly is a technology that allows developers to compile code written in languages other than Javascript and run it on the web browser at near-native speeds. WASM’s major goal is to make the code of web apps fast, portable, and secure.

Before WASM you could only use high-level languages like  Ruby to write backend code but WASM now lets developers write client-side code using high-level languages and run it directly on the browser. WASM achieves this by compiling Ruby code to binary instruction format making it run at near-native performance speed. Unlike Javascript which is an interpreted language, WASM is a compiled language making Ruby WASM apps run at optimum performance.

WASM improves performance because of the following features:

1. WASM is fast.
  a. WASM code is smaller since it’s in binary format so it compiles faster. This leads to an increased performance since it loads faster on the browser.

  b. It takes a short time to fetch the code from the server leading to more responsive sites. 

These factors improve the speed of the app making it feel like you’re running binary on the command line.

2. WASM is statically typed. This minimizes the compilation time required in a dynamic language to check the validity of declared variables at run time.**

3. WASM uses linear memory. The binary code is stored in contiguous mutable arrays making the data easily accessible.

WASM provides more benefits apart from performance optimization for Ruby apps. You’ll learn about the various benefits you could leverage from using WASM below.

## Opportunities for Ruby Developers

As a Ruby developer, delving into WASM will help you gain insight into new possibilities and opportunities for your app. By the end of this section, you’ll have learned about some of the benefits that WASM presents for your applications.



I. **Performance optimization.** 
Ruby scripts and apps can be slow to load due to resource-intensive database queries that slow response times. WASM offers native-like performance where it feels like you're directly executing your code on the kernel. Compiling your Ruby code to WASM significantly reduces it’s size and makes your app lightweight. This will in turn improve the execution speed and your users will experience a fast load time. 

II. **Portability.** 
Ruby has support for developing cross-platform applications. You could build a desktop app, a web application, or even a mobile app using it. If you want to build a cross-platform application, you have two options. You can either create separate codebases for each environment or add a Ruby Interpreter on mobile, web, and desktop environments. The major challenge faced with cross-platform Ruby apps is distribution and problems with compiling the code in different environments.

WASM overcomes this problem since it runs on any hardware and operating system that has a WASM runtime. This reduces complexity and setup time.


III. **Leveraging WASM in browser contexts for Ruby developers.** 
The latest version of Ruby now ships with ruby.wasm which is a collection of WASM ports for CRuby(the Ruby interpreter). This enables developers to run their Ruby code directly on the browser without the need for a backend. It’s also quick to set-up since all you need is to embed a script in your HTML code similar to the code snippet below: 

```
<html>
<script src="https://cdn.jsdelivr.net/npm/ruby-3_2-wasm-wasi@2.1.0/dist/browser.script.iife.js"></script>
script type="text/ruby">
puts "Hello, world!"
</script>
</html>

```

When you run the code above, you’ll see that Ruby is running directly in your browser without connecting to the backend. You’ll also notice that WASM gets downloaded before your “Hello World” string is printed on the developer console.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q0ofspspwvcer1ffi5ao.png)

This lets you switch from using JavaScript for webpage functionality to embedding Ruby code directly in your browser.


IV. **Using WASM beyond the browser: server-side and cloud applications.**
While WASM’s primary goal was to run binary code in the browser, there are many opportunities for utilizing WASM beyond its browser capabilities. Running WASM on the server side and cloud environments has the same benefits as running it on the client side. 
WASM offers security, cross-platform, and high performance for server-side apps running on Ruby. Previously, Linux containers and Docker were popular for cloud-based binary instructions. Now, WASM containers provide a lighter, more secure, and highly portable alternative. This paradigm shift opens up exciting opportunities for deploying Ruby applications with WASM in cloud environments, revolutionizing the way server-side applications are developed and deployed.

V. **Enhanced Security**
Ruby now supports the WebAssembly System Interface(WASI) and all its features. The core feature of WASI is that it runs untrusted code in a sandbox isolated from the rest of your application. This will be highly beneficial for apps that require a high level of security like banking apps. 
Running the code in a sandbox offers a level of obfuscation that would protect your apps from malicious attacks. WASM has a feature where apps only get access to .wasm files and modules that they’ve been granted access to. This will help prevent excessive data exposure in apps.

VI. **Optimizing Ruby with WASM Best Practices.
While harnessing the power of WASM, it's essential to implement best practices for optimizing Ruby code. This entails effective memory management, using static types, and utilizing WASM-specific features. By adhering to these practices, developers will unlock the full potential of WASM.

VII. **Can be integrated into your existing apps


## Compiling Ruby to WebAssembly
WASM goes through the following process to compile your Ruby code:

1. You write your program in Ruby which is a dynamic language
2. You generate pre-compiled WASM modules using `wasi-vfs`
3. The .wasm files are then run by the compiler

You’ll follow the steps below to package your Ruby code to .wasm files:

1. Create a simple ruby project with a **sample.rb** file with the string “Hello WASM” in your **src** directory.
2. Install [wasi-vfs](https://github.com/kateinoigakukun/wasi-vfs) and [wasmtime](https://github.com/bytecodealliance/wasmtime) if not already installed.
3. Open a new terminal tab.
4. Use wasi-vfs to bundle your Ruby code into a WASM module with this command:  `wasi-vfs pack ruby.wasm --mapdir /src::./src --mapdir /usr::./3_2-wasm32-unknown-wasi-full/usr -o my-ruby-app.wasm` \
The command above does the following:
    a. wasi-vfs: This is the name of the tool being used to compile your program.

    b. `pack`: This is a command provided by the wasi-vfs tool to package a WASM module along with a virtual file system.

    c. `ruby.wasm`: This is the input Ruby WASM module. 
Presumably, it contains compiled Ruby code.

    d. `-mapdir /src::./src`: This option specifies that the contents of the local ./src directory which should be mapped to the /src directory in the virtual file system. This means that files in ./src will be accessible in the WASM environment under the /src path.

    e. `-mapdir /usr::./3_2-wasm32-unknown-wasi-full/usr`: This option does a similar mapping, but it maps the contents of `./3_2-wasm32-unknown-wasi-full/usr` to the `/usr `directory in the virtual file system.

    f. `o my-ruby-app.wasm:` This option specifies the output file name for the packaged WASM module. In this case, it will be named **my-ruby-app.wasm**.

5. Run the WASM app(**my-ruby-app.wasm)** you created in the previous step with wasmtime: `wasmtime my-ruby-app.wasm -- /src/my_app.rb`. This command runs the WASM app, printing “Hello WASM” to your terminal.

You have successfully compiled a simple Ruby app to WASM. You can read more about the inner workings of WASM [in this article](https://www.linux.com/news/an-introduction-to-webassembly/).

## Conclusion

WASM is a game changer for Ruby developers. It is the future of creating performant, cross-platform, portable, and secure Ruby applications. Explore WASM and expand the capabilities of your Ruby projects.

If you're looking for a tool to monitor your Ruby applications effortlessly, check us out at [scoutapm.com](https://scoutapm.com/?utm_source=dev.to&utm_medium=referral&utm_campaign=dev.to_blog).