Build Query Strings with Rack::Utils
May 13th 2012A query string is part of a URL that contains data to be passed to web applications. For our purposes I’ll pretend we are working with a Rails Controller and want to customize some redirects to contain additional parameters.
Say we have
redirect_to root_path
which takes us to http://www.mywebsite.com but we would like to pass an aditional parameter along with the redirect, in this case authorization_token. What we want to see is a url like http://www.mywebsite.com/?authorization_token=foo
We could use string interpolation and end up with something like
redirect_to "#{root_path}/?authorization_token=foo"
This is probably fine for a query string with only one key and value, but what if we have a whole bunch of options we’d like passed as parameters? This could quickly grow into a very long string with multiple interpolated values. I’m a fan of succinct and easy to understand code and this is where Rack::Utils comes into play.
We’re going to take a look at two methods provided by Rack::Utils for building query strings, build_query and build_nested_query.
Let’s say we want to build the URL http://www.mywebsite.com/?authorization_token=foo&access_level=moderator&previous=index Using build_query, we can do
redirect_to root_path + Rack::Utils.build_query(
authorization_token: "foo",
access_level: "moderator",
previous: "index"
)
That’s basically all there is to it. I’d recommend taking a look at the source for both build_query and build_nested_query, the latter of which let’s you pass in a prefix as a second argument to build URLs like http://www.mywebsite.com?foo[name]=John&foo[id]=20 with ease.