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

console, ruby-on-rails

Solution

If you use `irb`, just add a method in `~/.irbrc` (create one if 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!

Problem

Is there a way to execute some code that is run only when the console starts? Kind of like an rc file (`.bashrc`, `.zshrc`, etc.)? I find myself always doing certain things a lot. For example, where would I put this ``` u = User.find_by_username('my_console_user') ``` so that `u` is available in `rails console`? I have resorted to this, the use of `$` as global variable declaration, and the use of the obscure `console do`. I assume 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 ```

Original source