Ruby 的設計哲學核心在於「讓程式設計師快樂」,其強大的元編程能力正是實現這一目標的關鍵。鉤子方法 作為 Ruby 運行時擴展行為的核心機制,讓我們能在類別繼承、模組混入、方法調用等關鍵時機攔截並自定義邏輯。本文將系統剖析五大核心鉤子方法,並結合 Devise、ActiveRecord 等知名框架的原始碼實例,展示其在實戰中的優雅應用。
鉤子方法提供了一種在程式運行時動態擴展行為的機制。典型場景包括:
include/extend/prepend 時執行額外邏輯NoMethodError)不同框架透過組合這些鉤子,實現了 DSL 風格的 API、自動程式碼生成、跨領域關注點分離等高級功能。
當模組被 include 進類別時呼叫,接收包含該模組的類別作為參數 base。
module Person
def self.included(base)
puts "#{base} included #{self}"
end
def name
"My name is Person"
end
end
class User
include Person
end
User.new.name
# 輸出:
# User included Person
# My name is Person
Devise 的 devise :database_authenticatable, :validatable 語法背後,正是利用 included 鉤子在模型類別中動態注入驗證規則:
module Devise::Models::Validatable
def self.included(base)
base.extend ClassMethods
assert_validations_api!(base)
base.class_eval do
validates_presence_of :email, if: :email_required?
validates_uniqueness_of :email, allow_blank: true, if: :email_changed?
validates_format_of :email, with: email_regexp, allow_blank: true, if: :email_changed?
validates_presence_of :password, if: :password_required?
validates_confirmation_of :password, if: :password_required?
validates_length_of :password, within: password_length, allow_blank: true
end
end
end
class_eval 讓驗證宏直接在目標類別上下文中執行,實現「零配置」驗證。
extend 將模組方法作為類別方法(或單例方法)混入,而非實例方法。
module Person
def name
"My name is Person"
end
end
class User
extend Person
end
User.name # => "My name is Person"
# 單例方法示例
u1 = User.new
u1.extend Person
u1.name # => "My name is Person"
User.new.name # => NoMethodError
prepend 將模組插入繼承鏈的最前端,方法查找優先級高於類別本身,適合「裝飾器」模式或修補既有行為。
module Logging
def self.prepended(base)
puts "#{base} prepended #{self}"
end
def call
puts "Before call"
super
puts "After call"
end
end
class Service
prepend Logging
def call; puts "Service running"; end
end
Service.new.call
# 輸出:
# Service prepended Logging
# Before call
# Service running
# After call
追蹤類別體系擴展,常用於註冊子類別、自動建立 STI(單表繼承)對應等。
class Animal
def self.inherited(subclass)
puts "#{subclass} inherited from #{self}"
(@@subclasses ||= []) << subclass
end
end
class Dog < Animal; end
class Cat < Animal; end
Animal.class_variable_get(:@@subclasses) # => [Dog, Cat]
動態代理、DSL 建構、委派模式的核心基石。
class Router
def method_missing(name, *args, &block)
if name.to_s =~ /^route_to_(.+)$/
destination = $1
puts "Routing to #{destination} with args: #{args}"
else
super
end
end
def respond_to_missing?(name, include_private = false)
name.to_s.start_with?('route_to_') || super
end
end
Router.new.route_to_home(user: 'admin') # => Routing to home with args: [{:user=>"admin"}]
| 鉤子 | 觸發時機 | 典型用途 | 接收參數 |
|---|---|---|---|
included | 模組被 include | 混入實例方法、注入驗證/回調 | base (包含類別) |
extended | 模組被 extend | 混入類別/單例方法 | base (擴展對象) |
prepended | 模組被 prepend | 方法修飾、前置攔截 | base (前置類別) |
inherited | 類別被繼承 | 子類別註冊、STI 設定 | subclass (子類別) |
method_missing | 調用不存在方法 | 動態代理、DSL、委派 | name, *args, &block |
掌握鉤子方法,即掌握了 Ruby 元編程的靈魂。它們讓框架作者能創造出極具表達力的 API,也讓應用開發者能以極小代價實現橫切關注點。下次當你看到 include SomeModule 就能自動獲得神奇功能時,記得背後正是這些鉤子在默默工作。