How to run script before every Rails console invocation?
Asked Answered
G

3

5

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!

Gymnasiarch answered 3/3, 2016 at 12:46 Comment(0)
S
4

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.

Spastic answered 3/3, 2016 at 14:5 Comment(1)
@mudasobwa thank you. I want to add that we should execute it from local .irbrc file, otherwise, we will get error any time we execute irb(not rails console). Here are the instructions.Gymnasiarch
F
3

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
Fluidextract answered 20/7, 2018 at 15:32 Comment(0)
L
2

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.

Lorislorita answered 3/3, 2016 at 13:20 Comment(2)
In fact, it's a good idea, but Rails console doesn't provide us with this feature. I have only one idea, just to fork irb, add default autoloading, and pass it to app as specified hereGymnasiarch
IRB executes ~/.irbrc and ./.irbrc files on startup automatically.Spastic

© 2022 - 2024 — McMap. All rights reserved.