如何使用 Ruby 或 Rails 从 URL 中提取 URL 参数?

发布于 2024-08-26 09:27:19 字数 531 浏览 12 评论 0原文

我有一些 URL,例如

http://www.example.com/something?param1=value1&param2=value2&param3=value3

,我想从这些 URL 中提取参数并将它们放入哈希中。显然,我可以使用正则表达式,但我只是想知道是否有更简单的方法可以使用 Ruby 或 Rails 来做到这一点。我没有在 Ruby 模块 URI 中找到任何内容,但也许我错过了一些东西。

事实上,我需要一种方法来做到这一点:

extract_parameters_from_url("http://www.example.com/something?param1=value1&param2=value2&param3=value3")
#=> {:param1 => 'value1', :param2 => 'value2', :param3 => 'value3'}

你有一些建议吗?

I have some URLs, like

http://www.example.com/something?param1=value1¶m2=value2¶m3=value3

and I would like to extract the parameters from these URLs and get them in a Hash. Obviously, I could use regular expressions, but I was just wondering if there was easier ways to do that with Ruby or Rails. I haven't found anything in the Ruby module URI but perhaps I missed something.

In fact, I need a method that would do that:

extract_parameters_from_url("http://www.example.com/something?param1=value1¶m2=value2¶m3=value3")
#=> {:param1 => 'value1', :param2 => 'value2', :param3 => 'value3'}

Would you have some advices?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

流年已逝 2024-09-02 09:27:20

对于 Ruby 2.7/3,使用 CGI 可能是一种过时的方法。

这是使用 URI 执行此操作的巧妙方法:

uri = URI.parse 'https://duckduckgo.com/?q=ruby+programming+language'
params = Hash[URI.decode_www_form uri.query]
# => {"q"=>"ruby programming language"} 

Using CGI might be an outdated approach with Ruby 2.7/3.

Here's a neat way to do this with URI:

uri = URI.parse 'https://duckduckgo.com/?q=ruby+programming+language'
params = Hash[URI.decode_www_form uri.query]
# => {"q"=>"ruby programming language"} 
骄傲 2024-09-02 09:27:20

您也可以使用此方法,


require 'uri'
require 'cgi'
uri = URI("https://example.com/?query=1&q=2&query=5")
a = CGI::parse(uri.query)
puts a                   #=> {"query"=>["1", "5"], "q"=>["2"]}
puts a["query"].to_s     #=> ["1", "5"]
puts a["query"][0]       #=>  1
puts a["query"][1]       #=>  5
puts a["q"][0]           #=>  2


它安全且更容易

you can also use this method


require 'uri'
require 'cgi'
uri = URI("https://example.com/?query=1&q=2&query=5")
a = CGI::parse(uri.query)
puts a                   #=> {"query"=>["1", "5"], "q"=>["2"]}
puts a["query"].to_s     #=> ["1", "5"]
puts a["query"][0]       #=>  1
puts a["query"][1]       #=>  5
puts a["q"][0]           #=>  2


its safe and much easier

夜声 2024-09-02 09:27:20

遗憾的是,在尝试从有问题的 URL 中提取查询参数时,URIaddressable 库都会崩溃。例如,这会破坏两者:

http://localhost:4300/webapp/foo/#//controller/action?account=001-001-111&email=john%40email.com

构建在 Arthur / Levi 的解决方案上,使用 url.split("?").try(:last) 您可以仅获取 URL 的查询参数部分,并使用 Rack::Utils.parse_nested_query 将参数字符串解析为哈希值。

或完整:

Rack::Utils.parse_nested_query(url.split("?").try(:last))

在我的示例中返回:

{"account": "001-001-111", "email": "[email protected]"}

Sadly both the URI and addressable libraries break when attempting to extract query params from buggy URLs. E.g. this breaks both:

http://localhost:4300/webapp/foo/#//controller/action?account=001-001-111&email=john%40email.com

Building on Arthur / Levi's solution, with url.split("?").try(:last) you can grab just the query param portion of the URL, and use Rack::Utils.parse_nested_query to parse that string of parameters into a hash.

Or in full:

Rack::Utils.parse_nested_query(url.split("?").try(:last))

returning in my example:

{"account": "001-001-111", "email": "[email protected]"}
情何以堪。 2024-09-02 09:27:20

上面的答案写得很好并且达到了目的,但是我尝试了一些查询操作并想在这里分享。所以,这是我的看法:

   URI("http://example.com?par=hello&par2=bye").query.split('&').map { |param| {query_param: param.split('=')[0] , value: param.split('=')[1]}  }

它达到目的并为每个查询参数返回一个对象数组。话虽如此,请记住ROR的COC原则。

The above answers are very well written and they serve the purpose, however I tried some query manipulation and wanted to share here. So, here is my take:

   URI("http://example.com?par=hello&par2=bye").query.split('&').map { |param| {query_param: param.split('=')[0] , value: param.split('=')[1]}  }

It serves the purpose and return an array of objects for each query param. Having said that, please keep in mind the COC principle of ROR.

安人多梦 2024-09-02 09:27:20

在您的控制器中,您应该能够访问名为 params 的字典(哈希)。因此,如果您知道每个查询参数的名称是什么,那么只需执行 params[:param1] 即可访问它...如果您不知道参数的名称是什么,您可以可以遍历字典并获取密钥。

