tags:

views:

107

answers:

2

I would like to take out a parameter from url by it's name without knowing if it is the first, middle or last parameter and reassemble url again. I guess it is not that hard to write something on my own using CGI or URI, but I imagine such functionality exists already. Any suggestions?

in:

http://example.com/path?param1=one&param2=2&param3=something3

out:

http://example.com/path?param2=2&param3=something3

+1  A: 

The only claim this code has to elegance is that it hides the ugly in a method:

#!/usr/bin/ruby1.8

def reject_param(url, param_to_reject)
  # Regex from RFC3986
  url_regex = %r"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$"
  raise "Not a url: #{url}" unless url =~ url_regex
  scheme_plus_punctuation = $1
  authority_with_punctuation = $3
  path = $5
  query = $7
  fragment = $9
  query = query.split('&').reject do |param|
    param_name = param.split(/=/).first
    param_name == param_to_reject
  end.join('&')
  [scheme_plus_punctuation, authority_with_punctuation, path, '?', query, fragment].join
end   

url = "http://example.com/path?param1=one&param2=2&param3=something3"
p url
p reject_param(url, 'param2')

# => "http://example.com/path?param1=one&param2=2&param3=something3"
# => "http://example.com/path?param1=one&param3=something3"
Wayne Conrad
Upvote for using the actual regex from the RFC. Excellent reference.
btelles
+3  A: 

I came up with something like this

 def uri_remove_param(uri, params = nil)
   return uri unless params
   params = Array(params)
   uri_parsed = URI.parse(uri)
   return uri unless uri_parsed.query
   escaped = uri_parsed.query.grep(/&/).size > 0
   new_params = uri_parsed.query.gsub(/&/, '&').split('&').reject { |q| params.include?(q.split('=').first) }
   uri = uri.split('?').first
   amp = escaped ? '&' : '&'
   "#{uri}?#{new_params.join(amp)}"
 end
dimus
Give yourself the checkmark; I like your answer better. URI.parse? Yet another handy library I knew nothing about. Oh, your params = [params] if... line? You can replace that with params = Array(params). I learned that trick on SO, of course.
Wayne Conrad
params=Array(params) is cool!
dimus
actually after playing with Array(params) for a while... Array({}) should be used with caution because it also converts hash to array.
dimus