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?
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
@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
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 :)
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.
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