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.
$IN_SERVER=true if ARGV[0]=='server'
in script/rails is a great solution. – Dedal