Ruby中最优雅的方式是从URL中删除参数?

前端之家收集整理的这篇文章主要介绍了Ruby中最优雅的方式是从URL中删除参数?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想从URL中取出一个参数,而不知道它是哪个参数,然后再次重新组合URL.

我想这不是很难用CGI或者URI自己编写的东西,但是我想像这样的功能已经存在了.有什么建议么?

在:

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

日期:

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

解决方法

可寻址的宝石会很好地做到这一点;请看“天男”的上级答案.但是,如果你想自己滚动,这是怎么回事.唯一要求这个代码优雅的是它在一个方法中隐藏了丑陋:
#!/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"

猜你在找的Ruby相关文章