11

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.

Nimrod Priell
  • 233
  • 2
  • 8

2 Answers2

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
Robert Brown
  • 10,888
  • 7
  • 34
  • 40
  • 8
    `if defined?(::Rails::Server)` is shorter and works with the new changes allowing us to use `rails` for all tasks like `rails db:migrate` – eXa May 20 '19 at 00:05
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.

riffraff
  • 2,429
  • 1
  • 23
  • 32
  • I like it very much, so something like `$IN_SERVER=true if ARGV[0]=='server'` in script/rails is a great solution. – Nimrod Priell Dec 28 '11 at 20:07
  • 1
    I'm not sure that passenger starts up Rails with `script/rails`. Did anyone actually get this method to work with passenger? – jordanpg Nov 13 '12 at 18:27