模組是 Ruby 實現程式碼組織、命名空間隔離與多重繼承替代方案的核心機制。本文詳細解析模組定義、require/include 機制、Mixin 模式實現原理與實戰應用模式。
模組將方法、類別、常數組織在一起,提供兩大效益:
語法:
module Identifier
statement1
statement2
...
end
常數首字母大寫,模組方法定義如 module Trig; def Trig.sin(x); end; end。呼叫方式:Trig.sin(Trig::PI/4)。
require 'trig.rb'
require 'moral'
y = Trig.sin(Trig::PI/4)
wrongdoing = Moral.sin(Moral::VERY_BAD)
模組避免同名方法衝突,透過模組名稱限定呼叫。
將模組實例方法混入類別,成為該類別的實例方法:
require "support"
class Decade
include Week
no_of_yrs = 10
def no_of_months
puts Week::FIRST_DAY
number = 10 * 12
puts number
end
end
輸出:
Sunday
You have four weeks in a month
You have 52 weeks in a year
Sunday
120
Ruby 不支援類別多重繼承,但類別可 include 多個模組:
module A
def a1; end
def a2; end
end
module B
def b1; end
def b2; end
end
class Sample
include A
include B
def s1; end
end
samp = Sample.new
samp.a1; samp.a2; samp.b1; samp.b2; samp.s1
Sample 實例擁有 A、B 所有方法,實現「多重繼承」效果。查找順序:類別本身 → 最後 include 的模組 → 最先 include 的模組 → 父類別 → ... → Object → Kernel → BasicObject。
module Greeting
def hello; "Hello"; end
end
class MyClass
extend Greeting
end
MyClass.hello # => "Hello"
prepend 將模組插入繼承鏈最前端,可覆寫類別方法並透過 super 呼叫原實現:
module Log
def call
puts "Before"
super
puts "After"
end
end
class Service
prepend Log
def call; puts "Service"; end
end
Service.new.call
# Before / Service / After
include 實現行為共享,extend 用於類別層級擴展。prepend 實現裝飾器模式、日誌攔截等橫切關注點。CamelCase,檔名用 snake_case。