Last active
November 12, 2015 00:15
-
-
Save jnsprnw/64fe62c57aaa1e257b0b to your computer and use it in GitHub Desktop.
Generate URIs from Hash in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "net/https" | |
# Regular URI | |
URI::HTTP.build( | |
:host => "domain.com" | |
) | |
# http://domain.com | |
# Secure URI | |
URI::HTTPS.build( | |
:host => "domain.com" | |
) | |
# https://domain.com | |
# Advanced URI | |
URI::HTTPS.build( | |
:host => "sub.domain.com", | |
:path => "/path", | |
:port => 8888, | |
:userinfo => 'user:pass', | |
:query => 'foo=bar&bar=foo' | |
) | |
# https://user:pass@sub.domain.com:8888/path?foo=bar&bar=foo | |
# Alternative version | |
class Hash # http://stackoverflow.com/a/20894914 | |
def to_param | |
self.to_a.map { |x| "#{x[0]}=#{x[1]}" }.join("&") | |
end | |
end | |
URI::HTTPS.build( | |
:host => "sub.domain.com", | |
:path => "/path", | |
:port => 8888, | |
:userinfo => 'user:pass', | |
:query => { | |
:foo => 'bar', | |
:bar => 'foo' | |
}.to_param | |
) | |
# https://user:pass@sub.domain.com:8888/path?foo=bar&bar=foo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment