Skip to main content

Ruby

The Ruby interpreter is not embedded in Wasm Workers Server. To create workers based on this language, you first need to install a Ruby runtime.

Fortunately, we provide precompiled ruby.wasm modules in our WebAssembly Language Runtimes project, so the installation is simple.

Run a Ruby example

  1. Download wws:

    curl -fsSL https://workers.wasmlabs.dev/install | bash
  2. Run the ruby-basic example from the Wasm Workers Server's repository. The -i flag will install the Ruby runtime automatically.

    wws https://github.com/vmware-labs/wasm-workers-server.git -i --git-folder "examples/ruby-basic"
  3. Access to http://localhost:8080.

Ruby runtime installation

To install the Ruby Wasm module, run the following command:

wws runtimes install ruby latest

Your first Ruby worker

Ruby workers are based on the Request / Response objects from the Web Fetch API. Since these entities don't exist in the Ruby language, the worker includes a polyfill with these two classes. You can find the polyfill code here.

In this example, the worker will get a request and print all the related information.

  1. First, create a new index.rb file with the following content. The worker method is mandatory as it will be the entrypoint for the worker:

    ./index.rb
    def worker(req)
    Response.new("Hello from Ruby in WebAssembly!")
    end
  2. Now, you can add more content to the worker method to show the request information. In addition to that, let's add a response header.

    ./index.rb
    def worker(req)
    # Body response
    body = %{
    <!DOCTYPE html>
    <body>
    <h1>Hello from Wasm Workers Server</h1>
    <p>Replying to #{req.url}</p>
    <p>Method: #{req.method}</p>
    <p>User Agent: #{req.headers["user-agent"]}</p
    <p>Payload: #{req.body || "-"}</p>
    <p>
    This page was generated by a Ruby file inside WebAssembly
    </p>
    </body>
    }

    # Build a new response
    res = Response.new(body)

    # Add a new header
    res.headers["x-generated-by"] = "wasm-workers-server"

    res
    end
  3. Save the file

  4. If you didn't download the wws server yet, check our Getting Started guide.

  5. Install the Ruby runtime

  6. Run your worker with wws

    wws

    ⚙️ Loading routes from: .
    🗺 Detected routes:
    - http://127.0.0.1:8080/
    => index.rb (name: default)
    🚀 Start serving requests at http://127.0.0.1:8080
  7. Finally, open http://127.0.0.1:8080 in your browser.

Add a Key / Value store

Wasm Workers allows you to add a Key / Value store to your workers. Read more information about this feature in the Key / Value store section.

To add a KV store to your worker, follow these steps:

  1. First, create a counter.rb file. It will access the KV store through the Cache object:

    ./counter.rb
    CACHE_KEY = "counter";

    def worker(request)
    # Prepare the body
    count = Cache.get(CACHE_KEY).to_i || 0
    body = "The counter value is: #{count}"

    # Update the counter
    count += 1
    Cache.set(CACHE_KEY, count)

    # Return the response
    Response.new(body)
    end
  2. Create a counter.toml file with the following content. Note the name of the TOML file must match the name of the worker. In this case we have counter.rb and counter.toml in the same folder:

    ./counter.toml
    name = "counter"
    version = "1"

    [data]
    [data.kv]
    namespace = "counter"
  3. If you didn't download the wws server yet, check our Getting Started guide. You also need to install the Ruby runtime with the command below:

    wws runtimes install ruby latest
  4. Save the file and run your worker with wws:

    wws

    ⚙️ Loading routes from: .
    🗺 Detected routes:
    - http://127.0.0.1:8080/counter
    => counter.rb (name: default)
    🚀 Start serving requests at http://127.0.0.1:8080
  5. Finally, open http://127.0.0.1:8080/counter in your browser.

Dynamic routes

You can define dynamic routes by adding route parameters to your worker files (like [id].rb). To read them in Ruby, access to the request.params object:

def worker(request)
Response.new("The URL parameter is: #{request.params['id']}")
end

Read environment variables

Environment variables are configured via the related TOML configuration file. These variables are directly injected as global constants in your worker. To read them, just use the same name you configured in your TOML file:

./envs.toml
name = "envs"
version = "1"

[vars]
MESSAGE = "Hello 👋! This message comes from an environment variable"

Now, you can read the MESSAGE environment variable using the Ruby ENV class:

./envs.rb
def worker(request)
Response.new(
"The environment variable value is: #{ENV.fetch('MESSAGE')}"
)
end

If you prefer, you can configure the environment variable value dynamically by following these instructions.

Examples

Feature compatibility

Workers' features that are available in Ruby:

K/V StoreEnvironment VariablesDynamic RoutesFoldersHTTP Requests