Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing a part of a URL with Ruby

Removing the query string from a URL in Ruby could be done like this:

url.split('?')[0]

Where url is the complete URL including the query string (e.g. url = http://www.domain.extension/folder?schnoo=schnok&foo=bar).

Is there a faster way to do this, i.e. without using split, but rather using Rails?

edit: The goal is to redirect from http://www.domain.extension/folder?schnoo=schnok&foo=bar to http://www.domain.extension/folder.

EDIT: I used:

url = 'http://www.domain.extension/folder?schnoo=schnok&foo=bar'
parsed_url = URI.parse(url)
new_url = parsed_url.scheme+"://"+parsed_url.host+parsed_url.path
like image 400
TTT Avatar asked Nov 27 '22 11:11

TTT


1 Answers

Easier to read and harder to screw up if you parse and set fragment & query to nil instead of rebuilding the URL.

parsed = URI::parse("http://www.domain.extension/folder?schnoo=schnok&foo=bar#frag")
parsed.fragment = parsed.query = nil
parsed.to_s

# => "http://www.domain.extension/folder"
like image 139
TTT Avatar answered Dec 05 '22 00:12

TTT