1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-02 22:58:01 +00:00

Add Build HTTP And HTTPS URLs as a Ruby til

This commit is contained in:
jbranchaud
2021-06-11 09:36:31 -05:00
parent 04929c65f3
commit 2cb95c1ffb
2 changed files with 49 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
_1129 TILs and counting..._
_1130 TILs and counting..._
---
@@ -865,6 +865,7 @@ _1129 TILs and counting..._
- [Assert About An Object's Attributes With RSpec](ruby/assert-about-an-objects-attributes-with-rspec.md)
- [Assoc For Hashes](ruby/assoc-for-hashes.md)
- [Block Comments](ruby/block-comments.md)
- [Build HTTP And HTTPS URLs](ruby/build-http-and-https-urls.md)
- [Chaining Multiple RSpec Change Matchers](ruby/chaining-multiple-rspec-change-matchers.md)
- [Check Return Status Of Running A Shell Command](ruby/check-return-status-of-running-a-shell-command.md)
- [Click On Text With Capybara](ruby/click-on-text-with-capybara.md)

View File

@@ -0,0 +1,47 @@
# Build HTTP And HTTPS URLs
There are two modules you can use to build URLs in Ruby. The `URI::HTTP` module
will build URLs with the `http` protocol. And then to build URLs with the
`https` protocol, you can reach for the `URI::HTTPS` module.
We can specify just the `host` and optionally include a `port` if that is
needed.
Here is `URI::HTTP` in action.
```ruby
> URI::HTTP.build(host: 'example.com', port: 3000)
=> #<URI::HTTP http://example.com:3000>
> URI::HTTP.build(host: 'example.com', port: 3000, protocol: 'https')
=> #<URI::HTTP http://example.com:3000>
```
Note that we can try to override the protocol, but it will be ignored.
Here is the `URI::HTTPS` module.
```ruby
> URI::HTTPS.build(host: 'example.com', port: 3000)
=> #<URI::HTTPS https://example.com:3000>
```
If we want the URL as a string, we can call `#to_s` on it.
```ruby
> URI::HTTPS.build(host: 'example.com', port: 3000).to_s
=> "https://example.com:3000"
```
We can even include the `path`, though be sure to include the leading slash.
```ruby
> URI::HTTP.build(host: 'example.com', port: 3000, path: '/taco/bell')
=> #<URI::HTTP http://example.com:3000/taco/bell>
> URI::HTTP.build(host: 'example.com', port: 3000, path: 'taco/bell')
URI::InvalidComponentError: bad component(expected absolute path component): taco/bell
from /Users/jbranchaud/.asdf/installs/ruby/2.6.6/lib/ruby/2.6.0/uri/generic.rb:761:in `check_path'
```
[source](https://ruby-doc.org/stdlib-2.5.1/libdoc/uri/rdoc/URI/HTTP.html)