为了避免造成 Model 文件过长,把 callbacks 移到 Subscriber 中。
当更新商品价格时,需要更新相关订单的价格。
class Product < ApplicationRecord
has_many :orders
after_update do
if price_changed?
orders.each do |order|
order.update! price: price
end
end
end
end
# ./app/subscribers/order_subscriber.rb
subscribe_model :product, :after_update do
if price_changed?
orders.each do |order|
order.update! price: price
end
end
end
# ./config/initializers/subscribe_model.rb
def subscribe_model(model_name, event_name, &block)
ActiveSupport::Notifications.subscribe("active_record.#{model_name}.#{event_name}") do |_name, _started, _finished, _unique_id, data|
data[:model].instance_eval(&block)
end
end
class ActiveRecord::Base
class_attribute :skip_model_subscribers
self.skip_model_subscribers = false
end
%i(after_create after_update after_destroy after_save after_commit after_create_commit after_update_commit).each do |name|
ActiveRecord::Base.public_send(name) do
unless skip_model_subscribers
readonly! unless readonly?
ActiveSupport::Notifications.instrument "active_record.#{self.class.model_name.singular}.#{name}", model: self
ActiveSupport::Notifications.instrument "active_record.#{self.class.base_class.model_name.singular}.#{name}", model: self if self.class.base_class != self.class
public_send(:instance_variable_set, :@readonly, false)
end
end
end
Rails.application.config.after_initialize do
Dir[Rails.root.join('app/subscribers/*.rb')].each { |f| require f }
end
Q: 为什么不用 concern?
A: 团队内部约定,只有两个及以上的 model 有共用代码,才能移到 concern。
Q: 为什么不创建 service 层?
A: service 层不够直观,而且对于小型团队来说,维护成本高于 subscriber。