在Ruby中从URL删除参数的最优雅的方法是什么? [英] What is the most elegant way in Ruby to remove a parameter from a URL?

查看:89
本文介绍了在Ruby中从URL删除参数的最优雅的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按名称从URL中取出一个参数,而不知道它是哪个参数,然后重新组装URL.

I would like to take out a parameter from a URL by its name without knowing which parameter it is, and reassemble the URL again.

我想使用CGI或URI自己编写一些东西并不难,但是我想这样的功能已经存在.有什么建议吗?

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?

在:

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

出局:

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

推荐答案

可寻址宝石将很好地完成此任务;请查看 The Tin Man 的上等答案.但是,如果您想自己动手,请按以下步骤进行.该代码唯一具有优雅感的地方是,它在方法中隐藏了丑陋的地方:

The addressable gem will do this nicely; please see the superior answer by The Tin Man. But if you want to roll your own, here's how. 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"

这篇关于在Ruby中从URL删除参数的最优雅的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