Skip to content

Instantly share code, notes, and snippets.

@awesome
Created December 9, 2021 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save awesome/bc2e6c6ec2024b0d2e412b8f92045cf4 to your computer and use it in GitHub Desktop.
Save awesome/bc2e6c6ec2024b0d2e412b8f92045cf4 to your computer and use it in GitHub Desktop.
Ruby: URL-to-Hash & Query-to-Hash
RX_URL = Regexp.new('^((?<protocol>https?):\/\/)?(?<host>[^\/]+)(\/(?<path>[^\?#]+))?(\?(?<query>[^#]+))?(#(?<fragment>.*))?', 'i')
# @see http://stackoverflow.com/questions/18825669/how-to-do-named-capture-in-ruby#18825787
# @param url_str [String] URL string with or without `https://`, `http://`
# @return [Hash] hash with keys: `:protocol, :host, :path, :query, :fragment`
def url_to_hash(url_str)
m = url_str.match(RX_URL)
m.names.map(&:to_sym).zip(m.captures).to_h
end
# @see http://stackoverflow.com/questions/2500462/how-to-extract-url-parameters-from-a-url-with-ruby-or-rails#25598247
# @see http://ruby-doc.org/stdlib-2.1.0/libdoc/uri/rdoc/URI.html#method-c-decode_www_form
def query_to_hash(query_str)
URI::decode_www_form(query_str).each_with_object({}) {|(k,v),h| h[k.to_sym] = v}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment