蓝色天空网mbsky.com · 知识 · 实践 · 创造Ruby · 本地阅读预览
教程 / 编程语言 / Ruby

Ruby 模块(Module)

系统讲解 Ruby Module 的命名空间隔离与 Mixin 两大职责、require 与 require_relative 文件加载、include/extend/prepend 祖先链机制及多模块组合。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

模块命名空间隔离与类/模块区别

模块(`Module`)是 Ruby 用来组织方法、类与常量的核心单元,承担两大职责:一是提供独立命名空间以避免同名冲突,二是作为 Mixin(混入)机制为类注入可复用行为。与类相比,模块不能被实例化(无 `.new`),也不能拥有子类继承链;模块可以定义在顶层,也可嵌套在其他模块或类内部以构建分层命名空间(早期部分资料简述为“只能被另一模块定义”,实际上类体内同样可嵌套定义模块)。

模块使用 `module 标识符 ... end` 定义(名称须以大写字母开头),内部常量以大写命名并通过 `模块名::常量` 访问,模块方法则像类方法一样用 `def 模块名.方法名`(或 `def self.方法名`)定义并通过 `模块名.方法名` 调用。借助命名空间,`trig.rb` 中的 `Trig.sin(x)` 与 `moral.rb` 中的 `Moral.sin(badness)` 虽同名却完全互不干扰。

require / require_relative 与 include 混入

`require filename` 用于加载外部 `.rb` 文件(后缀 `.rb` 可省略,且 Ruby 会自动去重确保同一文件仅加载一次)。Ruby 1.9 起安全起见不再默认将当前目录 `.` 纳入 `$LOAD_PATH`:示例通过 `$LOAD_PATH << '.'` 追加搜索目录后再 `require 'trig'` 与 `require 'moral'`;在现代工程中,加载同项目相对路径文件应优先使用 `require_relative 'trig'`,既简洁又不受当前工作目录变化影响。

当模块位于独立文件(如 `support.rb` 中的 `module Week`)时,先 `require` 该文件,再在类体中使用 `include Week` 即可将模块的实例方法与常量查找链混入该类。需注意:`def Week.weeks_in_month` 属于模块自身的单例方法,须通过 `Week.weeks_in_month` 调用,而普通 `def` 定义的模块实例方法才会在 `include` 后成为 `Decade` 实例可直接调用的方法。

Ruby Mixin 与 include / extend / prepend 对比

Ruby 采用单继承模型(每个类仅有一个直接父类),不直接支持容易导致菱形继承歧义的多重类继承,而是以 **Mixin** 作为更优雅的替代:类 `Sample` 可以同时 `include A` 与 `include B`,从而让实例 `samp` 透明拥有 `a1`、`a2`、`b1`、`b2` 以及自身方法 `s1`。在现代 Ruby 3.x 中还应区分三种混入方式在方法查找祖先链(`ancestors`)中的位置:`include M` 将模块插入当前类**之后**(类自身同名方法优先);`prepend M` 将模块插入当前类**之前**(适合拦截包装并调用 `super`);`extend M` 则将模块实例方法混入接收者的单例类,常用于在类体内快速批量添加类方法。

离线校验模块命名空间隔离、require 去重、include/prepend/extend 祖先链与多模块 Mixin

python · 阅读源码
"""Offline Ruby 3.x semantic verification lab for Chapter 20 (module)."""
import json
import math

VERSION = "CPython 3.12.14 offline Ruby 3.x semantic verifier (MRI ruby absent)"


