### Install Dependencies and Setup ruby.wasm Source: https://github.com/ruby/ruby.wasm/blob/main/CONTRIBUTING.md Installs project dependencies, clones the repository recursively, sets up the environment, and compiles extension libraries. This is the initial setup step for contributing to the project. ```console git clone https://github.com/ruby/ruby.wasm --recursive cd ruby.wasm ./bin/setup # Compile extension library bundle exec rake compile rake --tasks ``` -------------------------------- ### Quick Start: Load Ruby in Browser/Node.js Source: https://github.com/ruby/ruby.wasm/blob/main/packages/npm-packages/ruby-wasm-emscripten/README.md A JavaScript example demonstrating how to load the Ruby interpreter using the loadRuby function from the @ruby/head-wasm-emscripten package in both browser and Node.js environments. ```javascript import { loadRuby } from "@ruby/head-wasm-emscripten"; const main = async () => { const args = ["--disable-gems", "-e", "puts 'Hello :)'"]; console.log(`$ ruby.wasm ${args.join(" ")}`); const defaultModule = { locateFile: (path) => "./node_modules/@ruby/head-wasm-emscripten/dist/" + path, setStatus: (msg) => console.log(msg), print: (line) => console.log(line), arguments: args, }; await loadRuby(defaultModule); }; main(); ``` -------------------------------- ### Install @ruby/wasm-emscripten Package Source: https://github.com/ruby/ruby.wasm/blob/main/packages/npm-packages/ruby-wasm-emscripten/README.md Commands to install the @ruby/wasm-emscripten package and its specific versions, including snapshots and nightly builds, using npm. ```bash # Install the latest stable version $ npm install --save @ruby/wasm-emscripten@latest @ruby/head-wasm-emscripten@latest # Install the nightly snapshot $ npm install --save @ruby/head-wasm-emscripten@next # Install a specific snapshot version $ npm install --save @ruby/head-wasm-emscripten@2.7.1-2025-01-23-a ``` -------------------------------- ### Install Release Channels for @ruby/wasm-wasi Source: https://github.com/ruby/ruby.wasm/blob/main/CONTRIBUTING.md Demonstrates how to install different release channels for the `@ruby/wasm-wasi` npm package. You can install the latest stable release, the pre-release version (`next`), or a specific snapshot version. ```console $ npm install --save @ruby/wasm-wasi@latest # or if you want the nightly snapshot $ npm install --save @ruby/wasm-wasi@next # or you can specify the exact snapshot version $ npm install --save @ruby/wasm-wasi@2.7.1-2025-01-23-a ``` -------------------------------- ### Install and Run Ruby.wasm in Node.js Source: https://github.com/ruby/ruby.wasm/blob/main/docs/cheat_sheet.md Installs the necessary packages and demonstrates how to instantiate a Ruby VM and execute Ruby code within a Node.js environment. Requires the `--experimental-wasi-unstable-preview1` flag for WASI support. ```console npm install --save @ruby/3.4-wasm-wasi @ruby/wasm-wasi ``` ```javascript import fs from "fs/promises"; import { DefaultRubyVM } from "@ruby/wasm-wasi/dist/node"; const binary = await fs.readFile("./node_modules/@ruby/3.4-wasm-wasi/dist/ruby.wasm"); const module = await WebAssembly.compile(binary); const { vm } = await DefaultRubyVM(module); vm.eval(`puts "hello world"`); ``` ```console $ node --experimental-wasi-unstable-preview1 index.mjs ``` -------------------------------- ### Build CRuby for Emscripten Target Source: https://github.com/ruby/ruby.wasm/blob/main/CONTRIBUTING.md Steps to build CRuby for WebAssembly/Emscripten. This requires installing Emscripten separately. The output of the build process will be in the `rubies` directory. ```console # Build only a specific combination of ruby version, profile, and target $ rake build:head-wasm32-unknown-emscripten-full # Output is in the `rubies` directory $ tree -L 3 rubies/head-wasm32-unknown-emscripten-full ``` -------------------------------- ### Package Ruby App as WASI with rbwasm Source: https://github.com/ruby/ruby.wasm/blob/main/README.md Demonstrates packaging a Ruby application into a WASI-compatible WebAssembly module using the `rbwasm` tool. This involves installing the gem, downloading a prebuilt Ruby WASM runtime, organizing application files, and then using `rbwasm pack` to create the executable WASM file. The process requires `wasmtime` to run the packed application. ```bash $ gem install ruby_wasm # Download a prebuilt Ruby release $ curl -LO https://github.com/ruby/ruby.wasm/releases/latest/download/ruby-3.4-wasm32-unknown-wasip1-full.tar.gz $ tar xfz ruby-3.4-wasm32-unknown-wasip1-full.tar.gz # Extract ruby binary not to pack itself $ mv ruby-3.4-wasm32-unknown-wasip1-full/usr/local/bin/ruby ruby.wasm # Put your app code $ mkdir src $ echo "puts 'Hello'" > src/my_app.rb # Pack the whole directory under /usr and your app dir $ rbwasm pack ruby.wasm --dir ./src::/src --dir ./ruby-3.4-wasm32-unknown-wasip1-full/usr::/usr -o my-ruby-app.wasm # Run the packed scripts $ wasmtime my-ruby-app.wasm /src/my_app.rb ``` -------------------------------- ### Interact with JavaScript from Ruby: Call Methods Source: https://github.com/ruby/ruby.wasm/blob/main/docs/cheat_sheet.md Shows how to invoke JavaScript methods from Ruby code. It includes an example of calling `createElement` and demonstrates both direct method calls and symbol-based calls. ```ruby require "js" JS.global[:document].createElement("div") JS.global[:document].call(:createElement, "div".to_js) # same as above ``` -------------------------------- ### Re-bindgen from .wit files Source: https://github.com/ruby/ruby.wasm/blob/main/CONTRIBUTING.md Generates glue code from `.wit` files, which define WebAssembly module interfaces. This process requires the Rust compiler (`rustc`) and Cargo. The `wit-bindgen` tool is installed on demand. Ensure `cargo` is in your `PATH`. ```console rake check:bindgen ``` -------------------------------- ### Interact with JavaScript from Ruby: Instantiate Objects Source: https://github.com/ruby/ruby.wasm/blob/main/docs/cheat_sheet.md Demonstrates how to create new JavaScript instances from Ruby code using the `new` keyword via the `js` gem. The example shows creating a new `Date` object. ```ruby require "js" JS.global[:Date].new(2000, 9, 13) ``` -------------------------------- ### Await JavaScript Promises in Ruby (Browser) Source: https://github.com/ruby/ruby.wasm/blob/main/docs/cheat_sheet.md Provides examples of how to `await` JavaScript Promises directly from Ruby code in a browser environment. This is achieved either by using the `data-eval="async"` attribute in ` ``` ```html ``` -------------------------------- ### Build and Test ruby-wasm-wasi Source: https://github.com/ruby/ruby.wasm/blob/main/CONTRIBUTING.md Commands to download prebuilt Ruby releases or build Ruby from scratch for WASI targets. It also includes steps for building and testing the ruby-wasm-wasi npm package. If you need to rebuild Ruby, clean the `./rubies` directory first. ```console # Download a prebuilt Ruby release (if you don't need to re-build Ruby) rake build:download_prebuilt # Build Ruby (if you need to build Ruby by yourself) rake build:head-wasm32-unknown-wasip1-full # Build npm package rake npm:ruby-head-wasm-wasip2:build # Test npm package rake npm:ruby-head-wasm-wasip2:check ``` -------------------------------- ### Build Package in Docker Container Source: https://github.com/ruby/ruby.wasm/blob/main/packages/npm-packages/ruby-wasm-emscripten/README.md Docker command to set up an environment for building the Ruby.wasm Emscripten package. It mounts local directories into the container for build artifacts and the Emscripten SDK. ```bash $ docker run -it --rm \ -v $(pwd):/src \ -v path/to/wasm32-unknown-emscripten-full:/install \ emscripten/emsdk /bin/bash ``` -------------------------------- ### Build Ruby.wasm Emscripten Package from Source Source: https://github.com/ruby/ruby.wasm/blob/main/packages/npm-packages/ruby-wasm-emscripten/README.md Shell commands for building the @ruby/wasm-emscripten package from source. This involves preparing a Ruby build produced by Emscripten and using a provided build script. ```bash # Check the directory structure of your Ruby build $ tree -L 3 path/to/wasm32-unknown-emscripten-full/ path/to/wasm32-unknown-emscripten-full/ ├── usr │ └── local │ ├── bin │ ├── include │ ├── lib │ └── share └── var └── lib └── gems # Run the build script $ ./build-package.sh path/to/wasm32-unknown-emscripten-full/ Remember to build the main file with -s FORCE_FILESYSTEM=1 so that it includes support for loading this file package index.js → dist... created dist in 3.5s ``` -------------------------------- ### Run Ruby.wasm in Browser with ES Modules Source: https://github.com/ruby/ruby.wasm/blob/main/docs/cheat_sheet.md Demonstrates how to instantiate a Ruby VM and run Ruby code from JavaScript in a browser environment using ES Modules and CDN. It fetches the WASM module and compiles it for execution. ```html ``` -------------------------------- ### Create New npm Package for Ruby Version Source: https://github.com/ruby/ruby.wasm/blob/main/CONTRIBUTING.md This snippet demonstrates the process of creating a new npm package for a specific Ruby version by copying an existing package and updating its metadata. It is a shell command sequence. ```shell # Copy from head package $ cp -r packages/npm-packages/ruby-head-wasm-wasi packages/npm-packages/ruby-NEW.VERSION-wasm-wasi # Update version references # - In package.json: Update name, version, and description # - In README.md: Update version references ``` -------------------------------- ### Test New Ruby Version Build and npm Package Source: https://github.com/ruby/ruby.wasm/blob/main/CONTRIBUTING.md These commands are used to test the build process for a newly added Ruby version and its corresponding npm package. They verify the integrity and functionality of the build artifacts. ```shell $ rake build:NEW.VERSION-wasm32-unknown-wasip1-full $ rake npm:ruby-NEW.VERSION-wasm-wasi:build $ rake npm:ruby-NEW.VERSION-wasm-wasi:check ``` -------------------------------- ### Build CRuby for WASI Target Source: https://github.com/ruby/ruby.wasm/blob/main/CONTRIBUTING.md Instructions for building CRuby for WebAssembly/WASI on Linux or macOS. Dependencies are downloaded automatically. You can select build profiles and clean up the build directory. The output is located in the `rubies` directory. ```console # Build only a specific combination of ruby version, profile, and target $ rake build:head-wasm32-unknown-wasip1-full # Clean up the build directory $ rake build:head-wasm32-unknown-wasip1-full:clean # Force to re-execute "make install" $ rake build:head-wasm32-unknown-wasip1-full:remake # Output is in the `rubies` directory $ tree -L 3 rubies/head-wasm32-unknown-wasip1-full ``` -------------------------------- ### Bump npm Package Version Source: https://github.com/ruby/ruby.wasm/blob/main/CONTRIBUTING.md Sequence of commands to update the npm package version, commit the changes, tag the release, push to origin, download build artifacts from GitHub Actions, push gems to their respective registries, and finally bump the development version. ```console $ rake 'bump_version[0.6.0]' $ git commit -m"Bump version to 0.6.0" $ git tag 0.6.0 $ git push origin 0.6.0 # After GitHub Actions "Build gems" is done # https://github.com/ruby/ruby.wasm/actions/workflows/build-gems.yml $ gh run download $ for pkg in cross-gem-*/ruby_wasm-*; do gem push $pkg; done $ gem build && gem push ruby_wasm-*.gem && rm ruby_wasm-*.gem $ (cd packages/gems/js/ && gem build && gem push js-*.gem && rm js-*.gem) $ rake bump_dev_version ``` -------------------------------- ### Run Ruby.wasm in Browser without ES Modules (UMD) Source: https://github.com/ruby/ruby.wasm/blob/main/docs/cheat_sheet.md An alternative method for running Ruby.wasm in the browser without using ES Modules, leveraging the UMD bundle from a CDN. It initializes the VM and executes Ruby code using `window["ruby-wasm-wasi"]`. ```html ``` -------------------------------- ### loadRuby Function API Source: https://github.com/ruby/ruby.wasm/blob/main/packages/npm-packages/ruby-wasm-emscripten/README.md The `loadRuby` function is the primary API provided by this package. It asynchronously loads the CRuby interpreter and its standard library into the WebAssembly environment. It accepts a configuration object for the Emscripten Module. ```APIDOC ## loadRuby(defaultModule) ### Description Loads the Ruby interpreter and stdlib asynchronously. ### Method `async` ### Parameters #### Request Body - **defaultModule** (object) - Required - An Emscripten Module object configuration used to control the interpreter's behavior. See [Emscripten Module documentation](https://emscripten.org/docs/api_reference/module.html) for details. - **locateFile** (function) - Optional - A function to resolve the path of WebAssembly binary files. - **setStatus** (function) - Optional - A function to report the loading status. - **print** (function) - Optional - A function to capture Ruby's standard output. - **arguments** (array) - Optional - An array of strings representing command-line arguments for the Ruby interpreter. ### Request Example ```javascript const defaultModule = { locateFile: (path) => "./node_modules/@ruby/head-wasm-emscripten/dist/" + path, setStatus: (msg) => console.log(msg), print: (line) => console.log(line), arguments: ["--disable-gems", "-e", "puts 'Hello :)'"] }; await loadRuby(defaultModule); ``` ### Response #### Success Response (200) - **Module** (object) - The Emscripten Module object, representing the loaded Ruby environment. ``` -------------------------------- ### Format Code Source: https://github.com/ruby/ruby.wasm/blob/main/CONTRIBUTING.md Command to format all files in the project using multiple code formatters for different languages. It is recommended to run this command before submitting a pull request to ensure code consistency. ```console rake format ``` -------------------------------- ### Redirecting STDOUT in Ruby.wasm Source: https://github.com/ruby/ruby.wasm/blob/main/docs/faq.md This snippet demonstrates how to redirect the standard output (STDOUT) in Ruby.wasm. By default, `puts` goes to `console.log`, but this code overrides `$stdout` to write directly to the HTML document using `JS.global[:document].write`. ```ruby $stdout = Object.new.tap do |obj| def obj.write(str) JS.global[:document].write(str) end end puts "Hello, world!" # => Prints "Hello, world!" to the HTML document ``` -------------------------------- ### Run Ruby.wasm in Browser via CDN (IIFE) Source: https://github.com/ruby/ruby.wasm/blob/main/docs/cheat_sheet.md A simple method to embed and run Ruby code directly in an HTML file using a script from a CDN. Ruby code is executed within a ` ``` -------------------------------- ### Interact with JavaScript from Ruby: Pass Callbacks Source: https://github.com/ruby/ruby.wasm/blob/main/docs/cheat_sheet.md Illustrates how to pass Ruby Procs as callbacks to JavaScript functions, such as `setTimeout` and event listeners. This allows Ruby code to be executed in response to JavaScript events. ```ruby require "js" JS.global.setTimeout(proc { puts "Hello, world!" }, 1000) input = JS.global[:document].querySelector("input") input.addEventListener("change") do |event| puts event[:target][:value].to_s end ``` -------------------------------- ### Run Ruby in Browser with ruby.wasm Source: https://github.com/ruby/ruby.wasm/blob/main/README.md Integrates ruby.wasm into an HTML page to execute Ruby code directly in the browser. It requires including the browser script and embedding Ruby code within a script tag. The output is visible in the browser's console and can directly manipulate the DOM. ```html ``` -------------------------------- ### Interact with JavaScript from Ruby: Convert Types Source: https://github.com/ruby/ruby.wasm/blob/main/docs/cheat_sheet.md Explains how to convert JavaScript String, Boolean, and Number types to their corresponding Ruby types. It shows the use of `.to_s`, `.to_i`, and `.to_f` methods for type conversion. ```ruby require "js" title = JS.global[:document].title # => JS::Object("Hello, world!") title.to_s # => "Hello, world!" JS.global[:document].hasFocus? # => true JS.global[:document].hasFocus # => JS::Object(true) rand = JS.global[:Math].random # JS::Object(0.123456789) rand.to_i # => 0 rand.to_f # => 0.123456789 ``` -------------------------------- ### Interact with JavaScript from Ruby: Get/Set Variables Source: https://github.com/ruby/ruby.wasm/blob/main/docs/cheat_sheet.md Demonstrates how to access and modify JavaScript global variables, specifically the document's title, from within Ruby code using the `js` gem. ```ruby require "js" document = JS.global[:document] document[:title] = "Hello, world!" ``` -------------------------------- ### Patch require_relative for Remote Loading in Ruby Source: https://github.com/ruby/ruby.wasm/blob/main/packages/npm-packages/ruby-wasm-wasi/example/require_relative/index.html This Ruby code modifies the `require_relative` method to first attempt loading a file locally. If a `LoadError` occurs, it falls back to loading the module from a remote URL using `JS::RequireRemote`. This enables dynamic loading of modules from web resources. ```ruby # Patch require_relative to load from remote require 'js/require_remote' module Kernel alias original_require_relative require_relative # The require_relative may be used in the embedded Gem. # First try to load from the built-in filesystem, and if that fails, # load from the URL. def require_relative(path) caller_path = caller_locations(1, 1).first.absolute_path || '' dir = File.dirname(caller_path) file = File.absolute_path(path, dir) original_require_relative(file) rescue LoadError JS::RequireRemote.instance.load(path) end end # The above patch should not break the original require_relative require 'uri' URI.parse('http://example.com') # Load the main script require_relative 'main' ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.