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

Compare commits

...

26 Commits

Author SHA1 Message Date
Karim Bouchez
cbfb7e7b96 Merge 15337dfd71 into ab9d2b5bf6 2024-10-13 17:47:54 +03:00
jbranchaud
ab9d2b5bf6 Add Check Media Queries From JavaScript as a JavaScript TIL 2024-10-12 12:30:07 -05:00
jbranchaud
aa00c55b06 Add Jump To Problems In The Current File as a VSCode TIL 2024-10-12 10:35:52 -05:00
jbranchaud
cc858382d8 Add Temporarily Turn Off Pending Migrations Error as a Rails TIL 2024-10-11 15:05:31 -05:00
jbranchaud
dbb8c585c1 Add updated note to TIL about godoc 2024-10-11 13:57:47 -05:00
jbranchaud
f25064031f Add Export List Of Everything Installed By Brew as a Brew TIL 2024-10-11 10:57:42 -05:00
jbranchaud
cfbe640eb0 Add Keyboard Shortcuts For Interacting With Text Areas as a Mac TIL 2024-10-10 11:52:22 -05:00
jbranchaud
bf04dfcca5 Add Rollback A Couple Migrations as a Rails TIL 2024-10-09 17:44:45 -05:00
jbranchaud
24b1b02d52 Add Define The Root Path For The App as a Rails TIL 2024-10-09 13:23:09 -05:00
jbranchaud
8ef2cfdc69 Add Prevent erb_lint From Removing Opening Tags as a Ruby TIL 2024-10-09 10:53:39 -05:00
jbranchaud
02086e7115 Add Link A Scalar To An Array as a Zsh TIL 2024-10-07 18:51:57 -05:00
jbranchaud
0ecc41bd29 Add Add To The Path Via Path Array as a Zsh TIL 2024-10-07 18:37:23 -05:00
jbranchaud
569220e734 Add Find Any Dotfiles That Modify Path Env Var as a Unix TIL 2024-10-07 13:44:21 -05:00
jbranchaud
594ec08636 Add Download A File With Curl as a Unix TIL 2024-10-04 12:46:21 -05:00
jbranchaud
475f125f4b Add List Running Docker Containers as a Docker TIL 2024-10-03 11:38:13 -05:00
jbranchaud
ba6492d46e Add Run A Hello World Program In Eclipse as a Java TIL 2024-10-02 21:22:43 -05:00
jbranchaud
3ac3014659 Add table of contents entry for Java 2024-10-02 21:22:23 -05:00
jbranchaud
4b6833c437 Add Install Java On Mac With Brew as a Java TIL 2024-10-01 19:21:14 -05:00
jbranchaud
fc93ecfed4 Add Validate Column Data With Check Constraints as a Rails TIL 2024-09-30 19:50:52 -05:00
jbranchaud
a07a19e6d9 Add Generate Modern Primary Key Columns as a Postgres TIL 2024-09-27 09:57:33 -05:00
jbranchaud
951a2f04ad Add Find Executables Installed By Go as a Go TIL 2024-09-26 20:54:41 -05:00
jbranchaud
6b9ec224b8 Add Connect To A Database By Color as a Heroku TIL 2024-09-26 08:47:31 -05:00
jbranchaud
c33be14ec2 Add Skip The Front Of An Array With Drop as a Ruby TIL 2024-09-25 22:43:04 -05:00
jbranchaud
2922bbdd6a Add Check Network Quality Stats From The Command Line as a Mac TIL 2024-09-24 11:08:38 -05:00
jbranchaud
2e72ec1160 Add Generate A Model as a Rails TIL 2024-09-20 20:54:52 -05:00
Karim Bouchez
15337dfd71 Update the old way to capture a GitHub Actions output
See [here](https://github.blog/changelog/2022-10-11-github-actions-deprecating-save-state-and-set-output-commands/) for more explanations:
> We are monitoring telemetry for the usage of these commands and plan to fully disable them on 31st May 2023. Starting 1st June 2023 workflows using save-state or set-output commands via stdout will fail with an error.
2023-02-12 10:36:45 +01:00
25 changed files with 761 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).
_1441 TILs and counting..._
_1463 TILs and counting..._
---
@@ -37,6 +37,7 @@ _1441 TILs and counting..._
* [HTTP](#http)
* [Inngest](#inngest)
* [Internet](#internet)
* [Java](#java)
* [JavaScript](#javascript)
* [jq](#jq)
* [Kitty](#kitty)
@@ -79,6 +80,7 @@ _1441 TILs and counting..._
* [XState](#xstate)
* [YAML](#yaml)
* [Zod](#zod)
* [Zsh](#zsh)
---
@@ -99,6 +101,7 @@ _1441 TILs and counting..._
### Brew
- [Configure Brew Environment Variables](brew/configure-brew-environment-variables.md)
- [Export List Of Everything Installed By Brew](brew/export-list-of-everything-installed-by-brew.md)
- [List All Services Managed By Brew](brew/list-all-services-managed-by-brew.md)
### Chrome
@@ -196,6 +199,7 @@ _1441 TILs and counting..._
### Docker
- [Configure Different Host And Container Ports](docker/configure-different-host-and-container-ports.md)
- [List Running Docker Containers](docker/list-running-docker-containers.md)
- [Run A Basic PostgreSQL Server In Docker](docker/run-a-basic-postgresql-server-in-docker.md)
### Elixir
@@ -376,6 +380,7 @@ _1441 TILs and counting..._
- [Access Go Docs Offline](go/access-go-docs-offline.md)
- [Build For A Specific OS And Architecture](go/build-for-a-specific-os-and-architecture.md)
- [Find Executables Installed By Go](go/find-executables-installed-by-go.md)
- [Not So Random](go/not-so-random.md)
- [Replace The Current Process With An External Command](go/replace-the-current-process-with-an-external-command.md)
- [Sleep For A Duration](go/sleep-for-a-duration.md)
@@ -390,6 +395,7 @@ _1441 TILs and counting..._
### Heroku
- [Connect To A Database By Color](heroku/connect-to-a-database-by-color.md)
- [Deploy A Review App To A Different Stack](heroku/deploy-a-review-app-to-a-different-stack.md)
- [Diagnose Problems In A Heroku Postgres Database](heroku/diagnose-problems-in-a-heroku-postgres-database.md)
- [Open Dashboard For Specific Add-On](heroku/open-dashboard-for-specific-add-on.md)
@@ -428,6 +434,11 @@ _1441 TILs and counting..._
- [Search Tweets By Author](internet/search-tweets-by-author.md)
- [Show All Pivotal Stories With Blockers](internet/show-all-pivotal-stories-with-blockers.md)
### Java
- [Install Java On Mac With Brew](java/install-java-on-mac-with-brew.md)
- [Run A Hello World Program In Eclipse](java/run-a-hello-world-program-in-eclipse.md)
### JavaScript
- [Accessing Arguments To A Function](javascript/accessing-arguments-to-a-function.md)
@@ -438,6 +449,7 @@ _1441 TILs and counting..._
- [Check If A Number Is Positive Or Negative](javascript/check-if-a-number-is-positive-or-negative.md)
- [Check If File Exists Before Reading It](javascript/check-if-file-exists-before-reading-it.md)
- [Check If Something Is An Array](javascript/check-if-something-is-an-array.md)
- [Check Media Queries From JavaScript](javascript/check-media-queries-from-javascript.md)
- [Check The Password Confirmation With Yup](javascript/check-the-password-confirmation-with-yup.md)
- [Compare The Equality Of Two Date Objects](javascript/compare-the-equality-of-two-date-objects.md)
- [Computed Property Names In ES6](javascript/computed-property-names-in-es6.md)
@@ -571,6 +583,7 @@ _1441 TILs and counting..._
- [Access All Screen And Video Capture Options](mac/access-all-screen-and-video-capture-options.md)
- [Access System Information On OS X](mac/access-system-information-on-osx.md)
- [Access Unsupported Screen Resolutions With RDM](mac/access-unsupported-screen-resolutions-with-rdm.md)
- [Check Network Quality Stats From The Command Line](mac/check-network-quality-stats-from-the-command-line.md)
- [Clean Up Old Homebrew Files](mac/clean-up-old-homebrew-files.md)
- [Convert An HEIC Image File To JPG](mac/convert-an-heic-image-file-to-jpg.md)
- [Default Screenshot Location](mac/default-screenshot-location.md)
@@ -579,6 +592,7 @@ _1441 TILs and counting..._
- [Find The Process Using A Specific Port](mac/find-the-process-using-a-specific-port.md)
- [Gesture For Viewing All Windows Of Current App](mac/gesture-for-viewing-all-windows-of-current-app.md)
- [Insert A Non-Breaking Space Character](mac/insert-a-non-breaking-space-character.md)
- [Keyboard Shortcuts For Interesting With Text Areas](mac/keyboard-shortcuts-for-interacting-with-text-areas.md)
- [List All The Say Voices](mac/list-all-the-say-voices.md)
- [Open Finder.app To Specific Directory](mac/open-finder-app-to-specific-directory.md)
- [Quickly Type En Dashes And Em Dashes](mac/quickly-type-en-dashes-and-em-dashes.md)
@@ -733,6 +747,7 @@ _1441 TILs and counting..._
- [Fizzbuzz With Common Table Expressions](postgres/fizzbuzz-with-common-table-expressions.md)
- [Force SSL When Making A psql Connection](postgres/force-ssl-when-making-a-psql-connection.md)
- [Generate A UUID](postgres/generate-a-uuid.md)
- [Generate Modern Primary Key Columns](postgres/generate-modern-primary-key-columns.md)
- [Generate Random UUIDs Without An Extension](postgres/generate-random-uuids-without-an-extension.md)
- [Generate Series Of Numbers](postgres/generate-series-of-numbers.md)
- [Generating UUIDs With pgcrypto](postgres/generating-uuids-with-pgcrypto.md)
@@ -887,6 +902,7 @@ _1441 TILs and counting..._
- [Custom Validation Message](rails/custom-validation-message.md)
- [Customize Paths And Helpers For Devise Routes](rails/customize-paths-and-helpers-for-devise-routes.md)
- [Customize The Path Of A Resource Route](rails/customize-the-path-of-a-resource-route.md)
- [Define The Root Path For The App](rails/define-the-root-path-for-the-app.md)
- [Delete Paranoid Records](rails/delete-paranoid-records.md)
- [Demodulize A Class Name](rails/demodulize-a-class-name.md)
- [Different Ways To Add A Foreign Key Reference](rails/different-ways-to-add-a-foreign-key-reference.md)
@@ -897,6 +913,7 @@ _1441 TILs and counting..._
- [Find Or Create A Record With FactoryBot](rails/find-or-create-a-record-with-factory-bot.md)
- [Find Records With Multiple Associated Records](rails/find-records-with-multiple-associated-records.md)
- [Force All Users To Sign Out](rails/force-all-users-to-sign-out.md)
- [Generate A Model](rails/generate-a-model.md)
- [Generate A Rails App From The Main Branch](rails/generate-a-rails-app-from-the-main-branch.md)
- [Generating And Executing SQL](rails/generating-and-executing-sql.md)
- [Get A Quick Approximate Count Of A Large Table](rails/get-a-quick-approximate-count-of-a-large-table.md)
@@ -951,6 +968,7 @@ _1441 TILs and counting..._
- [Rescue From With A Separate Method](rails/rescue-from-with-a-separate-method.md)
- [Respond With JSON Regardless of Content Type](rails/respond-with-json-regardless-of-content-type.md)
- [Retrieve An Object If It Exists](rails/retrieve-an-object-if-it-exists.md)
- [Rollback A Couple Migrations](rails/rollback-a-couple-migrations.md)
- [Rollback A Specific Migration Out Of Order](rails/rollback-a-specific-migration-out-of-order.md)
- [Rounding Numbers With Precision](rails/rounding-numbers-with-precision.md)
- [Run A Rake Task Programmatically](rails/run-a-rake-task-programmatically.md)
@@ -973,6 +991,7 @@ _1441 TILs and counting..._
- [Skip Validations When Creating A Record](rails/skip-validations-when-creating-a-record.md)
- [Specify New Attributes For #find_or_create_by](rails/specify-new-attributes-for-find-or-create-by.md)
- [Temporarily Disable strong_params](rails/temporarily-disable-strong-params.md)
- [Temporarily Turn Off Pending Migrations Error](rails/temporarily-turn-off-pending-migrations-error.md)
- [Test For A Subset Of Attributes On A Model](rails/test-for-a-subset-of-attributes-on-a-model.md)
- [Test If An Instance Variable Was Assigned](rails/test-if-an-instance-variable-was-assigned.md)
- [Test If deliver_later Is Called For A Mailer](rails/test-if-deliver-later-is-called-for-a-mailer.md)
@@ -981,6 +1000,7 @@ _1441 TILs and counting..._
- [Update Column Versus Update Attribute](rails/update-column-versus-update-attribute.md)
- [Upgrading Your Manifest For Sprocket's 4](rails/upgrading-your-manifest-for-sprockets-4.md)
- [Use IRB And Ruby Flags With Rails Console](rails/use-irb-and-ruby-flags-with-rails-console.md)
- [Validate Column Data With Check Constraints](rails/validate-column-data-with-check-constraints.md)
- [Verify And Read A Signed Cookie Value](rails/verify-and-read-a-signed-cookie-value.md)
- [Where Am I In The Partial Iteration?](rails/where-am-i-in-the-partial-iteration.md)
- [Why Redirect And Return In Controllers](rails/why-redirect-and-return-in-controllers.md)
@@ -1198,6 +1218,7 @@ _1441 TILs and counting..._
- [Pattern Match Values From A Hash](ruby/pattern-match-values-from-a-hash.md)
- [Percent Notation](ruby/percent-notation.md)
- [Precedence Of Logical Operators](ruby/precedence-of-logical-operators.md)
- [Prevent erb_lint From Removing Opening Tags](ruby/prevent-erb-lint-from-removing-opening-tags.md)
- [Print Data To Formatted Table](ruby/print-data-to-formatted-table.md)
- [Question Mark Operator](ruby/question-mark-operator.md)
- [Rake Only Lists Tasks With Descriptions](ruby/rake-only-lists-tasks-with-descriptions.md)
@@ -1222,6 +1243,7 @@ _1441 TILs and counting..._
- [Silence The Output Of A Ruby Statement In Pry](ruby/silence-the-output-of-a-ruby-statement-in-pry.md)
- [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)
- [Skip The Front Of An Array With Drop](ruby/skip-the-front-of-an-array-with-drop.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)
@@ -1373,6 +1395,7 @@ _1441 TILs and counting..._
- [Display The Contents Of A Directory As A Tree](unix/display-the-contents-of-a-directory-as-a-tree.md)
- [Do A Dry Run Of An rsync](unix/do-a-dry-run-of-an-rsync.md)
- [Do Not Overwrite Existing Files](unix/do-not-overwrite-existing-files.md)
- [Download A File With Curl](unix/download-a-file-with-curl.md)
- [Enable Multi-Select Of Results With fzf](unix/enable-multi-select-of-results-with-fzf.md)
- [Exclude A Command From The ZSH History File](unix/exclude-a-command-from-the-zsh-history-file.md)
- [Exclude A Directory With Find](unix/exclude-a-directory-with-find.md)
@@ -1381,6 +1404,7 @@ _1441 TILs and counting..._
- [File Type Info With File](unix/file-type-info-with-file.md)
- [Find All Files Matching A Name With fd](unix/find-all-files-matching-a-name-with-fd.md)
- [Find All Files With A Specific Extension With fd](unix/find-all-files-with-a-specific-extension-with-fd.md)
- [Find Any Dotfiles That Modify Path Env Var](unix/find-any-dotfiles-that-modify-path-env-var.md)
- [Find A File Installed By Brew](unix/find-a-file-installed-by-brew.md)
- [Find Duplicate Lines In A File](unix/find-duplicate-lines-in-a-file.md)
- [Find Files With fd](unix/find-files-with-fd.md)
@@ -1648,6 +1672,7 @@ _1441 TILs and counting..._
- [Advance Through Search Results](vscode/advance-through-search-results.md)
- [Enable Breadcrumbs For Version 1.26 Release](vscode/enable-breadcrumbs-for-version-126-release.md)
- [Find The Location Of User Settings JSON File](vscode/find-the-location-of-user-settings-json-file.md)
- [Jump To Problems In The Current File](vscode/jump-to-problems-in-the-current-file.md)
- [Open An Integrated Terminal Window](vscode/open-an-integrated-terminal-window.md)
- [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)
@@ -1710,6 +1735,11 @@ _1441 TILs and counting..._
- [Incorporate Existing Type Into Zod Schema](zod/incorporate-existing-type-into-zod-schema.md)
- [Set Custom Error Message For Nonempty Array](zod/set-custom-error-message-for-nonempty-array.md)
### Zsh
- [Add To The Path Via Path Array](zsh/add-to-the-path-via-path-array.md)
- [Link A Scalar To An Array](zsh/link-a-scalar-to-an-array.md)
## Usage
The `.vimrc` file for this project contains a function `CountTILs` that can

View File

@@ -0,0 +1,48 @@
# Export List Of Everything Installed By Brew
If you're on a Mac using Homebrew to install various tools and utilities, there
may come a time when you want a listing of what is installed.
Run this command:
```bash
$ brew bundle dump
```
It may take 10 or so seconds. When it is done, you'll have a `Brewfile` in your
current directory.
Open it up and you'll see a bunch of lines like the following:
```
tap "heroku/brew"
tap "homebrew/bundle"
tap "homebrew/services"
tap "mongodb/brew"
tap "planetscale/tap"
tap "stripe/stripe-cli"
brew "asdf"
brew "bat"
brew "direnv"
brew "entr"
brew "exa"
brew "fd"
brew "ffmpeg"
brew "fx"
brew "fzf"
brew "gcc"
brew "gh"
brew "planetscale/tap/pscale"
brew "stripe/stripe-cli/stripe"
cask "1password-cli"
vscode "ms-playwright.playwright"
vscode "ms-vsliveshare.vsliveshare"
vscode "prisma.prisma"
```
Notice there are `tap`, `brew`, `cask`, and even `vscode` directives.
This is a file you could export and then run on a 'new' machine to install all
the programs you're used to having available on your current machine.
[source](https://danmunoz.com/setting-up-a-new-computer-with-homebrew/)

View File

@@ -0,0 +1,22 @@
# List Running Docker Containers
The `docker` CLI has a `ps` command that will list all running container by
default.
When I run it, I can see that I have a container running a Postgres database
and another running a MySQL database.
```bash
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
ba792e185734 postgres:latest "docker-entrypoint.s…" 12 days ago Up 12 days 0.0.0.0:9876->5432/tcp better_reads-postgres-1
7ca7c1e882e0 mysql:8.0 "docker-entrypoint.s…" 19 months ago Up 8 seconds 33060/tcp, 0.0.0.0:3309->3306/tcp some-app-db-1
```
It lists several pieces of info about the containers: the container id, the
image it is based off, when it was created, the running status, the port
configuration, and the name of the container
If I run `docker ps --help` I can see some additional options. One option is
the `--all` flag which will display all known docker container instead of just
the running ones.

View File

@@ -23,11 +23,11 @@ version from my `.tool-versions` file with a step that uses `set-output`.
- name: Read Node.js version to install from `.tool-versions`
id: nodejs
run: >-
echo "::set-output name=NODE_VERSION::$(
echo "NODE_VERSION=$(
cat .tool-versions |
grep nodejs |
sed 's/nodejs \(.*\)$/\1/'
)"
)" >> $GITHUB_OUTPUT
```
`echo` runs the command in the string which sets `NODE_VERSION` as an output
@@ -45,4 +45,4 @@ This output value can be referenced in a later step.
`steps` has a reference to the `nodejs` step (note the `id` above) which then
has `outputs` like the `NODE_VERSION`.
[source](https://docs.github.com/en/actions/reference/workflow-commands-for-github-actions#using-workflow-commands-to-access-toolkit-functions)
[source](https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#setting-an-output-parameter)

View File

@@ -15,4 +15,10 @@ $ godoc -http=:6060
and then visit `localhost:6060`.
Note: if you do not already have `godoc` installed, you can install it with:
```bash
$ go install golang.org/x/tools/cmd/godoc@latest
```
[source](http://www.andybritcliffe.com/post/44610795381/offline-go-lang-documentation)

View File

@@ -0,0 +1,26 @@
# Find Executables Installed By Go
When you install an executable using `go install`, it puts that executable in
the `bin` directory designated by the `GOBIN` environment variable. If that env
var isn't set, then it falls back to one of `$GOPATH/bin` or `$HOME/go/bin`.
When I run `go help install`, it tells me as much:
```
Executables are installed in the directory named by the GOBIN environment
variable, which defaults to $GOPATH/bin or $HOME/go/bin if the GOPATH
environment variable is not set.
```
So, if I am to install something like [`tern`](https://github.com/jackc/tern),
```bash
$ go install github.com/jackc/tern/v2@latest
```
it is going to place that binary in `~/go/bin` for me.
```bash
$ which tern
/Users/jbranchaud/go/bin/tern
```

View File

@@ -0,0 +1,29 @@
# Connect To A Database By Color
All of your PostgreSQL databases in Heroku are given attachment names that use
a random color. This might be _pink_, _brown_, _cobalt_, etc. And the
attachment names then look like `HEROKU_POSTGRESQL_PINK`,
`HEROKU_POSTGRESQL_BROWN`, `HEROKU_POSTGRESQL_COBALT`, etc.
We can connect to a Heroku-managed PostgreSQL instance from the command-line
like so:
```bash
$ heroku pg:psql --app my-app
```
This is going to connect to the _default_ database which is the one with the
`DATABASE_URL` attachment.
There are lots of instances where we may have other databases besides the
primary (e.g. let's say we have a read replica follower). If we want to connect
to that one, we can do so by _color_.
If that database's attachment is `HEROKU_POSTGRESQL_IVORY`, then we'd connect
to it like so:
```bash
$ heroku pg:psql ivory --app my-app
```
[source](https://devcenter.heroku.com/articles/managing-heroku-postgres-using-cli#pg-psql)

View File

@@ -0,0 +1,47 @@
# Install Java On Mac With Brew
If you don't already have Java installed on your Mac, you can install it with
homebrew.
```bash
$ brew install java
```
This will take a bit to run and when all is complete, you'll go to run
something like a version check and see this:
```bash
$ java -version
The operation couldnt be completed. Unable to locate a Java Runtime.
Please visit http://www.java.com for information on installing Java.
```
This is because [OpenJDK](https://openjdk.org/) the open-source implementation
of the Java Development Kit (Java platform) does not get fully set up by
homebrew.
You'll need to symlink `openjdk` and the exact command with correct paths can
be found from running the following:
```bash
$ brew info openjdk
...
For the system Java wrappers to find this JDK, symlink it with
sudo ln -sfn /usr/local/opt/openjdk/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk.jdk
...
```
The paths may look different for you, so copy the exact command and run that.
Once the symlink is set, check the version again.
```bash
$ java -version
openjdk version "23" 2024-09-17
OpenJDK Runtime Environment Homebrew (build 23)
OpenJDK 64-Bit Server VM Homebrew (build 23, mixed mode, sharing)
```
[source](https://stackoverflow.com/a/65601197/535590)

View File

@@ -0,0 +1,27 @@
# Run A Hello World Program In Eclipse
First, you'll need to create a new Java Project if you don't already have one
to work in.
From there, you can add a new _Class_ to the `src` folder of that project. I'll
call mine `Greeting.java` and the only thing it will contain is a `main`
method.
```java
public class Greeting {
public static void main(String[] args) {
String name = args.length > 0 ? args[0] : "World";
System.out.println("Hello, " + name + "!");
}
}
```
This method tries to read a name from the arguments given to the program at
time of execution. If one wasn't provided the ternary falls back to `"World"`
as the default name. It then prints the greeting to stdout.
To run this program, we can either select _Run_ from the _Run_ menu (which will
result in `Hello, World!`) or we can select _Run Configurations..._ from the
same menu and add a custom name to _Program Arguments_ under the _Arguments_
tab.

View File

@@ -0,0 +1,28 @@
# Check Media Queries From JavaScript
I'm usually thinking about and [using media
queries](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries)
from a CSS context. I use them to control what styles are displayed for a
variety of scenarios, such as at different screen widths, when a user prefers
reduced motion, or when the user prefers a dark color scheme.
The current value of various media queries can be checked from a JavaScript
context as well.
For instance, if we want to see if the user prefers a _dark_ color schema, we
can look for a _match_ on that media query with
[`matchMedia`](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia).
```javascript
> window.matchMedia('(prefers-color-scheme: dark)')
MediaQueryList {media: '(prefers-color-scheme: dark)', matches: true, onchange: null}
> window.matchMedia('(prefers-color-scheme: dark)')['matches']
true
```
This queries for the [`prefers-color-scheme` media
feature](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme).
The [Astro.build Blog
Tutorial](https://docs.astro.build/en/tutorial/6-islands/2/#add-client-side-interactivity)
shows an example of using this to wire up a Light/Dark mode toggle.

View File

@@ -0,0 +1,44 @@
# Check Network Quality Stats From The Command Line
MacOS comes with a little known CLI utility for checking your current network
quality statistics. It is aptly named `networkQuality`.
Here is what a basic run of the tool might output:
```bash
$ networkQuality
...
Downlink: capacity 281.430 Mbps, responsiveness 101 RPM - Uplink: capacity 16.629 Mbps, responsiveness 101 R
Downlink: capacity 285.534 Mbps, responsiveness 101 RPM - Uplink: capacity 16.028 Mbps, responsiveness 101 R
==== SUMMARY ====
Uplink capacity: 22.982 Mbps
Downlink capacity: 288.152 Mbps
Responsiveness: Low (93 RPM)
Idle Latency: 26.375 milliseconds
```
You can get an even more detailed summary with the `-v` option:
```bash
$ networkQuality -v
...
==== SUMMARY ====
Uplink capacity: 18.257 Mbps (Accuracy: High)
Downlink capacity: 469.355 Mbps (Accuracy: High)
Responsiveness: Medium (252 RPM) (Accuracy: High)
Idle Latency: 25.583 milliseconds (Accuracy: High)
Interface: en0
Uplink bytes transferred: 19.750 MB
Downlink bytes transferred: 488.265 MB
Uplink Flow count: 8
Downlink Flow count: 12
Start: 9/24/24, 11:06:20 AM
End: 9/24/24, 11:06:30 AM
OS Version: Version 13.5.2 (Build 22G91)
```
See `man networkQuality` for more details.
[source](https://cyberhost.uk/the-hidden-macos-speedtest-tool-networkquality/)

View File

@@ -0,0 +1,24 @@
# Keyboard Shortcuts For Interacting With Text Areas
When interacting with a document text area on MacOS (such as in the Notes app),
there are a bunch of keyboard shortcuts made available to you via the operating
system.
A couple common ones that I'm used to from Unix environments are:
- `ctrl-a` to move the cursor to the beginning of the line
- `ctrl-e` to move the cursor to the end of the line
- `ctrl-p` to move the cursor up a line (this is a common _previous_ keybinding)
- `ctrl-n` to move the cursor down a line (this is a common _next_ keybinding)
A handy one that I wasn't aware of is `ctrl-l` which will scroll the text area
so that the cursor gets centered in the view area.
A much more niche one I wasn't aware of is `ctrl-t` which swaps the character
before the cursor with the character after the cursor. I can only imagine this
being useful for quickly fixing transposed characters in a misspelled word,
e.g. `baer`.
There are many more *Document Shortcuts* as well as well as keyboard shorcuts
for other apps and situations. The full listing is at [Mac Keyboard
Shortcuts](https://support.apple.com/en-us/102650).

View File

@@ -0,0 +1,43 @@
# Generate Modern Primary Key Columns
Chances are if you have looked at some examples, blog posts, or real-world
instances of a `create table` statement, it defined the primary key with
`serial` (or `bigserial`).
```sql
create table books (
id serial primary key,
title text not null,
author text not null,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
```
The `serial` syntax is everywhere, but for quite a while now it has not been
the recommended way to define a primary key column for the `int` or `bigint`
data types.
The ["Don't Do This" page of the PostgreSQL
wiki](https://wiki.postgresql.org/wiki/Don%27t_Do_This#Don.27t_use_serial) says
"Don't use serial".
> For new applications, identity columns should be used instead. The serial
> types have some weird behaviors that make schema, dependency, and permission
> management unnecessarily cumbersome.
The modern way to define a primary key column for `int` or `bigint` is with a
generated identity column.
```sql
create table books (
id int primary key generated always as identity,
title text not null,
author text not null,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
```
Check out the PostgreSQL docs for more about [identity
columns](https://www.postgresql.org/docs/17/ddl-identity-columns.html).

View File

@@ -0,0 +1,37 @@
# Define The Root Path For The App
The `root_path` helper that you might want to use in Rails controllers and
views is not available by default.
```ruby
> Rails.application.routes.url_helpers.root_path
ruby/3.2.2/lib/ruby/gems/3.2.0/gems/irb-1.14.0/lib/irb.rb:1285:in `full_message': undefined method `root_path' for #<Module:0x0000000106d11738> (NoMethodError)
Rails.application.routes.url_helpers.root_path
^^^^^^^^^^
Did you mean? logout_path
book_path
```
It needs to be declared in the `config/routes.rb` file with the controller
action that it points to.
```ruby
# config/routes.rb
Rails.application.routes.draw do
root 'home#index'
end
```
Once this is defined the `root_path` will now be available with the rest of
your URL helpers.
```ruby
better-reads(dev)> reload!
Reloading...
better-reads(dev)> Rails.application.routes.url_helpers.root_path
=> "/"
```
[source](https://guides.rubyonrails.org/routing.html#using-root)

26
rails/generate-a-model.md Normal file
View File

@@ -0,0 +1,26 @@
# Generate A Model
The `rails` CLI comes with a variety of generators. Perhaps the mostly common
one to use is the _model_ generator.
The model generator will create a migration and a model file for the entity
that you name. In the following example `Book` will result in a
`app/models/book.rb` file as well as a migration file for a `books` table.
These generators know the singular and plural conventions.
At the end of the command is a series of field definitions containing the field
_name_ and field _type_. These are used in the migration file for defining
columns on the new table.
```bash
bin/rails generate model Book title:string publication_date:date author:string
invoke active_record
create db/migrate/20240920223447_create_books.rb
create app/models/book.rb
invoke rspec
create spec/models/book_spec.rb
```
You may also notice that an `rspec` action was invoked as part of this
generator. That is because I have the `rspec-rails` gem in my project. That gem
hooks into the model generator so that a model spec also gets generated. Handy!

View File

@@ -0,0 +1,25 @@
# Rollback A Couple Migrations
Let's say we need to rollback a couple Rails migrations that have been applied
to our local environment. We run `rails db:migrate:status` and see that there
are _2_ migrations that we want to _undo_.
We can accomplish this by using the `STEP` env var with the rollback command.
```bash
$ rails db:rollback STEP=2
```
Just set `STEP` to the number of migrations that we need to rollback. If we
then rerun `rails db:migrate:status` we'll now see those latest two migrations
are `down`.
Note: by default Rails doesn't like to operate with pending migrations. If we
want to temporarily disable the pending migration check, we can alter the
migration error config in `config/development.rb`.
```diff
# Raise an error on page load if there are pending migrations.
- # config.active_record.migration_error = :page_load
+ config.active_record.migration_error = false
```

View File

@@ -0,0 +1,33 @@
# Temporarily Turn Off Pending Migrations Error
Whenever I'm working on an end-to-end feature in a Rails app, soon or later I
am going to see the _Pending Migrations_ error page. I try to visit one of the
routes in the browser and the Rails app serves this error page instead of my
actual request response.
This is typically what I want. If there are migrations just sitting there that
haven't been run yet, that's probably an issue. Maybe I just pulled down the
latest changes from my teammates. The app isn't going to work properly without
whatever schema changes are prescribed in those pending migrations.
The thing to do is run those migrations.
In some special cases though, I know what I'm doing and I would like to operate
my app locally with specific migrations not yet applied.
To skip the error, I can change this `config/environments/development.rb`
setting from:
```ruby
config.active_record.migration_error = :page_load
```
to:
```ruby
config.active_record.migration_error = false
```
I just need to make sure to switch it back when I'm done.
[source](https://til.hashrocket.com/posts/ujcixh5rwi-rails-ignore-pending-migrations)

View File

@@ -0,0 +1,32 @@
# Validate Column Data With Check Constraints
A check constraint is a feature of database systems like PostgreSQL that allows
you to enforce rules about the data that goes in a table's column. As of Rails
6.1, ActiveRecord provides a way to add a check constraint via the DSL.
In this example, we want to ensure that the value going into the
reading_statuses.status column is one of four values. Nothing else besides
these four values should be allowed.
```ruby
class AddReadingStatusTable < ActiveRecord::Migration[7.2]
def change
create_table :reading_statuses do |t|
t.references :user, null: false, foreign_key: true
t.references :book, null: false, foreign_key: true
t.string :status, null: false
t.timestamps
end
add_check_constraint
:reading_statuses,
"status in ('started', 'completed', 'abandoned', 'already_read')",
name: "reading_statuses_valid_status_check"
end
end
```
The `#add_check_constraint` method takes the name of the table and a SQL clause
that can evaluate to true or false for a given row. We can optionally include
the name of the check constraint (e.g. {table_name}_{column_name}_check) like
we've done above.

View File

@@ -0,0 +1,45 @@
# Prevent erb_lint From Removing Opening Tags
The [`erb_lint` gem](https://github.com/Shopify/erb_lint) is a tool from
shopify for linting and auto-formatting ERB files. When I first set it up in a
Rails codebase with the base `.erb-lint.yml` recommended in the README, I ran
into a pernicious issue. The linter wanted to remove opening tags (i.e. `<%`
and `<%=`) from my ERB files.
So, for a file that looked like this:
```erb
<div>
<%= form_with(url: login_path, scope: :session) do |f| %>
<div>
<%= f.label :email %>
<%= f.email_field :email %>
</div>
</div>
```
It would get formatted to this:
```erb
<div>
form_with(url: login_path, scope: :session) do |f| %>
<div>
f.label :email %>
f.email_field :email %>
</div>
</div>
```
Yikes!
I had to disable a couple rules (under `rubocop_config:`) in the `.erb-lint.yml` file to get it to stop
doing this.
```yaml
Layout/InitialIndentation:
Enabled: false
Layout/TrailingEmptyLines:
Enabled: false
```
[source](https://github.com/Shopify/erb_lint/issues/222)

View File

@@ -0,0 +1,44 @@
# Skip The Front Of An Array With Drop
I've long been familiar with Ruby's
[`Array#take`](https://apidock.com/ruby/Array/take) which is a handy way to
grab the first few elements of an array.
```ruby
> [:a, :b, :c, :d, :e, :f, :g].take(4)
=> [:a, :b, :c, :d]
```
But what if I want to skip those first four elements of the array and get what
remains. That is where [`Array#drop`](https://apidock.com/ruby/Array/drop)
comes in.
```ruby
> [:a, :b, :c, :d, :e, :f, :g].drop(4)
=> [:e, :f, :g]
```
How about a couple practical situations for use in a Rails app.
Here I want to segment out the first 6 books and whatever remains:
```
def index
@books = Book.order(created_at: :desc).limit(10)
@featured_books = @books.take(6)
@remaining_books = @books.drop(6)
end
```
Or, what about cleaning up all but the first of these duplicate records:
```
Book
.where(title: "The Murder of Roger Ackroyd")
.drop(1)
.each { |duplicate_book| duplicate_book.destroy }
```
The first record is ignored (dropped from the array) and the following records
are processed by the `#each` where they get destroyed.

View File

@@ -0,0 +1,23 @@
# Download A File With Curl
Though I typically think of cURL as a way of hitting an API endpoint to check
its headers or see what it returns, it can also be used as an alternative to
`wget` to download a file.
With the `-O` option (short for `--remote-name`) we instruct cURL to save the
contents of the remote file to a local file in the current directory _using the
same name as the remote_.
Here is an example:
```bash
$ curl -O https://www.apache.org/dist/db/derby/db-derby-10.17.1.0/db-derby-10.17.1.0-bin.zip.asc
```
This creates a file in my current directory called
`db-derby-10.17.1.0-bin.zip.asc`. Notice it only uses the last part of the path
for the file name.
See `man curl` for more details.
[source](https://stackoverflow.com/questions/4572153/os-x-equivalent-of-linuxs-wget#comment84857090_4572158)

View File

@@ -0,0 +1,37 @@
# Find Any Dotfiles That Modify Path Env Var
Whether you are using `zsh`, `bash`, or some other shell, there are a variety
of dotfiles where you can place statements to update the `PATH` env var. These
files don't all run in the same contexts and it can be tricky to debug if one
is clobbering the path set by another.
One way to audit how your `PATH` gets set and track down any issues is to find
any place where the path may be getting modified in your dotfiles.
I like to use [`rg` (ripgrep)](https://github.com/BurntSushi/ripgrep) for tasks
like this.
First, I want to check where the `PATH` is explicitly modified.
```bash
$ rg 'export PATH' ~/\.* --max-depth 0
```
This looks at all instances of dotfiles in my home directory where `export
PATH` appears. That should catch the majority of ways that it gets updated.
Next, because I am using `zsh` as my shell, I want to look for another way my
path might be set. `zsh` defaults to setting up `path` as proxy for `PATH` that
acts as an array.
I check for any instances of `path=` or `path+=` in my dotfiles:
```bash
$ rg 'path\+?=' ~/\.* --max-depth 0
```
Note that the `--max-depth 0` is really important for both because otherwise a
ton of irrelevant stuff buried in deeply-nested dot-directories will be
surfaced.
If you want just a file name summary of the results, tack on a `-l` flag.

View File

@@ -0,0 +1,18 @@
# Jump To Problems In The Current File
VSCode has a system for different extensions to report problems. The editor
will visually flag those problems in the editor with a red squiggly underline.
It will also list them in the _Problems_ tab of the bottom tray (hit `Cmd+j` to
pop that tray open).
If there are some active problems in your current file, you can jump right to
them.
Hit `F8` and you'll jump to the next problem after wherever the cursor is. Hit
`F8` again and it will go to the next one.
Want to track back through the file? Hit `Shift+F8` and you'll jump to the
closest problem _behind_ the current cursor position.
Using these two, you can quickly survey the current problems in your file
before deciding how to proceed.

View File

@@ -0,0 +1,25 @@
# Add To Path Via Path Array
Typically when managing what is on your path in a Unix shell environment, you
override the `PATH` environment variable with `export`. This is usually an
append or prepend to bring along the existing path entries.
```bash
$ export PATH="$PATH:/Users/me/.local/bin"
```
The `zsh` shell environment exposes another way of adding to your path. They
have a `path` array which can be a little easier to work with since you can use
an array operation instead of string interpolation.
Here is how we'd do the same as above:
```bash
$ path+=/Users/me/.local/bin
```
This works because there is an automatic linking in zsh between arrays and
colon-separated strings (_scalars_).
[source](https://www.zsh.org/mla/users//2005/msg01132.html)
[source](https://superuser.com/a/1447959)

View File

@@ -0,0 +1,38 @@
# Link A Scalar To An Array
`Zsh` has a builtin command `typeset` that does a variety of things. When given
the `-T` flag and the names of a scalar and an array, it will link them
together so that a change to one is reflected in the other.
The scalar is a string of values delimited by a colon (`:`). The array is an
array that can be interacted with using array operations like append (`+=`).
```bash
$ typeset -T FOO foo
$ echo $FOO
$ export FOO="one:two"
$ echo $foo
one two
$ foo+=three
$ echo $FOO
one:two:three
```
Notice `FOO` is initially empty. I then `export` it to overwrite it with two
values delimited by a colon. Since `foo` is automatically kept in sync, I can
`echo $foo` and see those values displayed as an array. I can then append a
third value using an array operation on `foo`. The update will be automatically
reflected in `FOO`.
`Zsh` does this under the hood for `PATH` and `path` which is why you can [add
to the path via the path array](add-to-the-path-via-path-array.md).
See `man zshbuiltins` for more details.
[source](http://devlib.symbian.slions.net/s3/GUID-D87C96CE-3F23-552D-927C-B6A1D61691BF.html)