Ruby URL Get/Set Field methods

I was writing a quick script and needed to modify a url quickly to change the fields on a url.

def url_get_field ( url, field )
  m=/.*[&?]#{field}=(.+?)(&.*)/.match(url)
  n=/.*[&?]#{field}=(.+)/.match(url)
  if !m.nil?
    return m[1]
  elsif !n.nil?
    return n[1]
  else
    return ""
  end
end

def url_set_field ( url, field, value )
  m=/(.*[&?]#{field}=)(.+?)(&.*)/.match(url)
  n=/(.*[&?]#{field}=)(.+)/.match(url)
  if !m.nil?
    url = m[1] + value + m[3]
  elsif !n.nil?
    url = n[1] + value
  else
    unless /.+[?&].+?=.+/.match(url).nil?
      url = url + '&'
    else
      url = url + '?'
    end
    url = url + field + "=" + value
  end
  url
end

def url_remove_field ( url, field )
  m=/(.*)([&?])(#{field}=(.+?))(&(.*))/.match(url)
  n=/(.*)([&?])(#{field}=(.+))/.match(url)
  unless m.nil?
    url = m[1] + m[2] + m[6]
  else
    url = n[1] unless n.nil?
  end
  url
end

Now it’s easy enough to do! check this out:

irb(main):160:0> url = 'http://pigsflew.com'
=> "http://pigsflew.com"
irb(main):161:0> url = url_set_field( url, 'test', 'omg' )
=> "http://pigsflew.com?test=omg"
irb(main):162:0> url = url_set_field( url, 'archives', '526')
=> "http://pigsflew.com?test=omg&archives=526"
irb(main):163:0> url_get_field( url, 'test' )
=> "omg"
irb(main):164:0> url_remove_field( url, 'test' )
=> "http://pigsflew.com?archives=526"
irb(main):165:0>
Tags: No tags

Leave a Comment