guest@websec: ~/websec/r05-model-callbacks/th — zsh — 100×40 เขียนโดย SaKKo YouTube ENTH

guest@websec ~ % man r05-model-callbacks

Model Callback

callback คือ method ที่ Active Record เรียกให้ ณ จังหวะที่กำหนดในชีวิตของ record: ก่อน validate หลัง save หลัง transaction commit การรู้ลำดับที่แน่นอนคือความต่างระหว่างการตั้งค่า default อย่างเรียบร้อย กับ bug บน production

สร้างค่าเริ่มต้นที่ต้องใช้ตรวจความถูกต้องใน before_validation สั่งงานภายนอก (เช่น ส่งอีเมล ยิง Webhook เข้าคิว Job) ใน after_commit เท่านั้นเพื่อกันธุรกรรมถูกยกเลิกทีหลัง และจำไว้ว่า update_columns (รวมถึง soft_delete!) จะข้าม callback ปกติทั้งหมด

การลงทะเบียน callback

class User < ApplicationRecord
  before_validation :initialize_authentication_token, on: [:create]   # method name + options
  after_soft_delete :cascade_soft_delete                              # custom callback (see below)
end

class Role < ApplicationRecord
  after_commit :broadcast_webhook_event
  before_save :strip_name, if: :name_changed?                         # conditional
  after_create_commit -> { Rails.logger.info("role #{id} created") }  # a block works too
end

option: on: (:create, :update หรือ validation context ที่กำหนดเอง), if: / unless: (ชื่อ method หรือ lambda), prepend: true (ให้ทำงานก่อน callback ที่ประกาศไว้ก่อนหน้า)

callback ทั้งหมดตามลำดับ

createupdatedestroy
before_validationbefore_validationbefore_destroy
after_validationafter_validationaround_destroy
before_savebefore_saveDELETE
around_savearound_saveafter_destroy
before_createbefore_updateafter_commit / after_rollback
around_createaround_update
INSERTUPDATE
after_createafter_update
after_saveafter_save
after_commit / after_rollbackafter_commit / after_rollback

นอกจากนี้: after_initialize (ทุกครั้งที่ new และทุก record ที่โหลด), after_find (ทุก record ที่โหลด ก่อน after_initialize), after_touch ทางลัดของ commit: after_create_commit, after_update_commit, after_destroy_commit, after_save_commit

explorer: callback ไหนทำงานบ้าง?เลือก operation และสถานการณ์

สิ่งที่ควรสังเกต: การเขียนฐานข้อมูลอยู่ตรงกลาง after_save ทำงานก่อน commit ถ้าล้มเหลวที่ใดก็ตามก่อน COMMIT ทุกอย่างจะถูกยกเลิก และ soft_delete! / update_columns ข้ามเกือบทั้งหมด

callback ในโค้ดของเรา

before_validation, on: :create

class ClientApplication < ApplicationRecord
  before_validation :generate_credentials, on: :create

  validates :name, :app_key, :api_secret, presence: true
  validates :app_key, uniqueness: true
  ...

ทำไมใช้ before_validation ไม่ใช่ before_create? เพราะ before_create ทำงานหลัง validation ทำให้การตรวจ presence ของ app_key ล้มเหลวก่อน ค่าที่ validation ต้องใช้ ให้สร้างใน before_validation

after_commit

class Role < ApplicationRecord
  after_commit :broadcast_webhook_event

  def broadcast_webhook_event
    return if client_application.nil?

    event_type = determine_event_type          # created / updated / destroyed
    return if event_type.nil?
    # ignore saves where only updated_at changed
    return if event_type == "role.updated" && previous_changes.except("updated_at").empty?

    client_application.notify_webhook(event_type, role_payload)   # -> perform_later
  end

  def determine_event_type
    if destroyed? || deleted_at.present? then "role.destroyed"
    elsif previously_new_record? then "role.created"
    else "role.updated"
    end
  end
end

side effect ที่ออกนอกฐานข้อมูล (job, webhook, email) ต้องอยู่ใน after_commit เพราะใน after_save transaction ยังเปิดอยู่: job อาจเริ่มก่อนที่แถวจะมองเห็นได้ หรือ transaction อาจ rollback หลังจากส่ง webhook ไปแล้ว previous_changes และ previously_new_record? บอกว่าเพิ่งเกิดอะไรขึ้น

