我在初始化程序中有一些代码,我希望它只在服务器启动时运行,而不是在控制台启动时运行。有没有办法告诉他们分开?
谢谢!
答案 0 :(得分:6)
如果你只是需要检查服务器是否正在运行,你可以使用这个
if defined?(Rails::Server)
# do something usefull
end
答案 1 :(得分:4)
我有这个任务的特别助手
#lib/initializer_helpers.rb
module InitializerHelpers
def self.skip_console_rake_generators &block
skip(defined?(Rails::Console) || defined?(Rails::Generators) || File.basename($0) == "rake", &block)
end
def self.skip_rake_generators &block
skip(defined?(Rails::Generators) || File.basename($0) == "rake", &block)
end
def self.skip_generators &block
skip(defined?(Rails::Generators), &block)
end
def self.skip_console &block
skip(defined?(Rails::Console), &block)
end
private
def self.skip(condition, &block)
raise ArgumentError.new("no block given") if block.blank?
unless condition
yield
end
end
end
# use it
InitializerHelpers.skip_console do
# not executed in console
end
更新:将此想法提取到gem https://github.com/olegantonyan/initializer_helpers
答案 2 :(得分:1)
您可以检查Rails控制台是否已定义:
run_code unless defined?(Rails::Console)