Search code examples
ruby-on-railsinitializationrake

Rails: How to run code when server starts up, but not when running a rake task or the console?


Before, I added code to a file called config/initializers/remote_publishers.rb which set up a connection to RabbitMQ using the Bunny gem on server startup.

However, this is now also executed when running rails c, rails g model SomeModel foo:integer, rails db:migrate etc.

For this app, the RabbitMQ-connection only makes sense when rails is started using rails s(erver).

What is the proper way to conditionally execute this code? Is there a way to see if Rails is starting as server, or only as task-runner?


Solution

  • What web server are you using? On Puma, for example, you can use

    on_worker_boot do
      # Establish RabbitMQ connection
    end
    

    Another possibility might be to check if defined?(Rails::Server) in your initializer: this should only be true when running in the context of the web server.