此处有一些简单的示例。

In your Controller, you should be able to access a dictionary (hash) called params. So, if you know what the names of each query parameter is, then just do params[:param1] to access it... If you don't know what the names of the parameters are, you could traverse the dictionary and get the keys.

Some simple examples here.

俯瞰星空 2024-09-02 09:27:19

我想你想将任何给定的 URL 字符串转换为 HASH?

您可以尝试 http://www.ruby- doc.org/stdlib/libdoc/cgi/rdoc/classes/CGI.html#M000075

require 'cgi'

CGI::parse('param1=value1¶m2=value2¶m3=value3')

返回

{"param1"=>["value1"], "param2"=>["value2"], "param3"=>["value3"]}

I think you want to turn any given URL string into a HASH?

You can try http://www.ruby-doc.org/stdlib/libdoc/cgi/rdoc/classes/CGI.html#M000075

require 'cgi'

CGI::parse('param1=value1¶m2=value2¶m3=value3')

returns

{"param1"=>["value1"], "param2"=>["value2"], "param3"=>["value3"]}
微暖i 2024-09-02 09:27:19

我发现自己在最近的项目中需要同样的东西。
基于 Levi's 解决方案,这里有一个更干净、更快速的方法:

Rack::Utils.parse_nested_query 'param1=value1¶m2=value2¶m3=value3'
# => {"param1"=>"value1", "param2"=>"value2", "param3"=>"value3"}

I found myself needing the same thing for a recent project.
Building on Levi's solution, here's a cleaner and faster method:

Rack::Utils.parse_nested_query 'param1=value1¶m2=value2¶m3=value3'
# => {"param1"=>"value1", "param2"=>"value2", "param3"=>"value3"}
花开雨落又逢春i 2024-09-02 09:27:19

只是根据上面的 Levi 答案进行了改进 -

Rack::Utils.parse_query URI("http://example.com?par=hello&par2=bye").query

对于像上面 url 这样的字符串,它将返回

{ "par" => "hello", "par2" => "bye" } 

Just Improved with Levi answer above -

Rack::Utils.parse_query URI("http://example.com?par=hello&par2=bye").query

For a string like above url, it will return

{ "par" => "hello", "par2" => "bye" } 
哥,最终变帅啦 2024-09-02 09:27:19

对于纯 Ruby 解决方案,将 URI.parseCGI.parse 结合起来(即使不需要 Rails/Rack 等,也可以使用):

CGI.parse(URI.parse(url).query) 
# =>  {"name1" => ["value1"], "name2" => ["value1", "value2", ...] }

For a pure Ruby solution combine URI.parse with CGI.parse (this can be used even if Rails/Rack etc. are not required):

CGI.parse(URI.parse(url).query) 
# =>  {"name1" => ["value1"], "name2" => ["value1", "value2", ...] }
再浓的妆也掩不了殇 2024-09-02 09:27:19

有不止一种方法可以解决您的问题。其他人已经向您展示了一些技巧。我还知道另一个窍门。这是我的尝试:-

require 'uri'
url = "http://www.example.com/something?param1=value1¶m2=value2¶m3=value3"
uri = URI(url)
# => #<URI::HTTP:0x89e4898 URL:http://www.example.com/something?param1=value1¶m2=value2¶m3=value3>
URI::decode_www_form(uri.query).to_h # if you are in 2.1 or later version of Ruby
# => {"param1"=>"value1", "param2"=>"value2", "param3"=>"value3"}
Hash[URI::decode_www_form(uri.query)] # if you are below 2.1 version of Ruby
# => {"param1"=>"value1", "param2"=>"value2", "param3"=>"value3"}

阅读 ::decode_www_form

There more than one ways, to solve your problem. Others has shown you the some tricks. I know another trick. Here is my try :-

require 'uri'
url = "http://www.example.com/something?param1=value1¶m2=value2¶m3=value3"
uri = URI(url)
# => #<URI::HTTP:0x89e4898 URL:http://www.example.com/something?param1=value1¶m2=value2¶m3=value3>
URI::decode_www_form(uri.query).to_h # if you are in 2.1 or later version of Ruby
# => {"param1"=>"value1", "param2"=>"value2", "param3"=>"value3"}
Hash[URI::decode_www_form(uri.query)] # if you are below 2.1 version of Ruby
# => {"param1"=>"value1", "param2"=>"value2", "param3"=>"value3"}

Read the method docomentation of ::decode_www_form.

清风夜微凉 2024-09-02 09:27:19

查看 addressable gem - Ruby URI 模块的流行替代品,使查询解析变得容易:(

require "addressable/uri"
uri = Addressable::URI.parse("http://www.example.com/something?param1=value1¶m2=value2¶m3=value3")
uri.query_values['param1']
=> 'value1'

它显然也处理参数编码/解码,与 URI 不同)

Check out the addressable gem - a popular replacement for Ruby's URI module that makes query parsing easy:

require "addressable/uri"
uri = Addressable::URI.parse("http://www.example.com/something?param1=value1¶m2=value2¶m3=value3")
uri.query_values['param1']
=> 'value1'

(It also apparently handles param encoding/decoding, unlike URI)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文