|
| 1 | +# Build HTTP And HTTPS URLs |
| 2 | + |
| 3 | +There are two modules you can use to build URLs in Ruby. The `URI::HTTP` module |
| 4 | +will build URLs with the `http` protocol. And then to build URLs with the |
| 5 | +`https` protocol, you can reach for the `URI::HTTPS` module. |
| 6 | + |
| 7 | +We can specify just the `host` and optionally include a `port` if that is |
| 8 | +needed. |
| 9 | + |
| 10 | +Here is `URI::HTTP` in action. |
| 11 | + |
| 12 | +```ruby |
| 13 | +> URI::HTTP.build(host: 'example.com', port: 3000) |
| 14 | +=> #<URI::HTTP http://example.com:3000> |
| 15 | + |
| 16 | +> URI::HTTP.build(host: 'example.com', port: 3000, protocol: 'https') |
| 17 | +=> #<URI::HTTP http://example.com:3000> |
| 18 | +``` |
| 19 | + |
| 20 | +Note that we can try to override the protocol, but it will be ignored. |
| 21 | + |
| 22 | +Here is the `URI::HTTPS` module. |
| 23 | + |
| 24 | +```ruby |
| 25 | +> URI::HTTPS.build(host: 'example.com', port: 3000) |
| 26 | +=> #<URI::HTTPS https://example.com:3000> |
| 27 | +``` |
| 28 | + |
| 29 | +If we want the URL as a string, we can call `#to_s` on it. |
| 30 | + |
| 31 | +```ruby |
| 32 | +> URI::HTTPS.build(host: 'example.com', port: 3000).to_s |
| 33 | +=> "https://example.com:3000" |
| 34 | +``` |
| 35 | + |
| 36 | +We can even include the `path`, though be sure to include the leading slash. |
| 37 | + |
| 38 | +```ruby |
| 39 | +> URI::HTTP.build(host: 'example.com', port: 3000, path: '/taco/bell') |
| 40 | +=> #<URI::HTTP http://example.com:3000/taco/bell> |
| 41 | + |
| 42 | +> URI::HTTP.build(host: 'example.com', port: 3000, path: 'taco/bell') |
| 43 | +URI::InvalidComponentError: bad component(expected absolute path component): taco/bell |
| 44 | +from /Users/jbranchaud/.asdf/installs/ruby/2.6.6/lib/ruby/2.6.0/uri/generic.rb:761:in `check_path' |
| 45 | +``` |
| 46 | + |
| 47 | +[source](https://ruby-doc.org/stdlib-2.5.1/libdoc/uri/rdoc/URI/HTTP.html) |
0 commit comments