How to run my ruby code after Rails server start?

2020-02-26 04:39发布

问题:

I tried:

after_initialize do
  #code
end

But: (documentation)

Some parts of your application, notably observers and routing, are not yet set up at the point where the after_initialize block is called.

I need routing and logger in my code

Any ideas?

回答1:

See section 3.1 from http://guides.rubyonrails.org/configuring.html

I beleive you would put this code in config/application.rb

config.after_initialize do
    # ....
end

# config.after_initialize takes a block which will be run after Rails has finished initializing the application. 
# That includes the initialization of the framework itself

Also http://guides.rubyonrails.org/initialization.html



回答2:

@house9's answer is correct, as pointed out by the comments, this will also execute when running rake tasks, console, etc. I used the following to recognize when a server was actually being executed:

# application.rb
if defined?(Rails::Server)
  config.after_initialize do
    # Do stuff here
  end
end


回答3:

Another option is to create a custom initializer. It's just a ruby file that lives under config/initializers/ and is executed exactly "on_server_start" event :)



回答4:

Since Rails 5 the default server is Puma, so code in config/puma.rb will be run just once, and only if the server is started.



回答5:

Lines added to config.ru will be run by the Rails server, but not by Rails console or Rake tasks that load the environment.

# config.ru
# This file is used by Rack-based servers to start the application.

require ::File.expand_path("../config/environment", __FILE__)
# your code here (after environment is loaded)
run Rails.application