Skip to content

Instantly share code, notes, and snippets.

@julianrubisch
Created November 13, 2022 16:01
Show Gist options
  • Save julianrubisch/0a2a71c26951b43bc81e6b508538d1c3 to your computer and use it in GitHub Desktop.
Save julianrubisch/0a2a71c26951b43bc81e6b508538d1c3 to your computer and use it in GitHub Desktop.
Pagespeed Runner
#!/usr/bin/env ruby
require_relative "../config/environment"
require "pagespeed_insights"
require "optparse"
require "concurrent"
options = {}
OptionParser.new do |parser|
parser.banner = "Usage: bin/run_pagespeed [options]"
parser.on("-n NUM", "--number-of-runs=NUM", "Specify how many times to run the request, default 10", Integer) do |n|
options[:runs] = n
end
parser.on("-s [desktop|mobile]", "--strategy [desktop|mobile]", "Provide the PageSpeed strategy, default 'mobile'", String) do |s|
raise "Valid strategies are: desktop, mobile" unless %w[desktop mobile].include? s
options[:strategy] = s
end
end.parse!
options[:runs] ||= 10
options[:strategy] ||= "mobile"
url = ARGV.shift
futures = (1..options[:runs]).map do
Concurrent::Future.execute do
request = PagespeedInsights::V5.new(
url: url,
key: Rails.application.credentials.dig(:google_pagespeed, :api_key),
strategy: options[:strategy]
)
response = request.results
raise "Pagespeed error: #{response.body}" unless response.status == 200
JSON.parse(response.body)
end
end
results = futures.map(&:value)
path = "#{Rails.root.join("tmp")}/pagespeed-#{url.parameterize}-#{Time.now.utc.strftime("%F-%H%M%S")}.json"
File.open(path, "w") do |file|
JSON.dump(results, file)
end
puts "Wrote #{options[:runs]} attempts to #{path}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment