Transforming URL Query Strings into Hashes: A Ruby on Rails Guide

Gonzalo Galdámez
Unagi
Published in
2 min readMar 14, 2024
Transforming URL Query Strings into Hashes: A Ruby on Rails Guide

In the world of Ruby on Rails, handling URL query strings becomes essential, particularly when building web applications that engage with external APIs or manage user input. When confronted with a URL housing a query string, the dynamic duo of Ruby’s URI and Rack::Utils modules come to the rescue, empowering us to effortlessly extract parameters and organize them into a convenient hash.

Extracting the query string with Ruby’s URI module

Let’s first parse a URL and extract its query string using the URI module, like the code snippet below:

require 'uri'

url = "https://example.com/search?query=rubyonrails&page=1"
parsed_url = URI.parse(url)

# This next line prints: query=rubyonrails&page=1
puts parsed_url.query

Harnessing Rack::Utils for Hash Transformation

Now, let’s use the Rack::Utils module. There is a method Rack::Utils.parse_query that converts a query string into a manageable hash. Take a look:

require 'rack'

query_string = "query=rubyonrails&page=1"
query_hash = Rack::Utils.parse_query(query_string)

# The following line prints: {"query" => "rubyonrails", "page" => "1"}
puts query_hash

Practical Navigation with Examples

Putting theory into practice, let’s envision a scenario where we extract and utilize a user’s search query and page number. The following code illustrates how to do this:

def process_search_url(url)
parsed_url = URI.parse(url)
query_hash = Rack::Utils.parse_query(parsed_url.query)

search_query = query_hash["query"]
page_number = query_hash["page"]

# You might include some logic to handle the search query
# and page number
puts "Search Query: #{search_query}, Page Number: #{page_number}"
end

# Example Usage
search_url = "https://unagisoftware.com/search?query=rubyexperts&page=3"
process_search_url(search_url)

# Output: Search Query: rubyexperts, Page Number: 3

Armed with these insights, we’re now ready to convert URL query strings into convenient hashes, elevating our Ruby on Rails skills ⚙️✨

Unagi is a software boutique that offers software development services in Ruby on Rails, a stack we still choose after +12 years. Check out more on our social media.

--

--