我有一个设置命令,我希望每次启动
rails console
时执行。MyClass.some_method()
每次启动rails c
时,我都厌倦了重新输入它 - 有没有办法在每次启动新控制台时自动运行它?
谢谢!
rails console
时执行。MyClass.some_method()
每次启动rails c
时,我都厌倦了重新输入它 - 有没有办法在每次启动新控制台时自动运行它?
谢谢!
# 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
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控制台时,它都会执行一些操作:
如果你只是想在控制台启动时运行某个代码片段,那么这样做比较复杂。相反,你可以在MyApp::Application中使用console()方法,它将作为"load_console"步骤的一部分来运行你希望运行的任何代码。(参考链接)
module MyApp
class Application < Rails::Application
...
console do
puts "do something"
end
end
end
我们遇到的一个问题是在打印环境之前运行代码,如果你要进行任何打印或交互,它会感觉有点奇怪:
当然,你可能没有我们这么讲究。做任何让你和你的团队感到最幸福的事情。
我不知道这是否是一种好的实践方法,但是您可以像Aditya所回答的那样在控制台上检查服务器是否正在运行。
if defined?(Rails::Console)
MyClass.some_method()
end
after_initialize
中调用它。config.after_initialize do
IndividualProject::Application.load_tasks
Rake::Task[ 'foo:bar' ].invoke
end