Class: GovukPublishingComponents::Middleware::Ga4Optimise

Inherits:
Object
  • Object
show all
Defined in:
lib/govuk_publishing_components/middleware/ga4_optimise.rb

Constant Summary collapse

DATA_GA4_REGEX =
/data-ga4-(?:link|event|form|focus-loss)=("[^"]*")/

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Ga4Optimise

Returns a new instance of Ga4Optimise.



6
7
8
# File 'lib/govuk_publishing_components/middleware/ga4_optimise.rb', line 6

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/govuk_publishing_components/middleware/ga4_optimise.rb', line 10

def call(env)
  status, headers, response = @app.call(env)
  return [status, headers, safe_body_from_response(response)] unless headers["content-type"]&.start_with?("text/html")

  body = response.each.first
  matched_sections = body.scan(DATA_GA4_REGEX)

  if matched_sections.any?
    matched_sections.each do |section|
      body.sub!(section.first, section.first.gsub('"', "'").gsub("&quot\;", '"'))
    end
  end

  [status, headers, [body]]
end

#safe_body_from_response(response) ⇒ Object



26
27
28
29
30
# File 'lib/govuk_publishing_components/middleware/ga4_optimise.rb', line 26

def safe_body_from_response(response)
  return [response.body] if response.respond_to?(:body)

  response
end