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

Add Load A File When Starting Rails Console as a Rails TIL

This commit is contained in:
jbranchaud
2022-05-30 16:50:00 -05:00
parent b7409d9c8f
commit 0715b7099f
2 changed files with 31 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://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)

View File

@@ -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.