使用 Rails 秘密武器:ActiveSupport::Notifications

2025-06-07

使用 Rails 秘密武器:ActiveSupport::Notifications

最初发表在我的博客中

Ruby on Rails 有一个强大的武器,但并非所有开发人员都知道它的存在。Rails框架使用ActiveSupport Instrumentations来处理应用程序运行时发生的事件。

Active Support 提供的 Instrumentation API 允许开发者提供钩子,供其他开发者使用。Rails 框架中提供了多个这样的钩子。通过此 API,开发者可以选择在其应用程序或其他 Ruby 代码中发生某些事件时接收通知。

幸运的是我们可以使用这个工具。

工作原理

它看起来像一个PUB/SUB图案。

在软件架构中,发布-订阅是一种消息传递模式。在这种模式下,消息的发送者(称为发布者)不会将消息直接发送给特定的接收者(称为订阅者)。相反,发布的消息会被划分为不同的类别,而并不知道具体的订阅者(如果有)。同样,订阅者会表达对一个或多个类别的兴趣,并且只接收感兴趣的消息,而不知道具体的发布者(如果有)。——维基百科

订阅活动非常简单:

# config/initializers/events.rb
ActiveSupport::Notifications.subscribe "my_custom.event" do |*args|
  event = ActiveSupport::Notifications::Event.new(*args)
end
Enter fullscreen mode Exit fullscreen mode

事件变量将包含类似这样的内容

=> #<ActiveSupport::Notifications::Event:0x0000559258433df8
 @children=[],
 @duration=nil,
 @end=2018-07-03 12:47:46 +0000,
 @name="my_custom.event",
 @payload={:foo=>"bar"},
 @time=2018-07-03 12:47:46 +0000,
 @transaction_id="37bb01f75132e0c0505publisher6">
Enter fullscreen mode Exit fullscreen mode

注意到了吗@payload?我们可以在事件中发送额外的数据。

检测事件

有一种方法叫做instrument发布事件。

你可以像这样使用它:

ActiveSupport::Notifications.instrument "my_custom.event", { foo: "bar" }
Enter fullscreen mode Exit fullscreen mode

很简单吧?

现实世界的例子

假设您有一个处理应用程序指标的外部服务,例如 Segment.IO、Keen IO 等。

您可以使用此模式将事件发送到其中一个服务。

# config/initializers/events.rb
# We can use regex to subscribe!
ActiveSupport::Notifications.subscribe /metrics/ do |*args|
  event = ActiveSupport::Notifications::Event.new(*args)
  MyMetricsService.send(event.name, event.payload)
end

# app/controllers/my_controller.rb
def create
  # some code
  ActiveSupport::Notifications.instrument "metrics.item_purchased", { uid: item.id }
end
Enter fullscreen mode Exit fullscreen mode

您可以在此处阅读有关ActiveSupport Instrumentation 的更多信息

希望有帮助:)


照片由Ciprian Boiciuc 在 Unsplash 上拍摄

文章来源:https://dev.to/hugodias/using-rails-secret-weapon-activesupportnotifications-12d3
PREV
你应该知道的 PhpStorm 插件
NEXT
FAANG - Guia Descomplicado de Entrevistas - 第 1 部分