Module: LogStruct::Integrations::Ahoy

Extended by:
T::Sig
Defined in:
lib/log_struct/integrations/ahoy.rb

Overview

Ahoy analytics integration. If Ahoy is present, prepend a small hook to Ahoy::Tracker#track to emit a structured log for analytics events.

Class Method Summary collapse

Class Method Details

.properties_for_log(properties) ⇒ Hash{Symbol => T.untyped}?

Event properties can come from the browser, so they can be anything; a non-Hash is logged as its class

Parameters:

  • properties (T.untyped)

Returns:

  • (Hash{Symbol => T.untyped}, nil)


47
48
49
50
51
52
53
54
# File 'lib/log_struct/integrations/ahoy.rb', line 47

def self.properties_for_log(properties)
  properties = properties.to_unsafe_h if properties.respond_to?(:to_unsafe_h)
  case properties
  when nil then nil
  when Hash then properties.to_h { |key, value| [key.to_s.to_sym, value] }
  else {_class: properties.class.name}
  end
end

.setup(config) ⇒ true?

Parameters:

Returns:

  • (true, nil)


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/log_struct/integrations/ahoy.rb', line 12

def self.setup(config)
  return nil unless defined?(::Ahoy)

  if defined?(::Ahoy::Tracker)
    mod = Module.new do
      extend T::Sig

      # Takes whatever Ahoy's track takes and passes it on as given, so Ahoy's defaults still apply
      sig { params(name: T.untyped, args: T.untyped).returns(T.untyped) }
      def track(name, *args)
        result = super
        begin
          LogStruct.info(
            LogStruct::Log::Ahoy.new(
              message: "ahoy.track",
              ahoy_event: name.to_s,
              properties: Integrations::Ahoy.properties_for_log(args.first)
            )
          )
        rescue => e
          # A problem with the log line is LogStruct's, and never fails the app's tracking call in production
          LogStruct.handle_exception(e, source: LogStruct::Source::Internal, context: {integration: :ahoy})
        end
        result
      end
    end

    ::Ahoy::Tracker.prepend(mod)
  end

  true
end