Last active
December 2, 2015 13:35
-
-
Save dmitry/ff2e7ca275fde01f6bc2 to your computer and use it in GitHub Desktop.
Add trackable links
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ruby script/trackable_links.rb script/a.txt "?a=2&c=3" | |
require 'addressable/uri' | |
require 'nokogiri' | |
class TrackableLinks | |
ALLOWED_SCHEMAS = %w(http https) | |
class << self | |
def add(body, options) | |
doc = Nokogiri::HTML(body) | |
doc.css("a[href]").each do |link| | |
uri = parse_uri(link["href"]) | |
next unless trackable_uri?(uri) | |
params = uri.query_values || {} | |
options.each do |key, value| | |
params[key] ||= value | |
end | |
uri.query_values = params | |
link["href"] = uri.to_s | |
end | |
doc.to_s | |
end | |
private | |
def trackable_uri?(uri) | |
uri && uri.absolute? && ALLOWED_SCHEMAS.include?(uri.scheme) | |
end | |
def parse_uri(href) | |
Addressable::URI.parse(href.to_s) rescue nil | |
end | |
end | |
end | |
options = Addressable::URI.parse(ARGV[1]).query_values | |
html = TrackableLinks.add(File.open(ARGV[0]).read, options) | |
File.open(ARGV[0], 'w').puts(html) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment