6

According to http://edgeapi.rubyonrails.org/classes/Rails/Railtie.html, if I write a Rails 3 plugin and I want to hook into the initialization process, I write

class MyRailtie < Rails::Railtie
  initializer "my_railtie.configure_rails_initialization" do
    # some initialization behavior
  end
end

However, this initializer appears to be executed when you run, for instance, a Rails rake task, not just when you run rails s or similar. My question is, how do I prevent my code in this block from being run during Rails tasks, as opposed to full Rails server boot-ups? This seems to be a common problem with Rails 3 plugins.

Trevor Burnham
  • 76,828
  • 33
  • 160
  • 196

2 Answers2

4

add this block to your initializer:

if defined?(Rails::Server)
  # do something
end

this should work with the current 3.0.6 rails version.

jelveh
  • 41
  • 4
  • Hmm, could you say more about the circumstances under which `Rails::Server` is defined? I haven't seen any plugins that use this. – Trevor Burnham Apr 08 '11 at 17:31
  • This is great, but it does not seem to work with Heroku ? Any alternatives ? – Alex Apr 09 '11 at 06:23
  • I needed something to use on our dev environment to start up some services but only when run in server mode, went thru the rails source code, that object gets loaded when you start the rails server. – jelveh Apr 11 '11 at 12:47
0

Way back when I posted this question, Mongoid was experiencing this issue. I reported it here, and it was resolved by wrapping the code in a config.after_initialize block. If Rails isn't initialized, then this block is never called. More information here.

Trevor Burnham
  • 76,828
  • 33
  • 160
  • 196
  • This does not work for me, whatever code I put in the config.after_initialize gets called even in console mode or rake mode – Alex Apr 09 '11 at 06:24
  • Hmm, are you using the same style as in [Mongoid's railtie.rb](https://github.com/mongoid/mongoid/blob/master/lib/mongoid/railtie.rb)? With `config.after_initialize` nested inside of an `initializer` block? – Trevor Burnham Apr 09 '11 at 19:52
  • I put the config.after_initialize block into my application.rb, but the code seems to run everytime no matter if it's launched by rails c or rails s, or even a simple rake – Alex Apr 10 '11 at 10:38
  • I also tried to add it in the environment initializer like developement.rb but in this case it seems that it never gets called... :( – Alex Apr 10 '11 at 11:58