iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
💎

Ruby in the Browser

に公開

I'm writing about what I presented at the NSEG 2024/06 Free Presentation Session - connpass here on this blog as well.

https://speakerdeck.com/tmtms/ruby-on-browser

Things I made with ruby.wasm

Restoring Mojibake

https://tmtms.net/mojibake/

You can restore garbled text (Mojibake) or intentionally garble strings.

This was the first page I created with ruby.wasm.

I had wanted to make something like this for a long time, but I thought it wasn't worth setting up a server just for this purpose. I wanted to make it a static page, but I gave up because I thought implementing it in JavaScript would be impossible.

Since Ruby has internal processes for character encoding conversion, I was able to achieve this. ruby.wasm is wonderful.

Shuffle

https://tmtms.net/shuffle.html

I made this to decide the committee members for my child's school.

Enter the choices in "Input" and press "Shuffle," and the randomly rearranged items will appear in the "Result" field.

Options are provided via the list URL parameter.
Since there is no server, nothing is recorded anywhere. However, the random seed value is included in the URL, so you can reproduce the results and share them with others by saving the URL.

With JavaScript's standard random numbers, you can't specify a seed value, so this was also made possible by ruby.wasm.

MySQL Parameters

This displays the differences in MySQL parameters between versions. Unusually, this one is practical.

https://mysql-params.tmtms.net/statement/

I originally made this about six years ago as practice for Vue.js, but I left it untouched because I didn't want to mess with JavaScript. I've now rebuilt it using ruby.wasm.

Switching to Ruby has motivated me to work on it again. It's a bit slower compared to Vue.js, but I figure if you care too much about that, you lose. Since it's not great to have nothing while waiting, I made a dolphin spin around.

I also wrote about recent updates in https://zenn.dev/tmtms/articles/202405-mysql-params.

Rabbit on Firefox

This tool displays a rabbit and a turtle while viewing slides on Firefox. Supported slide formats are Reveal.js, Speaker Deck, and PDF.

https://tmtms.net/rabbit/

It's an homage to, or a sign of respect for (or perhaps just a rip-off of), Rabbit - A presentation tool for Rubyists.

I love Rabbit and used to make slides with it until around 2015. After that, I started using Reveal.js, and I created this because I wanted to see the rabbit.

Initially, I built it as a Reveal.js plugin in JavaScript, but I've rebuilt it using ruby.wasm so it can be used as a bookmarklet.

Of course, the bookmarklet itself has to be written in JavaScript. Disappointing.

How to use ruby.wasm

Basic Usage

Write Ruby inside <script type="text/ruby">. It's easy.

<!DOCTYPE html>
<html>
  <script src="https://cdn.jsdelivr.net/npm/@ruby/3.3-wasm-wasi@2.6.2/dist/browser.script.iife.js"></script>
  <script type="text/ruby">
    # This is the Ruby script
    p Time.now  #=> Output goes to the browser console
    puts "Hello, world!"
  </script>
</html>

You can also load it as a separate file.

<!DOCTYPE html>
<html>
  <script src="https://cdn.jsdelivr.net/npm/@ruby/3.3-wasm-wasi@2.6.2/dist/browser.script.iife.js"></script>
  <script type="text/ruby" src="hogehoge.rb"></script>
</html>

If the code doesn't depend on the browser, keeping it in a separate file makes it easier to debug locally.

Using JavaScript Features

require 'js'

JS.eval('alert("hoge")')
JS.global.alert('hoge')

You can execute JavaScript using JS.eval. Through JS.global, you can retrieve JavaScript global objects and execute functions.

When viewed from Ruby, JavaScript values all become JS::Object.

n = JS.eval('return 123')     #=> JS::Object (123)
n.typeof                      #=> "number"
s = JS.eval('return "hoge"')  #=> JS::Object ("hoge")
s.typeof                      #=> "string"

Since they are difficult to handle in Ruby, they can be converted using to_i, to_s, etc.

JS.eval('return 123').to_i     #=> 123
JS.eval('return "hoge"').to_s  #=> "hoge"

Use JS::Object#[] to get and set properties. Use JS::Object#call to call JavaScript methods. You can also call them using JS::Object#method_name.

