Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 908
Nimrod Priell Avatar asked Dec 28 '11 18:12

Nimrod Priell


Video Answer


1 Answers

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.

like image 173
riffraff Avatar answered Oct 08 '22 09:10

riffraff