DEV Community

Discussion on: Using Rails secret weapon: ActiveSupport::Notifications

Collapse
 
hamled profile image
Charles Ellis

I'm unclear on why the real world example provided is preferable to an implementation that calls MyMetricsService.send directly (or indirectly through dependency injection).

Could you elaborate?

Collapse
 
hugodias profile image
Hugo Dias • Edited

Of course, Charles, and sorry if the example was confusing.

This API is a good use if you want to keep up with what is going on with your application under the hood.

Assuming that MyMetricsService.send is a service that sends a request to segment, now you need also to save this data to a log.

In this example you can add another line in that same event:

ActiveSupport::Notifications.subscribe /metrics/ do |*args|
  event = ActiveSupport::Notifications::Event.new(*args)
  MyMetricsService.send(event.name, event.payload)
  MyLogger.save(event)
end

You can also subscribe to a specific type of events and handle differently.

ActiveSupport::Notifications.subscribe /metrics.purchase/ do |*args|
  event = ActiveSupport::Notifications::Event.new(*args)
  NotifySales.call(event)
end

As you can see, you would need to change this in just one place.

The idea is basically to publish that something happened on the application and you can subscribe to this event.