加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 20:07:19 所属栏目:百科 来源:网络整理
导读:我想从URL中取出一个参数,而不知道它是哪个参数,然后再次重新组合URL. 我想这不是很难用CGI或者URI自己编写的东西,但是我想像这样的功能已经存在了.有什么建议么? 在: http://example.com/path?param1=oneparam2=2param3=something3 日期: http://example
我想从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"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读