1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-18 14:38:01 +00:00

Compare commits

...

14 Commits

Author SHA1 Message Date
Dylan Irlbeck
6e3d2f63cc Merge 5365e75267 into b6c8192a04 2024-04-17 10:48:10 +07:00
jbranchaud
b6c8192a04 Add Make Elements Non-Interactive With Inert as an HTML TIL 2024-04-12 11:54:52 -06:00
jbranchaud
c2f30615c3 Add Print DateTime Represented By Unix Timestamp as a Unix TIL 2024-04-08 09:24:09 -05:00
jbranchaud
f54eab20e7 Add Unrestrict Where ripgrep Searches as a Unix TIL 2024-04-04 13:24:51 -05:00
jbranchaud
b2ddce62fd Add Audit Your Ruby Project For Any CVEs as a Ruby TIL 2024-04-02 11:08:37 -05:00
jbranchaud
63a57c6bdd Add Turn Off Display Of Tabs For Files as a VS Code TIL 2024-03-28 20:01:32 -05:00
jbranchaud
87d116a4cd Add List Files In A Single Column as a Unix TIL 2024-03-27 17:21:54 -05:00
jbranchaud
71598d647b Add Add Subtitles To Existing Mux Video Asset as a Workflow TIL 2024-03-20 10:48:20 -05:00
jbranchaud
11859a096f Add Precedence Of Dot Env Files as a Next.js TIL 2024-03-18 13:57:33 -05:00
jbranchaud
6096f5af10 Add Format A Hash Into A String Template as a Ruby TIL 2024-03-18 09:34:06 -05:00
jbranchaud
b6e5ea4c03 Add Fetch Does Not Work In API Serverless Function as a Next.js TIL 2024-03-15 15:02:27 -05:00
jbranchaud
74a3dd3c3a Add Include Ignore Files In Ripgrep Search as a Unix TIL 2024-03-14 16:45:22 -05:00
jbranchaud
7208fad280 Add Specify How Random Array Sample Is as a Ruby TIL 2024-03-12 19:07:55 -05:00
Dylan Irlbeck
5365e75267 Update git show TIL 2020-04-29 22:17:44 -05:00
14 changed files with 413 additions and 4 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://crafty-builder-6996.ck.page/e169c61186).
_1396 TILs and counting..._
_1408 TILs and counting..._
---
@@ -397,6 +397,7 @@ _1396 TILs and counting..._
- [Adding Alt Text To An Image](html/adding-alt-text-to-an-image.md)
- [Determine Which Button Submitted The Form](html/determine-which-button-submitted-the-form.md)
- [Disable Auto-Completion For A Form Input](html/disable-auto-completion-for-a-form-input.md)
- [Make Elements Non-Interactive With Inert](html/make-elements-non-interactive-with-inert.md)
- [Prevent Search Engines From Indexing A Page](html/prevent-search-engines-from-indexing-a-page.md)
- [Render Text As Superscript](html/render-text-as-superscript.md)
- [Submit A Form With A Button Outside The Form](html/submit-a-form-with-a-button-outside-the-form.md)
@@ -621,8 +622,10 @@ _1396 TILs and counting..._
- [Create Files And Directories For Dynamic Routes](nextjs/create-files-and-directories-for-dynamic-routes.md)
- [Define URL Redirects In The Next Config](nextjs/define-url-redirects-in-the-next-config.md)
- [Fetch Does Not Work In API Serverless Function](nextjs/fetch-does-not-work-in-api-serverless-function.md)
- [Make Environment Variable Publicly Available](nextjs/make-environment-variable-publicly-available.md)
- [Match Middleware On Groups Of Paths](nextjs/match-middleware-on-groups-of-paths.md)
- [Precedence Of Dot Env Files](nextjs/precedence-of-dot-env-files.md)
- [Push A Route With A URL Object](nextjs/push-a-route-with-a-url-object.md)
- [Redirect An Unauthorized User](nextjs/redirect-an-unauthorized-user.md)
- [Remove A Query Param From The URL](nextjs/remove-a-query-param-from-the-url.md)
@@ -1087,6 +1090,7 @@ _1396 TILs and counting..._
- [Add Progress Reporting To Long-Running Script](ruby/add-progress-reporting-to-long-running-script.md)
- [Are They All True?](ruby/are-they-all-true.md)
- [Assert About An Object's Attributes With RSpec](ruby/assert-about-an-objects-attributes-with-rspec.md)
- [Audit Your Ruby Project For Any CVEs](ruby/audit-your-ruby-project-for-any-cves.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)
@@ -1128,6 +1132,7 @@ _1396 TILs and counting..._
- [Fetch Warns About Superseding Block Argument](ruby/fetch-warns-about-superseding-block-argument.md)
- [Find The Min And Max With A Single Call](ruby/find-the-min-and-max-with-a-single-call.md)
- [Finding The Source of Ruby Methods](ruby/finding-the-source-of-ruby-methods.md)
- [Format A Hash Into A String Template](ruby/format-a-hash-into-a-string-template.md)
- [Generate A Signed JWT Token](ruby/generate-a-signed-jwt-token.md)
- [Generate Ruby Version And Gemset Files With RVM](ruby/generate-ruby-version-and-gemset-files-with-rvm.md)
- [Get Info About Your RubyGems Environment](ruby/get-info-about-your-ruby-gems-environment.md)
@@ -1187,6 +1192,7 @@ _1396 TILs and counting..._
- [Single And Double Quoted String Notation](ruby/single-and-double-quoted-string-notation.md)
- [Skip Specific CVEs When Auditing Your Bundle](ruby/skip-specific-cves-when-auditing-your-bundle.md)
- [Specify Dependencies For A Rake Task](ruby/specify-dependencies-for-a-rake-task.md)
- [Specify How Random Array#sample Is](ruby/specify-how-random-array-sample-is.md)
- [Split A Float Into Its Integer And Decimal](ruby/split-a-float-into-its-integer-and-decimal.md)
- [Squeeze Out The Extra Space](ruby/squeeze-out-the-extra-space.md)
- [String Interpolation With Instance Variables](ruby/string-interpolation-with-instance-variables.md)
@@ -1363,6 +1369,7 @@ _1396 TILs and counting..._
- [Hexdump A Compiled File](unix/hexdump-a-compiled-file.md)
- [Ignore A Directory During ripgrep Search](unix/ignore-a-directory-during-ripgrep-search.md)
- [Ignore The Alias When Running A Command](unix/ignore-the-alias-when-running-a-command.md)
- [Include Ignore Files In Ripgrep Search](unix/include-ignore-files-in-ripgrep-search.md)
- [Interactively Browse Available Node Versions](unix/interactively-browse-availabile-node-versions.md)
- [Interactively Switch asdf Package Versions](unix/interactively-switch-asdf-package-versions.md)
- [Jump To The Ends Of Your Shell History](unix/jump-to-the-ends-of-your-shell-history.md)
@@ -1372,6 +1379,7 @@ _1396 TILs and counting..._
- [Less With Style](unix/less-with-style.md)
- [List All The Enabled ZSH Options](unix/list-all-the-enabled-zsh-options.md)
- [List All Users](unix/list-all-users.md)
- [List Files In A Single Column](unix/list-files-in-a-single-column.md)
- [List Files Ordered By Modification Date](unix/list-files-ordered-by-modification-date.md)
- [List Names Of Files With Matches](unix/list-names-of-files-with-matches.md)
- [List Of Sessions To A Machine](unix/list-of-sessions-to-a-machine.md)
@@ -1390,6 +1398,7 @@ _1396 TILs and counting..._
- [Partial String Matching In Bash Scripts](unix/partial-string-matching-in-bash-scripts.md)
- [PID Of The Current Shell](unix/pid-of-the-current-shell.md)
- [Print A Range Of Lines For A File With Bat](unix/print-a-range-of-lines-for-a-file-with-bat.md)
- [Print DateTime Represented By Unix Timestamp](unix/print-datetime-represented-by-unix-timestamp.md)
- [Print Milliseconds In Human-Readable Format](unix/print-milliseconds-in-human-readable-format.md)
- [Print Out Files In Reverse](unix/print-out-files-in-reverse.md)
- [Print The Current Date In Human-Readable Format](unix/print-the-current-date-in-human-readable-format.md)
@@ -1420,6 +1429,7 @@ _1396 TILs and counting..._
- [Tell direnv To Load The Env File](unix/tell-direnv-to-load-the-env-file.md)
- [Touch Access And Modify Times Individually](unix/touch-access-and-modify-times-individually.md)
- [Undo Some Command Line Editing](unix/undo-some-command-line-editing.md)
- [Unrestrict Where ripgrep Searches](unix/unrestrict-where-ripgrep-searches.md)
- [Update Package Versions Known By asdf Plugin](unix/update-package-versions-known-by-asdf-plugin.md)
- [Use fzf To Change Directories](unix/use-fzf-to-change-directories.md)
- [Use Regex Pattern Matching With Grep](unix/use-regex-pattern-matching-with-grep.md)
@@ -1606,6 +1616,7 @@ _1396 TILs and counting..._
- [Pop Open The Quick Fix Window](vscode/pop-open-the-quick-fix-window.md)
- [Step Through Project-Wide Search Results](vscode/step-through-project-wide-search-results.md)
- [Toggle Between Terminals](vscode/toggle-between-terminals.md)
- [Turn Off Display Of Tabs For Files](vscode/turn-off-display-of-tabs-for-files.md)
### Webpack
@@ -1617,6 +1628,7 @@ _1396 TILs and counting..._
### Workflow
- [Add Subtitles To Existing Mux Video Asset](workflow/add-subtitles-to-existing-mux-video-asset.md)
- [Change Window Name In iTerm](workflow/change-window-name-in-iterm.md)
- [Convert An ePub Document To PDF On Mac](workflow/convert-an-epub-document-to-pdf-on-mac.md)
- [Create A Local Sanity Dataset Backup](workflow/create-a-local-sanity-dataset-backup.md)

View File

@@ -2,16 +2,16 @@
Sometimes you want to view a file on another branch (without switching
branches). That is, you want to view the version of that file as it exists
on that branch. `git show` can help. If your branch is named `my_feature` and
on that branch. `git show` can help. If the other branch is named `some_branch` and
the file you want to see is `app/models/users.rb`, then your command should
look like this:
```
$ git show my_feature:app/models/users.rb
$ git show some_branch:app/models/users.rb
```
You can even tab-complete the filename as you type it out.
See `man git-show` for more details.
[source](http://stackoverflow.com/questions/7856416/view-a-file-in-a-different-git-branch-without-changing-branches)
[source](https://stackoverflow.com/questions/7856416/view-a-file-in-a-different-git-branch-without-changing-branches)

View File

@@ -0,0 +1,25 @@
# Make Elements Non-Interactive With Inert
The [`inert`
attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/inert)
global attribute is a boolean that can be applied to an element or section of
content in an HTML document. When it is `true`, that elements and anything
nested within it will not be interactive.
```html
<div class="fancy-animation" inert>
<!-- ... -->
</div>
```
This has a couple different implications:
1. Click events are not fired on these elements.
2. These elements will not be able to gain focus.
3. These elements and content are hidden from assistive technology.
This is useful for a variety of things. In particular, it is good for
accessibility when a portion of the document, like a fancy animation, isn't
meant to be traversed by assistive technology.

View File

@@ -0,0 +1,24 @@
# Fetch Does Not Work In API Serverless Function
Next.js ships with [its own implementation of
`fetch`](https://nextjs.org/docs/app/api-reference/functions/fetch) that
extends the [native `fetch`
API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).
I ran into a bug recently that was only reproducible in production. I had a
Next.js API function that was `POST`ing to another API endpoint using `fetch`.
I tested it several ways in development. It worked great. However, once the
feature was in production, it was silently failing. After some `console.log`
debugging, I discovered that the target API was getting an empty `body` in the
`POST` request.
I don't know the specifics of why, but somehow the `fetch` implementation
running in the Vercel serverless function environment apparently strips out the
`body` of a POST request.
The solution, for me, was to add the
[`node-fetch`](https://github.com/node-fetch/node-fetch) package and import
that version of fetch in my API function. Once I made that change, my feature
was working again.
[source](https://github.com/vercel/vercel/discussions/4971)

View File

@@ -0,0 +1,41 @@
# Precedence Of Dot Env Files
_Dot Env_ files like `.env`, `.env.development`, `.env.local`, etc. are one of
the main ways to configure your Next.js app across various environments.
It's not uncommon to see several different `.env*` files in production app that
is under active development.
Here is an example of almost every variant in play:
```bash
$ ls -a -1 .env*
.env
.env.development
.env.development.local
.env.development.local.example
.env.local
.env.production
.env.test
```
So, how does Next.js decide which files to load and in what order?
It will always attempt to load `.env` and `.env.local` (except in `test`) if
those exist. It will also look for environment-specific files based on the
`NODE_ENV` (which can be one of `development`, `test`, or `production`). So, in
`development`, the `.env.development` and `.env.development.local` will be
loaded. Something like `.env.development.local.example` isn't on the list, but
rather is a convention for a dotenv file's template.
As for the order, the environment itself (your system's environment variables)
which are present in `process.env` take the highest precedence. After that, it
looks in any of the follow present files in this order, stopping once it finds
what it is looking for:
- `.env.$(NODE_ENV).local`
- `.env.local`
- `.env.$(NODE_ENV)`
- `.env`
[source](https://nextjs.org/docs/pages/building-your-application/configuring/environment-variables#environment-variable-load-order)

View File

@@ -0,0 +1,45 @@
# Audit Your Ruby Project For Any CVEs
The [`bundler-audit` gem](https://github.com/rubysec/bundler-audit) is a handy
tool that you can run manually or integrate into your CI workflow to warn you
about any CVEs in your dependencies.
Running this tool without any arguments will perform a check of your
`Gemfile.lock` file. It will check against the
[`ruby-advisory-db`](https://github.com/rubysec/ruby-advisory-db) for any CVEs
linked to your dependencies, down to the patch-level.
```bash
$ bundle exec bundler-audit
Name: puma
Version: 4.3.12
CVE: CVE-2024-21647
GHSA: GHSA-c2f4-cvqm-65w2
Criticality: Medium
URL: https://github.com/puma/puma/security/advisories/GHSA-c2f4-cvqm-65w2
Title: Puma HTTP Request/Response Smuggling vulnerability
Solution: upgrade to '~> 5.6.8', '>= 6.4.2'
Vulnerabilities found!
```
In this example run, a vulnerability was found in the currently installed
version of the `puma` gem.
I believe a standard `bundler-audit` command will make sure the advisory DB is
up-to-date, but to be sure, you can run the `update` command.
```bash
$ bundle exec bundler-audit update
Updating ruby-advisory-db ...
From https://github.com/rubysec/ruby-advisory-db
* branch master -> FETCH_HEAD
Already up to date.
Updated ruby-advisory-db
ruby-advisory-db:
advisories: 884 advisories
last updated: 2024-03-26 16:27:16 -0700
commit: 840f21aeeb8a06a93a3c3bf1e2a92d7167029992
```

View File

@@ -0,0 +1,35 @@
# Format A Hash Into A String Template
The `%` method as defined by `String`
([`String#%`](https://ruby-doc.org/core-3.0.0/String.html#method-i-25)) allows
you to format (interpolate) an object or array of values into a string. That
string needs to contain template markers for where the values should go.
Here is an example of folding an array of values into a string with [`%s`
format
specifier](https://docs.ruby-lang.org/en/master/format_specifications_rdoc.html#label-Specifier+s):
```ruby
> User = Struct.new(:id)
=> User
> user1 = User.new(123)
=> #<struct User id=123>
> "%s ID: %s" % [user1.class.to_s, user1.id]
=> "User ID: 123"
```
Or perhaps more usefully for a string that acts as a template, you can used
named specifiers that correspond to hash keys:
```ruby
> template = "You paid %{formatted_price} for %{product}. Enjoy your purchase!"
=> "You paid %{formatted_price} for %{product}. Enjoy your purchase!"
> data = { product: "Ruby Explained™", formatted_price: "$38.99" }
=> {:product=>"Ruby Explained™", :formatted_price=>"$38.99"}
> template % data
=> "You paid $38.99 for Ruby Explained™. Enjoy your purchase!"
```
[source](https://hashrocket.com/blog/posts/using-a-hash-of-data-for-string-replacement-in-ruby)

View File

@@ -0,0 +1,46 @@
# Specify How Random Array#sample Is
A typical use of the
[`sample`](https://ruby-doc.org/core-2.4.0/Array.html#method-i-sample) method
on [`Array`](https://ruby-doc.org/core-2.4.0/Array.html) will look something
like this:
```ruby
> chars = [('a'..'z'), ('A'..'Z'), ('0'..'9')].map(&:to_a).flatten
> chars.sample(6)
=> ["o", "Z", "X", "i", "8", "Y"]
```
By default, this is using `Random` (a pseudo-random number generator) to
produce a _random_ sampling of elements from your array.
The longer form of this looks like:
```ruby
> chars.sample(6, random: Random)
=> ["F", "c", "g", "I", "w", "E"]
```
Or to get reproducible results, you can specify the `Random` seed:
```ruby
> chars.sample(6, random: Random.new(123))
=> ["T", "c", "D", "K", "P", "s"]
```
If instead you want a cryptographically random sampling of elements from your
array, you can specify a different random number generator. Such as
[`SecureRandom`](https://ruby-doc.org/stdlib-2.5.1/libdoc/securerandom/rdoc/SecureRandom.html).
```ruby
> require 'securerandom'
=> true
> chars.sample(6, random: SecureRandom)
=> ["3", "C", "o", "i", "K", "4"]
```
The
[`Array#shuffle`](https://ruby-doc.org/core-2.4.0/Array.html#method-i-shuffle)
method is another example of a method that can take a `random` option.

View File

@@ -0,0 +1,31 @@
# Include Ignore Files In Ripgrep Search
By default, [ripgrep (`rg`)](https://github.com/BurntSushi/ripgrep) will look
for and respect _ignore_ files like `.gitignore`. Any file and directory marked
by those ignore files will no be included in an `rg` search.
This is usually what you want. Sometimes, however, it can be useful to get
results from this ignored files as well.
In order to ignore your ignore files, pass the `--no-ignore` flag to `rg`:
```bash
$ rg --no-ignore ENV_VAR_KEY
```
Something to keep in mind is that `rg` also ignores _hidden_ files and
directories (those things that are prefixed with a `.`, such as `.env` or
`.config/`). If some of your ignored files are also _hidden_ files, then they
still won't show up in search. You'll need the `--hidden` flag as well.
```bash
$ rg --no-ignore --hidden ENV_VAR_KEY
```
A shorthand equivalent for that is `-uu`:
```bash
$ rg -uu ENV_VAR_KEY
```
See `man rg` for more details.

View File

@@ -0,0 +1,34 @@
# List Files In A Single Column
The `ls` command lists out the files and directories in your current directory
or a specified directory.
The standard output for an `ls` command expands the fit the width of your
terminal screen.
```bash
ls *.(ts|js)
cypress.config.ts postcss.config.js remix.config.js remix.env.d.ts server.ts tailwind.config.ts vitest.config.ts
```
This might not always be the ideal way to view that output. For instance, the
above example when shared as a code block like in this post ends up with
horizontal scroll.
With the `-1` flag, we can tell `ls` to display the results in a single
vertical column.
```bash
ls -1 *.(ts|js)
cypress.config.ts
postcss.config.js
remix.config.js
remix.env.d.ts
server.ts
tailwind.config.ts
vitest.config.ts
```
See `man ls` for more details.
[source](https://askubuntu.com/questions/954924/listing-files-in-directory-in-one-column)

View File

@@ -0,0 +1,16 @@
# Print DateTime Represented By Unix Timestamp
A lot of tools and systems use a Unix timestamp to represent a point in time.
It is the number of seconds since the Unix epoch (Jan 1, 1970). However, just
looking at a timestamp like `1623867544` doesn't tell a human much. I can't
mentally translate that to the date and time that it is representing.
The `date` utility can help. Give it the `-r` flag with the timestamp value (in
seconds) and it will display the date and time in a human-readable format.
```bash
date -r '1623867544'
Wed Jun 16 13:19:04 CDT 2021
```
See `man date` for more details.

View File

@@ -0,0 +1,33 @@
# Unrestrict Where ripgrep Searches
One of the conveniences of [`rg`
(ripgrep)](https://github.com/BurntSushi/ripgrep) is that by default it doesn't
search in places you probably don't want it to search. That means it ignores
anything specified by your `.gitignore` file, it excludes hidden files and
directories (dotfiles, e.g. `.git/` or `.env`), and it excludes binary files.
These restrictions can be incrementally undone as needed using the `-u` flag.
The `-u` flag on its own will remove the ignored files restriction. This is
equivalent to the `--no-ignore` flag.
```bash
$ rg -u pattern
```
Adding an additional `u` (`-uu`) to that flag will remove both the ignored files and
hidden files restrictions. This is a shorthand equivalent to both `--no-ignore`
and `--hidden`.
```bash
$ rg -uu pattern
```
Adding one more `u` (`-uuu`) will additionally remove the binary file
restriction. Equivalent to those other two flags plus `--text`.
```bash
$ rg -uuu pattern
```
[source](https://github.com/BurntSushi/ripgrep/blob/master/GUIDE.md#automatic-filtering)

View File

@@ -0,0 +1,18 @@
# Turn Off Display Of Tabs For Files
Each time a file is opened in VS Code, it appears as one of many toward the top
of the window right above the text editor area. It shows the name of the file
and the 'dirty' status. Over time as more and more files are opened and edited,
the tabs accumulate and can only be viewed by horizontally scrolling left and
right.
There are other ways to navigate to files besides selecting tabs of already
opened files. So, if you'd like to reclaim some screen real estate and reduce
the visual clutter of the tabs, you can turn them off.
Hit `Cmd+Shift+P`, then search for and go to _Preferences: Open Settings (UI)_.
Search for _Show Tabs_ which will show up under _Workbench > Editor_.
The default is _Multiple_. You can switch it to _None_ to completely hide tabs.
You can also set it to _Single_ which will display file name and path for the
current file, but eliminate the clutter of all other tabs.

View File

@@ -0,0 +1,49 @@
# Add Subtitles To Existing Mux Video Asset
There is a [JavaScript/TypeScript Mux
SDK](https://github.com/muxinc/mux-node-sdk) for interacting with Mux via their
[API](https://docs.mux.com/api-reference).
With a Mux client (initialized from `MUX_ACCESS_TOKEN` and `MUX_SECRET_KEY` in
our environment), we can destructure `Video` which will allow us to call
`Video.Assets.createTrack`. We pass that function the ID of an existing video
asset and then an object of data defining the subtitle track. In this case, it
is an English subtitle track. We need to point Mux to a `url` where the WebVTT
formatted subtitles are hosted.
```typescript
// add-srt-to-specific-video.ts
import Mux from '@mux/mux-node'
require('dotenv-flow').config({
default_node_env: 'development',
})
const assetId = "mux-asset-id" // set this value
const srtUrl = "https://public-webvtt-file" // set this value
// Set up Mux API Client
const MUX_ACCESS_TOKEN = process.env.MUX_ACCESS_TOKEN as string
const MUX_SECRET_KEY = process.env.MUX_SECRET_KEY as string
const muxClient = new Mux(MUX_ACCESS_TOKEN, MUX_SECRET_KEY)
const {Video} = muxClient
await Video.Assets.createTrack(assetId, {
url: srtUrl,
type: 'text',
text_type: 'subtitles',
closed_captions: false,
language_code: 'en-US',
name: 'English',
passthrough: 'English',
})
```
We can run the above script with `ts-node` from the command-line like so:
```bash
$ npx ts-node --files --skipProject add-srt-to-specific-video.ts
```
We'll see the new track on the existing asset in the Mux dashboard.