由 Bownlux 制作,RevivalSMP.net 的开发者
关于更新: 本项目的大型更新不会频繁发布,因为我的大部分时间都投入到了 RevivalSMP.net 和 Retromod 上。请预期会有较小的维护版本(新的 Minecraft 版本、JRuby 升级、错误修复),而不是持续的功能流。欢迎提交问题报告和拉取请求。
用 Ruby 编写 Fabric 模组!这是一个 Fabric 语言模块,相当于 fabric-language-kotlin 的 Ruby 版本。它由嵌入在模组 jar 包中的 JRuby 运行时驱动,并附带完整的 Ruby 标准库。
你的模组的 fabric.mod.json 将入口点指向一个 .rb 脚本,本模组负责其余工作:它启动 JRuby(惰性启动,仅在实际需要 Ruby 入口点时),评估你的脚本,并将生成的 Ruby 对象作为常规入口点交给 Fabric Loader。Ruby 方法名会自动映射到 Java,因此 def on_initialize 实现了 ModInitializer#onInitialize。
class MyRubyMod
LOGGER = org.slf4j.LoggerFactory.getLogger('my-ruby-mod')
def on_initialize
LOGGER.info("Hello from Ruby #{RUBY_VERSION}!")
end
end
MyRubyMod
日志记录说明: Minecraft 仅在 1.18.2+ 版本中提供 slf4j。如果目标是旧版本?请使用 Log4j,它在所有受支持版本中都存在:LOGGER = org.apache.logging.log4j.LogManager.getLogger('my-ruby-mod'),或者直接使用普通的 puts。
支持的版本
Fabric 支持的每个 Minecraft 版本,从最初版(1.14)开始。每个发行版发布两个文件。安装与你 Minecraft 版本匹配的那个:
| 文件 |
Minecraft |
Java |
捆绑运行时 |
fabric-language-ruby-<v>+jruby.10.x.jar |
1.20.5 及更高版本(包括 26.x) |
21+ |
JRuby 10.0 (Ruby 3.4) |
fabric-language-ruby-<v>+jruby.9.4.x.jar |
1.14-1.20.4 |
8+ |
JRuby 9.4 (Ruby 3.1) |
两者都是相同的模组(fabric-language-ruby,相同的功能,相同的适配器);它们仅在捆绑的 JRuby 方面有所不同,因为 JRuby 10 需要 Java 21,而较旧的 Minecraft 运行在 Java 8-17 上。Modrinth 会自动为你的游戏版本提供正确的文件。需要 Fabric Loader 0.16.0 或更高版本。
Fabric Language Ruby 与 fabric-language-kotlin 完全兼容:这两个语言模块可以同时安装,因此 Ruby 模组可以与 Kotlin 模组一起在一个整合包中运行。这已通过在一台服务器上同时运行两个适配器以及一个用 Kotlin 编写的模组(Ledger)进行测试验证。
对于玩家
如果你安装的某个模组需要此库,请从 Modrinth(或 GitHub releases)下载与你的 Minecraft 版本匹配的文件,并将其放入你的 mods/ 文件夹中,放在需要它的模组旁边。无需配置。
对于模组开发者
设置
将 ruby 适配器添加到 fabric.mod.json 中的入口点,将值指向你模组 jar 内的 Ruby 脚本,并依赖于 fabric-language-ruby:
{
"schemaVersion": 1,
"id": "my-ruby-mod",
"version": "1.0.0",
"entrypoints": {
"main": [
{
"adapter": "ruby",
"value": "my_ruby_mod/main.rb"
}
]
},
"depends": {
"fabricloader": ">=0.16.0",
"fabric-language-ruby": ">=1.0.0"
}
}
my_ruby_mod/main.rb 位于你模组的 resources(资源)中(因此它会出现在你 jar 包的该路径下)。给目录起一个唯一的、特定于模组的名字,因为所有模组共享同一个 JVM 类路径。
脚本的最后一个表达式 是入口点。在上方的示例中,它是类本身,适配器会对其进行实例化。
入口点值语法
value |
含义 |
"path/to/script.rb" |
评估脚本;其最后一个表达式是入口点。类将通过 new 实例化;模块、实例或 lambda 则按原样使用。 |
"path/to/script.rb::Some::Constant" |
评估脚本,然后解析(命名空间化的)常量。类将被实例化;其他任何内容均按原样使用。 |
"path/to/script.rb::Some::Constant#method_name" |
解析常量并绑定 method_name。对于类,实例方法优先(为其创建新实例);否则绑定类/模块级别的方法(module_function,def self.)。对于任何其他常量,该方法将在对象本身上绑定。 |
三种形式的示例:
# value: "my_mod/main.rb"。最后一个表达式是一个 lambda,适用于像 ModInitializer 这样的单方法入口点。
-> { puts 'initialized!' }
# value: "my_mod/main.rb::MyMod::Initializer"
module MyMod
class Initializer
def on_initialize
# ...
end
end
end
# value: "my_mod/main.rb::MyMod#init"
module MyMod
module_function
def init
# ...
end
end
方法引用和 lambda 入口点会将入口点接口的每个方法路由到那一个方法/lambda,因此它们适合像 ModInitializer 这样的单方法接口;对于实现多方法入口点接口,请使用类或模块。
Ruby 对象如何成为 Java 入口点
JRuby 会将你的 Ruby 对象强制转换为目标入口点接口(ModInitializer、ClientModInitializer、DedicatedServerModInitializer、自定义接口等)。方法名会自动映射:对 onInitialize 的 Java 调用会分发到你的 Ruby on_initialize(如果你定义的是字面量 onInitialize,则分发到该名称)。
无论有多少个入口点引用它,脚本最多只会被评估一次。如果最后一个表达式是类,每个入口点引用都会获得自己的实例;如果是实例(例如 MyMod.new)或模块,则该对象被共享。
一个共享的 JRuby 运行时
所有 Ruby 模组都在一个共享的 JRuby 解释器中运行。顶层常量、全局变量、monkey-patches(猴子补丁)以及 java_import 在所有 Ruby 模组之间可见,加载较晚的模组可以重新打开(或覆盖)另一个模组的顶层类。请确保每个模组内的所有内容都位于一个唯一命名的模块中(module MyRubyMod ... end),在您的类/模块内部而非顶层进行 java_import,并避免使用 $globals。
多文件模组与标准库
require_relative 可在 jar 包内的脚本之间正常工作,完整的 Ruby 标准库可通过普通的 require 使用:
require 'json'
require_relative 'helper'
使用 gems(构建时本地化)
不支持在运行时安装 gems(因为标准库位于 jar 包内),但可以在构建模组时将 gems 本地化到模组中。此仓库提供了一个 Gradle 辅助工具 gradle/gem-vendor.gradle,用于运行整个流程:它使用构建时的 JRuby 从 rubygems.org 解析您列出的 gems(及其传递依赖项),将每个解析到的 gem 复制到模组的资源中,并生成一个 vendor/setup.rb,通过 uri:classloader: 方案将所有 gem 添加到 $LOAD_PATH。
将该文件复制到您的项目中,并在 build.gradle 中进行配置:
apply from: 'gradle/gem-vendor.gradle'
gemVendor {
vendorPath = 'my_ruby_mod/vendor' // gems 存放的资源路径
gem 'dentaku', '3.5.7'
// 根据需要添加更多 gem 'name', 'version' 行;传递依赖项会自动解析,显式列出其中一个以固定其版本
}
然后在您的脚本中通过普通的 require 加载 gems:
require_relative 'vendor/setup'
require 'dentaku'
可行与不可行的情况:
- Pure-Ruby gems 可以工作,带有预构建 JRuby jar 的 gem(例如 concurrent-ruby)也可以工作。包含 C 扩展的 gem 会在安装时失败,这正是发现问题的好时机。
- 在磁盘上读取或写入自身文件的 gem 无法在 jar 包内工作。
- 本地化会将 gems 分发到您 jar 包内部。请检查每个 gem 的许可证是否允许这样做,并按照许可证要求注明出处。
- 如果您同时发布两个变体版本,请针对每个变体构建 vendoring 步骤(该辅助工具会使用您指定的 JRuby 版本),以便 gem 解析与您用户运行的 Ruby 版本匹配。
src/testmod 中的示例模组以这种方式本地化了 dentaku,并且每次 CI 构建都会针对两个变体测试该流程。如果您希望手动本地化,生成的 setup.rb 展示了所需的一切:每个 gem 的 require 目录作为 uri:classloader:/<resource path> 添加到 $LOAD_PATH(所有模组资源都在共享类路径上)。
调用 Minecraft 和 Fabric API
Java 互操作是标准的 JRuby:
class MyRubyMod
java_import 'net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents'
def on_initialize
on_started = lambda do |server|
puts "server started: #{server.class.java_class.simple_name}"
end
ServerLifecycleEvents::SERVER_STARTED.register(
on_started.to_java(ServerLifecycleEvents::ServerStarted)
)
end
end
MyRubyMod
重要提示: Fabric API 的 Event#register(T) 是一个泛型方法,因此 JRuby 无法从裸块中推断监听器接口。如上所示,请使用 lambda.to_java(TheListenerInterface) 进行显式转换。对于接受函数接口的非泛型 Java 方法,直接传递块即可正常工作。
关于不同 Minecraft 版本的类名说明: 在 Minecraft 26.x 及更高版本中,游戏未混淆,因此 Ruby 脚本可以通过其真实名称(Mojang 命名)调用 Minecraft 类。在旧版本(1.14-1.21.x)中,Minecraft 自身的类在运行时具有 intermediary 名称(net.minecraft.class_310 风格)。入口点接口、Fabric API、Fabric Loader API(包括 FabricLoader.getInstance.getMappingResolver 用于转换名称)以及所有 Java 库不受影响,并保持其正常名称。
限制
- 不支持从 Ruby 使用 mixins。 Mixins 需要编译时的类;如果需要 mixins 的 Ruby 模组应与其 Ruby 入口点一起提供一个小型 Java/mixin 核心(两者可以存在于同一个 jar 包中)。
- 不支持运行时 gem 安装。 如前所述,请在构建时本地化 gems。
- 目标为遗留文件的脚本应坚持使用 Ruby 3.1 特性(现代文件运行 Ruby 3.4)。
示例模组
一个完整可用的示例位于 src/testmod:一个完全用 Ruby 编写的模组,从其 main 入口点记录日志,使用 require/require_relative,调用本地化的 gem(dentaku),并注册 Fabric API 生命周期回调。使用以下命令针对开发服务器运行它:
./gradlew runTestmodServer
从源代码构建
需要 JDK 25(构建出的 jar 包仍如上文所述在 Java 8/21+ 上运行)。
./gradlew build # 现代变体 -> build/libs/*+jruby.10.*.jar
./gradlew build -Pvariant=legacy # 遗留变体 -> build/libs/*+jruby.9.4.*.jar
每次构建都会针对该变体的 JRuby 运行单元测试套件,并生成一个独立的示例模组 jar 包(*-testmod.jar)。JRuby 以 jar-in-jar 方式捆绑(org.jruby:jruby-core + org.jruby:jruby-stdlib);如果安装了多个携带 JRuby 的模组,Fabric Loader 会根据版本去重嵌套 jar 包。
版本控制
格式为 <modVersion>+jruby.<bundledJRubyVersion>,例如 1.0.0+jruby.10.0.6.0。这模仿了 fabric-language-kotlin 的方案。只有 + 之前的部分参与依赖解析,因此 "fabric-language-ruby": ">=1.0.0" 匹配两个变体文件。
许可证
MIT
Made by Bownlux, A developer of RevivalSMP.net
A note on updates: big updates to this project will not come often, since most of my time
goes into RevivalSMP.net and Retromod. Expect smaller maintenance
releases (new Minecraft versions, JRuby bumps, bug fixes) rather than a steady stream of
features. Issues and pull requests are still welcome.
Write Fabric mods in Ruby! This is a Fabric language module, the Ruby
equivalent of fabric-language-kotlin. It is
powered by an embedded JRuby runtime that ships inside the mod jar
together with the full Ruby standard library.
Your mod's fabric.mod.json points an entrypoint at a .rb script, and this mod does the rest:
it boots JRuby (lazily, only when a Ruby entrypoint is actually needed), evaluates your script, and
hands the resulting Ruby object to Fabric Loader as a regular entrypoint. Ruby method names map to
Java automatically, so def on_initialize implements ModInitializer#onInitialize.
class MyRubyMod
LOGGER = org.slf4j.LoggerFactory.getLogger('my-ruby-mod')
def on_initialize
LOGGER.info("Hello from Ruby #{RUBY_VERSION}!")
end
end
MyRubyMod
Logging note: Minecraft ships slf4j only on 1.18.2+. Targeting older versions? Use Log4j,
which exists on every supported version:
LOGGER = org.apache.logging.log4j.LogManager.getLogger('my-ruby-mod'), or just use plain puts.
Supported versions
Every Minecraft version Fabric supports, back to the very first (1.14). Two files are published per
release. Install the one matching your Minecraft version:
| File |
Minecraft |
Java |
Bundled runtime |
fabric-language-ruby-<v>+jruby.10.x.jar |
1.20.5 and newer (incl. 26.x) |
21+ |
JRuby 10.0 (Ruby 3.4) |
fabric-language-ruby-<v>+jruby.9.4.x.jar |
1.14-1.20.4 |
8+ |
JRuby 9.4 (Ruby 3.1) |
Both are the same mod (fabric-language-ruby, same features, same adapter); they differ only in the
bundled JRuby, because JRuby 10 needs Java 21 while older Minecraft runs on Java 8-17. Modrinth
serves the right file for your game version automatically. Fabric Loader 0.16.0+ is required.
Fabric Language Ruby is fully compatible with
fabric-language-kotlin: both language modules
can be installed at the same time, so Ruby mods run alongside Kotlin mods in one modpack. This is
verified in testing by running both adapters plus a Kotlin-written mod (Ledger) on one server.
For players
If a mod you installed needs this library, download the file matching your Minecraft version from
Modrinth (or the GitHub releases) and drop
it into your mods/ folder, next to the mod that needs it. There is no configuration.
For mod developers
Setting up
Add the ruby adapter to your entrypoints in fabric.mod.json, point the value at a Ruby script
inside your mod jar, and depend on fabric-language-ruby:
{
"schemaVersion": 1,
"id": "my-ruby-mod",
"version": "1.0.0",
"entrypoints": {
"main": [
{
"adapter": "ruby",
"value": "my_ruby_mod/main.rb"
}
]
},
"depends": {
"fabricloader": ">=0.16.0",
"fabric-language-ruby": ">=1.0.0"
}
}
my_ruby_mod/main.rb lives in your mod's resources (so it ends up at that path inside your
jar). Give the directory a unique, mod-specific name, because every mod shares one JVM classpath.
The last expression of the script is the entrypoint. In the example at the top it is the class
itself, which the adapter instantiates.
Entrypoint value syntax
value |
Meaning |
"path/to/script.rb" |
Evaluate the script; its last expression is the entrypoint. A class is instantiated with new; a module, instance, or lambda is used as-is. |
"path/to/script.rb::Some::Constant" |
Evaluate the script, then resolve the (namespaced) constant. A class is instantiated; anything else is used as-is. |
"path/to/script.rb::Some::Constant#method_name" |
Resolve the constant and bind method_name. For a class, an instance method wins (a new instance is created for it); otherwise a class/module-level method (module_function, def self.) is bound. For any other constant the method is bound on the object itself. |
Examples of all three forms:
# value: "my_mod/main.rb". The last expression is a lambda, which works for
# single-method entrypoints like ModInitializer.
-> { puts 'initialized!' }
# value: "my_mod/main.rb::MyMod::Initializer"
module MyMod
class Initializer
def on_initialize
# ...
end
end
end
# value: "my_mod/main.rb::MyMod#init"
module MyMod
module_function
def init
# ...
end
end
Method-reference and lambda entrypoints route every method of the entrypoint interface to that
one method/lambda, so they suit single-method interfaces like ModInitializer; implement
multi-method entrypoint interfaces with a class or module instead.
How Ruby objects become Java entrypoints
JRuby coerces your Ruby object into the requested entrypoint interface
(ModInitializer, ClientModInitializer, DedicatedServerModInitializer, custom interfaces, and so on).
Method names map automatically: a Java call to onInitialize dispatches to your Ruby
on_initialize (or a literal onInitialize if you define that instead).
A script is evaluated at most once per mod, no matter how many entrypoints reference it. If the
last expression is a class, each entrypoint reference gets its own instance; if it is an
instance (e.g. MyMod.new) or a module, that one object is shared.
One shared JRuby runtime
All Ruby mods run in a single shared JRuby interpreter. Top-level constants, global variables,
monkey-patches, and java_imports are visible across every Ruby mod, and a later-loading mod can
reopen (or clobber) another mod's top-level classes. Keep everything inside one uniquely-named
module per mod (module MyRubyMod ... end), do java_import inside your own class/module rather
than at the top level, and avoid $globals.
Multi-file mods and the standard library
require_relative works between the scripts in your jar, and the full Ruby standard library is
available with plain require:
require 'json'
require_relative 'helper'
Using gems (build-time vendoring)
Installing gems at runtime is not supported (the stdlib lives inside a jar), but gems can be
vendored into your mod while it is being built. This repository ships a Gradle helper,
gradle/gem-vendor.gradle, that runs the whole pipeline: it resolves
the gems you list (plus their transitive dependencies) from rubygems.org using a build-time JRuby,
copies each resolved gem into your mod's resources, and generates a vendor/setup.rb that puts
every gem on $LOAD_PATH with the uri:classloader: scheme.
Copy the file into your project and wire it up in build.gradle:
apply from: 'gradle/gem-vendor.gradle'
gemVendor {
vendorPath = 'my_ruby_mod/vendor' // resource path the gems land under
gem 'dentaku', '3.5.7'
// more gem 'name', 'version' lines as needed; transitive dependencies
// are resolved automatically, list one explicitly to pin its version
}
Then load the gems from your script with a plain require:
require_relative 'vendor/setup'
require 'dentaku'
What can and cannot work:
- Pure-Ruby gems work, and so do gems that ship a prebuilt JRuby jar (concurrent-ruby, for
example). Gems with C extensions fail at install time, which is the right moment to find out.
- Gems that read or write their own files on disk will not work from inside a jar.
- Vendoring redistributes the gems inside your jar. Check that each gem's license permits that
and attribute it as the license requires.
- If you release for both variants, build the vendor step per variant (the helper uses the JRuby
version you give it), so gem resolution matches the Ruby version your users run.
The example mod in src/testmod vendors dentaku this way, and every CI build
exercises the pipeline on both variants. If you would rather vendor by hand, the generated
setup.rb shows everything that is needed: each gem's require directory added to $LOAD_PATH as
uri:classloader:/<resource path> (all mod resources are on the shared classpath).
Calling Minecraft and Fabric API
Java interop is standard JRuby:
class MyRubyMod
java_import 'net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents'
def on_initialize
on_started = lambda do |server|
puts "server started: #{server.class.java_class.simple_name}"
end
ServerLifecycleEvents::SERVER_STARTED.register(
on_started.to_java(ServerLifecycleEvents::ServerStarted)
)
end
end
MyRubyMod
Important: Fabric API's Event#register(T) is a generic method, so JRuby cannot infer the
listener interface from a bare block. Convert explicitly with
lambda.to_java(TheListenerInterface) as above. For non-generic Java methods that take a
functional interface, passing a block directly works fine.
A note on class names per Minecraft era: on Minecraft 26.x and newer the game is unobfuscated,
so Ruby scripts can call Minecraft classes by their real (Mojang) names. On older versions
(1.14-1.21.x) Minecraft's own classes have intermediary names at runtime
(net.minecraft.class_310 style). Entrypoint interfaces, Fabric API, Fabric Loader API
(including FabricLoader.getInstance.getMappingResolver to translate names), and all Java
libraries are unaffected and keep their normal names.
Limitations
- No mixins from Ruby. Mixins need compile-time classes; a Ruby mod that requires them should
ship a small Java/mixin core alongside its Ruby entrypoints (both can live in one jar).
- No runtime gem installation. Vendor gems at build time instead, as explained above.
- Scripts targeting the legacy file should stick to Ruby 3.1 features (the modern file runs
Ruby 3.4).
Example mod
A complete working example lives in src/testmod: a mod written entirely in Ruby
that logs from its main entrypoint, uses require/require_relative, calls a vendored gem
(dentaku), and registers a Fabric API lifecycle callback. Run it against a dev server with:
./gradlew runTestmodServer
Building from source
Requires JDK 25 (the built jars still run on Java 8/21+ as described above).
./gradlew build # modern variant -> build/libs/*+jruby.10.*.jar
./gradlew build -Pvariant=legacy # legacy variant -> build/libs/*+jruby.9.4.*.jar
Each build runs the unit test suite against that variant's JRuby and also produces a standalone
example-mod jar (*-testmod.jar). JRuby is bundled jar-in-jar (org.jruby:jruby-core +
org.jruby:jruby-stdlib); Fabric Loader deduplicates nested jars by version if several installed
mods ship JRuby.
Versioning
<modVersion>+jruby.<bundledJRubyVersion>, for example 1.0.0+jruby.10.0.6.0. This mirrors
fabric-language-kotlin's scheme. Only the part before + participates in dependency resolution, so
"fabric-language-ruby": ">=1.0.0" matches both variant files.
License
MIT
评论 0
登录后参与评分
还没有评论,来抢沙发吧