ข้อควรระวัง: soft_delete! เขียนข้อมูลด้วย update_columns ซึ่งข้าม after_commit ดังนั้น branch "role.destroyed" ข้างบนจะไม่ทำงานเมื่อ soft delete ถ้า client ต้องได้รับแจ้งการลบ ให้เรียก broadcast_webhook_event จาก after_soft_delete ลองเลือก role.soft_delete! ใน explorer ข้างบน

callback ที่นิยามเอง: define_model_callbacks

module SoftDeletable
  included do
    define_model_callbacks :soft_delete, :restore    # creates before_/around_/after_soft_delete etc.
    after_soft_delete :execute_cascade_soft_delete
    after_restore :execute_cascade_restore
    validate :ensure_unique_attributes_on_restore, on: :restore   # custom validation context
  end

  def soft_delete!
    return false if soft_deleted?
    run_callbacks :soft_delete do                     # before_* ... block ... after_*
      update_columns(deleted_at: Time.current, updated_at: Time.current)
    end
    true
  end

  def restore(context: :restore)
    self.deleted_at = nil
    return false unless valid?(context)               # runs validations tagged on: :restore
    run_callbacks(:restore) { update_columns(deleted_at: nil, updated_at: Time.current) }
    true
  end
end

define_model_callbacks ทำให้ operation ที่เราเขียนเองมี hook before_/around_/after_ เหมือน save ส่วน validation context (valid?(:restore)) ทำให้ validation หนึ่งทำงานเฉพาะ operation เดียว ในที่นี้ การ restore user ที่ username ถูกคนอื่นใช้ไปแล้วระหว่างที่ถูกลบ จะล้มเหลวอย่างเรียบร้อย

การจัดรูปข้อมูล: ใช้ writer ไม่ใช่ callback

def permissions=(values)
  super(Array(values).compact.map(&:to_s).sort)   # always a sorted array of strings
end

การ override writer ของ attribute ทำให้ค่าถูกจัดรูปทันทีที่กำหนด validation และ changed? จึงเห็นค่าที่สะอาดแล้ว Rails 7.1 ขึ้นไปยังมี normalizes :email, with: -> { _1.strip.downcase } สำหรับงานเดียวกัน

การหยุดและการข้าม

before_destroy :ensure_not_last_admin

def ensure_not_last_admin
  return unless is_admin? && User.where(is_admin: true).count == 1
  errors.add(:base, "Cannot remove the last admin")
  throw :abort                     # stops the chain; destroy returns false / destroy! raises
end

method เหล่านี้ข้าม callback และ validation ทั้งหมด ให้ใช้อย่างตั้งใจ อย่าใช้โดยไม่รู้ตัว:

update_column · update_columns · update_all · delete · delete_all · delete_by · insert / insert_all · upsert / upsert_all · increment! · decrement! · touch_all · update_counters

หลักการทั่วไป

  • callback ควรเกี่ยวกับrecord นี้: ค่า default, key ที่สร้างอัตโนมัติ, การจัดรูปค่า, การ cascade soft delete
  • อะไรก็ตามที่ออกนอก process (HTTP, email, webhook) ให้อยู่ใน after_commit และปกติแค่ส่ง job เข้าคิว
  • ห้ามเรียก service ภายนอกที่ช้าใน before_* หรือ after_save เพราะจะทำให้ transaction ของฐานข้อมูลเปิดค้าง
  • ถ้า callback ต้องรู้ว่าใครทำ หรือ endpoint ไหนถูกเรียก แปลว่าควรอยู่ใน controller หรือ service แทน

ลองเช็กความเข้าใจ

ต้องส่งอีเมลหาผู้ใช้หลังจากสร้างบัญชี ใช้ callback ไหน?

หลัง commit แถวของ user มีอยู่จริงแน่นอนสำหรับ mail job ให้ส่งเข้าคิวด้วย deliver_later

before_create :set_code ตั้งค่าที่ validates :code, presence: true ตรวจอยู่ แต่ save แล้วล้มเหลวด้วย "Code can't be blank" ทำไม?

ย้ายไปไว้ที่ before_validation :set_code, on: :create แบบเดียวกับ generate_credentials