Skip to content

Instantly share code, notes, and snippets.

@jnsprnw
Last active November 12, 2015 00:15
Show Gist options
  • Save jnsprnw/64fe62c57aaa1e257b0b to your computer and use it in GitHub Desktop.
Save jnsprnw/64fe62c57aaa1e257b0b to your computer and use it in GitHub Desktop.
Generate URIs from Hash in Ruby
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