Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 487
pixelearth Avatar asked May 01 '12 18:05

pixelearth


1 Answers

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!

like image 173
Juanito Fatas Avatar answered Oct 03 '22 10:10

Juanito Fatas