Appending Values to a Querystring with Ruby

Featured image for sharing metadata for article

Let's say that you have a URL and you want to append on query parameters, for instance to add tracking data to a URL.

For example, let's say we want to add on utm_medium=example&utm_source=my_blog to a given URL.

You could do this by simply appending ?utm_medium=example&utm_source=my_blog to a URL we've been given, but that doesn't work in the case that a URL already has a querystring, because a number of URL parsers will reject that as a invalid URL, or it will not parse as you're expecting to.

The solution I've found that works best is to parse the URI, then use URI.encode_www_form on the parsed querystring once we've appended our parameters:

def add_tracking(url)
  parsed = URI.parse(url)
  query = if parsed.query
           CGI.parse(parsed.query)
         else
           {}
         end

  query['utm_medium'] = %w(example)
  query['utm_source'] = %w(my_blog)

  parsed.query = URI.encode_www_form(query)
  parsed.to_s
end

This works for the following cases:

add_tracking 'https://foo.com'
=> "https://foo.com?utm_medium=example&utm_source=my_blog"
add_tracking 'https://foo.com/'
=> "https://foo.com/?utm_medium=example&utm_source=my_blog"
add_tracking 'https://foo.com/?page=1'
=> "https://foo.com/?page=1&utm_medium=example&utm_source=my_blog"
add_tracking 'https://foo.com/?page=1&page=2'
=> "https://foo.com/?page=1&page=2&utm_medium=example&utm_source=my_blog"

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #ruby.

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.