How to run some code only when the rails console starts, like an rc file?

Is there a way to execute some code that runs only when the console starts? A kind of rc file ( .bashrc , .zshrc , etc.)? I find that I always do certain things a lot.

For example, where would I place this

 u = User.find_by_username('my_console_user') 

so is u available in rails console ?

I resorted to this, using $ as a global variable declaration and using the obscure console do . I guess there is something more elegant somehow ...

  class Application < Rails::Application #this is only executed in the console, also doens't seem to be documented anywhere but here: https://github.com/rails/rails/pull/3139 console do $u1 = User.find_by_username('user1') $u2 = User.find_by_username('user2') end end 
+7
source share
1 answer

If you use irb , just add the method to ~/.irbrc (create it if it does not exist):

 def find_by_username(username) User.find_by_username('my_console_user') end 

Or add to ~/.pryrc if you use pry-rails .

Hope this helps!

+3
source

All Articles