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

2

12

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.

Dedal answered 28/12, 2011 at 18:54 Comment(0)
F
4

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.

Felisafelise answered 28/12, 2011 at 19:32 Comment(2)
I like it very much, so something like $IN_SERVER=true if ARGV[0]=='server' in script/rails is a great solution.Dedal
I'm not sure that passenger starts up Rails with script/rails. Did anyone actually get this method to work with passenger?Cavit
A
4

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
Azimuth answered 17/5, 2017 at 0:37 Comment(1)
if defined?(::Rails::Server) is shorter and works with the new changes allowing us to use rails for all tasks like rails db:migrateHarlen

© 2022 - 2024 — McMap. All rights reserved.