人生就是不斷學習,調整與更新持續前進。

探索與分享 Rails xxx_service.rb 的定義與應用定位?!

Rails 中的 Service Objects 確實是個很有趣的討論點。讓我分享一下我的想法:

  1. 最適合的使用場景:

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 一些設計原則: