仅在服务器模式下向 Rails 3 启动过程添加初始化步骤
根据 http://edgeapi.rubyonrails.org/classes/Rails/Railtie.html,如果我编写一个 Rails 3 插件并且想要挂钩初始化过程,我会写
class MyRailtie < Rails::Railtie
initializer "my_railtie.configure_rails_initialization" do
# some initialization behavior
end
end
但是,这个初始化程序似乎是在您运行时执行的,例如,Rails rake
任务,而不是就在您运行 rails s
或类似命令时。我的问题是,如何防止此块中的代码在 Rails 任务期间运行,而不是在完整的 Rails 服务器启动期间运行?这似乎是 Rails 3 插件的常见问题。
According to http://edgeapi.rubyonrails.org/classes/Rails/Railtie.html, if I write a Rails 3 plugin and I want to hook into the initialization process, I write
class MyRailtie < Rails::Railtie
initializer "my_railtie.configure_rails_initialization" do
# some initialization behavior
end
end
However, this initializer appears to be executed when you run, for instance, a Rails rake
task, not just when you run rails s
or similar. My question is, how do I prevent my code in this block from being run during Rails tasks, as opposed to full Rails server boot-ups? This seems to be a common problem with Rails 3 plugins.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将此块添加到您的初始化程序中:
这应该适用于当前的 3.0.6 Rails 版本。
add this block to your initializer:
this should work with the current 3.0.6 rails version.
早在我发布这个问题时,Mongoid 就遇到了这个问题。我在此处报告了该问题,并通过将代码包装在
config 中解决了这个问题.after_initialize
块。如果 Rails 未初始化,则永远不会调用此块。更多信息请参见此处。Way back when I posted this question, Mongoid was experiencing this issue. I reported it here, and it was resolved by wrapping the code in a
config.after_initialize
block. If Rails isn't initialized, then this block is never called. More information here.