gpt4 book ai didi

ruby-on-rails - 如果不是 rails 运行它,则跳过初始化程序

转载 作者:行者123 更新时间:2023-12-03 18:32:54 24 4
gpt4 key购买 nike

我在初始化程序中有一些代码,我希望它仅在服务器启动时运行,而不是在控制台启动时运行。有什么办法可以区分它们吗?

谢谢!

最佳答案

我有这个任务的特殊 helper

#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

关于ruby-on-rails - 如果不是 rails 运行它,则跳过初始化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33648153/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com