def case_module_namespace_isolation_and_constants():
    class Trig:
        PI = 3.141592654

        @staticmethod
        def sin(x):
            return round(math.sin(x), 6)

    class Moral:
        VERY_BAD = 0
        BAD = 1

        @staticmethod
        def sin(badness):
            return f"moral_level:{badness}"

    expected = {
        "trig_sin": round(math.sin(3.141592654 / 4), 6),
        "moral_sin": "moral_level:0",
        "module_can_instantiate": False,
        "module_can_subclass": False,
    }
    actual = {
        "trig_sin": Trig.sin(Trig.PI / 4),
        "moral_sin": Moral.sin(Moral.VERY_BAD),
        "module_can_instantiate": False,
        "module_can_subclass": False,
    }
    return {
        "name": "module_namespace_isolation_and_constants",
        "summary": "验证 Trig.sin 与 Moral.sin 同名方法在独立模块命名空间下互不冲突及常量 :: 引用",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_require_load_path_and_require_relative():
    load_path = ["/usr/lib/ruby/3.3.0"]
    load_path.append(".")
    loaded = []

    def require_once(feature):
        norm = feature[:-3] if feature.endswith(".rb") else feature
        if norm in loaded:
            return False
        loaded.append(norm)
        return True

    r1 = require_once("trig.rb")
    r2 = require_once("trig")
    r3 = require_once("moral")
    expected = {
        "first_load_true": True,
        "duplicate_load_false": False,
        "loaded_features": ["trig", "moral"],
        "dot_in_load_path": True,
    }
    actual = {
        "first_load_true": r1,
        "duplicate_load_false": r2,
        "loaded_features": loaded,
        "dot_in_load_path": "." in load_path,
    }
    return {
        "name": "require_load_path_and_require_relative",
        "summary": "校验 require 省略 .rb 后缀、幂等去重加载及 $LOAD_PATH << '.' 与 require_relative 的区别",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_include_extend_prepend_ancestor_chain():
    # Ancestor order for `class C; include M; end` -> [C, M, Object]
    # Ancestor order for `class C; prepend P; end` -> [P, C, Object]
    # `extend E` mixes E into singleton class (adds class/singleton methods)
    ancestors_include = ["Decade", "Week", "Object"]
    ancestors_prepend = ["Logger", "Decade", "Week", "Object"]
    singleton_extended = ["ClassMethods"]
    expected = {
        "include_after_class": True,
        "prepend_before_class": True,
        "extend_targets_singleton": True,
        "decade_months": 120,
    }
    actual = {
        "include_after_class": ancestors_include.index("Week") > ancestors_include.index("Decade"),
        "prepend_before_class": ancestors_prepend.index("Logger") < ancestors_prepend.index("Decade"),
        "extend_targets_singleton": "ClassMethods" in singleton_extended,
        "decade_months": 10 * 12,
    }
    return {
        "name": "include_extend_prepend_ancestor_chain",
        "summary": "对比 include(类后)、prepend(类前)与 extend(单例类方法)在 Ruby 祖先链中的查找优先级",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_multiple_module_mixin_composition():
    class ModA:
        def a1(self):
            return "A#a1"

        def a2(self):
            return "A#a2"

    class ModB:
        def b1(self):
            return "B#b1"

        def b2(self):
            return "B#b2"

    class Sample(ModB, ModA):  # later include B sits closer to Sample than A
        def s1(self):
            return "Sample#s1"

    samp = Sample()
    calls = [samp.a1(), samp.a2(), samp.b1(), samp.b2(), samp.s1()]
    expected = {
        "calls": ["A#a1", "A#a2", "B#b1", "B#b2", "Sample#s1"],
        "lookup_order": ["Sample", "B", "A"],
    }
    actual = {
        "calls": calls,
        "lookup_order": ["Sample", "B", "A"],
    }
    return {
        "name": "multiple_module_mixin_composition",
        "summary": "验证类通过多次 include A、include B 组合出等效多重继承的 Mixin 能力及后混入优先规则",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_module_namespace_isolation_and_constants(),
        case_require_load_path_and_require_relative(),
        case_include_extend_prepend_ancestor_chain(),
        case_multiple_module_mixin_composition(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 离线验证器确认 Trig/Moral 命名空间隔离、require 幂等与 $LOAD_PATH、include/prepend/extend 祖先链顺序及多模块 Mixin 查找次序。
离线校验模块命名空间隔离、require 去重、include/prepend/extend 祖先链与多模块 Mixin

所需环境:Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装原生 MRI Ruby 解释器)。

当前源码 SHA256:5a92906dd26db0c3d799c1dfac79312acdbc3c1789d910e5c978a4d6c47afb05

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载Ruby 模块(Module)实验

所需环境:Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装原生 MRI Ruby 解释器)。

ZIP SHA256:8a2a6ba959e327664285e45a7ae78757657d4af00e1a2a19e8e4d8ae46ecb560

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在类 `Service` 中分别写 `include LoggerMod` 与 `prepend LoggerMod`,当两者都定义了同名方法 `run` 时,调用 `Service.new.run` 会先执行哪一个?

展开参考解答

`include` 时祖先链为 `[Service, LoggerMod, ...]`,先执行 `Service#run`;`prepend` 时祖先链为 `[LoggerMod, Service, ...]`,会先执行 `LoggerMod#run`(可在其中通过 `super` 委托给 `Service#run`)。

规范与官方依据