s = JS.eval('return "hoge"')  #=> JS::Object ("hoge")
s[:length]                    #=> JS::Object (4)
s.call(:charAt, 2)            #=> JS::Object ("g")
s.charAT(2)                   #=> JS::Object ("g")

JavaScript null and undefined are also instances of JS::Object. Note that when evaluated as booleans in Ruby, they will naturally be truthy.

JS.eval('return null')       #=> JS::Object (JS::Null)
JS.eval('return undefined')  #=> JS::Object (JS::Undefined)

!!JS::Null       #=> true
!!JS::Undefined  #=> true

JavaScript Promises can be awaited using await. However, specifying data-eval="async" is required.

<script type="text/ruby" data-eval="async">
  promise = JS.global.fetch("https://tmtms.net")  #=> JS::Object (Promise)
  resp = promise.await  #=> JS::Object (Response)
  promise = resp.text   #=> JS::Object (Promise)
  promise.await         #=> JS::Object ("<!DOCTYPE html>\n<html>\n .... ")
</script>

DOM Manipulation

Almost the same as JavaScript.

document = JS.global[:document]
hoge = document.getElementById('hoge')
fuga = document.createElement('div')
fuga[:id] = 'fuga'
hoge.appendChild(fuga)

To set events on HTML elements, use addEventListener().
Since HTML attributes like onclick call JavaScript, you cannot write Ruby code there (which makes sense).

<input id="b" type="button">
<script type="text/ruby">
  require 'js'
  document = JS.global[:document]
  document.getElementById('b').addEventListener('click') do |ev|
    JS.global.alert('hoge')
  end
</script>

Since you can call Ruby using rubyVM.eval(), one option is to use rubyVM.eval() inside onclick.

<input id="b" type="button" onclick="rubyVM.eval('hoge')">
<script type="text/ruby">
  require 'js'
  def hoge
    JS.global.alert('hoge')
  end
</script>

require

While you can load .rb files from a server using <script type="text/ruby" src="...rb">, you cannot use require to load .rb files from the server. This is because <script src> is handled via HTTP, whereas require involves loading from the file system.

The reason you can use require 'js' and similar commands is that those files are pre-integrated into the virtual file system of ruby.wasm.

Therefore, you should load the necessary .rb files in your HTML first.

<script type="text/ruby" src="hoge.rb"></script>
<script type="text/ruby" src="fuga.rb"></script>
<script type="text/ruby" src="piyo.rb"></script>

This works fine if there are no dependencies between them. However, if hoge.rb contains require 'fuga', it will fail at that point.

To require files in the same way as the standard library, you need to build ruby.wasm with the .rb files already placed inside the virtual file system.

But I really don't want to do those kinds of troublesome things, like you often have to do with JavaScript frameworks.

Using JS::RequireRemote.instance.load makes it possible to read .rb files from the server using positions relative to the current file.

For example, if require_relative 'fuga' is written inside hoge.rb, you can load it as-is by applying a patch like the following to require_relative.

require 'js/require_remote'
module Kernel
  def require_relative(path) = JS::RequireRemote.instance.load(path)
end

If you want to use a gem library, you can use it just by extracting the gem, taking out the .rb files, and placing them in a location accessible via HTTP—it's super convenient!!
(Though if require is used internally, you'll need to go through the effort of replacing it with require_relative, etc.)

However, with this simple patch, it will try to fetch even the require_relative calls that should originally be loaded from the file system from the server instead. To allow loading from both, it seems a patch like this is recommended. (From Ruby in Browser Observation Diary Part 2 - @ledsun blog. Slightly modified.)

require 'js/require_remote'
module Kernel
  prepend Module.new {
    def require_relative(path)
      caller_path = caller_locations(1,1).first.absolute_path || ''
      dir = File.dirname(caller_path)
      file = File.absolute_path(path, dir)
      super file
    rescue LoadError
      JS::RequireRemote.instance.load(path)
    end
  }
end

Summary

  • If you can do it in JavaScript, you can do it.
  • You can even do things that weren't possible in JavaScript.
  • It's slower than JavaScript, but if you let that bother you, you lose.
  • Writing the frontend in Ruby is the best!

Discussion