Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run script before every Rails console invocation?

I'm pretty tired of writing this line every time I want to open the Rails console:

irb(main):001:0> ActsAsTenant.current_tenant = User.find(1).account

Is there any way to run command/script before every "rails c"/"irb" invocation?

Thanks in advance!

like image 558
shunter Avatar asked Mar 03 '16 12:03

shunter


3 Answers

Put the code you want to execute into .irbrc file in the root folder of your project:

echo 'ActsAsTenant.current_tenant = User.find(1).account' >> .irbrc
bundle exec rails c # ⇐ the code in .irbrc got executed

Sidenote: Use Pry instead of silly IRB. Try it and you’ll never roll back.

like image 152
Aleksei Matiushkin Avatar answered Oct 19 '22 04:10

Aleksei Matiushkin


I wrote an extended answer to this in another question but the short answer is that if you are using Rails 3 or above you can use the console method on YourApp::Application to make it happen:

module YourApp
  class Application < Rails::Application
    ...

    console do
      ActsAsTenant.current_tenant = User.find(1).account
    end
  end
end
like image 27
Jeremy Baker Avatar answered Oct 19 '22 02:10

Jeremy Baker


You could put your setup code in a rb file, for example:

foo.rb:

def irb_setup
    ActsAsTenant.current_tenant = User.find(1).account
end

launch irb like this:

irb -r ./foo.rb 

and call the method (which will autocomplete pressing tab)

2.3.0 :001 > init_irb

In fact maybe you could put the code directly, without any method, and it would be executed when it is loaded. But I'm not sure if that would work or mess with the load order.

like image 1
fgperianez Avatar answered Oct 19 '22 02:10

fgperianez