每次rails控制台启动时执行命令

我有一个我想在每次启动rails console 执行的设置命令 –

 MyClass.some_method() 

每次启动rails c时我都厌倦了重新输入它 – 有没有办法让它在每次启动新控制台时自动运行?

谢谢!

我会尝试为它创建一个Rake任务并使用after_initialize调用它:

 config.after_initialize do IndividualProject::Application.load_tasks Rake::Task[ 'foo:bar' ].invoke end 

我不知道它是否是一个很好的做法,但你可以检查服务器是否在控制台上运行,就像Aditya awnsered一样

 if defined?(Rails::Console) MyClass.some_method() end 

请注意,在运行Spring时Rails初始化期间这不起作用,如Swartz所说。

我们这样做是为了在每次控制台启动时询问租户。 这需要一些调查,但我们的工作相当优雅。 请注意,这适用于Rails 5.2,但它自Rails 4以来的工作方式大致相同。

另外需要注意的是,这是专门编写的,因为我们希望能够在启动时运行该方法一次,然后能够在使用控制台时再次运行它,比如我们是否想在会话期间切换租户。

第一步是在lib文件中创建一组模块和类。 以下是从我们提取的示例:

 # lib/console_extension.rb module ConsoleExtension # This module provides methods that are only available in the console module ConsoleHelpers def do_someting puts "doing something" end end # This is a simple class that allows us access to the ConsoleHelpers before # we get into the console class ConsoleRunner include ConsoleExtension::ConsoleHelpers end # This is specifically to patch into the startup behavior for the console. # # In the console_command.rb file, it does this right before start: # # if defined?(console::ExtendCommandBundle) # console::ExtendCommandBundle.include(Rails::ConsoleMethods) # end # # This is a little tricky. We're defining an included method on this module # so that the Rails::ConsoleMethods module gets a self.included method. # # This causes the Rails::ConsoleMethods to run this code when it's included # in the console::ExtendCommandBundle at the last step before the console # starts, instead of during the earlier load_console stage. module ConsoleMethods def included(_klass) ConsoleExtension::ConsoleRunner.new.do_someting end end end 

下一步是将以下内容添加到application.rb文件中:

 module MyApp class Application < Rails::Application ... console do require 'console_extension' # lib/console_extension.rb Rails::ConsoleMethods.send :include, ConsoleExtension::ConsoleHelpers Rails::ConsoleMethods.send :extend, ConsoleExtension::ConsoleMethods end end end 

现在,每次运行rails console时,它都会执行以下操作:

在此处输入图像描述

如果你只是想在每次控制台启动时运行一次,这比它需要的更复杂。 相反,您可以在MyApp :: Application中使用console()方法,它将在load_console步骤中运行您想要的任何代码。

 module MyApp class Application < Rails::Application ... console do puts "do something" end end end 

我们遇到的一个问题是它在打印出环境之前运行代码,所以如果你正在进行任何打印或交互,那会感觉有点奇怪:

在此处输入图像描述

你可能不像我们那样挑剔。 做任何让你和你的团队最快乐的事情。