Rails 中的 Service Objects 確實是個很有趣的討論點。讓我分享一下我的想法:
- 最適合的使用場景:
- 複雜的表單提交處理:
class UserRegistrationService
def initialize(user_params, plan_type)
@user_params = user_params
@plan_type = plan_type
end
def call
ActiveRecord::Base.transaction do
user = User.create!(@user_params)
subscription = create_subscription(user)
send_welcome_email(user)
notify_admin(user)
user
end
end
end
第三方API整合:
class PaymentProcessingService
def initialize(order, payment_method)
@order = order
@payment_method = payment_method
end
def process
begin
payment = stripe_charge
update_order_status
send_receipt
true
rescue Stripe::Error => e
handle_payment_error(e)
false
end
end
end
複雜的資料處理:
class ReportGenerationService
def initialize(start_date, end_date)
@start_date = start_date
@end_date = end_date
end
def generate
sales_data = collect_sales_data
process_statistics(sales_data)
generate_pdf
end
end
Service 一些設計原則:
- 單一職責:每個service只做一件事
- 可測試性:容易寫單元測試
- 依賴注入:通過初始化傳入依賴
- 明確的公共介面:通常是
call
或具有描述性的方法名