Today I Learned

hashrocket A Hashrocket project

Parse a Query String in Ruby

If you ever need to parse a query string in Ruby - or Rails, Rack has a convenient utility to do just that. parse_nested_query will parse from a string to a hash:

Rack::Utils.parse_nested_query("&sort_dir=asc&sort_by=date_created&filter_by=lead")

=>  {"sort_dir"=>"asc", "sort_by"=>"date_created", "filter_by"=>"lead"}

You can also go the opposite way with build_nested_query and generate a query string:

Rack::Utils.build_nested_query({"sort_dir"=>"asc", "sort_by"=>"date_created", "filter_by"=>"lead"})

=>  "sort_dir=asc&sort_by=date_created&filter_by=lead"

https://www.rubydoc.info/gems/rack/Rack/Utils

See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.