method_missing 是 Ruby 元編程核心,但濫用會導致效能劣化與除錯困難。本文對比「方法代理」應用場景、展示 define_method 緩存優化、規範動態方法 (元方法) 適用條件、制定四步驟正確使用模式。
class A; def hi; puts "Hi from #{self.class}"; end; end
class B
def initialize; @b = A.new; end
def method_missing(name, *args, &block)
@b.send(name, *args, &block)
end
end
B.new.hi # 每次調用都走完繼承鏈觸發 method_missing
問題:每次呼叫都遍歷完整繼承鏈 (Rails 模型繼承鏈極深) 才觸發 method_missing,效能損耗大。
class B
def initialize; @b = A.new; end
[:hi, :bye, :achoo].each do |m|
define_method(m) { @b.send(m) }
end
end
優點:類別載入時一次性定義,後續呼叫直接命中實體方法,零額外開銷。
A.instance_methods.each do |name|
define_method("what_is_#{name}") do
@b.respond_to?(name) ? @b.send(name) : false
end
end
只有當「方法集合極大且稀疏使用」時,如 ActiveRecord 動態查找器 find_by_*:
define_method (記憶體/啟動時間不可接受)。method_missing 按需動態響應,配合 define_method 緩存熱點方法。
def method_missing(method_id, *args, &block)
if method_id.to_s =~ /^what_is_\w+$/ # 1. 先檢查模式
self.class.send :define_method, method_id do # 2. 包進 define_method 緩存
# 實際業務邏輯
end
send(method_id, *args, &block) # 執行新定義的方法
else
super # 3. 善後:交給父類
end
end
def respond_to?(method_id, include_private=false) # 4. 昭告天下
method_id.to_s =~ /^what_is_\w+$/ || super
end
define_method 是日常好基友,優先使用。method_missing 是元方法情婦,僅在方法空間極大且稀疏時使用。