Module: Shrine::Plugins::Instrumentation::ClassMethods

Defined in:
lib/shrine/plugins/instrumentation.rb

Instance Method Summary collapse

Instance Method Details

#instrument(event_name, payload = {}, &block) ⇒ Object

Sends a `*.shrine` event.

# sends a `my_event.shrine` event
Shrine.instrument(:my_event) do
  # work
end

29
30
31
32
33
# File 'lib/shrine/plugins/instrumentation.rb', line 29

def instrument(event_name, payload = {}, &block)
  payload[:uploader] = self

  notifications.instrument("#{event_name}.shrine", payload, &block)
end

#subscribe(event_name, &subscriber) ⇒ Object

Subscribes to a `*.shrine` event. It rejects duplicate subscribers.

# subscribes to the `storage_upload.shrine` event
Shrine.subscribe(:storage_upload) do |event|
  event.name #=> :storage_upload
  event.payload #=> { location: "...", ... }
  event[:location] #=> "..."
  event.duration #=> 50 (in milliseconds)
end

44
45
46
47
48
49
50
51
52
53
54
# File 'lib/shrine/plugins/instrumentation.rb', line 44

def subscribe(event_name, &subscriber)
  return if subscriber.nil?
  return if subscribers[event_name]&.include?(subscriber)

  notifications.subscribe("#{event_name}.shrine") do |event|
    subscriber.call(event) if event[:uploader] <= self
  end

  subscribers[event_name] ||= []
  subscribers[event_name] << subscriber
end