Class: BackfillSecurityFieldsInAhoyEvents

Inherits:
Object
  • Object
show all
Defined in:
lib/generators/ruby_cms/templates/db/migrate/20251216064753_backfill_security_fields_in_ahoy_events.rb

Instance Method Summary collapse

Instance Method Details

#downObject



46
47
48
# File 'lib/generators/ruby_cms/templates/db/migrate/20251216064753_backfill_security_fields_in_ahoy_events.rb', line 46

def down
  # no-op (we intentionally do not restore properties)
end

#upObject



2
3
4
5
6
7
8
9
10
11
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
44
# File 'lib/generators/ruby_cms/templates/db/migrate/20251216064753_backfill_security_fields_in_ahoy_events.rb', line 2

def up
  say_with_time "Backfilling Ahoy::Event columns from properties and clearing properties..." do
    Ahoy::Event.find_in_batches(batch_size: 1_000) do |events|
      events.each do |event|
        props =
          begin
            case event.properties
            when String
              JSON.parse(event.properties)
            when Hash
              event.properties
            else
              {}
            end
          rescue JSON::ParserError
            {}
          end

        updates = {}

        # Universal mapping (works for both security + page_view events)
        ip_from_props = props["ip_address"] || props["ip"]
        ua_from_props = props["user_agent"]
        path_from_props = props["request_path"] || props["path"]
        desc_from_props = props["description"]
        page_name_from_props = props["page_name"]

        updates[:ip_address] = ip_from_props if event.ip_address.blank? && ip_from_props.present?
        updates[:user_agent] = ua_from_props if event.user_agent.blank? && ua_from_props.present?
        updates[:request_path] = path_from_props if event.request_path.blank? && path_from_props.present?

        updates[:description] = desc_from_props if event.respond_to?(:description) && event.description.blank? && desc_from_props.present?
        # Page views: copy page_name into its new column (if present)
        updates[:page_name] = page_name_from_props if event.respond_to?(:page_name) && event.page_name.blank? && page_name_from_props.present?

        # Stop using properties going forward: clear it once we’ve extracted whatever we can
        updates[:properties] = nil if event.properties.present?

        event.update_columns(updates) if updates.any?
      end
    end
  end
end