How to run my ruby code after Rails server start?

2020-02-26 04:36发布

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?

5条回答
放我归山
2楼-- · 2020-02-26 04:49

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

查看更多
走好不送
3楼-- · 2020-02-26 04:57

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
查看更多
够拽才男人
4楼-- · 2020-02-26 04:58

@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
查看更多
Fickle 薄情
5楼-- · 2020-02-26 05:03

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 :)

查看更多
爱情/是我丢掉的垃圾
6楼-- · 2020-02-26 05:05

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.

查看更多
登录 后发表回答