Class: Railscope::Subscribers::ModelSubscriber

Inherits:
BaseSubscriber show all
Defined in:
lib/railscope/subscribers/model_subscriber.rb

Constant Summary collapse

IGNORED_MODEL_PREFIXES =
%w[Railscope:: ActiveRecord::].freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.subscribe ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/railscope/subscribers/model_subscriber.rb', line 8

def self.subscribe
  return if @subscribed

  @subscribed = true

  Rails.logger.info("[Railscope] ModelSubscriber.subscribe called - registering callbacks on ActiveRecord::Base")

  ActiveRecord::Base.after_create_commit do
    Rails.logger.debug("[Railscope] after_create_commit fired for #{self.class.name}:#{self.id}")
    Railscope::Subscribers::ModelSubscriber.track("created", self)
  end

  ActiveRecord::Base.after_update_commit do
    Rails.logger.debug("[Railscope] after_update_commit fired for #{self.class.name}:#{self.id}")
    Railscope::Subscribers::ModelSubscriber.track("updated", self)
  end

  ActiveRecord::Base.after_destroy_commit do
    Rails.logger.debug("[Railscope] after_destroy_commit fired for #{self.class.name}:#{self.id}")
    Railscope::Subscribers::ModelSubscriber.track("deleted", self)
  end
end

.track(action, model) ⇒ Object



31
32
33
34
# File 'lib/railscope/subscribers/model_subscriber.rb', line 31

def self.track(action, model)
  Rails.logger.debug("[Railscope] ModelSubscriber.track(#{action}, #{model.class.name}:#{model.id})")
  new.record(action: action, model: model)
end

Instance Method Details

#record(action:, model:) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/railscope/subscribers/model_subscriber.rb', line 36

def record(action:, model:)
  Rails.logger.debug("[Railscope] ModelSubscriber.record - enabled=#{Railscope.enabled?} ready=#{Railscope.ready?} recording=#{recording?}")

  return unless Railscope.enabled?
  return unless Railscope.ready?

  model_name = model.class.name
  return if model_name.nil?
  return if IGNORED_MODEL_PREFIXES.any? { |prefix| model_name.start_with?(prefix) }
  return unless Railscope.should_track_model?(model_name)

  create_entry!(
    entry_type: "model",
    payload: build_payload(action, model),
    tags: build_tags(action, model),
    family_hash: build_family_hash(action, model),
    should_display_on_index: true
  )

  # Conditional recording: flush buffered entries when trigger matches
  if Railscope.conditional_recording? && !context.triggered? && Railscope.matches_trigger?(model_name, action)
    context.trigger!
    context.flush_pending!
  end

  Rails.logger.debug("[Railscope] ModelSubscriber - entry created for #{model_name}")
rescue StandardError => e
  Rails.logger.error("[Railscope] Failed to record model event: #{e.class}: #{e.message}")
  Rails.logger.error(e.backtrace&.first(5)&.join("\n"))
end