mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 15:18:01 +00:00
Add Run Some Code When Rails Console Starts as a Rails til
This commit is contained in:
@@ -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).
|
||||
|
||||
_1196 TILs and counting..._
|
||||
_1197 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -772,6 +772,7 @@ _1196 TILs and counting..._
|
||||
- [Retrieve An Object If It Exists](rails/retrieve-an-object-if-it-exists.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 Some Code Whenever Rails Console Starts](rails/run-some-code-whenever-rails-console-starts.md)
|
||||
- [Schedule Sidekiq Jobs Out Into The Future](rails/schedule-sidekiq-jobs-out-into-the-future.md)
|
||||
- [Secure Passwords With Rails And Bcrypt](rails/secure-passwords-with-rails-and-bcrypt.md)
|
||||
- [Select A Select By Selector](rails/select-a-select-by-selector.md)
|
||||
|
||||
36
rails/run-some-code-whenever-rails-console-starts.md
Normal file
36
rails/run-some-code-whenever-rails-console-starts.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# Run Some Code Whenever Rails Console Starts
|
||||
|
||||
It can be handy to run some code whenever the `rails console` command is run.
|
||||
You may want to have some modules required, some variables set up, or, both
|
||||
fancy and practical, default to the read replica database in production.
|
||||
|
||||
Rails provides a hook into the console startup with the `console` block in
|
||||
`config/application.rb`.
|
||||
|
||||
Here is what it looks like to `puts` out the environment:
|
||||
|
||||
```ruby
|
||||
class Application < Rails::Application
|
||||
# everything else ...
|
||||
|
||||
console do
|
||||
puts '############################################'
|
||||
puts 'Connected to the #{Rails.env.upcase} console'
|
||||
puts '############################################'
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
To avoid cluttering `config/application.rb` with a bunch of console-specific
|
||||
logic, you can move it to another file and then have the console block require
|
||||
that file with the `-r` flag.
|
||||
|
||||
```ruby
|
||||
class Application < Rails::Application
|
||||
console do
|
||||
ARGV.push "-r", Rails.root.join("lib/console.rb")
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
[source](https://til.hashrocket.com/posts/avb2v3ubdt-pass-a-block-on-console-load)
|
||||
Reference in New Issue
Block a user