ruby / ruby.wasm

ruby.wasm is a collection of WebAssembly ports of the CRuby.
https://ruby.github.io/ruby.wasm/
MIT License
668 stars 52 forks source link

Add a base_url property to JS::RequreRemote to specify the base URL for resolving relative paths. #506

Closed ledsun closed 1 month ago

ledsun commented 1 month ago

Before

Currently, JS::RequireRemote treats the URL of the HTML file that calls ruby.wasm as the base URL for resolving relative paths. For this reason, you will have to write an uncomfortable require_relative if you place the Ruby script that serves as the entry point in a directory different from the HTML file.

For example, if the entry point for a Ruby script is placed in the lib directory as follows:

<script type="text/ruby" src="lib/init.rb" data-eval="async"></script>

If you want to read the jsrb.rb file in the same lib directory, include the lib directory in the require_relative argument, like require_relative 'lib/jsrb'. Or, specify an absolute path, such as /lib/jsrb.

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

require_relative '/lib/jsrb'

After

If you set lib in the base_url property as follows, you can write require_relative 'jsrb' as a relative path from lib/init.rb.

require 'js/require_remote'

JS::RequireRemote.instance.base_url = "lib" # Set base_url

module Kernel
  def require_relative(path)
    JS::RequireRemote.instance.load(path)
  end
end

require_relative 'jsrb' # We can specify relative_path for jsrb.rb

Why not automatically resolve the base URL?

I do not know if JS::RequireRemote is used when a ruby script is loaded with the script tag. It is not appropriate to change the JS::RequireRemote setting at this time.

Also, when multiple ruby scripts are loaded in a script tag, I am not sure which ruby script path should be used as the base URL.