如何在每次 Rails 控制台调用之前 运行 编写脚本?
How to run script before every Rails console invocation?
每次我想打开 Rails 控制台时,我都厌倦了写这一行:
irb(main):001:0> ActsAsTenant.current_tenant = User.find(1).account
有什么方法可以在每次 "rails c"/"irb" 调用之前 运行 command/script 吗?
提前致谢!
您可以将设置代码放在 rb 文件中,例如:
foo.rb:
def irb_setup
ActsAsTenant.current_tenant = User.find(1).account
end
像这样启动 irb:
irb -r ./foo.rb
并调用方法(按 Tab 键自动完成)
2.3.0 :001 > init_irb
其实也可以直接把代码放上去,不用任何方法,加载的时候就会执行。但我不确定这是否会影响加载顺序。
将要执行的代码放入项目根文件夹的.irbrc
文件中:
echo 'ActsAsTenant.current_tenant = User.find(1).account' >> .irbrc
bundle exec rails c # ⇐ the code in .irbrc got executed
旁注:使用Pry
而不是愚蠢的IRB
。试试吧,你永远不会回滚。
我写了一个 extended answer to this in another question but the short answer is that if you are using Rails 3 or above 你可以在 YourApp::Application 上使用控制台方法来实现它:
module YourApp
class Application < Rails::Application
...
console do
ActsAsTenant.current_tenant = User.find(1).account
end
end
end
每次我想打开 Rails 控制台时,我都厌倦了写这一行:
irb(main):001:0> ActsAsTenant.current_tenant = User.find(1).account
有什么方法可以在每次 "rails c"/"irb" 调用之前 运行 command/script 吗?
提前致谢!
您可以将设置代码放在 rb 文件中,例如:
foo.rb:
def irb_setup
ActsAsTenant.current_tenant = User.find(1).account
end
像这样启动 irb:
irb -r ./foo.rb
并调用方法(按 Tab 键自动完成)
2.3.0 :001 > init_irb
其实也可以直接把代码放上去,不用任何方法,加载的时候就会执行。但我不确定这是否会影响加载顺序。
将要执行的代码放入项目根文件夹的.irbrc
文件中:
echo 'ActsAsTenant.current_tenant = User.find(1).account' >> .irbrc
bundle exec rails c # ⇐ the code in .irbrc got executed
旁注:使用Pry
而不是愚蠢的IRB
。试试吧,你永远不会回滚。
我写了一个 extended answer to this in another question but the short answer is that if you are using Rails 3 or above 你可以在 YourApp::Application 上使用控制台方法来实现它:
module YourApp
class Application < Rails::Application
...
console do
ActsAsTenant.current_tenant = User.find(1).account
end
end
end