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!

shunter
  • 139
  • 2
  • 9

3 Answers3

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.

Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
  • @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](http://samuelmullen.com/2010/04/irb-global-local-irbrc/) are the instructions. – shunter Mar 05 '16 at 15:22
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
Jeremy Baker
  • 3,986
  • 3
  • 24
  • 27
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.

fgperianez
  • 111
  • 5
  • 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 [here](https://github.com/rails/rails/blob/7f18ea14c893cb5c9f04d4fda9661126758332b5/railties/lib/rails/commands/console.rb#L36) – shunter Mar 03 '16 at 13:59
  • `IRB` executes `~/.irbrc` and `./.irbrc` files on startup automatically. – Aleksei Matiushkin Mar 03 '16 at 14:09