diff --git a/README.md b/README.md index 6147796..3eb4a05 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/ruby/build-http-and-https-urls.md b/ruby/build-http-and-https-urls.md new file mode 100644 index 0000000..fefe261 --- /dev/null +++ b/ruby/build-http-and-https-urls.md @@ -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.build(host: 'example.com', port: 3000, protocol: 'https') +=> # +``` + +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) +=> # +``` + +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.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)