From 6ea7e4a76af4d23cd8abc41a82a613369e088868 Mon Sep 17 00:00:00 2001 From: Tatsuya Sato Date: Tue, 25 Dec 2018 21:19:35 +0900 Subject: [PATCH] Embeds javascript into the head to track page view with app insights --- lib/application_insights.rb | 1 + .../rack/track_page_view.rb | 44 +++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 lib/application_insights/rack/track_page_view.rb diff --git a/lib/application_insights.rb b/lib/application_insights.rb index 0a683d4..12d2f98 100644 --- a/lib/application_insights.rb +++ b/lib/application_insights.rb @@ -5,5 +5,6 @@ require_relative 'application_insights/version' module ApplicationInsights module Rack autoload :TrackRequest, "application_insights/rack/track_request" + autoload :TrackPageView, "application_insights/rack/track_page_view" end end diff --git a/lib/application_insights/rack/track_page_view.rb b/lib/application_insights/rack/track_page_view.rb new file mode 100644 index 0000000..afb5723 --- /dev/null +++ b/lib/application_insights/rack/track_page_view.rb @@ -0,0 +1,44 @@ +require 'rack' + +module ApplicationInsights + module Rack + class TrackPageView + def initialize(app, instrumentation_key) + @app = app + @instrumentation_key = instrumentation_key + end + + def call(env) + status, headers, response = @app.call(env) + + content_type = headers['Content-Type'] + return [status, headers, response] unless content_type && content_type.include?('text/html') + + unless response.is_a?(::Rack::Response) + response = ::Rack::Response.new(response, status, headers) + end + new_response = ::Rack::Response.new([], response.status, response.headers) + response.body.each do |b| + new_response.write(b.sub(/<\/head>/, "\n#{embedded_script_code}\n")) + end + + [new_response.status, new_response.headers, new_response] + end + + private + def embedded_script_code + <<~"SCRIPT" + + SCRIPT + end + end + end +end \ No newline at end of file