Rails 3 initializers that run only on `rails server` and not `rails generate`, etc

三世轮回 提交于 2019-12-18 04:45:38

问题


I have a relatively small piece of initializer code that I want to run whenever rails server runs, but not when I run rails generate, rails console or any other rails command (including rake tasks that require the environment task). This piece of code pre-fills some caches and is relatively expensive so I really don't want it to run on anything but rails s

Solutions that are unsatisfactory:

Foreman et al. will mean it'll run on a different process which is (a) over the top for that small piece of code, (b) requires interprocess communication instead of the simple in-memory approach afforded by the initializer.

On the server I've solved this by configuring passenger to pass a special environment variable into rails, telling it it's running in server context. However I'd like it if possible to work out of the box on all developer's machines without resorting to remembering to run rails server in a way that'll also provide that environment variable (i.e IN_SERVER=true rails server).

This question has always been asked before with respect to running an initializer when running in rails server and not in rake. However I want it to run specifically only in server initialization - the fix for rake is great but isn't comprehensive.


回答1:


Can you do something like overriding Rails::Server#initializeso that it invokes your initialization code in your initializer?

Or, more easily, just put your code in script/rails, as that will be run everytime you run rails server, you can easily fiddle with ARGV or ENV in there.




回答2:


Here's one way:

# config/initializers/my_init.rb
Rails.application.config.after_initialize do
    # tweak this as required...
    unless defined?(::Rails::Generators) || defined?(::Rails::Console) || File.basename($0) =='rake'
        Rails.logger.info("Doing some init")
        # ...
    end
end


来源:https://stackoverflow.com/questions/8660019/rails-3-initializers-that-run-only-on-rails-server-and-not-rails-generate-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!