How do I process a URL in ruby to extract the component parts (scheme, username, password, host, etc)?

淺唱寂寞╮ 提交于 2019-12-13 14:14:25

问题


I'm trying create a program using ruby (and Net::SSH) to connect to servers and perform some tasks. The details of the server are to be provided as something like:

ssh://user:pass@host:port (for a host that does not yet have SSH keys)

or

user@host

Net::SSH expects the following format:

Net::SSH.start('host', 'user', :password => "password")

Is there are gem/stdlib that can process the URL into this format? Or a simple regex that can match the different parts?

Note: I'm aware of, and use, capistrano but in this case I need lower level control.


回答1:


Both URI and Addressable::URI can parse URLs and let you break them down into their components.

URI is included in Ruby's Standard Library, which is nice, but Addressable::URI has more features, and is what I use when I have to do a lot of work on URLs.

require 'addressable/uri'

uri = Addressable::URI.parse('ssh://user:pass@www.example.com:81') 
uri.host # => "www.example.com"
uri.user # => "user"
uri.password # => "pass"
uri.scheme # => "ssh"
uri.port # => 81

require 'uri'
uri = URI.parse('ssh://user:pass@www.example.com:81')
uri.host # => "www.example.com"
uri.user # => "user"
uri.password # => "pass"
uri.scheme # => "ssh"
uri.port # => 81



回答2:


There is a URI class that should help. You might have to replace the ssh scheme with http by hand first though, I don't think URI understands the ssh scheme out of the box.



来源:https://stackoverflow.com/questions/4274213/how-do-i-process-a-url-in-ruby-to-extract-the-component-parts-scheme-username

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!