diff --git a/README.md b/README.md index b8b8b22..d409a2b 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://crafty-builder-6996.ck.page/e169c61186). -_1210 TILs and counting..._ +_1211 TILs and counting..._ --- @@ -755,6 +755,7 @@ _1210 TILs and counting..._ - [Link To The Current Page With Query Params](rails/link-to-the-current-page-with-query-params.md) - [List All Installable Rails Versions](rails/list-all-installable-rails-versions.md) - [List The Enqueued Jobs](rails/list-the-enqueued-jobs.md) +- [Load A File When Starting Rails Console](rails/load-a-file-when-starting-rails-console.md) - [Load Records In Batches With find_each](rails/load-records-in-batches-with-find-each.md) - [Log SQL Queries Executed By ActiveRecord](rails/log-sql-queries-executed-by-activerecord.md) - [Mark A Migration As Irreversible](rails/mark-a-migration-as-irreversible.md) diff --git a/rails/load-a-file-when-starting-rails-console.md b/rails/load-a-file-when-starting-rails-console.md new file mode 100644 index 0000000..793c354 --- /dev/null +++ b/rails/load-a-file-when-starting-rails-console.md @@ -0,0 +1,29 @@ +# Load A File When Starting Rails Console + +The `rails console` command uses `irb` under the hood. That means you can use +any of the flags that `irb` supports when running `rails c`. One of those flags +is `-r` which "causes `irb` to load the [specified] library using require." + +This `-r` flag can come in handy if we want to load a little bit of setup code +or some utility methods for our `rails console` session. + +Let's say we have `vendor/show_env.rb` with this snippet of code: + +```ruby +puts "#{'*' * 7} #{Rails.env.upcase} #{'*' * 7} +``` + +And we want that to display as we open the console. We can pass the path to +that file to the `-r` flag. + +```bash +$ rails console -- -r ./vendor/show_env.rb +``` + +[Notice the +`--`](https://tosbourn.com/speed-up-pasting-text-into-rails-console/). That is +to indicate that we are done with `console` specific arguments and anything +else should be passed along to `irb`. Without the `--`, the `-r` flag won't be +recognized. + +See `man irb` to see what other flags `irb` supports.