檔案載入:require vs load
| 特性 | require | load |
| 載入次數 | 只載入一次(快取 $LOADED_FEATURES) | 每次呼叫都重新載入 |
| 副檔名 | 可省略 .rb | 必須完整檔名 |
| 適用場景 | 函式庫、Gem、不常變動的程式碼 | 設定檔、開發中頻繁修改的檔案 |
| 回傳值 | 首次載入 true,重複 false | 總是 true |
# require 'library' # 載入 library.rb (一次)
# load 'config.rb' # 每次都重新載入 config.rb
模組混入:include vs extend
| 特性 | include | extend |
| 方法變成 | 實例方法 | 類別方法(單例方法) |
| 呼叫方式 | obj.method | Class.method |
| 變數共享 | 模組實例變數在各實例間獨立 | 模組實例變數在類別層級共享 |
| 查找鏈 | 插入類別的祖先鏈 | 插入類別的單例類別祖先鏈 |
include 範例:實例方法
module Greeting
def hello
"Hello, #{self.class}!"
end
end
class Person
include Greeting
end
Person.new.hello # => "Hello, Person!"
extend 範例:類別方法
module ClassInfo
def description
"This is #{self}"
end
end
class User
extend ClassInfo
end
User.description # => "This is User"
進階:include 不會複製方法
module M
def foo; "original"; end
end
class A; include M; end
class B; include M; end
M.module_eval { define_method(:foo) { "modified" } }
A.new.foo # => "modified"
B.new.foo # => "modified"
# 兩類別共享同一模組方法定義,動態修改即時生效
常見組合模式
# 檔案載入 + 混入
require 'my_module'
class MyClass
include MyModule # 實例方法
extend MyModule # 類別方法(若模組設計支援)
end
# ActiveSupport::Concern 模式(Rails)
module MyConcern
extend ActiveSupport::Concern
included do
# 類別層級執行:scope, validates, has_many 等
end
class_methods do
# 定義類別方法
end
end